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:
2026-04-10 17:45:34 +02:00
parent 7d214dc614
commit 96a8c210b2
25 changed files with 1835 additions and 257 deletions

View File

@@ -1,35 +1,93 @@
import { Hono } from 'hono';
import type { CryptoProvider } from '@shade/core';
import { fromBase64, errorToHttpStatus, ShadeError, ValidationError } from '@shade/core';
import type { PrekeyStore } from './store.js';
import { verifyPayload, validateAddress } from './auth.js';
import { RateLimiter, MemoryRateLimitStore, REGISTER_LIMIT, FETCH_LIMIT, REPLENISH_LIMIT, DELETE_LIMIT } from './rate-limit.js';
/** Max POST body size in bytes (64KB) */
const MAX_BODY_SIZE = 64 * 1024;
/**
* Create the Shade Prekey Server Hono app.
*
* Routes:
* POST /v1/keys/register — Register identity + upload prekey bundle
* GET /v1/keys/bundle/:address — Fetch a prekey bundle (consumes one OTP key)
* POST /v1/keys/replenish — Upload additional one-time prekeys
* GET /v1/keys/count/:address — Get remaining one-time prekey count
* DELETE /v1/keys/:address — Unregister (delete all keys)
* POST /v1/keys/register — Register identity + upload prekey bundle (SIGNED)
* GET /v1/keys/bundle/:address — Fetch a prekey bundle (anonymous)
* POST /v1/keys/replenish — Upload additional one-time prekeys (SIGNED)
* GET /v1/keys/count/:address — Get remaining one-time prekey count (anonymous)
* DELETE /v1/keys/:address — Unregister (SIGNED)
*
* Write routes require a valid Ed25519 signature. See auth.ts.
*/
export function createPrekeyRoutes(store: PrekeyStore): Hono {
export interface PrekeyRoutesOptions {
/** Disable rate limiting (for tests). Default: enabled. */
disableRateLimit?: boolean;
}
export function createPrekeyRoutes(
store: PrekeyStore,
crypto: CryptoProvider,
options: PrekeyRoutesOptions = {},
): Hono {
const app = new Hono();
// Rate limiters (one per route, per IP or per identity)
const rlStore = new MemoryRateLimitStore();
const registerRL = new RateLimiter(rlStore, REGISTER_LIMIT);
const fetchRL = new RateLimiter(rlStore, FETCH_LIMIT);
const replenishRL = new RateLimiter(rlStore, REPLENISH_LIMIT);
const deleteRL = new RateLimiter(rlStore, DELETE_LIMIT);
const rateLimitEnabled = !options.disableRateLimit;
// Helper: extract client IP from request headers
const getClientIp = (c: any): string => {
return (
c.req.header('x-forwarded-for')?.split(',')[0]?.trim() ??
c.req.header('x-real-ip') ??
'unknown'
);
};
// Global error handler — maps ShadeError to HTTP status
app.onError((err, c) => {
if (err instanceof ShadeError) {
const status = errorToHttpStatus(err);
const body: any = err.toJSON();
if ((err as any).retryAfterSeconds) {
c.header('Retry-After', String((err as any).retryAfterSeconds));
}
return c.json(body, status as any);
}
console.error('[Shade] Unhandled error:', err);
return c.json({ error: 'Internal server error' }, 500);
});
// ─── Register ──────────────────────────────────────────────
app.post('/v1/keys/register', async (c) => {
const body = await c.req.json();
if (rateLimitEnabled) await registerRL.consume(`register:${getClientIp(c)}`);
const rawBody = await c.req.text();
if (rawBody.length > MAX_BODY_SIZE) {
throw new ValidationError(`Request body too large (max ${MAX_BODY_SIZE} bytes)`);
}
const body = JSON.parse(rawBody);
const { address, identitySigningKey, identityDHKey, signedPreKey, oneTimePreKeys } = body;
if (!address || !identitySigningKey || !identityDHKey || !signedPreKey) {
return c.json({ error: 'Missing required fields' }, 400);
const addr = validateAddress(address);
if (!identitySigningKey || !identityDHKey || !signedPreKey) {
throw new ValidationError('Missing required fields');
}
// Decode base64 keys
const signingKey = b64ToBytes(identitySigningKey);
const dhKey = b64ToBytes(identityDHKey);
await store.saveIdentity(address, signingKey, dhKey);
// Verify signature against the identity's own signing key (TOFU)
await verifyPayload(crypto, signingKey, body);
await store.saveIdentity(addr, signingKey, dhKey);
await store.saveSignedPreKey(
address,
addr,
signedPreKey.keyId,
b64ToBytes(signedPreKey.publicKey),
b64ToBytes(signedPreKey.signature),
@@ -40,27 +98,27 @@ export function createPrekeyRoutes(store: PrekeyStore): Hono {
keyId: k.keyId,
publicKey: b64ToBytes(k.publicKey),
}));
await store.saveOneTimePreKeys(address, keys);
await store.saveOneTimePreKeys(addr, keys);
}
return c.json({ ok: true });
});
// ─── Fetch Bundle ──────────────────────────────────────────
// ─── Fetch Bundle (anonymous) ──────────────────────────────
app.get('/v1/keys/bundle/:address', async (c) => {
const address = c.req.param('address');
if (rateLimitEnabled) await fetchRL.consume(`fetch:${getClientIp(c)}`);
const address = validateAddress(c.req.param('address'));
const identity = await store.getIdentity(address);
if (!identity) {
return c.json({ error: 'Address not found' }, 404);
return c.json({ error: 'Address not found', code: 'SHADE_NOT_FOUND' }, 404);
}
const signedPreKey = await store.getSignedPreKey(address);
if (!signedPreKey) {
return c.json({ error: 'No signed prekey' }, 404);
return c.json({ error: 'No signed prekey', code: 'SHADE_NOT_FOUND' }, 404);
}
// Consume one one-time prekey (if available)
const oneTimePreKey = await store.consumeOneTimePreKey(address);
const bundle: any = {
@@ -83,35 +141,59 @@ export function createPrekeyRoutes(store: PrekeyStore): Hono {
return c.json(bundle);
});
// ─── Replenish One-Time Prekeys ────────────────────────────
// ─── Replenish One-Time Prekeys (signed) ───────────────────
app.post('/v1/keys/replenish', async (c) => {
const body = await c.req.json();
const rawBody = await c.req.text();
if (rawBody.length > MAX_BODY_SIZE) {
throw new ValidationError(`Request body too large (max ${MAX_BODY_SIZE} bytes)`);
}
const body = JSON.parse(rawBody);
const { address, oneTimePreKeys } = body;
if (!address || !oneTimePreKeys || !Array.isArray(oneTimePreKeys)) {
return c.json({ error: 'Missing address or oneTimePreKeys' }, 400);
const addr = validateAddress(address);
if (rateLimitEnabled) await replenishRL.consume(`replenish:${addr}`);
if (!oneTimePreKeys || !Array.isArray(oneTimePreKeys)) {
throw new ValidationError('Missing oneTimePreKeys');
}
// Look up the stored identity and verify the signature against it
const identity = await store.getIdentity(addr);
if (!identity) {
return c.json({ error: 'Address not registered', code: 'SHADE_NOT_FOUND' }, 404);
}
await verifyPayload(crypto, identity.identitySigningKey, body);
const keys = oneTimePreKeys.map((k: any) => ({
keyId: k.keyId,
publicKey: b64ToBytes(k.publicKey),
}));
await store.saveOneTimePreKeys(address, keys);
await store.saveOneTimePreKeys(addr, keys);
const count = await store.getOneTimePreKeyCount(address);
const count = await store.getOneTimePreKeyCount(addr);
return c.json({ ok: true, remaining: count });
});
// ─── Get Count ─────────────────────────────────────────────
// ─── Get Count (anonymous) ─────────────────────────────────
app.get('/v1/keys/count/:address', async (c) => {
const address = c.req.param('address');
const address = validateAddress(c.req.param('address'));
const count = await store.getOneTimePreKeyCount(address);
return c.json({ count });
});
// ─── Delete ────────────────────────────────────────────────
// ─── Delete (signed) ───────────────────────────────────────
app.delete('/v1/keys/:address', async (c) => {
const address = c.req.param('address');
const address = validateAddress(c.req.param('address'));
if (rateLimitEnabled) await deleteRL.consume(`delete:${address}`);
const body = await c.req.json();
// Look up the stored identity and verify the signature
const identity = await store.getIdentity(address);
if (!identity) {
return c.json({ error: 'Address not registered', code: 'SHADE_NOT_FOUND' }, 404);
}
// Include address in the signed payload
await verifyPayload(crypto, identity.identitySigningKey, { ...body, address });
await store.deleteAll(address);
return c.json({ ok: true });
});