Skip to content

Design Session Key Backend Architecture and Storage #190

@premiumjibles

Description

@premiumjibles

Objective

Design and implement the backend architecture for securely storing and managing session keys that enable automated transaction execution without user signatures.

Background

Session keys are the foundation of automation features (TWAP orders, stop-loss, sweepers). A session key is a cryptographic key with limited permissions that the backend holds to execute transactions on behalf of users. The backend must:

  1. Securely store session keys
  2. Track permissions (which contracts, functions, amounts, time limits)
  3. Enforce permission boundaries
  4. Handle session expiration
  5. Support revocation
  6. Enable audit trails

Acceptance Criteria

  • Design database schema for session key storage
  • Implement session key creation and storage
  • Implement permission validation logic
  • Track session key usage (execution count, amounts spent)
  • Handle session expiration (time-based)
  • Support session revocation by user
  • Encrypt session keys at rest
  • Implement rate limiting per session
  • Create audit log for all session key operations
  • Provide API endpoints for session management

Database Schema Design

SessionKey Table:

id: UUID
userId: string (reference to user)
walletAddress: string (embedded wallet address)
sessionKeyAddress: string (the session key's address)
sessionKeyPrivate: string (encrypted private key)
createdAt: timestamp
expiresAt: timestamp
revokedAt: timestamp | null
status: 'active' | 'expired' | 'revoked'

SessionPermissions Table:

id: UUID
sessionKeyId: UUID (reference to SessionKey)
chainId: number
contractAddress: string (allowed contract)
allowedFunctions: string[] (function selectors)
maxPerTransaction: bigint (amount limit)
maxTotalAmount: bigint (total spending limit)
spentAmount: bigint (tracking spent)
rateLimit: {count: number, period: number} (e.g., 1 tx per hour)

SessionExecutions Table (audit log):

id: UUID
sessionKeyId: UUID
transactionHash: string
contractAddress: string
functionName: string
amount: bigint
executedAt: timestamp
status: 'pending' | 'success' | 'failed'
errorMessage: string | null

Security Requirements

Encryption:

  • Session key private keys MUST be encrypted at rest
  • Use strong encryption (AES-256 or better)
  • Store encryption keys in secure environment (AWS KMS, HashiCorp Vault, etc.)
  • Never log unencrypted private keys

Access Control:

  • Only authenticated backend services can access session keys
  • Implement rate limiting on session key usage
  • Monitor for suspicious activity (unusual spending patterns, etc.)

Permission Enforcement:
Before each transaction execution:

  1. Verify session is active (not expired/revoked)
  2. Check transaction is within allowed contracts/functions
  3. Verify amount is within limits (per-tx and total)
  4. Check rate limit hasn't been exceeded
  5. Log execution attempt

API Endpoints Design

POST /api/session-keys/create
  - Create new session key with permissions
  - Returns session key address for user approval

POST /api/session-keys/:id/approve
  - Store user's approval signature
  - Activate session key

POST /api/session-keys/:id/revoke
  - Revoke session key (user-initiated)
  - Mark as revoked, prevent future use

GET /api/session-keys
  - List user's active session keys
  - Include usage stats (spent amount, executions, etc.)

POST /api/session-keys/:id/execute
  - Execute transaction using session key
  - Validates permissions before execution
  - Returns transaction hash

GET /api/session-keys/:id/executions
  - Get audit log of session key executions
  - For user transparency

Implementation Considerations

Backend Framework:
Depends on existing agentic chat backend:

  • Check /packages/server or similar for backend code
  • May be Node.js/Express, Bun/Hono, or other

Database:

  • Determine if project uses PostgreSQL, MongoDB, etc.
  • Use existing database if available
  • Consider separate database for security-sensitive session keys

Session Key Generation:
Use ZeroDev's SDK for session key creation:

  • Creates session key pair
  • Generates approval signature for user
  • User signs to approve session
  • Backend stores session key + approval

Reference: https://docs.zerodev.app/sdk/advanced/session-keys

Testing Requirements

  • Test session key creation and storage
  • Test permission validation (should allow valid txs, reject invalid)
  • Test expiration handling
  • Test revocation
  • Test rate limiting
  • Test encryption/decryption of keys
  • Test audit logging
  • Test concurrent executions with same session key

Files to Create/Modify

  • Backend session key service/module
  • Database migration files
  • API route handlers
  • Permission validation logic
  • Encryption utilities
  • Audit logging service

Non-Goals (Separate Tickets)

  • TWAP executor implementation (separate ticket)
  • Stop-loss monitor (separate ticket)
  • Frontend UI for session management (separate ticket)
  • Session key approval flow in chat (separate ticket)

Dependencies

  • Requires "Integrate ZeroDev for ERC-4337 Smart Wallet Support"
  • Requires backend infrastructure to be set up (API server, database)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Status

    Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions