Saltar a contenido

Encrypted Computation Architecture

1. Abstract

CyberEco's first tenet is Digital Sovereignty — users own their data. But data ownership creates a tension: users want personalized analytics, group summaries, and cross-app insights, all of which traditionally require a server to see their raw data. The more useful the computation, the more data must be exposed.

This document resolves that tension. It defines how three privacy-preserving computation techniques — Fully Homomorphic Encryption (FHE), Trusted Execution Environments (TEEs), and Multi-Party Computation (MPC) — integrate into the CyberEco data layer. The goal is concrete: users benefit from shared computation without any server, cloud provider, or other user ever seeing their raw data.

All three techniques plug into the existing StorageAdapter and DataLayerService architecture. No domain service changes. No new storage dependencies. The encryption layer is a decorator, not a replacement.

2. The Problem

CyberEco is an ecosystem of 30+ interconnected applications sharing identity, permissions, financial data, groups, and notifications. That interconnection creates enormous analytical value — and enormous privacy risk. Consider the specific scenarios where raw data exposure is unacceptable:

  • JustSplit: A group of roommates splits rent, groceries, and utilities. Computing who owes whom requires seeing every individual expense. Today, the server sees all of it. Users should be able to compute settlement balances without any single server seeing individual spending records.

  • Hub: A user's financial dashboard aggregates transactions across JustSplit, a budgeting app, and a savings tracker. Generating the summary today means the Hub server reads raw transaction data from every app. Users should get their cross-app financial summary without centralizing raw transaction data on any server.

  • Demos: A community votes on a local initiative. The tally must be accurate, but individual votes must remain secret. Today, the server that counts the votes can see every ballot. The system should tally votes without revealing individual choices to anyone — not the server, not the administrators, not other voters.

  • Plantopia: A neighborhood tracks water and energy usage to optimize shared resources. Computing community aggregates (average usage, peak hours, conservation targets) currently requires each household to expose its consumption data to a central server. Households should contribute to community analytics without exposing their individual usage patterns.

In every case, the pattern is the same: useful computation requires data from multiple sources, and the computation infrastructure can see all of it. Encrypted computation breaks this assumption.

3. Three Pillars of Privacy-Preserving Computation

3.1 Fully Homomorphic Encryption (FHE)

What it is: An encryption scheme that allows computation on ciphertext. The result, when decrypted, matches the result of computing on plaintext. The server performs meaningful work on data it cannot read.

How it works (simplified):

  1. User generates an FHE key pair (public key, private key, evaluation key)
  2. User encrypts data with their FHE public key
  3. User sends encrypted data and the evaluation key to the server
  4. Server performs operations on encrypted data (addition, multiplication, comparison) using the evaluation key
  5. Server returns the encrypted result
  6. User decrypts the result with their private key
  7. The server never sees plaintext data at any point in this process

CyberEco use cases:

  • Financial summaries: Sum encrypted transaction amounts across apps. The Hub server computes the total on ciphertext. The user decrypts locally to see their actual balance.
  • Group analytics: Average encrypted spending within a JustSplit group. The server computes the encrypted average. The group admin (holding the group decryption key) decrypts the aggregate only — individual amounts remain hidden.
  • Encrypted search: An encrypted index allows querying without revealing query content or data content to the server. The user encrypts their search term, the server evaluates it against the encrypted index, and returns encrypted matching document IDs.

Technology options:

Library Language Scheme Best For
Zama Concrete Rust/Python TFHE General computation, ML inference
Microsoft SEAL C++ BFV/CKKS Arithmetic on integers and reals
OpenFHE C++ Multiple Research, flexibility, protocol experimentation
tfhe-rs Rust TFHE High-performance server-side, WASM-compatible for browser

Performance characteristics:

Operation Latency Notes
Key generation Seconds One-time cost per user
Encryption Milliseconds Per-value; batching amortizes overhead
Decryption Milliseconds Per-value; fast on client
Addition (ciphertext) Microseconds Efficient; chains well
Multiplication (ciphertext) Milliseconds Noise growth limits depth
Complex functions Seconds to minutes Bootstrapping required for deep circuits
Key sizes 1-100 MB Depends on security parameters and scheme

Practical limit: FHE is suited for batch processing, not real-time interactive queries. A nightly financial summary is feasible. A keystroke-by-keystroke search is not.

Integration pattern:

class FHEComputeService {
  // --- Client-side (runs in browser / mobile app) ---

  /**
   * Generate a complete FHE key set for a user.
   * The privateKey never leaves the client device.
   * The evaluationKey is sent to the server to enable computation.
   */
  generateKeys(): {
    publicKey: FHEPublicKey;
    privateKey: FHEPrivateKey;
    evaluationKey: FHEEvalKey;
  };

  /**
   * Encrypt an array of numeric values under the user's public key.
   * The resulting ciphertext can be stored via any StorageAdapter.
   */
  encrypt(data: number[], publicKey: FHEPublicKey): FHECiphertext;

  /**
   * Decrypt a server-computed result using the user's private key.
   * This is the only step where plaintext is recovered.
   */
  decrypt(result: FHECiphertext, privateKey: FHEPrivateKey): number[];

  // --- Server-side (operates on encrypted data only) ---

  /**
   * Homomorphic addition across multiple ciphertexts.
   * Use case: summing encrypted transaction amounts.
   */
  sum(ciphertexts: FHECiphertext[], evalKey: FHEEvalKey): FHECiphertext;

  /**
   * Homomorphic average: sum divided by known count.
   * The count is public; individual values remain encrypted.
   */
  average(
    ciphertexts: FHECiphertext[],
    count: number,
    evalKey: FHEEvalKey
  ): FHECiphertext;

  /**
   * Homomorphic comparison of two encrypted values.
   * Returns an encrypted boolean (0 or 1).
   */
  compare(
    a: FHECiphertext,
    b: FHECiphertext,
    evalKey: FHEEvalKey
  ): FHECiphertext;
}

3.2 Trusted Execution Environments (TEEs)

What it is: Hardware-isolated memory regions (enclaves) where code executes securely. The operating system, hypervisor, and even the cloud provider cannot read enclave memory. Trust is rooted in the hardware manufacturer's attestation, not in the operator of the machine.

How it works:

  1. CyberEco deploys computation code into a secure enclave
  2. The enclave performs remote attestation — a cryptographic proof that the enclave is genuine hardware running the exact expected code, with no modifications
  3. The client verifies the attestation report (critically, the client verifies, not the server)
  4. Data is encrypted in transit to the enclave using a key established during attestation
  5. The enclave decrypts the data, processes it, and re-encrypts the result
  6. Only the enclave sees plaintext — not the host operating system, not the cloud provider, not CyberEco operators

CyberEco use cases:

  • Permission evaluation: The CyberEco permission graph is complex (roles, conditions, cross-app grants). Evaluating permissions requires reading the full graph. A TEE can evaluate access rights on decrypted permission rules without exposing the graph structure to the host server.
  • Search indexing: Build and query encrypted search indices inside a TEE. Unlike FHE-based search, TEE-based search operates at near-native speed, enabling real-time interactive search.
  • Real-time queries: Full query capability (filters, joins, aggregations) with TEE-level privacy. This covers use cases where FHE is too slow — interactive dashboards, live expense feeds, instant notifications.
  • Key management: The TEE serves as a secure key vault. Encryption keys for the data layer can be derived, stored, and used inside the enclave without ever existing in host memory.

Technology options:

Platform Availability Trust Model
ARM TrustZone Mobile devices (Android, iOS) ARM manufacturer
Intel SGX / TDX Server-class Intel CPUs Intel attestation service
AMD SEV-SNP Server-class AMD CPUs AMD attestation service
AWS Nitro Enclaves AWS cloud instances Amazon hardware + Nitro hypervisor
Apple Secure Enclave Apple devices (iPhone, Mac) Apple hardware + Secure Boot chain

Performance characteristics:

Aspect Value Notes
Overhead vs. plaintext 5-30% Dramatically better than FHE
Memory per enclave 128-256 MB (SGX); larger for TDX/SEV Limits data set size per operation
Suitable for Real-time operations, interactive queries The go-to choice for latency-sensitive paths
Not suitable for Data sets larger than enclave memory; scenarios requiring zero hardware trust Use FHE or MPC if hardware trust is unacceptable

Integration pattern:

class TEEComputeService {
  // --- Attestation (client verifies server) ---

  /**
   * Request an attestation report from the enclave.
   * The report proves: (1) genuine hardware, (2) expected code hash,
   * (3) no tampering since boot.
   */
  getAttestation(): AttestationReport;

  /**
   * Client-side verification of the attestation report.
   * Must be performed by the CLIENT, not the server hosting the enclave.
   */
  verifyAttestation(report: AttestationReport): boolean;

