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,63 +1,175 @@
|
||||
/** Base class for all Shade errors */
|
||||
/**
|
||||
* Shade error hierarchy.
|
||||
*
|
||||
* All errors have:
|
||||
* - `name`: class name for `instanceof` checks
|
||||
* - `code`: stable string code for error mapping (e.g. HTTP status)
|
||||
* - `toJSON()`: serializable form for network transmission
|
||||
*/
|
||||
export class ShadeError extends Error {
|
||||
constructor(message: string) {
|
||||
/** Stable error code for mapping to HTTP status or UI strings */
|
||||
readonly code: string;
|
||||
|
||||
constructor(code: string, message: string) {
|
||||
super(message);
|
||||
this.name = 'ShadeError';
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
toJSON(): { name: string; code: string; message: string } {
|
||||
return { name: this.name, code: this.code, message: this.message };
|
||||
}
|
||||
}
|
||||
|
||||
/** Signature verification failed (e.g. invalid signed prekey) */
|
||||
// ─── Crypto / Protocol Errors ────────────────────────────────
|
||||
|
||||
export class InvalidSignatureError extends ShadeError {
|
||||
constructor(message = 'Signature verification failed') {
|
||||
super(message);
|
||||
super('SHADE_INVALID_SIGNATURE', message);
|
||||
this.name = 'InvalidSignatureError';
|
||||
}
|
||||
}
|
||||
|
||||
/** AES-GCM decryption failed (wrong key, tampered ciphertext, or bad nonce) */
|
||||
export class DecryptionError extends ShadeError {
|
||||
constructor(message = 'Decryption failed') {
|
||||
super(message);
|
||||
super('SHADE_DECRYPTION_FAILED', message);
|
||||
this.name = 'DecryptionError';
|
||||
}
|
||||
}
|
||||
|
||||
/** No session exists for the given address */
|
||||
export class NoSessionError extends ShadeError {
|
||||
constructor(address: string) {
|
||||
super(`No session for address: ${address}`);
|
||||
this.name = 'NoSessionError';
|
||||
}
|
||||
}
|
||||
|
||||
/** Too many skipped messages in a chain (possible DoS or sync issue) */
|
||||
export class MaxSkipExceededError extends ShadeError {
|
||||
constructor(requested: number, max: number) {
|
||||
super(`Cannot skip ${requested} messages (max: ${max})`);
|
||||
super('SHADE_MAX_SKIP_EXCEEDED', `Cannot skip ${requested} messages (max: ${max})`);
|
||||
this.name = 'MaxSkipExceededError';
|
||||
}
|
||||
}
|
||||
|
||||
/** Duplicate message detected (message key already consumed) */
|
||||
export class DuplicateMessageError extends ShadeError {
|
||||
constructor() {
|
||||
super('Duplicate message: key already consumed');
|
||||
super('SHADE_DUPLICATE_MESSAGE', 'Duplicate message: key already consumed');
|
||||
this.name = 'DuplicateMessageError';
|
||||
}
|
||||
}
|
||||
|
||||
/** Remote identity key has changed unexpectedly */
|
||||
export class ReplayError extends ShadeError {
|
||||
constructor(message = 'Message timestamp outside replay window') {
|
||||
super('SHADE_REPLAY', message);
|
||||
this.name = 'ReplayError';
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Session / Identity Errors ───────────────────────────────
|
||||
|
||||
export class NoSessionError extends ShadeError {
|
||||
constructor(address: string) {
|
||||
super('SHADE_NO_SESSION', `No session for address: ${address}`);
|
||||
this.name = 'NoSessionError';
|
||||
}
|
||||
}
|
||||
|
||||
export class UntrustedIdentityError extends ShadeError {
|
||||
constructor(address: string) {
|
||||
super(`Untrusted identity key for: ${address}`);
|
||||
super('SHADE_UNTRUSTED_IDENTITY', `Untrusted identity key for: ${address}`);
|
||||
this.name = 'UntrustedIdentityError';
|
||||
}
|
||||
}
|
||||
|
||||
/** Required prekey not found in storage */
|
||||
export class PreKeyNotFoundError extends ShadeError {
|
||||
constructor(keyId: number, type: 'signed' | 'one-time') {
|
||||
super(`${type} prekey not found: ${keyId}`);
|
||||
super('SHADE_PREKEY_NOT_FOUND', `${type} prekey not found: ${keyId}`);
|
||||
this.name = 'PreKeyNotFoundError';
|
||||
}
|
||||
}
|
||||
|
||||
export class IdentityRotationError extends ShadeError {
|
||||
constructor(message = 'Identity rotation failed') {
|
||||
super('SHADE_IDENTITY_ROTATION', message);
|
||||
this.name = 'IdentityRotationError';
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Infrastructure Errors ───────────────────────────────────
|
||||
|
||||
export class NetworkError extends ShadeError {
|
||||
constructor(message: string, public readonly statusCode?: number) {
|
||||
super('SHADE_NETWORK', message);
|
||||
this.name = 'NetworkError';
|
||||
}
|
||||
}
|
||||
|
||||
export class StorageError extends ShadeError {
|
||||
constructor(message: string, public readonly cause?: unknown) {
|
||||
super('SHADE_STORAGE', message);
|
||||
this.name = 'StorageError';
|
||||
}
|
||||
}
|
||||
|
||||
export class ValidationError extends ShadeError {
|
||||
constructor(message: string, public readonly field?: string) {
|
||||
super('SHADE_VALIDATION', message);
|
||||
this.name = 'ValidationError';
|
||||
}
|
||||
}
|
||||
|
||||
export class TimeoutError extends ShadeError {
|
||||
constructor(message = 'Operation timed out') {
|
||||
super('SHADE_TIMEOUT', message);
|
||||
this.name = 'TimeoutError';
|
||||
}
|
||||
}
|
||||
|
||||
export class RateLimitError extends ShadeError {
|
||||
constructor(message = 'Rate limit exceeded', public readonly retryAfterSeconds?: number) {
|
||||
super('SHADE_RATE_LIMIT', message);
|
||||
this.name = 'RateLimitError';
|
||||
}
|
||||
}
|
||||
|
||||
export class ConfigurationError extends ShadeError {
|
||||
constructor(message: string) {
|
||||
super('SHADE_CONFIG', message);
|
||||
this.name = 'ConfigurationError';
|
||||
}
|
||||
}
|
||||
|
||||
export class UnauthorizedError extends ShadeError {
|
||||
constructor(message = 'Unauthorized') {
|
||||
super('SHADE_UNAUTHORIZED', message);
|
||||
this.name = 'UnauthorizedError';
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Error → HTTP Status Mapping ────────────────────────────
|
||||
|
||||
/**
|
||||
* Map a ShadeError to an HTTP status code.
|
||||
* Used by the prekey server's global error handler.
|
||||
*/
|
||||
export function errorToHttpStatus(error: unknown): number {
|
||||
if (!(error instanceof ShadeError)) return 500;
|
||||
switch (error.code) {
|
||||
case 'SHADE_INVALID_SIGNATURE':
|
||||
case 'SHADE_UNAUTHORIZED':
|
||||
return 401;
|
||||
case 'SHADE_UNTRUSTED_IDENTITY':
|
||||
return 403;
|
||||
case 'SHADE_NO_SESSION':
|
||||
case 'SHADE_PREKEY_NOT_FOUND':
|
||||
return 404;
|
||||
case 'SHADE_VALIDATION':
|
||||
return 400;
|
||||
case 'SHADE_REPLAY':
|
||||
case 'SHADE_DUPLICATE_MESSAGE':
|
||||
return 409;
|
||||
case 'SHADE_RATE_LIMIT':
|
||||
return 429;
|
||||
case 'SHADE_TIMEOUT':
|
||||
return 504;
|
||||
case 'SHADE_NETWORK':
|
||||
case 'SHADE_STORAGE':
|
||||
case 'SHADE_CONFIG':
|
||||
return 503;
|
||||
default:
|
||||
return 500;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user