diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1a190ae..2b6e4cc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -64,3 +64,10 @@ jobs: with: workspaces: contracts - run: cargo test --locked + + docker: + name: Docker images build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: docker compose build diff --git a/README.md b/README.md index 1e2b92f..7383660 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,22 @@ See [Status](#status) before trusting this with real funds. [![CI](https://github.com/CiipherProtocol/CipherProtocol/actions/workflows/ci.yml/badge.svg)](https://github.com/CiipherProtocol/CipherProtocol/actions/workflows/ci.yml) +## Try it + +**Live demo:** _link coming soon_ (Stellar testnet). No wallet extension +needed: click **Try demo wallet** for a throwaway key in your tab, or connect +Freighter. A banner shows exactly what's on-chain and what's simulated. + +**Run the whole system locally**, with 5 validators in separate containers: + +```bash +docker compose up --build # then open http://localhost:8080 +docker compose stop validator-2 validator-4 # still works: 3 of 5 suffice +``` + +Hosting on Render, Vercel or Netlify, and enabling on-chain sealing, are +covered in [docs/DEPLOY.md](docs/DEPLOY.md). + ## Architecture ``` @@ -85,9 +101,13 @@ What's real and tested: from Soroban itself and refuses to decrypt anything that doesn't match, so a pending order can't be decrypted early, even by the backend. The batch monitor links each batch to its sealing transaction. -- **Tests and CI**: 70 backend tests (crypto, DKG, malicious coordinator, +- **Deployable demo**: Docker Compose stack (each validator container mounts + only its own key), a Render blueprint, a demo wallet for reviewers without + Freighter, per-IP rate limiting, and an in-app banner that reports which + parts run on-chain and which are simulated. +- **Tests and CI**: 73 backend tests (crypto, DKG, malicious coordinator, remote validators, batch sealing, end-to-end pipeline, auth), - 8 frontend tests, and the contract suites. They run on every PR, together + 11 frontend tests, the contract suites, and a Docker image build. They run on every PR, together with a source-integrity check that blocks hidden or obfuscated code. What's **not** real yet: diff --git a/backend/.dockerignore b/backend/.dockerignore new file mode 100644 index 0000000..a3008cf --- /dev/null +++ b/backend/.dockerignore @@ -0,0 +1,6 @@ +node_modules +dist +data +.env +*.log +tests diff --git a/backend/Dockerfile b/backend/Dockerfile new file mode 100644 index 0000000..6e5c537 --- /dev/null +++ b/backend/Dockerfile @@ -0,0 +1,24 @@ +# One image for the API and for validator processes: +# API: node dist/index.js (default) +# validator: node dist/validator/main.js +# bootstrap: node dist/validator/initCluster.js +FROM node:22-bookworm-slim AS build +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci +COPY tsconfig.json ./ +COPY src ./src +RUN npm run build && npm prune --omit=dev + +FROM node:22-bookworm-slim +ENV NODE_ENV=production +WORKDIR /app +COPY --from=build /app/package.json ./ +COPY --from=build /app/node_modules ./node_modules +COPY --from=build /app/dist ./dist +RUN mkdir -p /app/data /data /cluster && chown -R node:node /app/data /data /cluster +USER node +EXPOSE 5001 +HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=5 \ + CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||5001)+'/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))" +CMD ["node", "dist/index.js"] diff --git a/backend/src/app.ts b/backend/src/app.ts index 914953b..44b7e0a 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -2,9 +2,12 @@ import express, { Express, Request, Response } from 'express'; import cors from 'cors'; import { errorHandler } from './middleware/errorHandler'; import * as routes from './routes'; +import { config } from './config'; +import { rateLimit } from './middleware/rateLimit'; export function createApp(): Express { const app = express(); + if (config.trustProxy) app.set('trust proxy', config.trustProxy); app.use(cors()); app.use(express.json({ limit: '100kb' })); @@ -17,7 +20,7 @@ export function createApp(): Express { app.use('/api/batches', routes.batches); app.use('/api/settlement', routes.settlement); app.use('/api/config', routes.config); - app.use('/api/auth', routes.auth); + app.use('/api/auth', rateLimit({ name: 'sign-in', windowMs: 60_000, max: config.rateLimitAuthPerMin }), routes.auth); app.use(errorHandler); return app; diff --git a/backend/src/config.ts b/backend/src/config.ts index 7c3cb87..2817577 100644 --- a/backend/src/config.ts +++ b/backend/src/config.ts @@ -23,6 +23,13 @@ export const config = { * a random per-process key is used and sessions reset on restart. */ authTokenSecret: process.env.AUTH_TOKEN_SECRET || '', + /** Number of reverse-proxy hops to trust for the client IP (e.g. 1 on + * Render/Fly/Railway). 0 = use the socket address. */ + trustProxy: Number(process.env.TRUST_PROXY) || 0, + /** Per-IP limits for public endpoints (per minute). */ + rateLimitAuthPerMin: Number(process.env.RATE_LIMIT_AUTH_PER_MIN) || 30, + rateLimitOrdersPerMin: Number(process.env.RATE_LIMIT_ORDERS_PER_MIN) || 20, + /** Token symbol -> Soroban contract address, until there's a real token * registry. Populated with testnet addresses for local/dev use. */ tokenContracts: parseTokenContracts(process.env.TOKEN_CONTRACTS), diff --git a/backend/src/controllers/configController.ts b/backend/src/controllers/configController.ts index dfa8479..d131a54 100644 --- a/backend/src/controllers/configController.ts +++ b/backend/src/controllers/configController.ts @@ -1,8 +1,18 @@ import { validatorService } from '../services/validatorService'; +import { getValidatorNetwork } from '../services/validatorNetwork'; +import { config } from '../config'; export const configController = { /** The validator set's group public key — what clients encrypt orders to. */ getPublicConfig() { - return validatorService.getPublicKeyInfo(); + return { + ...validatorService.getPublicKeyInfo(), + /** Where batches are sealed: the real order-vault on-chain, or the in-memory dev ledger. */ + sealing: config.orderVaultContract ? 'onchain' : 'dev-ledger', + order_vault_contract: config.orderVaultContract || null, + /** 'simulated' = orders are decrypted and validated but no tokens move (e.g. public demo). */ + settlement: config.settlementEngineContract ? 'onchain' : 'simulated', + validator_mode: getValidatorNetwork().mode, + }; }, }; diff --git a/backend/src/controllers/settlementController.ts b/backend/src/controllers/settlementController.ts index d0cc5c0..03e72b7 100644 --- a/backend/src/controllers/settlementController.ts +++ b/backend/src/controllers/settlementController.ts @@ -6,6 +6,7 @@ import { sorobanService } from '../services/sorobanService'; import { validatorService } from '../services/validatorService'; import { AppError, NotFoundError } from '../utils/errors'; import logger from '../utils/logger'; +import { config } from '../config'; export const settlementController = { async getSettlementResults(batchId: string) { @@ -47,7 +48,12 @@ export const settlementController = { await Promise.all([ ...decrypted.map((d, i) => Order.update( - { ...d.order, amount_out: results[i]?.amount_out ?? null, status: 'settled' }, + { + ...d.order, + // Simulated settlement moves no tokens, so there is no real amount_out to record. + amount_out: config.settlementEngineContract ? (results[i]?.amount_out ?? null) : null, + status: 'settled', + }, { where: { id: d.id } } ) ), diff --git a/backend/src/middleware/rateLimit.ts b/backend/src/middleware/rateLimit.ts new file mode 100644 index 0000000..1ddec10 --- /dev/null +++ b/backend/src/middleware/rateLimit.ts @@ -0,0 +1,36 @@ +import { Request, Response, NextFunction } from 'express'; + +/** + * Small fixed-window rate limiter (in-memory, per process). Enough to keep + * a public demo from being trivially flooded. A multi-instance deployment + * would move the counters to a shared store such as Redis. + */ +export function rateLimit(opts: { windowMs: number; max: number; key?: (req: Request) => string; name: string }) { + const hits = new Map(); + const keyOf = opts.key ?? ((req: Request) => req.ip ?? 'unknown'); + + const sweep = setInterval(() => { + const now = Date.now(); + for (const [k, v] of hits) if (v.resetAt <= now) hits.delete(k); + }, opts.windowMs); + sweep.unref(); + + return (req: Request, res: Response, next: NextFunction) => { + const now = Date.now(); + const k = keyOf(req); + let entry = hits.get(k); + if (!entry || entry.resetAt <= now) { + entry = { count: 0, resetAt: now + opts.windowMs }; + hits.set(k, entry); + } + entry.count++; + res.setHeader('RateLimit-Limit', String(opts.max)); + res.setHeader('RateLimit-Remaining', String(Math.max(0, opts.max - entry.count))); + if (entry.count > opts.max) { + res.setHeader('Retry-After', String(Math.ceil((entry.resetAt - now) / 1000))); + res.status(429).json({ error: `Too many ${opts.name} requests; try again shortly` }); + return; + } + next(); + }; +} diff --git a/backend/src/routes/orders.ts b/backend/src/routes/orders.ts index 569b4ea..5e383b3 100644 --- a/backend/src/routes/orders.ts +++ b/backend/src/routes/orders.ts @@ -2,13 +2,23 @@ import { Router, Request, Response, NextFunction } from 'express'; import { orderController } from '../controllers/orderController'; import { validateAuth } from '../middleware/auth'; import { validateOrderInput } from '../middleware/validation'; +import { rateLimit } from '../middleware/rateLimit'; +import { config } from '../config'; import { SubmitOrderBody } from '../types/order'; const router = Router(); +const submitLimit = rateLimit({ + name: 'order', + windowMs: 60_000, + max: config.rateLimitOrdersPerMin, + key: (req) => `${req.ip}|${req.user?.address ?? ''}`, +}); + router.post( '/', validateAuth, + submitLimit, validateOrderInput, async (req: Request, res: Response, next: NextFunction) => { try { diff --git a/backend/src/validator/initCluster.ts b/backend/src/validator/initCluster.ts new file mode 100644 index 0000000..ddb0189 --- /dev/null +++ b/backend/src/validator/initCluster.ts @@ -0,0 +1,60 @@ +/** + * One-shot cluster bootstrap for Docker Compose (the `validator-init` + * service). Writes into the shared /cluster volume: + * + * validator-/identity.json that validator's identity key + * validator-/validator.env its API token, peer keys, sealing config + * coordinator/cluster.json what the backend needs to reach them + * + * Each container then mounts only its own subdirectory, so a validator + * never sees another validator's files. Idempotent: existing identities + * and tokens are kept, so restarts don't re-key anything. + * + * NOTE: this bootstrap is run by one operator, so it is a single-operator + * demo. Real independent validators generate their own identity and + * exchange only public keys. + */ +import crypto from 'crypto'; +import fs from 'fs'; +import path from 'path'; +import { loadOrCreateIdentity } from './main'; +import { ClusterFile } from './remoteValidator'; + +const root = process.env.CLUSTER_DIR || '/cluster'; +const count = Number(process.env.VALIDATOR_COUNT) || 5; +const urlFor = (i: number) => (process.env.VALIDATOR_URL_TEMPLATE || 'http://validator-{i}:7700').replace('{i}', String(i)); + +const clusterPath = path.join(root, 'coordinator', 'cluster.json'); +const previous: ClusterFile | null = fs.existsSync(clusterPath) ? JSON.parse(fs.readFileSync(clusterPath, 'utf8')) : null; + +const members = Array.from({ length: count }, (_, k) => { + const index = k + 1; + const dir = path.join(root, `validator-${index}`); + const identity = loadOrCreateIdentity(dir); + const apiToken = previous?.validators.find((v) => v.index === index)?.apiToken ?? crypto.randomBytes(32).toString('hex'); + return { index, dir, identity, apiToken }; +}); + +const peerKeys = members.map((m) => `${m.index}:${m.identity.publicKey}`).join(','); +const sealing = process.env.ORDER_VAULT_CONTRACT + ? [ + `VALIDATOR_ORDER_VAULT_CONTRACT=${process.env.ORDER_VAULT_CONTRACT}`, + `VALIDATOR_SOROBAN_RPC_URL=${process.env.SOROBAN_RPC_URL || 'https://soroban-testnet.stellar.org'}`, + `VALIDATOR_NETWORK_PASSPHRASE="${process.env.STELLAR_NETWORK_PASSPHRASE || 'Test SDF Network ; September 2015'}"`, + ] + : ['VALIDATOR_INSECURE_SKIP_COMMITMENT_CHECK=1']; + +for (const m of members) { + const env = [`VALIDATOR_API_TOKEN=${m.apiToken}`, `VALIDATOR_PEER_KEYS=${peerKeys}`, ...sealing].join('\n') + '\n'; + fs.writeFileSync(path.join(m.dir, 'validator.env'), env, { mode: 0o600 }); +} + +const cluster: ClusterFile = { + validators: members.map((m) => ({ index: m.index, url: urlFor(m.index), identityKey: m.identity.publicKey, apiToken: m.apiToken })), +}; +fs.mkdirSync(path.dirname(clusterPath), { recursive: true }); +fs.writeFileSync(clusterPath, JSON.stringify(cluster, null, 2), { mode: 0o600 }); + +console.log( + `cluster ready: ${count} validators, sealing check ${process.env.ORDER_VAULT_CONTRACT ? 'ON (on-chain)' : 'OFF (no ORDER_VAULT_CONTRACT)'}` +); diff --git a/backend/tests/demoReadiness.test.ts b/backend/tests/demoReadiness.test.ts new file mode 100644 index 0000000..bb8f4bd --- /dev/null +++ b/backend/tests/demoReadiness.test.ts @@ -0,0 +1,51 @@ +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import express from 'express'; +import request from 'supertest'; +import { rateLimit } from '../src/middleware/rateLimit'; +import { createApp } from '../src/app'; +import { sequelize } from '../src/db'; +import { Order } from '../src/db/models/Order'; +import { validatorService } from '../src/services/validatorService'; +import { batchingService } from '../src/services/batchingService'; +import { newUser, submitSwap } from './helpers'; + +describe('rate limiting', () => { + const app = express(); + app.set('trust proxy', 1); + app.get('/x', rateLimit({ name: 'test', windowMs: 60_000, max: 3 }), (_req, res) => { + res.json({ ok: true }); + }); + + it('allows up to the limit per client, then answers 429 with Retry-After', async () => { + const ip = { 'x-forwarded-for': '203.0.113.7' }; + for (let i = 0; i < 3; i++) expect((await request(app).get('/x').set(ip)).status).toBe(200); + const blocked = await request(app).get('/x').set(ip); + expect(blocked.status).toBe(429); + expect(Number(blocked.headers['retry-after'])).toBeGreaterThan(0); + // A different client is unaffected. + expect((await request(app).get('/x').set({ 'x-forwarded-for': '203.0.113.8' })).status).toBe(200); + }); +}); + +describe('demo mode reporting', () => { + const app = createApp(); + beforeAll(async () => { + await sequelize.sync({ force: true }); + await validatorService.syncValidatorRegistry(); + }); + afterAll(() => sequelize.close()); + + it('says how sealing and settlement actually run', async () => { + const { body } = await request(app).get('/api/config'); + expect(body).toMatchObject({ sealing: 'dev-ledger', settlement: 'simulated', validator_mode: 'local' }); + }); + + it('simulated settlement reveals the order but records no fake amount received', async () => { + const res = await submitSwap(app, newUser()); + await batchingService.runOnce(); + const order = await Order.findByPk(res.body.order.id); + expect(order!.status).toBe('settled'); + expect(order!.amount_in).toBe('15000000'); + expect(order!.amount_out).toBeNull(); + }); +}); diff --git a/backend/tests/setupEnv.ts b/backend/tests/setupEnv.ts index 9fcf045..d89db21 100644 --- a/backend/tests/setupEnv.ts +++ b/backend/tests/setupEnv.ts @@ -7,3 +7,5 @@ process.env.VALIDATOR_THRESHOLD = '3'; process.env.ORDER_VAULT_CONTRACT = ''; process.env.SETTLEMENT_ENGINE_CONTRACT = ''; process.env.AUTH_TOKEN_SECRET = 'test-secret-test-secret-test-secret'; +process.env.RATE_LIMIT_AUTH_PER_MIN = '100000'; +process.env.RATE_LIMIT_ORDERS_PER_MIN = '100000'; diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..38d775b --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,99 @@ +# Full system, one command: docker compose up --build +# +# validator-init generates identities + tokens (once; idempotent) +# validator-1..5 separate containers, each mounting ONLY its own key dir +# backend coordinator: runs the DKG over HTTP on first start +# frontend nginx serving the app on http://localhost:8080, proxying /api +# +# Sealing: set ORDER_VAULT_CONTRACT + BACKEND_SIGNER_SECRET (e.g. in a .env +# next to this file) to seal batches on Stellar testnet and have every +# validator verify the seal on-chain. Without them, batches use the backend's +# in-memory dev ledger and validators run with the sealing check DISABLED. + +x-validator: &validator + build: ./backend + image: cipher-protocol-backend + command: ["sh", "-c", "set -a && . /data/validator.env && exec node dist/validator/main.js"] + environment: &validator-env + VALIDATOR_KEY_DIR: /data + VALIDATOR_HOST: 0.0.0.0 + VALIDATOR_PORT: "7700" # not 6000: fetch() refuses it (WHATWG bad-port list) + healthcheck: + test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:7700/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"] + interval: 5s + timeout: 3s + retries: 10 + depends_on: + validator-init: + condition: service_completed_successfully + restart: unless-stopped + +services: + validator-init: + build: ./backend + image: cipher-protocol-backend + command: ["node", "dist/validator/initCluster.js"] + environment: + CLUSTER_DIR: /cluster + VALIDATOR_COUNT: "5" + ORDER_VAULT_CONTRACT: ${ORDER_VAULT_CONTRACT:-} + SOROBAN_RPC_URL: ${SOROBAN_RPC_URL:-https://soroban-testnet.stellar.org} + volumes: + - cluster:/cluster + + validator-1: + <<: *validator + environment: { <<: *validator-env, VALIDATOR_INDEX: "1" } + volumes: [{ type: volume, source: cluster, target: /data, volume: { subpath: validator-1 } }] + validator-2: + <<: *validator + environment: { <<: *validator-env, VALIDATOR_INDEX: "2" } + volumes: [{ type: volume, source: cluster, target: /data, volume: { subpath: validator-2 } }] + validator-3: + <<: *validator + environment: { <<: *validator-env, VALIDATOR_INDEX: "3" } + volumes: [{ type: volume, source: cluster, target: /data, volume: { subpath: validator-3 } }] + validator-4: + <<: *validator + environment: { <<: *validator-env, VALIDATOR_INDEX: "4" } + volumes: [{ type: volume, source: cluster, target: /data, volume: { subpath: validator-4 } }] + validator-5: + <<: *validator + environment: { <<: *validator-env, VALIDATOR_INDEX: "5" } + volumes: [{ type: volume, source: cluster, target: /data, volume: { subpath: validator-5 } }] + + backend: + build: ./backend + image: cipher-protocol-backend + environment: + PORT: "5001" + TRUST_PROXY: "1" + VALIDATOR_CLUSTER_FILE: /coordinator/cluster.json + VALIDATOR_COUNT: "5" + VALIDATOR_THRESHOLD: "3" + BATCH_TIMEOUT_MS: ${BATCH_TIMEOUT_MS:-10000} + AUTH_TOKEN_SECRET: ${AUTH_TOKEN_SECRET:-} + ORDER_VAULT_CONTRACT: ${ORDER_VAULT_CONTRACT:-} + SETTLEMENT_ENGINE_CONTRACT: ${SETTLEMENT_ENGINE_CONTRACT:-} + BACKEND_SIGNER_SECRET: ${BACKEND_SIGNER_SECRET:-} + TOKEN_CONTRACTS: ${TOKEN_CONTRACTS:-} + volumes: + - { type: volume, source: cluster, target: /coordinator, read_only: true, volume: { subpath: coordinator } } + - backend-data:/app/data + depends_on: + validator-1: { condition: service_healthy } + validator-2: { condition: service_healthy } + validator-3: { condition: service_healthy } + validator-4: { condition: service_healthy } + validator-5: { condition: service_healthy } + restart: unless-stopped + + frontend: + build: ./frontend + ports: ["8080:80"] + depends_on: + backend: { condition: service_healthy } + +volumes: + cluster: + backend-data: diff --git a/docs/CONTRIBUTOR_ISSUES.md b/docs/CONTRIBUTOR_ISSUES.md index 0fd91f7..9e77d4c 100644 --- a/docs/CONTRIBUTOR_ISSUES.md +++ b/docs/CONTRIBUTOR_ISSUES.md @@ -28,16 +28,16 @@ All existing `dkg.test.ts` cases must still pass. --- -### 2. Validator deployment: Docker Compose + TLS (150) +### 2. TLS between coordinator and validators (150) -Validators already run as separate processes (`npm run validators:dev`), -but only on one host over plain HTTP. Add a Docker Compose setup (one -container and one volume per validator, plus the backend), and put the -coordinator-to-validator transport behind TLS. Mutual TLS is a bonus. +`docker-compose.yml` runs each validator in its own container, but +coordinator↔validator traffic is plain HTTP with bearer tokens on the +Docker network. Add TLS. Mutual TLS, with each validator pinning the +coordinator's certificate, is a bonus. Document how an independent +operator would generate and exchange certs. -**Acceptance:** `docker compose up` brings up 5 validators and the backend. -The DKG completes, and an order settles. Stopping 2 validator containers -doesn't stop settlement. +**Acceptance:** the compose stack runs over TLS, and a validator rejects +plaintext connections. --- @@ -73,10 +73,11 @@ matching `db/models/`, and run them in the backend tests. --- -### 5. Rate limiting and request-size hardening (100) +### 5. Shared rate-limit store (100) -`/api/auth/challenge` and `/api/orders` have no rate limits. Add per-IP -limits for challenges and per-address limits for orders, with tests. +`backend/src/middleware/rateLimit.ts` keeps counters in process memory, +which is fine for one instance. Add an optional Redis-backed store (enabled +by `REDIS_URL`) so limits hold across replicas, with tests for both. --- diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md new file mode 100644 index 0000000..07fab9a --- /dev/null +++ b/docs/DEPLOY.md @@ -0,0 +1,102 @@ +# Deploying the demo + +Three ways to run Cipher Protocol, from quickest to most realistic. + +| | What runs | Validators | Good for | +|---|---|---|---| +| **A. Render (hosted)** | API + static app | 5, in-process | A public link for reviewers | +| **B. Docker Compose** | API + app + 5 validator containers | 5 separate containers, each with only its own key | The full architecture on one machine | +| **C. Local dev** | `npm run dev` in `backend/` and `frontend/` | in-process, or `npm run validators:dev` | Development | + +Anyone can try any of them without a wallet extension: **Try demo wallet** +creates a throwaway testnet key in the browser tab. + +## Before you deploy: the sealing key + +To seal batches on-chain (recommended), the backend needs +`ORDER_VAULT_CONTRACT` and `BACKEND_SIGNER_SECRET`. That secret must be +the **admin** the contract was `initialize`d with. + +> **If the admin key of the existing testnet `order-vault` was ever on the +> machine that was compromised (commit `7913b3a`), don't reuse it.** The +> contract has no way to change its admin. Deploy a fresh `order-vault` +> with a new key instead (it takes about two minutes): +> +> ```bash +> stellar keys generate cipher-demo --network testnet --fund +> cd contracts && cargo build --target wasm32v1-none --release +> stellar contract deploy --wasm target/wasm32v1-none/release/order_vault.wasm \ +> --source cipher-demo --network testnet # prints the new contract id +> stellar contract invoke --id --source cipher-demo --network testnet \ +> -- initialize --admin $(stellar keys address cipher-demo) +> stellar keys show cipher-demo # the BACKEND_SIGNER_SECRET +> ``` +> +> Then update the contract table in the README. + +Without these two values, everything still works, but batches are sealed in +an in-memory dev ledger instead of on-chain. The site's banner always says +which mode is running. + +Settlement in the demo is **simulated**. Demo users hold no testnet tokens, +so `settle_batch` would have nothing to move. Orders are still really +encrypted, sealed, threshold-decrypted and validated. Only the token +transfer is skipped, and the UI says so. Set `SETTLEMENT_ENGINE_CONTRACT` and +`TOKEN_CONTRACTS` only for users who hold and approved testnet tokens. + +## A. Render + +1. Push the repo to GitHub, then go to Render → **New → Blueprint** and + select it. It reads [`render.yaml`](../render.yaml). +2. When prompted, fill in: + - `cipher-protocol-api`: `ORDER_VAULT_CONTRACT` and + `BACKEND_SIGNER_SECRET` (or leave both empty). + - `cipher-protocol-app`: `VITE_API_URL`, set to the API's URL plus + `/api`, e.g. `https://cipher-protocol-api.onrender.com/api`. If you + don't know it yet, deploy, copy it, set it, then **Manual Deploy** + the app again (Vite bakes it in at build time). +3. Open the app URL. Free instances sleep when idle, so the first request + can take about 30 seconds, and the banner says so. + +The free tier has no persistent disk, so a restart re-runs the DKG (new +group key) and starts with an empty order book. That's fine for a demo. +Add a disk mounted at `/app/data` to keep state across restarts. + +**Vercel or Netlify for the frontend instead:** set the project root to +`frontend/`, the build command to `npm run build`, the output to `dist/`, +and `VITE_API_URL` as above. SPA routing is preconfigured (`vercel.json`, +`public/_redirects`). + +## B. Docker Compose + +```bash +cp backend/.env.example .env # optional: set ORDER_VAULT_CONTRACT + BACKEND_SIGNER_SECRET +docker compose up --build +# app: http://localhost:8080 +``` + +`validator-init` generates each validator's identity and API token once. +Each `validator-N` container mounts **only its own** key directory. On first +start the backend runs the DKG over HTTP. Try stopping two validators: + +```bash +docker compose stop validator-2 validator-4 # orders still settle (3 of 5) +docker compose stop validator-5 # now they fail cleanly, nothing decrypted +``` + +With `ORDER_VAULT_CONTRACT` set, every validator checks the batch seal on +Stellar testnet before decrypting. Without it, the validators log that the +check is disabled. + +Note that `validator-init` makes this a **single-operator** setup: one +party generates every identity. Independent operators would each generate +their own and exchange only public keys. + +## Production notes + +- Put validator traffic behind TLS (contributor issue #2). +- Set `AUTH_TOKEN_SECRET` explicitly so sessions survive restarts. +- Use Postgres (`DATABASE_URL`) and persistent volumes for validator keys. +- Rate limits: `RATE_LIMIT_AUTH_PER_MIN` (default 30) and + `RATE_LIMIT_ORDERS_PER_MIN` (default 20), per client IP, with + `TRUST_PROXY=1` behind a proxy. diff --git a/frontend/.dockerignore b/frontend/.dockerignore new file mode 100644 index 0000000..3b24e4a --- /dev/null +++ b/frontend/.dockerignore @@ -0,0 +1,4 @@ +node_modules +dist +.env +*.log diff --git a/frontend/Dockerfile b/frontend/Dockerfile new file mode 100644 index 0000000..8a33cbb --- /dev/null +++ b/frontend/Dockerfile @@ -0,0 +1,14 @@ +FROM node:22-bookworm-slim AS build +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci +COPY . . +# Same-origin by default: nginx below proxies /api to the backend. +ARG VITE_API_URL=/api +ENV VITE_API_URL=$VITE_API_URL +RUN npm run build + +FROM nginx:1.27-alpine +COPY nginx.conf /etc/nginx/conf.d/default.conf +COPY --from=build /app/dist /usr/share/nginx/html +EXPOSE 80 diff --git a/frontend/README.md b/frontend/README.md index 77a4573..a3786d6 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -11,20 +11,27 @@ cp .env.example .env # defaults point at a local backend on :5001 npm run dev # http://localhost:5173 ``` -Requires the [Freighter](https://www.freighter.app/) browser extension to -connect a wallet. Without a backend running, the swap form and batch monitor -still render — API calls just fail gracefully (empty lists, logged errors). +Connect with the [Freighter](https://www.freighter.app/) extension, or click +**Try demo wallet** to use a throwaway testnet key held in the tab. The demo +key is only used to sign the sign-in challenge, and it's discarded on +disconnect. Without a backend, the app still renders, and a banner says the +backend is unreachable. ## Scripts - `npm run dev` — dev server with hot reload - `npm run build` — type-check (`tsc -b`) + production build - `npm run preview` — preview the production build +- `npm test` — Vitest (encryption wire format, amounts, SwapForm, demo wallet) + +Deploying: see [docs/DEPLOY.md](../docs/DEPLOY.md). `vercel.json` and +`public/_redirects` set up SPA routing on Vercel and Netlify, and the +`Dockerfile` serves the build through nginx, proxying `/api`. ## Structure See the root [README](../README.md#architecture) for the overall data flow. Key entry points: `src/pages/SwapPage.tsx` (main flow), `src/services/api.ts` -(backend client), `src/services/encryption.ts` (placeholder — see root -README's Status section), `src/context/WalletContext.tsx` (Freighter -connection state). +(backend client), `src/crypto/orderCipher.ts` (threshold encryption, byte-identical to the +backend copy), `src/services/wallet.ts` (Freighter or demo key), and +`src/components/layout/ModeBanner.tsx` (what's real versus simulated). diff --git a/frontend/nginx.conf b/frontend/nginx.conf new file mode 100644 index 0000000..152f456 --- /dev/null +++ b/frontend/nginx.conf @@ -0,0 +1,20 @@ +server { + listen 80; + root /usr/share/nginx/html; + + # Re-resolve the backend through Docker's DNS instead of pinning the IP + # it had at startup; otherwise every backend restart breaks /api with 502. + resolver 127.0.0.11 valid=10s ipv6=off; + set $backend http://backend:5001; + + location /api/ { + proxy_pass $backend; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + } + + # Single-page app: unknown paths serve index.html. + location / { + try_files $uri /index.html; + } +} diff --git a/frontend/public/_redirects b/frontend/public/_redirects new file mode 100644 index 0000000..ad37e2c --- /dev/null +++ b/frontend/public/_redirects @@ -0,0 +1 @@ +/* /index.html 200 diff --git a/frontend/src/__tests__/wallet.test.ts b/frontend/src/__tests__/wallet.test.ts new file mode 100644 index 0000000..143c2cb --- /dev/null +++ b/frontend/src/__tests__/wallet.test.ts @@ -0,0 +1,40 @@ +import { describe, it, expect } from 'vitest'; +import { Account, Keypair, Networks, Operation, TransactionBuilder } from '@stellar/stellar-sdk'; +import { walletService } from '../services/wallet'; + +function challengeFor(address: string) { + return new TransactionBuilder(new Account(address, '-1'), { fee: '100', networkPassphrase: Networks.TESTNET }) + .addOperation(Operation.manageData({ name: 'cipher-protocol auth', value: 'x'.repeat(64) })) + .setTimeout(300) + .build() + .toXDR(); +} + +describe('demo wallet', () => { + it('creates a throwaway key and signs challenges the backend can verify', async () => { + const address = await walletService.connect('demo'); + expect(walletService.kind()).toBe('demo'); + expect(address).toMatch(/^G[A-Z2-7]{55}$/); + + const signed = TransactionBuilder.fromXDR( + await walletService.signTransaction(challengeFor(address), Networks.TESTNET), + Networks.TESTNET + ); + const kp = Keypair.fromPublicKey(address); + expect(signed.signatures).toHaveLength(1); + expect(kp.verify(signed.hash(), signed.signatures[0].signature())).toBe(true); + }); + + it('a new demo session gets a new key, and disconnect discards it', async () => { + const a = await walletService.connect('demo'); + const b = await walletService.connect('demo'); + expect(a).not.toBe(b); + walletService.disconnect(); + expect(walletService.kind()).toBeNull(); + expect(await walletService.getAddress()).toBeNull(); + }); + + it('points users to the demo wallet when Freighter is missing', async () => { + await expect(walletService.connect('freighter')).rejects.toThrow(/demo wallet/); + }); +}); diff --git a/frontend/src/components/common/WalletConnect.tsx b/frontend/src/components/common/WalletConnect.tsx index 4c52e59..9d3f521 100644 --- a/frontend/src/components/common/WalletConnect.tsx +++ b/frontend/src/components/common/WalletConnect.tsx @@ -3,23 +3,41 @@ import { shortenAddress } from '../../utils/formatting'; import Button from './Button'; export default function WalletConnect() { - const { address, isConnected, connecting, connect, disconnect } = useWallet(); + const { address, isConnected, connecting, kind, error, connect, disconnect } = useWallet(); if (isConnected && address) { return ( ); } return ( - +
+
+ + +
+ {error &&

{error}

} +
); } diff --git a/frontend/src/components/layout/Layout.tsx b/frontend/src/components/layout/Layout.tsx index 04c5855..46763c0 100644 --- a/frontend/src/components/layout/Layout.tsx +++ b/frontend/src/components/layout/Layout.tsx @@ -1,10 +1,12 @@ import React from 'react'; import Header from './Header'; import Footer from './Footer'; +import ModeBanner from './ModeBanner'; export default function Layout({ children }: { children: React.ReactNode }) { return (
+
{children}