  // --- Secure operations (execute inside enclave) ---

  /**
   * Execute a query inside the enclave.
   * Data is decrypted only within enclave memory.
   */
  secureQuery(
    encryptedQuery: Buffer,
    encryptedData: Buffer[]
  ): Buffer;

  /**
   * Evaluate permission rules inside the enclave.
   * The host server never sees the permission graph or the user identity.
   */
  securePermissionCheck(
    encryptedUserId: Buffer,
    encryptedRules: Buffer
  ): Buffer;

  /**
   * Aggregate encrypted records inside the enclave.
   * Supports sum, average, count, min, max operations.
   */
  secureAggregation(
    encryptedRecords: Buffer[],
    operation: AggregateOp
  ): Buffer;
}

3.3 Multi-Party Computation (MPC)

What it is: A cryptographic protocol where multiple parties jointly compute a function over their combined inputs, without any party revealing their input to any other party. The result is the only information that any party learns.

How it works (Shamir's Secret Sharing example):

  1. Each party splits their secret data into N shares using polynomial secret sharing
  2. Each party distributes one share to each other party (keeping one share for themselves)
  3. All parties perform computation on their received shares locally — these local computations are meaningfully related to the final result, but no individual share reveals any input
  4. Each party sends their computed result share to a designated combiner (or all parties act as combiners)
  5. The combiner reconstructs the final result from K-of-N result shares (threshold reconstruction)
  6. No single party (or any coalition of fewer than K parties) can reconstruct any other party's input

CyberEco use cases:

  • Group expense splitting (JustSplit): Each group member holds their expense data locally. The MPC protocol computes "who owes whom" across all members without any single party (or any server) seeing another member's individual expenses. Each member learns only the net settlement amounts.
  • Voting (Demos): Each voter submits their vote as secret shares distributed across multiple tally servers. The servers jointly compute the tally. No single server (or any coalition below the threshold) can see any individual ballot. The public learns only the final count.
  • Shared budgets: A family or organization tracks spending against a shared budget limit. MPC computes the remaining budget and flags overages without exposing individual members' transaction details to each other or to a central server.
  • Fair random selection: Generate an unbiased random number that no party can predict or manipulate. Useful for random audits, lottery-style selections, or tiebreaking in Demos votes.

Technology options:

Protocol Type Parties Best For
Shamir's Secret Sharing Threshold 3+ Secret distribution, key management, threshold decryption
Garbled Circuits (Yao's) 2-party 2 Boolean functions, comparisons, private set intersection
SPDZ / MASCOT N-party 2+ Arithmetic operations, general-purpose MPC at scale
Oblivious Transfer 2-party 2 Private information retrieval, private set intersection

Performance characteristics:

Aspect Value Notes
Communication rounds 2-10 Depends on protocol and circuit depth
Latency Network-bound All parties must be online simultaneously
Local computation Near-plaintext speed Each party's share computation is fast
Bottleneck Network communication Not CPU; round-trip latency dominates
Practical party count 2-20 Works well for small groups; overhead grows with party count

Integration pattern:

class MPCComputeService {
  // --- Session management ---

  /**
   * Create an MPC session for a group of participants.
   * The protocol determines the sharing scheme and computation rules.
   */
  createSession(
    participants: string[],
    protocol: MPCProtocol
  ): MPCSession;

  /**
   * Join an existing session. Blocks until all participants have joined.
   */
  joinSession(sessionId: string): Promise<void>;

  // --- Secret sharing ---

  /**
   * Split a secret value into shares for distribution.
   * Each share goes to one participant; no single share reveals the value.
   */
  shareSecret(value: number, session: MPCSession): Share[];

  /**
   * Reconstruct a secret from K-of-N shares (threshold reconstruction).
   * Only possible when enough shares are combined.
   */
  reconstructSecret(shares: Share[], threshold: number): number;

  // --- Computation ---

  /**
   * Secure summation: all participants contribute a value,
   * the protocol outputs only the sum. No individual values are revealed.
   */
  secureSum(session: MPCSession): Promise<number>;

  /**
   * Secure comparison: determine whether a > b without revealing a or b.
   * Used for budget threshold checks without exposing balances.
   */
  secureComparison(
    session: MPCSession,
    a: Share,
    b: Share
  ): Promise<boolean>;

  /**
   * Secure voting: each participant contributes a vote (encoded as a number),
   * the protocol outputs only the tally. Individual votes are never revealed.
   */
  secureVote(session: MPCSession, vote: number): Promise<VoteTally>;
}

4. Comparison Matrix

Aspect FHE TEE MPC
Trust model Cryptographic (mathematical hardness) Hardware (manufacturer attestation) Cryptographic (protocol guarantees)
Speed vs. plaintext ~1000x slower ~1.2x slower Near real-time (network-bound)
Parties needed 1 (server computes on ciphertext) 1 (enclave computes on decrypted data) 2+ (all parties participate)
Online requirement Async (submit encrypted data, collect result later) Sync (real-time request/response) Sync (all parties must be online)
Data size limit Unlimited (but slow for large sets) Enclave memory (~256 MB for SGX) Practical for small inputs per party
Failure mode Math is wrong (implementation bug) Hardware is compromised (side-channel attack) Collusion exceeds threshold
Best CyberEco fit Batch analytics, financial summaries Real-time queries, permission evaluation, key management Group operations, voting, expense splitting
Maturity Research-grade, improving rapidly Production-ready (cloud providers offer it now) Production-ready for specific protocols

When to use which:

  • Use FHE when the user wants analytics on their own data without trusting the server, and can tolerate batch latency.
  • Use TEE when real-time performance is required and trusting the hardware manufacturer is acceptable.
  • Use MPC when multiple users jointly compute a result and no single party (including the server) should see individual inputs.
  • Use combinations for defense in depth: encrypt data with FHE, process inside a TEE, and use MPC for key management.

5. Integration with CyberEco Data Layer

The three compute techniques integrate into the existing data layer architecture without modifying domain services. The integration follows the same decorator/injection pattern that the rest of the system uses.

5.1 EncryptedStorageAdapter

A decorator that wraps any StorageAdapter, adding transparent field-level encryption:

class EncryptedStorageAdapter implements StorageAdapter {
  constructor(
    private readonly inner: StorageAdapter,   // Firebase, IPFS, or any other adapter
    private readonly keyManager: KeyManager,  // Per-user encryption keys
    private readonly encryptionConfig: {
      /** Map of collection name to field names that should be encrypted at rest */
      fieldsToEncrypt: Record<string, string[]>;
      /** Map of collection name to field names that support FHE operations */
      fheFields?: Record<string, string[]>;
    }
  );

  // --- Transparent encryption on write ---
  // setDocument(collection, id, data):
  //   1. Look up fieldsToEncrypt[collection]
  //   2. For each matching field in data, encrypt the value
  //   3. Delegate to inner.setDocument(collection, id, encryptedData)
  //   4. Return the WriteResult from inner

  // --- Transparent decryption on read ---
  // getDocument(collection, id):
  //   1. Delegate to inner.getDocument(collection, id)
  //   2. Look up fieldsToEncrypt[collection]
  //   3. For each matching field, decrypt the value
  //   4. Return the decrypted document

  // --- Query handling ---
  // query(collection, filters, options):
  //   For non-encrypted fields: delegate to inner.query normally
  //   For FHE-enabled fields:   use FHEComputeService for server-side evaluation
  //   For encrypted non-FHE fields: fetch all, decrypt, filter client-side (slow)

  // --- All other methods ---
  // subscribe, batchWrite, serverTimestamp, generateId:
  //   Delegate to inner with encryption/decryption wrapping as needed
}

This adapter is invisible to domain services. SharedDataService, PermissionService, DashboardService, and all others continue to call IDataLayerService methods. They never know whether the underlying adapter encrypts or not.

5.2 ComputeService

A new domain service registered in @cyber-eco/services alongside the existing services:

class ComputeService {
  constructor(
    private readonly dataLayer: IDataLayerService,
    private readonly fhe?: FHEComputeService,
    private readonly tee?: TEEComputeService,
    private readonly mpc?: MPCComputeService
  );

  /**
   * Route an aggregation request to the best compute method
   * based on the requested privacy level and available services.
   *
   * - 'standard': No encryption. Delegates to normal adapter query.
   * - 'fhe': Server computes on encrypted data. Result decrypted by client.
   * - 'tee': Server computes inside enclave. Data encrypted in transit.
   * - 'mpc': Multi-party protocol. Requires participant coordination.
   */
  async aggregate(options: {
    collection: string;
    field: string;
    operation: 'sum' | 'average' | 'count' | 'min' | 'max';
    filters?: QueryFilter[];
    privacyLevel: 'standard' | 'fhe' | 'tee' | 'mpc';
    mpcParticipants?: string[];  // Required when privacyLevel is 'mpc'
  }): Promise<AggregateResult>;
}

The ComputeService follows the same patterns as other domain services:

  • Receives IDataLayerService via constructor injection (no module-level state)
  • Does not import any storage backend
  • Does not know whether the underlying adapter is Firebase, IPFS, or anything else
  • Registered in the createDataLayer() factory alongside existing services

5.3 DataLayerService Extension

The existing DataLayerService orchestration pipeline gains an optional encryption layer. The pipeline steps are:

Write flow (with encryption):

Request: create(userId, collection, data)
  |
  +- 1. Permission Check
  |     +- permissionChecker(userId, collection, 'write')
  |     +- If denied -> throw AuthorizationError
  |
  +- 2. Enrich Data
  |     +- Add id, createdAt, createdBy
  |
  +- 3. Encrypt (NEW)
  |     +- EncryptedStorageAdapter encrypts specified fields
  |     +- Non-encrypted fields pass through unchanged
  |
  +- 4. Adapter Write
  |     +- adapter.setDocument(collection, id, encryptedData)
  |
  +- 5. Cache Invalidate
  |     +- cache.deletePattern(`${collection}:*`)
  |     +- cache.set(`${collection}:${id}`, plaintextData)  // cache holds plaintext
  |
  +- 6. Sync Broadcast
  |     +- sync.broadcast({ type: 'created', collection, documentId })
  |     +- Broadcast does NOT include data payload (privacy)
  |
  +- 7. Webhook Emit
  |     +- webhooks.emit({ type: `${collection}.created`, payload: metadata-only })
  |
  +- 8. Return id

Read flow (with decryption):

Request: get(userId, collection, id)
  |
  +- 1. Permission Check
  |     +- permissionChecker(userId, collection, 'read', id)
  |     +- If denied -> throw AuthorizationError
  |
  +- 2. Cache Lookup
  |     +- key = `${collection}:${id}`
  |     +- If hit -> return cached plaintext value (skip decryption)
  |
  +- 3. Adapter Fetch
  |     +- adapter.getDocument(collection, id) returns encrypted data
  |
  +- 4. Decrypt (NEW)
  |     +- EncryptedStorageAdapter decrypts specified fields
  |     +- Non-encrypted fields pass through unchanged
  |
  +- 5. Cache Set
  |     +- cache.set(key, plaintextResult, ttl[collection])
  |
  +- 6. Return plaintext result

The cache stores plaintext data. This is intentional: the L1 cache is in-process memory (same trust boundary as the application), and caching plaintext avoids redundant decryption on repeated reads. If a future L2 cache backend (e.g., Redis) is added, that backend should store encrypted data and decrypt on retrieval.

6. Key Management

Key management is the hardest part of any encryption system. Losing a key means losing the data it protects. The CyberEco key hierarchy is designed for both security and recoverability.

6.1 Per-User Key Hierarchy

Master Key (derived from user password or passphrase via Argon2id)
    |
    +-- Storage Encryption Key (AES-256-GCM)
    |       Purpose: encrypting data fields at rest
    |       Derivation: HKDF(masterKey, "storage-encryption", salt)
    |       Usage: EncryptedStorageAdapter field encryption
    |
    +-- FHE Key Pair (public + private + evaluation)
    |       Purpose: homomorphic computation on user data
    |       Derivation: FHE key generation seeded from HKDF(masterKey, "fhe-keygen", salt)
    |       Usage: FHEComputeService encrypt/decrypt
    |       Note: evaluation key is shared with server; private key never leaves client
    |
    +-- Signing Key (Ed25519)
    |       Purpose: peer identity verification, message authentication
    |       Derivation: HKDF(masterKey, "signing", salt)
    |       Usage: authenticating requests in P2P/decentralized mode
    |
    +-- Key Exchange Key (X25519)
            Purpose: establishing shared secrets with other users
            Derivation: HKDF(masterKey, "key-exchange", salt)
            Usage: encrypting data shared between specific users (DMs, shared expenses)

All keys are deterministically derived from the master key. If the user remembers their passphrase, all keys can be regenerated. If the user loses their passphrase, all keys are lost — this is the trade-off of true digital sovereignty.

6.2 Group Key Management

Groups (families, roommate groups, communities) require shared encryption that supports member changes.

  • Threshold encryption: Group data is encrypted with a k-of-n threshold scheme. Any k members can decrypt the group data, but fewer than k members cannot. This prevents a single member from unilaterally accessing all group data while ensuring the group survives individual member unavailability.

  • Key rotation: When a member leaves a group, the group key is rotated. All data encrypted with the old key is re-encrypted with the new key (this is a background operation, batched to avoid performance impact). The departing member's shares are invalidated.

  • Key escrow (optional): A user can designate recovery contacts. The user's master key is split into shares (Shamir's Secret Sharing) and distributed to the recovery contacts. If the user loses access, the recovery contacts can jointly reconstruct the master key. This is opt-in — users who prefer full self-custody can skip key escrow.

6.3 Key Storage

Keys are stored in the most secure facility available on each platform:

Platform Storage Mechanism Security Properties
Browser Web Crypto API + IndexedDB (encrypted with browser-managed key) Non-extractable key flag; keys usable but not readable by JavaScript
iOS Secure Enclave via Keychain Services Hardware-isolated; keys never leave the Secure Enclave chip
Android Android Keystore (hardware-backed on supported devices) TEE or StrongBox-backed; keys bound to device
Server TEE-protected key vault (e.g., AWS Nitro Enclaves) Keys exist only inside enclave memory
Backup Encrypted key backup to user-controlled storage (cloud drive, USB, paper) Encrypted under a passphrase-derived key; user controls the backup location

The server key vault is used only for server-side operations (FHE evaluation keys, TEE enclave keys). User private keys are never stored on the server. If a user's device is lost, recovery is through the backup or the key escrow mechanism — not through the server.

7. Phased Rollout

Encrypted computation is not an all-or-nothing deployment. Each phase builds on the previous one and delivers standalone value. The phases are sequenced by implementation complexity and dependency on external infrastructure.

Phase A: Client-Side Encryption at Rest (2025-2026)

Prerequisite: None. Implementable now with existing architecture.

What ships:

  • EncryptedStorageAdapter wrapping FirebaseStorageAdapter
  • AES-256-GCM encryption of sensitive fields before they reach any storage backend
  • Key derivation from user credentials (Argon2id + HKDF)
  • Key storage via Web Crypto API (browser) and platform-native keystores (mobile)

Fields encrypted in Phase A:

Collection Encrypted Fields Rationale
transactions amount, description, notes Financial privacy
expenses amount, description Expense privacy in JustSplit
notifications body, metadata Notification content privacy
users phoneNumber, address (if present) PII protection

What does NOT change:

  • No server-side changes. Encrypted data is stored as opaque blobs in Firebase.
  • No domain service changes. The EncryptedStorageAdapter is invisible to SharedDataService, DashboardService, etc.
  • No query changes for non-encrypted fields. Queries on createdAt, collection, userId, and other metadata fields work exactly as before.

Trade-off: Encrypted fields cannot be queried server-side. Queries like "find all transactions where amount > 100" require client-side decryption and filtering. This is acceptable for Phase A because the encrypted fields are primarily accessed by document ID, not by range queries.

New package: @cyber-eco/crypto (depends only on @cyber-eco/types).

Phase B: TEE-Based Permission Evaluation (2027-2028)

Prerequisite: Cloud infrastructure with TEE support (AWS Nitro Enclaves, Azure Confidential Computing, or self-hosted SGX/TDX servers).

What ships:

  • Permission evaluation logic deployed inside a TEE enclave
  • Remote attestation protocol: clients verify enclave integrity before sending data
  • Encrypted permission rules processed inside the enclave
  • TEEComputeService for real-time secure queries

Why permissions first: The permission graph is the most sensitive metadata in CyberEco. It describes who can see what, across all apps. Moving permission evaluation into a TEE means the server operator cannot inspect or tamper with access control decisions.

New package: @cyber-eco/tee (depends only on @cyber-eco/types).

Phase C: FHE Batch Analytics (2028-2029)

Prerequisite: FHE parameter tuning for CyberEco's specific computation circuits. Key distribution infrastructure from Phase A. Sufficient server compute for FHE operations.

What ships:

  • FHE-enabled fields in financial collections (transactions.amount, expenses.amount)
  • Server-side homomorphic aggregation: sum, average, count on encrypted financial data
  • User-side decryption of personal financial summaries
  • Batch processing pipeline: encrypted data submitted, results available within minutes

Why this phase is later: FHE performance is improving rapidly but is not yet suitable for real-time use. By 2028-2029, hardware acceleration (FHE-specific instructions) and algorithmic improvements are expected to make batch FHE practical for CyberEco's scale.

New package: @cyber-eco/fhe (depends only on @cyber-eco/types; WASM bindings for tfhe-rs).

Phase D: MPC for Multi-Party Operations (2029-2030)

Prerequisite: MPC session management infrastructure. Network coordination layer for synchronizing participants. At least two CyberEco apps with multi-party operations (JustSplit and Demos are the primary candidates).

What ships:

  • Expense splitting protocol via MPC (JustSplit): compute settlements without revealing individual expenses
  • Voting protocol via MPC (Demos): tally votes with cryptographic ballot secrecy
  • Shared budget tracking via MPC: monitor group spending limits without exposing individual transactions
  • Fair randomness generation: unbiasable random numbers for audits and selections

Why this phase is last: MPC requires all participants to be online simultaneously and introduces network coordination complexity. It also requires the most user-facing UX work (session management, participant synchronization, timeout handling). The preceding phases provide significant privacy improvements while the MPC infrastructure matures.

New package: @cyber-eco/mpc (depends only on @cyber-eco/types).

8. Security Considerations

Cryptographic Parameter Selection

  • FHE parameters must provide at least 128-bit security. Parameter selection must be reviewed by a cryptographer before deployment. Incorrect parameters can make the scheme trivially breakable.
  • FHE bootstrapping keys must be regenerated if the computation circuit changes. A mismatch between key parameters and circuit depth will produce incorrect results silently.

Attestation Verification

  • TEE attestation must be verified by clients, not by the server hosting the enclave. If the server verifies its own attestation, a compromised server can forge the verification result.
  • Attestation verification must check: hardware genuineness, code measurement (hash of the enclave binary), and freshness (to prevent replay of old attestation reports).

Protocol Auditing

  • MPC protocols must be audited for the specific use case they are deployed for. A protocol that is secure for summation may not be secure for comparison. Off-the-shelf protocols must be reviewed by a cryptographer in the context of CyberEco's threat model.
  • Side-channel resistance must be evaluated for all TEE deployments. Known side-channel attacks on SGX (Spectre, Foreshadow) must be mitigated with up-to-date microcode and software countermeasures.

Key Management Risks

  • Key loss means data loss. There is no backdoor, no master key, no "forgot password" recovery that bypasses encryption. This is the fundamental trade-off of true digital sovereignty.
  • Key escrow (optional) mitigates this risk but introduces a new attack surface: compromising enough recovery contacts can reconstruct the master key.
  • Key rotation for group keys is computationally expensive (re-encryption of all group data). Batch processing and incremental re-encryption are necessary to avoid service disruption.

Defense in Depth

No single technique is sufficient. The recommended approach is layered:

  1. Always: Client-side encryption at rest (Phase A). This is the baseline.
  2. When available: TEE for real-time operations (Phase B). This covers the performance gap.
  3. For sensitive analytics: FHE for batch computation (Phase C). This provides the strongest server-trust-free guarantee.
  4. For group operations: MPC where multiple parties are involved (Phase D). This provides input privacy among participants.

Using multiple techniques in combination — for example, encrypting data with FHE before sending it to a TEE — provides defense against failures in any single layer.

9. Future Packages

Package Purpose Dependencies
@cyber-eco/crypto EncryptedStorageAdapter, KeyManager, client-side AES-256-GCM encryption, key derivation (Argon2id + HKDF) @cyber-eco/types
@cyber-eco/fhe FHEComputeService, WASM bindings for tfhe-rs, FHE key management, ciphertext serialization @cyber-eco/types
@cyber-eco/tee TEEComputeService, remote attestation verification, enclave communication protocol @cyber-eco/types
@cyber-eco/mpc MPCComputeService, session management, Shamir's Secret Sharing, garbled circuit evaluation @cyber-eco/types

All four packages depend only on @cyber-eco/types. This maintains the storage-agnostic constraint: no package in this list imports firebase/* or any other storage backend. The encryption and computation layers are orthogonal to storage — they work with FirebaseStorageAdapter, IPFSStorageAdapter, or any future adapter without modification.

The ComputeService domain service lives in @cyber-eco/services (alongside SharedDataService, PermissionService, etc.) and receives the compute services via constructor injection, following the same dependency inversion pattern used throughout the ecosystem.