Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,112 @@
# OpenSpec Change: network-plugin-crypto-messages
- **Change ID**: network-plugin-crypto-messages
- **Package**: `@suaveplan/network-plugin-crypto-messages` (new)
- **Status**: PROPOSED
- **Type**: new-package
- **Date**: 2026-04-29
## Why
In a decentralized mesh where the central server may be offline, peers must cryptographically verify each other's authority. A malicious peer cannot be allowed to create arbitrary sessions, spoof host identities, or forge activity logs. This plugin provides cryptographic integrity for the entire network layer: every host-signed message, server-signed session tokens, peer identity verification, and append-only signed log chains. It consumes `@suaveplan/crypto-cipher`, `@suaveplan/crypto-hash`, and `@suaveplan/crypto-keys`.
## What changes
- **ADDED**: `CryptoMessagesPlugin` class implementing `NetworkPlugin`.
- **ADDED**: `MessageSigner` — signs every outbound message with the sender's private key using Ed25519. Verifies signatures on inbound messages using peer public keys from the registry.
- **ADDED**: `SessionTokenAuthority` — validates server-signed session tokens. Every session creation requires a token signed by the central server's private key. Tokens include: `sessionId`, `parentSessionId`, `capacity`, `rulesHash`, `expiresAt`, `serverSignature`. Peers reject `session:create` without a valid token.
- **ADDED**: `MeshTokenAuthority` — validates server-signed mesh tokens. Every mesh creation requires a server-signed token with: `meshId`, `maxCapacity`, `allowedTiers`, `expiresAt`, `serverSignature`.
- **ADDED**: `PeerIdentityVerifier` — verifies peer identity via challenge-response during handshake. Prevents peer ID spoofing.
- **ADDED**: `LogChainSigner` — signs activity log entries in a hash chain: `entry[n] = sign(hash(entry[n-1]) + payload)`. Provides tamper-evident audit trails.
- **ADDED**: `KeyRotationManager` — rotates signing keys periodically and broadcasts new public keys to the mesh. Old signatures remain valid for a grace period.
- **ADDED**: `NETWORK_CRYPTO_CODES` — frozen error registry.
## Token format
```typescript
interface SessionToken {
readonly sessionId: string;
readonly parentSessionId: string | null;
readonly capacity: number;
readonly rulesHash: string; // hash of session rules
readonly issuedAt: number;
readonly expiresAt: number;
readonly serverSignature: Uint8Array; // Ed25519 signature
}
interface MeshToken {
readonly meshId: string;
readonly maxCapacity: number;
readonly allowedTiers: number;
readonly issuedAt: number;
readonly expiresAt: number;
readonly serverSignature: Uint8Array;
}
```
## Offline operation model
- Tokens have an `expiresAt` timestamp. While tokens are valid, the mesh operates autonomously.
- When tokens expire, new sessions/meshes cannot be created. Existing sessions continue.
- Token refresh requires server connectivity (via `network-plugin-server-bridge`).
- During extended outages, hosts can request emergency token extension via a quorum of peer signatures (Byzantine-tolerant voting).
## Out of scope
- Full Byzantine fault tolerance for voting → future hardening.
- Quantum-resistant signatures → future `network-plugin-crypto-pq`.
- Hardware security module (HSM) integration → future scope.
## Source mapping
This is a **new design** — suaveplan has no equivalent cryptographic integrity layer for the network mesh.
### Requirements with no source line
| Requirement | Justification |
|---|---|
| Server-signed session tokens | Prevents rogue peers from creating arbitrary sessions when server is offline |
| Server-signed mesh tokens | Prevents mesh sprawl and unauthorized topology changes |
| Ed25519 message signatures | Every host message is attributable and tamper-evident |
| Challenge-response peer identity | Prevents peer ID spoofing in the registry |
| Hash-chained signed logs | Append-only, tamper-evident audit trail for server reconciliation |
| Key rotation | Limits blast radius if a private key is compromised |
| Token expiry with quorum extension | Balances security (server authority) with resilience (offline operation) |
## Verification approach
- `src/signer/signer.spec-conformance.test.ts` — pins sign/verify roundtrip, invalid signature rejection.
- `src/session-token/session-token.spec-conformance.test.ts` — pins valid token acceptance, expired rejection, forged rejection.
- `src/mesh-token/mesh-token.spec-conformance.test.ts` — pins mesh token validation.
- `src/identity/identity.spec-conformance.test.ts` — pins challenge-response, spoof detection.
- `src/log-chain/log-chain.spec-conformance.test.ts` — pins hash chain integrity, tamper detection.
- `src/key-rotation/key-rotation.spec-conformance.test.ts` — pins rotation, grace period, broadcast.
- `src/error-codes.spec-conformance.test.ts` — frozen registry.
## Enhancement: Plugin Security Verifier
**Source**: `docs/old-network-planning/RELAY_SECURITY_IMPLEMENTATION_PLAN.md` §PluginSecurityVerifier, `MODULAR_IMPLEMENTATION_PHASE_6.md` §Security Verifier
Because the architecture is plugin-based, a compromised plugin could hijack the mesh. The crypto-messages plugin extends with plugin integrity verification:
- `PluginSecurityVerifier` — validates plugin integrity before registration. Checks code signatures, declared capabilities vs requested capabilities.
- `PluginCapabilityValidator` — enforces that plugins cannot exceed their declared capability set.
- `PluginActivityMonitor` — monitors plugin message patterns for anomalous behavior (e.g., excessive broadcast, unauthorized peer kicks).
- `SandboxedPluginContext` — restricts plugin access to sensitive node operations via capability-based access control.
## Enhancement: Tier-Specific Security Policies
**Source**: `docs/old-network-planning/RELAY_SECURITY_IMPLEMENTATION_PLAN.md` §Tier-Specific Security
Security policies vary by tier:
- `TierSecurityPolicy` — configurable rules per tier:
- Tier 0 (Host): full authority — can sign messages, issue tokens, override votes.
- Tier 1 (SubHost): relay authority + voting, no token issuance, no override.
- Tier 2 (Leaf): read-only for sensitive ops, can send game state, cannot sign logs.
- `CrossTierCredentialDelegation` — cross-tier operations require explicit credential delegation from higher tier.
- `GeographicSecurityPolicy` — optional regional restrictions on sensitive operations.
## Migration impact
None — additive only.

View File

@@ -0,0 +1,113 @@
# Tasks — network-plugin-crypto-messages
> Blocked on: `network-core`, `network-plugin-registry`.
## 1. Scaffold
- [x] 1.1 `packages/network/network-plugin-crypto-messages/` with `package.json`, `tsconfig.json`, `vitest.config.ts`, `README.md`.
- [x] 1.2 Workspace deps: `@suaveplan/network`, `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/events`, `@suaveplan/crypto-cipher`, `@suaveplan/crypto-hash`, `@suaveplan/crypto-keys`, `@suaveplan/timing`, `@opentelemetry/api`, `zod`.
- [x] 1.3 `sideEffects: false`.
## 2. Types
- [x] 2.1 `src/types/token.types.ts` — `SessionToken`, `MeshToken`, `TokenPayload`.
- [x] 2.2 `src/types/signature.types.ts` — `MessageSignature`, `SignedMessage`, `KeyPair`.
- [x] 2.3 `src/types/identity.types.ts` — `IdentityChallenge`, `IdentityResponse`.
- [x] 2.4 `src/error-codes.ts` — `defineCodes("NET_CRYPTO", [...])`.
## 3. Message signer
- [x] 3.1 `src/signer/message-signer.ts` — `MessageSigner`.
- [x] 3.2 Signs outbound with Ed25519 private key.
- [x] 3.3 Verifies inbound using peer public key from registry.
## 4. Session token authority
- [x] 4.1 `src/token/session-token-authority.ts` — `SessionTokenAuthority`.
- [x] 4.2 Validates server Ed25519 signature on session tokens.
- [x] 4.3 Rejects expired tokens, forged tokens, replayed tokens.
- [x] 4.4 Emits `token:valid` / `token:invalid` on bus.
## 5. Mesh token authority
- [x] 5.1 `src/token/mesh-token-authority.ts` — `MeshTokenAuthority`.
- [x] 5.2 Validates server signature on mesh creation tokens.
## 6. Peer identity verifier
- [x] 6.1 `src/identity/peer-identity-verifier.ts` — `PeerIdentityVerifier`.
- [x] 6.2 Challenge-response during peer handshake.
- [x] 6.3 Prevents peer ID spoofing.
## 7. Log chain signer
- [x] 7.1 `src/log-chain/log-chain-signer.ts` — `LogChainSigner`.
- [x] 7.2 `entry[n] = sign(hash(entry[n-1]) + payload)`.
- [x] 7.3 Tamper detection via hash chain break.
## 8. Key rotation manager
- [x] 8.1 `src/key-rotation/key-rotation-manager.ts` — `KeyRotationManager`.
- [x] 8.2 Periodic rotation with configurable interval.
- [x] 8.3 Grace period for old signatures.
- [x] 8.4 Broadcasts new public key on bus.
## 9. Plugin wrapper
- [x] 9.1 `src/plugin/crypto-messages-plugin.ts` — `CryptoMessagesPlugin` implements `NetworkPlugin`.
## 10. Spec
- [x] 10.1 Update `openspec/specs/network/spec.md` with `NET-CRYPTO` requirements.
## 11. Conformance tests
- [x] 11.1 `src/signer/signer.spec-conformance.test.ts` — sign/verify, invalid rejection.
- [x] 11.2 `src/session-token/session-token.spec-conformance.test.ts` — valid, expired, forged.
- [x] 11.3 `src/mesh-token/mesh-token.spec-conformance.test.ts` — mesh token validation.
- [x] 11.4 `src/identity/identity.spec-conformance.test.ts` — challenge-response, spoof.
- [x] 11.5 `src/log-chain/log-chain.spec-conformance.test.ts` — chain integrity, tamper.
- [x] 11.6 `src/key-rotation/key-rotation.spec-conformance.test.ts` — rotation, grace.
- [x] 11.7 `src/error-codes.spec-conformance.test.ts` — frozen registry.
## 12. Plugin security verifier
- [ ] 12.1 `src/plugin-security/plugin-security-verifier.ts` — `PluginSecurityVerifier`, validates plugin integrity.
- [ ] 12.2 `src/plugin-security/capability-validator.ts` — `PluginCapabilityValidator`, enforces declared capabilities.
- [ ] 12.3 `src/plugin-security/activity-monitor.ts` — `PluginActivityMonitor`, detects anomalous patterns.
- [ ] 12.4 `src/plugin-security/sandboxed-context.ts` — `SandboxedPluginContext`, restricts sensitive operations.
## 13. Tier-specific security policies
- [ ] 13.1 `src/policy/tier-security-policy.ts` — `TierSecurityPolicy`, rules per tier.
- [ ] 13.2 Tier 0: full authority. Tier 1: relay + voting, no tokens. Tier 2: read-only sensitive ops.
- [ ] 13.3 `src/policy/credential-delegation.ts` — `CredentialDelegation`, cross-tier delegation.
- [ ] 13.4 `src/policy/geo-security-policy.ts` — `GeoSecurityPolicy`, optional regional restrictions.
## 14. Spec
- [ ] 14.1 Update `openspec/specs/network/spec.md` with `NET-47`, `NET-48`.
## 15. Conformance tests
- [ ] 15.1 `src/plugin-security/plugin-security.spec-conformance.test.ts` — integrity, capability enforcement.
- [ ] 15.2 `src/plugin-security/activity.spec-conformance.test.ts` — anomaly detection, rate limits.
- [ ] 15.3 `src/policy/tier-policy.spec-conformance.test.ts` — tier rules, delegation, geo restrictions.
## 16. Verify
- [x] 16.1 `bunx turbo lint typecheck test --filter=@suaveplan/network-plugin-crypto-messages` green.
- [x] 16.2 `bunx turbo test:coverage --filter=@suaveplan/network-plugin-crypto-messages` 100/100/100/100.
- [x] 16.3 `bun scripts/openspec-conformance.ts @suaveplan/network-plugin-crypto-messages` PASS.
---
## Audit Note (2026-05-05)
**Status**: PARTIAL — core sections (1–11, 16) shipped at full quality (100/100/100/100 coverage, 100% docs, openspec-conformance PASS, 65 tests across 9 files). Stretch sections deferred to follow-up changes:
- Section 12 (PluginSecurityVerifier / CapabilityValidator / ActivityMonitor / SandboxedPluginContext) → follow-up `network-plugin-crypto-messages-plugin-security`.
- Section 13 (TierSecurityPolicy / CredentialDelegation / GeoSecurityPolicy) → follow-up `network-plugin-crypto-messages-tier-policy`.
- Sections 14–15 conformance tests + spec entries (`NET-47`, `NET-48`) ship with the corresponding follow-up.
The shipped core (`MessageSigner`, `SessionTokenAuthority`, `MeshTokenAuthority`, `PeerIdentityVerifier`, `LogChainSigner`, `KeyRotationManager`, `CryptoMessagesPlugin`) covers `NET-27` … `NET-30` from the network spec and is fully self-contained; the deferred follow-ups can be added without breaking the shipped surface.