diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..47dfcd5 --- /dev/null +++ b/TODO.md @@ -0,0 +1,343 @@ +# Implementation TODO + +Remaining tasks from [MIGRATION.md](./MIGRATION.md) for the Nebula Key Enclave. + +## Status Summary + +| Category | Status | Notes | +|----------|--------|-------| +| Schema (10 tables) | Complete | `internal/migrations/schema.sql` | +| SQLC Queries | Complete | `internal/migrations/query.sql` | +| Generated Code | Complete | `internal/keybase/*.go` | +| Basic Plugin Functions | Complete | `generate`, `load`, `exec`, `query`, `ping` | +| Encryption | Not Started | WebAuthn PRF key derivation needed | +| UCAN Authorization | Placeholder | Validation logic not implemented | +| MPC Key Shares | Not Started | Key share management missing | +| Database Serialization | Incomplete | Export dumps comments only | + +--- + +## 1. Encryption Strategy + +> Reference: MIGRATION.md lines 770-814 + +### 1.1 WebAuthn PRF Key Derivation +- [ ] Implement `DeriveEncryptionKey(prfOutput []byte) ([]byte, error)` +- [ ] Use HKDF with SHA-256 to derive 256-bit encryption key +- [ ] Salt with `"nebula-enclave-v1"` as info parameter + +### 1.2 Database Encryption +- [ ] Implement application-level AES-GCM encryption for serialized pages +- [ ] Add encryption wrapper around `Serialize()` output +- [ ] Add decryption wrapper for `Load()` input +- [ ] Store encryption metadata (IV, auth tag) with serialized data + +### 1.3 Encrypted Database Wrapper +- [ ] Create `internal/enclave/enclave.go` - Encrypted database wrapper +- [ ] Create `internal/enclave/crypto.go` - WebAuthn PRF key derivation +- [ ] Integrate with existing `internal/keybase` package + +--- + +## 2. Database Serialization + +> Current implementation in `conn.go:exportDump()` only outputs comments + +### 2.1 Proper Serialization +- [ ] Implement full row export with proper SQL INSERT statements +- [ ] Handle JSON columns correctly (escape special characters) +- [ ] Include table creation order for foreign key constraints +- [ ] Add version header for migration compatibility + +### 2.2 Proper Deserialization +- [ ] Parse serialized SQL dump in `Load()` +- [ ] Execute INSERT statements to restore data +- [ ] Validate data integrity after restore +- [ ] Handle schema version mismatches + +--- + +## 3. Action Manager Extensions + +> Reference: `internal/keybase/actions.go` + +### 3.1 Key Share Actions +- [ ] `CreateKeyShare(ctx, params) (*KeyShareResult, error)` +- [ ] `ListKeyShares(ctx) ([]KeyShareResult, error)` +- [ ] `GetKeyShareByID(ctx, shareID) (*KeyShareResult, error)` +- [ ] `GetKeyShareByKeyID(ctx, keyID) (*KeyShareResult, error)` +- [ ] `RotateKeyShare(ctx, shareID) error` +- [ ] `ArchiveKeyShare(ctx, shareID) error` +- [ ] `DeleteKeyShare(ctx, shareID) error` + +### 3.2 UCAN Token Actions +- [ ] `CreateUCAN(ctx, params) (*UCANResult, error)` +- [ ] `ListUCANs(ctx) ([]UCANResult, error)` +- [ ] `GetUCANByCID(ctx, cid) (*UCANResult, error)` +- [ ] `ListUCANsByAudience(ctx, audience) ([]UCANResult, error)` +- [ ] `RevokeUCAN(ctx, cid) error` +- [ ] `IsUCANRevoked(ctx, cid) (bool, error)` +- [ ] `CreateRevocation(ctx, params) error` +- [ ] `CleanExpiredUCANs(ctx) error` + +### 3.3 Delegation Actions +- [ ] `CreateDelegation(ctx, params) (*DelegationResult, error)` +- [ ] `ListDelegationsByDelegator(ctx, delegator) ([]DelegationResult, error)` +- [ ] `ListDelegationsByDelegate(ctx, delegate) ([]DelegationResult, error)` +- [ ] `ListDelegationsForResource(ctx, resource) ([]DelegationResult, error)` +- [ ] `GetDelegationChain(ctx, delegationID) ([]DelegationResult, error)` +- [ ] `RevokeDelegation(ctx, delegationID) error` +- [ ] `RevokeDelegationChain(ctx, delegationID) error` + +### 3.4 Verification Method Actions +- [ ] `CreateVerificationMethod(ctx, params) (*VerificationMethodResult, error)` +- [ ] `ListVerificationMethods(ctx) ([]VerificationMethodResult, error)` +- [ ] `GetVerificationMethod(ctx, methodID) (*VerificationMethodResult, error)` +- [ ] `DeleteVerificationMethod(ctx, methodID) error` + +### 3.5 Service Actions +- [ ] `CreateService(ctx, params) (*ServiceResult, error)` +- [ ] `GetServiceByOrigin(ctx, origin) (*ServiceResult, error)` +- [ ] `GetServiceByID(ctx, serviceID) (*ServiceResult, error)` +- [ ] `UpdateService(ctx, params) error` +- [ ] `ListVerifiedServices(ctx) ([]ServiceResult, error)` + +### 3.6 Grant Actions (Extend Existing) +- [ ] `CreateGrant(ctx, params) (*GrantResult, error)` +- [ ] `GetGrantByService(ctx, serviceID) (*GrantResult, error)` +- [ ] `UpdateGrantScopes(ctx, grantID, scopes, accounts) error` +- [ ] `UpdateGrantLastUsed(ctx, grantID) error` +- [ ] `SuspendGrant(ctx, grantID) error` +- [ ] `ReactivateGrant(ctx, grantID) error` +- [ ] `CountActiveGrants(ctx) (int64, error)` + +### 3.7 Account Actions (Extend Existing) +- [ ] `CreateAccount(ctx, params) (*AccountResult, error)` +- [ ] `ListAccountsByChain(ctx, chainID) ([]AccountResult, error)` +- [ ] `GetDefaultAccount(ctx, chainID) (*AccountResult, error)` +- [ ] `SetDefaultAccount(ctx, accountID, chainID) error` +- [ ] `UpdateAccountLabel(ctx, accountID, label) error` +- [ ] `DeleteAccount(ctx, accountID) error` + +### 3.8 Credential Actions (Extend Existing) +- [ ] `CreateCredential(ctx, params) (*CredentialResult, error)` +- [ ] `UpdateCredentialCounter(ctx, credentialID, signCount) error` +- [ ] `RenameCredential(ctx, credentialID, name) error` +- [ ] `DeleteCredential(ctx, credentialID) error` +- [ ] `CountCredentialsByDID(ctx) (int64, error)` + +### 3.9 Session Actions (Extend Existing) +- [ ] `GetSessionByID(ctx, sessionID) (*SessionResult, error)` +- [ ] `GetCurrentSession(ctx) (*SessionResult, error)` +- [ ] `UpdateSessionActivity(ctx, sessionID) error` +- [ ] `SetCurrentSession(ctx, sessionID) error` +- [ ] `DeleteExpiredSessions(ctx) error` + +### 3.10 Sync Checkpoint Actions +- [ ] `GetSyncCheckpoint(ctx, resourceType) (*SyncCheckpointResult, error)` +- [ ] `UpsertSyncCheckpoint(ctx, params) error` +- [ ] `ListSyncCheckpoints(ctx) ([]SyncCheckpointResult, error)` + +--- + +## 4. UCAN Authorization + +> Reference: MIGRATION.md lines 820-821 + +### 4.1 Token Validation +- [ ] Implement proper UCAN token parsing (JWT-like structure) +- [ ] Validate token signature against issuer's public key +- [ ] Check token expiration (`exp` claim) +- [ ] Check token not-before (`nbf` claim) +- [ ] Validate audience matches expected DID + +### 4.2 Capability Verification +- [ ] Parse capabilities array from token +- [ ] Match requested action against granted capabilities +- [ ] Implement resource pattern matching (e.g., `sonr://vault/*`) +- [ ] Respect action restrictions (e.g., `sign`, `read`, `write`) + +### 4.3 Proof Chain Validation +- [ ] Follow proof chain to root UCAN +- [ ] Validate each link in the chain +- [ ] Ensure capability attenuation (child can't exceed parent) +- [ ] Check revocation status for all tokens in chain + +### 4.4 Revocation Checking +- [ ] Query `ucan_revocations` table +- [ ] Check all tokens in proof chain +- [ ] Cache revocation status for performance + +--- + +## 5. MPC Key Share Management + +> Reference: MIGRATION.md lines 823-824 + +### 5.1 Key Share Storage +- [ ] Parse key share data from MPC protocol +- [ ] Encrypt share data before storage +- [ ] Store public key and chain code +- [ ] Track party index and threshold + +### 5.2 Account Derivation +- [ ] Implement BIP44 derivation path parsing +- [ ] Derive addresses from public keys +- [ ] Support multiple chains (Cosmos 118, Ethereum 60) +- [ ] Generate proper address encoding per chain + +### 5.3 Key Rotation +- [ ] Implement key rotation workflow +- [ ] Archive old shares +- [ ] Update status transitions +- [ ] Handle rotation failures gracefully + +--- + +## 6. Plugin Function Extensions + +> Reference: `main.go` + +### 6.1 Extend `exec` Resource Handlers +- [ ] Add `key_shares` resource handler +- [ ] Add `ucans` resource handler +- [ ] Add `delegations` resource handler +- [ ] Add `verification_methods` resource handler +- [ ] Add `services` resource handler +- [ ] Add `sync_checkpoints` resource handler + +### 6.2 Extend `generate` Function +- [ ] Parse WebAuthn credential properly (CBOR/COSE format) +- [ ] Extract public key from credential +- [ ] Create initial verification method +- [ ] Create initial credential record +- [ ] Generate initial account (if key share provided) + +### 6.3 Signing Function +- [ ] Implement `sign` wasmexport function +- [ ] Support signing with MPC key shares +- [ ] Return signature in appropriate format +- [ ] Log signing operations for audit + +--- + +## 7. Capability Delegation + +> Reference: MIGRATION.md lines 826-827 + +### 7.1 Delegation Chain Management +- [ ] Enforce maximum delegation depth (prevent infinite chains) +- [ ] Validate delegator has capability to delegate +- [ ] Ensure proper capability attenuation +- [ ] Track parent-child relationships + +### 7.2 Delegation Status +- [ ] Implement expiration checking +- [ ] Handle revocation cascades (revoke chain) +- [ ] Update status on expiry + +--- + +## 8. DID State Sync + +> Reference: MIGRATION.md line 827 + +### 8.1 Sync Infrastructure +- [ ] Create `internal/enclave/sync.go` - DID state sync logic +- [ ] Implement checkpoint tracking +- [ ] Store last synced block height +- [ ] Track last processed transaction hash + +### 8.2 Sync Operations +- [ ] Fetch DID document updates from chain +- [ ] Validate on-chain document hash +- [ ] Update local state on changes +- [ ] Handle reorgs and rollbacks + +--- + +## 9. TypeScript SDK + +> Reference: README.md, `src/` directory + +### 9.1 Core SDK +- [ ] Implement `createEnclave(wasmPath)` factory +- [ ] Implement `generate(credential)` wrapper +- [ ] Implement `load(database)` wrapper +- [ ] Implement `exec(filter, token?)` wrapper +- [ ] Implement `query(did?)` wrapper + +### 9.2 Type Definitions +- [ ] Generate TypeScript types from Go structs +- [ ] Export type definitions for consumers +- [ ] Add JSDoc documentation + +### 9.3 WebAuthn Integration +- [ ] Helper for credential creation +- [ ] Helper for PRF extension output +- [ ] Proper encoding/decoding utilities + +--- + +## 10. Testing + +### 10.1 Unit Tests +- [ ] Test all ActionManager methods +- [ ] Test serialization/deserialization roundtrip +- [ ] Test encryption/decryption +- [ ] Test UCAN validation logic + +### 10.2 Integration Tests +- [ ] Test full generate → load → exec flow +- [ ] Test credential lifecycle +- [ ] Test session management +- [ ] Test grant management + +### 10.3 Plugin Tests +- [ ] Extend `make test-plugin` with all functions +- [ ] Add error case testing +- [ ] Test with various input formats + +--- + +## 11. Security Hardening + +### 11.1 Input Validation +- [ ] Validate all JSON inputs against schemas +- [ ] Sanitize SQL-sensitive characters in serialization +- [ ] Validate DID format on all inputs +- [ ] Validate base64 encoding + +### 11.2 Cryptographic Security +- [ ] Use constant-time comparison for sensitive data +- [ ] Clear sensitive data from memory after use +- [ ] Validate key sizes and formats +- [ ] Implement proper nonce generation + +### 11.3 Access Control +- [ ] Enforce DID ownership on all mutations +- [ ] Validate session before sensitive operations +- [ ] Check grant scopes before data access +- [ ] Log security-relevant operations + +--- + +## Priority Order + +1. **High Priority** (Core Functionality) + - Database Serialization (2.1, 2.2) + - Credential Creation (6.2, 3.8) + - Key Share Actions (3.1) + - Account Actions (3.7) + +2. **Medium Priority** (Authorization) + - UCAN Validation (4.1, 4.2) + - Delegation Management (7.1, 7.2) + - Encryption Strategy (1.1, 1.2) + +3. **Lower Priority** (Enhancement) + - TypeScript SDK (9.x) + - DID State Sync (8.x) + - Additional exec handlers (6.1) + - Testing (10.x) + - Security Hardening (11.x)