diff --git a/.github/workflows/chaos-testing.yml b/.github/workflows/chaos-testing.yml index fccad308..e50bf14e 100644 --- a/.github/workflows/chaos-testing.yml +++ b/.github/workflows/chaos-testing.yml @@ -37,7 +37,7 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v4 with: - node-version: '22' + node-version-file: '.nvmrc' cache: 'npm' cache-dependency-path: package-lock.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 718596e0..c914c141 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -76,7 +76,7 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v4 with: - node-version: '22' + node-version-file: '.nvmrc' cache: "npm" cache-dependency-path: package-lock.json @@ -155,7 +155,7 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v4 with: - node-version: '22' + node-version-file: '.nvmrc' cache: "npm" cache-dependency-path: package-lock.json diff --git a/.github/workflows/db-backup.yml b/.github/workflows/db-backup.yml index de85dd05..3c389e1a 100644 --- a/.github/workflows/db-backup.yml +++ b/.github/workflows/db-backup.yml @@ -21,7 +21,7 @@ jobs: - name: Set up Node.js uses: actions/setup-node@v4 with: - node-version: '22' + node-version-file: '.nvmrc' - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials@v4 diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 72048c61..1fbdbabc 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -24,7 +24,7 @@ jobs: - uses: actions/setup-node@v4 with: - node-version: 20 + node-version-file: '.nvmrc' # No lockfile is committed for the portal yet; once one lands, add # `cache: npm` + `cache-dependency-path: docs-site/package-lock.json` diff --git a/.github/workflows/dr-test.yml b/.github/workflows/dr-test.yml index 46b03f7a..390d51f1 100644 --- a/.github/workflows/dr-test.yml +++ b/.github/workflows/dr-test.yml @@ -35,7 +35,7 @@ jobs: - name: Set up Node.js uses: actions/setup-node@v4 with: - node-version: '22' + node-version-file: '.nvmrc' cache: npm cache-dependency-path: package-lock.json diff --git a/.github/workflows/pr-preview.yml b/.github/workflows/pr-preview.yml index 554d6063..be65fa80 100644 --- a/.github/workflows/pr-preview.yml +++ b/.github/workflows/pr-preview.yml @@ -63,7 +63,7 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v4 with: - node-version: '22' + node-version-file: '.nvmrc' cache: "npm" cache-dependency-path: package-lock.json diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 61b1ce3d..8dd9aaf3 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -24,7 +24,7 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v4 with: - node-version: '20.19.0' + node-version-file: '.nvmrc' cache: 'npm' - name: Install dependencies diff --git a/.github/workflows/testnet-e2e.yml b/.github/workflows/testnet-e2e.yml index 61a98138..12981fd6 100644 --- a/.github/workflows/testnet-e2e.yml +++ b/.github/workflows/testnet-e2e.yml @@ -140,7 +140,7 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v4 with: - node-version: '22' + node-version-file: '.nvmrc' cache: "npm" cache-dependency-path: package-lock.json diff --git a/.npmrc b/.npmrc new file mode 100644 index 00000000..b6f27f13 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +engine-strict=true diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 00000000..2bd5a0a9 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +22 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b3037bbf..7c22c183 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -86,7 +86,7 @@ cd flowfi Make sure you have the following installed: -- Node.js (LTS recommended) +- Node.js 22 (`^22.22.1`) — the version is pinned in `.nvmrc` and enforced via `engines` + `engine-strict`; run `nvm use` in the repo root - npm - Rust & Cargo - Docker & Docker Compose diff --git a/backend/Dockerfile b/backend/Dockerfile index 308821fd..a4fef05e 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -3,7 +3,7 @@ # Full Node toolchain (devDependencies incl. tsc + prisma CLI) compiles the # TypeScript and generates the Prisma client. Discarded from the final image. # ============================================================================ -FROM node:20-alpine@sha256:fb4cd12c85ee03686f6af5362a0b0d56d50c58a04632e6c0fb8363f609372293 AS builder +FROM node:22-alpine@sha256:1314fb30ec37592d5845e5a160d522c0e680972aa534549940b8d73bde88481a AS builder WORKDIR /app @@ -28,7 +28,7 @@ RUN npm run build # Stage 2 — production runner # Minimal Alpine base, production-only dependencies, non-root `node` user. # ============================================================================ -FROM node:20-alpine@sha256:fb4cd12c85ee03686f6af5362a0b0d56d50c58a04632e6c0fb8363f609372293 AS runner +FROM node:22-alpine@sha256:1314fb30ec37592d5845e5a160d522c0e680972aa534549940b8d73bde88481a AS runner WORKDIR /app diff --git a/backend/package.json b/backend/package.json index 3776f27e..ff932d2e 100644 --- a/backend/package.json +++ b/backend/package.json @@ -22,6 +22,9 @@ "prisma:studio": "prisma studio", "codegen:openapi": "tsx scripts/export-openapi.mts" }, + "engines": { + "node": "^22.22.1" + }, "prisma": { "seed": "tsx prisma/seed.ts" }, diff --git a/docs-site/docs/contracts/soroban-reference.md b/docs-site/docs/contracts/soroban-reference.md index 3cf53345..385f98e7 100644 --- a/docs-site/docs/contracts/soroban-reference.md +++ b/docs-site/docs/contracts/soroban-reference.md @@ -99,5 +99,5 @@ Most authorization errors (#3, #6, #24, #32, #43) mean you're calling from the w ::: :::note -For detailed error handling examples, see the [SDK Integration Guide](../sdk/overview.md) and [Testing Patterns](../development/testing.md). +For detailed error handling examples, see the [TypeScript SDK guide](../sdks/typescript.md) and [Running Tests](https://github.com/LabsCrypt/flowfi/blob/main/docs/DEVELOPMENT.md#running-tests). ::: diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 7970c020..bd651049 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -83,7 +83,7 @@ npm run dev:mock ### Prerequisites for the sandbox - Docker & Docker Compose (for Postgres, Redis, mock RPC) -- Node.js 20+ and npm (for backend, frontend, seed script) +- Node.js 22 (see `.nvmrc`) and npm (for backend, frontend, seed script) No Rust, no Stellar CLI, no testnet account needed. @@ -94,7 +94,7 @@ No Rust, no Stellar CLI, no testnet account needed. Required: - Rust toolchain (stable via rustup) -- Node.js 20+ +- Node.js 22 (`^22.22.1`) — the version is pinned in `.nvmrc` and enforced via `engines` + `engine-strict`; run `nvm use` in the repo root - npm - PostgreSQL 16 (matches the version pinned in `docker-compose.yml` and CI) - Docker & Docker Compose (recommended for local infra) diff --git a/docs/DISASTER_RECOVERY.md b/docs/DISASTER_RECOVERY.md index e53b8ef9..a0b3be6a 100644 --- a/docs/DISASTER_RECOVERY.md +++ b/docs/DISASTER_RECOVERY.md @@ -13,15 +13,55 @@ FlowFi stores encrypted PostgreSQL backups in Amazon S3. The backup includes a p ## Restore a backup -Restore to an empty PostgreSQL database. The script authenticates and decompresses the full archive before submitting SQL, then compares the restored count of every recorded public table to the manifest. It exits nonzero on decryption, archive, SQL, or row-count errors. +Restore into a freshly provisioned, empty PostgreSQL database whenever possible. ```sh export DATABASE_URL='postgresql://user:password@localhost:5432/flowfi_recovery' export BACKUP_ENCRYPTION_KEY='<64 hex characters from the secret store>' + +# 1. Rehearse first: decrypts and validates the backup, inspects the target, +# prints the plan, and changes nothing. +bash scripts/db-restore.sh --dry-run /secure/path/flowfi--.tar.gz.enc + +# 2. Restore. bash scripts/db-restore.sh /secure/path/flowfi--.tar.gz.enc ``` -For S3, download the selected object to a protected temporary location with `aws s3 cp`, then pass its path to the restore script. Restrict access to both the encrypted object and the key; encryption does not replace access controls. +For S3, download the selected object to a protected temporary location with `aws s3 cp`, then pass its path to the restore script. Restrict access to both the encrypted object and the key; encryption does not replace access controls. Run `bash scripts/db-restore.sh --help` for every option. + +### What the script does + +1. **Validates the backup before touching the database.** The archive is authenticated (AES-256-GCM), decompressed and checked for its dump and row-count manifest before any SQL is sent. A wrong key, tampered file or malformed manifest exits with code `1` and no changes. +2. **Checks that the target is empty.** If the target database contains any user tables, views, sequences, types or functions, the restore is **refused with exit code `3`** unless `--force` is given. +3. **Restores in a single transaction.** The SQL dump and the row-count verification for every recorded `public` table run inside one transaction (`psql --single-transaction`). If any statement fails or any count differs from the manifest, PostgreSQL rolls back the entire restore. + +### Replacing a non-empty database (`--force`) + +`--force` replaces the contents of a non-empty database. Use it only when restoring into a fresh database is impossible. + +```sh +bash scripts/db-restore.sh --dry-run --force # review the plan +bash scripts/db-restore.sh --force # asks you to type the database name +bash scripts/db-restore.sh --force --yes # non-interactive (automation only) +``` + +With `--force` the script: + +1. asks the operator to type the database name to confirm (skipped only with `--yes`; without a TTY `--yes` is mandatory); +2. writes an encrypted **pre-restore snapshot** of the current database, in the same format as regular backups, to `--snapshot-dir` (default `$RESTORE_SNAPSHOT_DIR` or `./restore-snapshots`). The snapshot is encrypted with the same `BACKUP_ENCRYPTION_KEY`; store it as carefully as a production backup; +3. drops every user schema and restores the backup, all in the same transaction as the verification. + +### Failure and recovery states + +| Failure point | State of the target database | What to do | +| --- | --- | --- | +| Decryption, archive or manifest validation | Untouched | Check the key and backup file, then retry. | +| Target not empty (exit `3`) | Untouched | Use a fresh database, or re-run with `--force`. | +| Snapshot fails (`--force`) | Untouched | Fix the cause (disk space, `pg_dump` version) and retry; no restore was attempted. | +| SQL error or row-count mismatch during restore | **Unchanged**: the transaction is rolled back, including the `--force` schema wipe | Read the error printed by the script, fix the cause and retry. | +| Connection lost mid-restore | Unchanged: PostgreSQL aborts the uncommitted transaction | Retry. | + +A successful run ends with `Restore completed and all N recorded public table row counts matched.` If a forced restore succeeded but the old data is needed again, restore the snapshot with `bash scripts/db-restore.sh --force `. ## Weekly disaster-recovery verification diff --git a/frontend/Dockerfile b/frontend/Dockerfile index d6ca2739..86244f7c 100644 --- a/frontend/Dockerfile +++ b/frontend/Dockerfile @@ -4,7 +4,7 @@ # emits a self-contained server bundle (`output: "standalone"` in # frontend/next.config.ts) instead of the full `.next` tree + node_modules. # ============================================================================ -FROM node:20-alpine@sha256:fb4cd12c85ee03686f6af5362a0b0d56d50c58a04632e6c0fb8363f609372293 AS builder +FROM node:22-alpine@sha256:1314fb30ec37592d5845e5a160d522c0e680972aa534549940b8d73bde88481a AS builder WORKDIR /app @@ -41,7 +41,7 @@ RUN npm run build --workspace frontend # Copies only the traced standalone output (never the workspace node_modules) # and runs as the non-root `node` user that ships with the Alpine base image. # ============================================================================ -FROM node:20-alpine@sha256:fb4cd12c85ee03686f6af5362a0b0d56d50c58a04632e6c0fb8363f609372293 AS runner +FROM node:22-alpine@sha256:1314fb30ec37592d5845e5a160d522c0e680972aa534549940b8d73bde88481a AS runner WORKDIR /app diff --git a/frontend/package.json b/frontend/package.json index f61c6f30..0b963085 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -14,6 +14,9 @@ "test:e2e:headed": "playwright test --headed", "codegen:api-types": "openapi-typescript ../backend/swagger/flowfi.openapi.json -o src/lib/api-types.generated.ts" }, + "engines": { + "node": "^22.22.1" + }, "dependencies": { "@stellar/freighter-api": "^6.0.1", "@stellar/stellar-sdk": "^17.0.1", diff --git a/frontend/src/app/streams/[id]/__tests__/stream-details-content.test.tsx b/frontend/src/app/streams/[id]/__tests__/stream-details-content.test.tsx index 3af3d088..cfb89dc3 100644 --- a/frontend/src/app/streams/[id]/__tests__/stream-details-content.test.tsx +++ b/frontend/src/app/streams/[id]/__tests__/stream-details-content.test.tsx @@ -52,6 +52,12 @@ const { mockToast, mockSoroban, mockTracker, mockUseStreamingAmount, mockTransac resumeStream: vi.fn(), toBaseUnits: vi.fn((v: string) => BigInt(Math.round(parseFloat(v)) * 10_000_000)), toSorobanErrorMessage: vi.fn((e: unknown) => (e instanceof Error ? e.message : String(e))), + // Consumed by the shared token resolver in `@/lib/tokens`. + TOKEN_ADDRESSES: { + USDC: "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA", + XLM: "CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCN", + EURC: "CCWAMYJME4YOIUNAKVYEBYOG5I65QMKEX2NMN4OJAPXRPIF24ONPSHY", + }, }; const mockTracker = { status: "idle" as string, diff --git a/frontend/src/app/streams/[id]/stream-details-content.tsx b/frontend/src/app/streams/[id]/stream-details-content.tsx index 780f17dd..4a2e7c47 100644 --- a/frontend/src/app/streams/[id]/stream-details-content.tsx +++ b/frontend/src/app/streams/[id]/stream-details-content.tsx @@ -31,6 +31,7 @@ import { formatAmount, streamProgressPercent, validateAmountInput } from "@/util import { shortenPublicKey } from "@/lib/wallet"; import { LiquidStreamVisualizer } from "@/components/LiquidStreamVisualizer"; import { TokenAvatar } from "@/components/TokenAvatar"; +import { resolveTokenSymbol } from "@/lib/tokens"; interface StreamDetail { id: string; @@ -56,12 +57,6 @@ interface StreamDetail { const API_BASE_URL = `${getApiBaseUrl()}/v1`; const EVENTS_PER_PAGE = 10; -const TOKEN_SYMBOLS: Record = { - "CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCN": "XLM", - "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA": "USDC", - "CCWAMYJME4YOIUNAKVYEBYOG5I65QMKEX2NMN4OJAPXRPIF24ONPSHY": "EURC", -}; - const EVENT_STYLES: Record = { CREATED: { color: "#22c55e", icon: "✓", label: "Created" }, TOPPED_UP: { color: "#3b82f6", icon: "+", label: "Topped Up" }, @@ -224,7 +219,7 @@ export default function StreamDetailsContent({ streamId }: { streamId: string }) const tokenSymbol = useMemo(() => { if (!stream) return "??"; - return (stream.tokenAddress && TOKEN_SYMBOLS[stream.tokenAddress]) || stream.tokenAddress?.slice(0, 4) || "??"; + return resolveTokenSymbol(stream.tokenAddress) || stream.tokenAddress?.slice(0, 4) || "??"; }, [stream]); const { data: tokenPrice } = useTokenPrice({ tokenSymbol, enabled: Boolean(stream) }); diff --git a/frontend/src/lib/api/streams.ts b/frontend/src/lib/api/streams.ts index d9a596c3..fc5fda6c 100644 --- a/frontend/src/lib/api/streams.ts +++ b/frontend/src/lib/api/streams.ts @@ -1,5 +1,5 @@ import type { BackendStream } from "@/lib/api-types"; -import { TOKEN_ADDRESSES } from "@/lib/soroban"; +import { resolveTokenLabel } from "@/lib/tokens"; import { shortenPublicKey } from "@/lib/wallet"; import { DEFAULT_FETCH_TIMEOUT_MS, @@ -33,14 +33,6 @@ interface StreamListResponse { data?: BackendStream[]; } -function resolveTokenLabel(tokenAddress: string): string { - const entry = Object.entries(TOKEN_ADDRESSES).find( - ([, address]) => address === tokenAddress, - ); - - return entry?.[0] ?? `${tokenAddress.slice(0, 6)}...${tokenAddress.slice(-4)}`; -} - function toIncomingStreamStatus(stream: BackendStream): IncomingStreamStatus { if (stream.isPaused) return "Paused"; if (stream.isActive) return "Active"; diff --git a/frontend/src/lib/dashboard.ts b/frontend/src/lib/dashboard.ts index 448e7185..eb8a0408 100644 --- a/frontend/src/lib/dashboard.ts +++ b/frontend/src/lib/dashboard.ts @@ -1,7 +1,7 @@ import { useQuery } from "@tanstack/react-query"; import type { BackendStream } from "./api-types"; import { getStreamsEndpointCandidates, toTokenAmount } from "./api/_shared"; -import { TOKEN_ADDRESSES } from "./soroban"; +import { resolveTokenLabel } from "./tokens"; import { logger } from "./logger"; export interface ActivityItem { @@ -64,18 +64,6 @@ function shortenAddress(address: string): string { return `${address.slice(0, 6)}...${address.slice(-4)}`; } -/** - * Resolves a token contract address to its symbol (XLM/USDC/EURC), falling - * back to a shortened address when the token is unknown. - */ -function resolveTokenLabel(tokenAddress: string): string { - const entry = Object.entries(TOKEN_ADDRESSES).find( - ([, address]) => address === tokenAddress, - ); - - return entry?.[0] ?? shortenAddress(tokenAddress); -} - /** * Derives the display status from the backend flags. A paused stream reads * "Paused"; an active one "Active". An inactive stream is "Cancelled" when a diff --git a/frontend/src/lib/tokens.test.ts b/frontend/src/lib/tokens.test.ts new file mode 100644 index 00000000..b90453a4 --- /dev/null +++ b/frontend/src/lib/tokens.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest"; +import { TOKEN_ADDRESSES } from "./soroban"; +import { resolveTokenLabel, resolveTokenSymbol } from "./tokens"; + +describe("token symbol resolution", () => { + it("resolves every address in TOKEN_ADDRESSES to its symbol", () => { + for (const [symbol, address] of Object.entries(TOKEN_ADDRESSES)) { + expect(resolveTokenSymbol(address)).toBe(symbol); + expect(resolveTokenLabel(address)).toBe(symbol); + } + }); + + it("returns undefined for unknown or empty addresses", () => { + expect(resolveTokenSymbol("CUNKNOWNTOKENADDRESS000000000000")).toBeUndefined(); + expect(resolveTokenSymbol(undefined)).toBeUndefined(); + expect(resolveTokenSymbol("")).toBeUndefined(); + }); + + it("falls back to a shortened address label for unknown tokens", () => { + expect(resolveTokenLabel("CUNKNOWNTOKENADDRESS0000000000WXYZ")).toBe("CUNKNO...WXYZ"); + }); +}); diff --git a/frontend/src/lib/tokens.ts b/frontend/src/lib/tokens.ts new file mode 100644 index 00000000..bc373afe --- /dev/null +++ b/frontend/src/lib/tokens.ts @@ -0,0 +1,33 @@ +import { TOKEN_ADDRESSES } from "@/lib/soroban"; + +/** + * Single source of truth for token contract address → symbol resolution. + * + * Everything is derived from `TOKEN_ADDRESSES` in `lib/soroban.ts`, so adding a + * new token there (or overriding an address via `NEXT_PUBLIC_*_ADDRESS`) is + * picked up by every surface that renders a token symbol. + */ + +/** Returns the symbol (e.g. "XLM", "USDC") for a known token address, else `undefined`. */ +export function resolveTokenSymbol( + tokenAddress: string | null | undefined, +): string | undefined { + if (!tokenAddress) return undefined; + const entry = Object.entries(TOKEN_ADDRESSES).find( + ([, address]) => address === tokenAddress, + ); + return entry?.[0]; +} + +function shortenTokenAddress(address: string): string { + if (!address || address.length < 10) return address; + return `${address.slice(0, 6)}...${address.slice(-4)}`; +} + +/** + * Resolves a token address to its symbol, falling back to a shortened address + * (e.g. "CABCDE...WXYZ") when the token is unknown. + */ +export function resolveTokenLabel(tokenAddress: string): string { + return resolveTokenSymbol(tokenAddress) ?? shortenTokenAddress(tokenAddress); +} diff --git a/package-lock.json b/package-lock.json index 665c1fee..e68b999a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -30,6 +30,9 @@ "lightningcss-darwin-arm64": "^1.31.1", "lightningcss-darwin-x64": "^1.32.0", "lightningcss-linux-x64-gnu": "^1.31.1" + }, + "engines": { + "node": "^22.22.1" } }, "backend": { @@ -81,6 +84,9 @@ "tsx": "^4.19.2", "typescript": "^5.9.3", "vitest": "^3.2.4" + }, + "engines": { + "node": "^22.22.1" } }, "backend/node_modules/@noble/hashes": { @@ -186,6 +192,9 @@ "tailwindcss": "^4", "typescript": "^5", "vitest": "^3.2.7" + }, + "engines": { + "node": "^22.22.1" } }, "frontend/node_modules/@noble/hashes": { diff --git a/package.json b/package.json index 92286947..4038e0e6 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,9 @@ "dev:mock:seed": "cd backend && npm run prisma:generate && DATABASE_URL=postgresql://flowfi:flowfi_dev_password@localhost:5433/flowfi npx prisma db push --accept-data-loss && cd .. && DATABASE_URL=postgresql://flowfi:flowfi_dev_password@localhost:5433/flowfi npx tsx scripts/seed-mock-data.ts", "dev:mock:start": "echo \"\\n✅ Mock sandbox ready — starting services...\\n Backend: http://localhost:3001\\n Frontend: http://localhost:3000\\n API docs: http://localhost:3001/api-docs\\n\" && concurrently --kill-others --names backend,frontend --prefix-colors cyan,magenta \"cd backend && SANDBOX_MODE_ENABLED=true SOROBAN_RPC_URL=http://localhost:8000 DATABASE_URL=postgresql://flowfi:flowfi_dev_password@localhost:5433/flowfi REDIS_URL=redis://localhost:6379 npm run dev\" \"cd frontend && NEXT_PUBLIC_API_URL=http://localhost:3001 npm run dev\"" }, + "engines": { + "node": "^22.22.1" + }, "devDependencies": { "@vitest/coverage-v8": "^3.2.7", "concurrently": "^9.1.2", diff --git a/render.yaml b/render.yaml index 4c7b3688..05596470 100644 --- a/render.yaml +++ b/render.yaml @@ -1,16 +1,31 @@ +# Render Blueprint — https://render.com/docs/blueprint-spec +# +# Deploy lifecycle for flowfi-backend (each step runs exactly once per deploy): +# 1. buildCommand install deps, generate the Prisma client, compile TS +# 2. preDeployCommand verify required env vars, then run database migrations +# (`prisma migrate deploy`). This is the ONLY place +# migrations run; if it fails the deploy is aborted and +# the previous release keeps serving traffic. +# 3. startCommand start the server (no migrations here) +# +# Note: preDeployCommand requires a paid instance type on Render. services: - type: web name: flowfi-backend - env: node - entrypoint: npm run start + runtime: node rootDir: backend - autoDeploy: true + autoDeployTrigger: commit buildCommand: npm ci && npm run prisma:generate && npm run build - startCommand: npm run prisma:deploy && npm run start + preDeployCommand: >- + : "${STREAM_CONTRACT_ID:?STREAM_CONTRACT_ID is required - set it in the Render dashboard}" + && : "${ADMIN_PUBLIC_KEY:?ADMIN_PUBLIC_KEY is required - set it in the Render dashboard}" + && npm run prisma:deploy + startCommand: npm run start healthCheckPath: /health envVars: + # Keep in sync with .nvmrc and the "engines" field in package.json. - key: NODE_VERSION - value: 20 + value: "22" - key: NODE_ENV value: production - key: PORT @@ -40,15 +55,19 @@ services: - key: SOROBAN_RPC_URL value: https://soroban-testnet.stellar.org + # REQUIRED — Render prompts for this when the Blueprint is created, and + # the preDeployCommand aborts the deploy if it is unset or empty. - key: STREAM_CONTRACT_ID - value: "" # REQUIRED: Set to your deployed contract ID (starts with C...) + sync: false # Deployed stream contract ID (starts with C...) - key: KEEPER_SECRET_KEY sync: false # Sensitive: Stellar secret key (S...) for signing on-chain top-ups # ─── Admin & Security (Required for admin endpoints) ────────────────── + # REQUIRED — Render prompts for this when the Blueprint is created, and + # the preDeployCommand aborts the deploy if it is unset or empty. - key: ADMIN_PUBLIC_KEY - value: "" # REQUIRED: Stellar public key (G...) of the authorized admin + sync: false # Stellar public key (G...) of the authorized admin # ─── Optional Configuration ─────────────────────────────────────────── - key: REDIS_URL diff --git a/scripts/db-restore.sh b/scripts/db-restore.sh index 56863948..afbdb327 100644 --- a/scripts/db-restore.sh +++ b/scripts/db-restore.sh @@ -1,17 +1,73 @@ #!/usr/bin/env bash +# Restore an encrypted FlowFi backup (produced by scripts/db-backup.sh) into a +# PostgreSQL database. See docs/DISASTER_RECOVERY.md for the full runbook. +# +# Usage: +# bash scripts/db-restore.sh [options] +# +# Options: +# --dry-run Decrypt and validate the backup, inspect the target database +# and report what would happen. Nothing is written. +# --force Allow restoring over a NON-EMPTY database. All user schemas +# in the target are dropped and replaced by the backup. A +# pre-restore snapshot is taken first (see --snapshot-dir). +# --yes Skip the interactive confirmation that --force requires. +# Needed when --force is used without a TTY (e.g. in CI). +# --snapshot-dir Directory for the pre-restore snapshot +# (default: $RESTORE_SNAPSHOT_DIR or ./restore-snapshots). +# -h, --help Show this help. +# +# Safety guarantees: +# * A non-empty target database is refused unless --force is given. +# * The schema wipe (with --force), the SQL restore and the row-count +# verification all run inside ONE transaction (psql --single-transaction). +# If any step fails, PostgreSQL rolls everything back and the target is +# left exactly as it was before the script ran. +# +# Exit codes: +# 0 success (or dry-run completed) 2 usage error +# 1 restore/validation failure 3 refused: target database is not empty set -euo pipefail umask 077 SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" -: "${DATABASE_URL:?DATABASE_URL must point to the empty PostgreSQL database to restore}" -: "${BACKUP_ENCRYPTION_KEY:?BACKUP_ENCRYPTION_KEY must be a 32-byte hex key}" -backup_file="${1:-${BACKUP_FILE:-}}" -: "${backup_file:?Pass the encrypted .tar.gz.enc backup path as an argument or set BACKUP_FILE}" -[[ -f "$backup_file" ]] || { echo "Backup file does not exist: $backup_file" >&2; exit 1; } -command -v psql >/dev/null || { echo "psql is required" >&2; exit 1; } -command -v tar >/dev/null || { echo "tar is required" >&2; exit 1; } -command -v gzip >/dev/null || { echo "gzip is required" >&2; exit 1; } +usage() { sed -n '2,/^set -euo pipefail$/{/^set -euo/d;s/^# \{0,1\}//;p;}' "${BASH_SOURCE[0]}"; } +die() { echo "db-restore: $*" >&2; exit 1; } + +dry_run=false +force=false +assume_yes=false +snapshot_dir="${RESTORE_SNAPSHOT_DIR:-./restore-snapshots}" +backup_file="${BACKUP_FILE:-}" + +while [[ $# -gt 0 ]]; do + case "$1" in + --dry-run) dry_run=true ;; + --force) force=true ;; + --yes|-y) assume_yes=true ;; + --snapshot-dir) + [[ $# -ge 2 ]] || { echo "--snapshot-dir requires a path" >&2; exit 2; } + snapshot_dir="$2"; shift ;; + --snapshot-dir=*) snapshot_dir="${1#*=}" ;; + -h|--help) usage; exit 0 ;; + --) shift; [[ $# -gt 0 ]] && backup_file="$1"; break ;; + -*) echo "Unknown option: $1 (see --help)" >&2; exit 2 ;; + *) backup_file="$1" ;; + esac + shift +done + +: "${DATABASE_URL:?DATABASE_URL must point to the PostgreSQL database to restore into}" +: "${BACKUP_ENCRYPTION_KEY:?BACKUP_ENCRYPTION_KEY must be a 32-byte hex key}" +[[ -n "$backup_file" ]] || { echo "Pass the encrypted .tar.gz.enc backup path as an argument or set BACKUP_FILE" >&2; exit 2; } +[[ -f "$backup_file" ]] || die "backup file does not exist: $backup_file" +for tool in psql tar gzip node; do + command -v "$tool" >/dev/null || die "$tool is required" +done +if [[ "$force" == true && "$dry_run" == false ]]; then + command -v pg_dump >/dev/null || die "pg_dump is required to take the pre-restore snapshot" +fi work_dir="$(mktemp -d)" trap 'rm -rf -- "$work_dir"' EXIT @@ -21,23 +77,158 @@ export PGSERVICEFILE="$work_dir/pg_service.conf" export PGSERVICE=flowfi_backup unset DATABASE_URL -# Authentication is checked before any SQL is sent to PostgreSQL. +# ── 1. Decrypt and validate the backup (no SQL is sent before this passes) ── node "$SCRIPT_DIR/backup-crypto.mjs" decrypt < "$backup_file" > "$work_dir/payload.tar.gz" gzip -t "$work_dir/payload.tar.gz" -tar -xzf "$work_dir/payload.tar.gz" -C "$work_dir" -[[ -s "$work_dir/database.sql" && -f "$work_dir/manifest.tsv" ]] || { - echo "Backup archive is missing its dump or integrity manifest" >&2 - exit 1 -} - -psql -X -v ON_ERROR_STOP=1 -f "$work_dir/database.sql" +mkdir "$work_dir/backup" +tar -xzf "$work_dir/payload.tar.gz" -C "$work_dir/backup" +[[ -s "$work_dir/backup/database.sql" && -f "$work_dir/backup/manifest.tsv" ]] || \ + die "backup archive is missing its dump or integrity manifest" +# Validate the manifest strictly: its contents are interpolated into SQL below. +manifest_tables=0 +manifest_rows=0 while IFS=$'\t' read -r table expected; do [[ -n "$table" ]] || continue - actual="$(psql -XAt -v ON_ERROR_STOP=1 -c "SELECT count(*) FROM $table")" - if [[ "$actual" != "$expected" ]]; then - printf 'Row count mismatch for %s: backup=%s restored=%s\n' "$table" "$expected" "$actual" >&2 - exit 1 + [[ "$table" =~ ^[A-Za-z0-9_\"]+\.[A-Za-z0-9_\"]+$ && "$expected" =~ ^[0-9]+$ ]] || \ + die "backup manifest contains an invalid entry: $table" + manifest_tables=$((manifest_tables + 1)) + manifest_rows=$((manifest_rows + expected)) +done < "$work_dir/backup/manifest.tsv" + +# ── 2. Inspect the target database ── +target="$(psql -XAt -v ON_ERROR_STOP=1 -c "SELECT current_database() || ' on ' || coalesce(inet_server_addr()::text, 'local socket')")" + +# User-created objects that would collide with the dump: relations, sequences, +# views, user types and functions outside the system schemas. Objects owned by +# extensions (e.g. plpgsql) are ignored. +existing_objects="$(psql -XAt -v ON_ERROR_STOP=1 <<'SQL' +WITH user_ns AS ( + SELECT oid FROM pg_namespace + WHERE nspname NOT IN ('pg_catalog', 'information_schema') + AND nspname NOT LIKE 'pg\_toast%' AND nspname NOT LIKE 'pg\_temp%' +), ext_owned AS ( + SELECT objid FROM pg_depend WHERE deptype = 'e' +) +SELECT + (SELECT count(*) FROM pg_class c + WHERE c.relnamespace IN (SELECT oid FROM user_ns) + AND c.relkind IN ('r','p','v','m','S','f') + AND c.oid NOT IN (SELECT objid FROM ext_owned)) ++ (SELECT count(*) FROM pg_type t + WHERE t.typnamespace IN (SELECT oid FROM user_ns) + AND t.typtype IN ('e','d','c') AND t.typrelid = 0 + AND t.oid NOT IN (SELECT objid FROM ext_owned)) ++ (SELECT count(*) FROM pg_proc p + WHERE p.pronamespace IN (SELECT oid FROM user_ns) + AND p.oid NOT IN (SELECT objid FROM ext_owned)); +SQL +)" +[[ "$existing_objects" =~ ^[0-9]+$ ]] || die "could not inspect the target database" + +if [[ "$existing_objects" -eq 0 ]]; then + plan="restore into the empty database" +elif [[ "$force" == true ]]; then + plan="take a pre-restore snapshot, DROP all user schemas, then restore (--force)" +else + plan="REFUSE: the database is not empty (re-run with --force to replace it)" +fi + +cat <&2 + echo "provisioned database, or pass --force to replace its contents." >&2 + exit 3 +fi + +# ── 3. Forced restore: confirm and snapshot the current contents first ── +if [[ "$existing_objects" -ne 0 ]]; then + if [[ "$assume_yes" != true ]]; then + [[ -t 0 ]] || die "--force requires interactive confirmation; pass --yes to skip it" + db_name="${target%% on *}" + read -r -p "This will DELETE all data in '$db_name'. Type the database name to continue: " reply + [[ "$reply" == "$db_name" ]] || die "confirmation did not match; aborting without changes" fi -done < "$work_dir/manifest.tsv" -echo "Restore completed and all recorded public table row counts matched." \ No newline at end of file + + # The snapshot uses the same encrypted format as db-backup.sh, so it can be + # restored with this script: db-restore.sh --force . + mkdir -p "$snapshot_dir" + snap="$work_dir/snapshot" + mkdir "$snap" + psql -XAt -v ON_ERROR_STOP=1 \ + -c "SELECT quote_ident(schemaname) || '.' || quote_ident(tablename) FROM pg_tables WHERE schemaname = 'public' ORDER BY tablename" \ + > "$snap/tables.txt" + : > "$snap/manifest.tsv" + while IFS= read -r table; do + [[ -n "$table" ]] || continue + count="$(psql -XAt -v ON_ERROR_STOP=1 -c "SELECT count(*) FROM $table")" + printf '%s\t%s\n' "$table" "$count" >> "$snap/manifest.tsv" + done < "$snap/tables.txt" + pg_dump --no-owner --no-acl --format=plain > "$snap/database.sql" + snapshot_file="${snapshot_dir%/}/pre-restore-$(date -u +%Y%m%dT%H%M%SZ)-$$.tar.gz.enc" + tar -C "$snap" -cf - database.sql manifest.tsv | gzip -c | \ + node "$SCRIPT_DIR/backup-crypto.mjs" encrypt > "$snapshot_file" + echo "Pre-restore snapshot written: $snapshot_file" +fi + +# ── 4. Restore + verify in a single transaction ── +plan_sql="$work_dir/restore.sql" +{ + echo '\set ON_ERROR_STOP on' + if [[ "$existing_objects" -ne 0 ]]; then + # Drop every user schema (and everything in it), then recreate an empty + # public schema for the dump to populate. + cat <<'SQL' +DO $wipe$ +DECLARE s text; +BEGIN + FOR s IN + SELECT nspname FROM pg_namespace + WHERE nspname NOT IN ('pg_catalog', 'information_schema') + AND nspname NOT LIKE 'pg\_%' + LOOP + EXECUTE format('DROP SCHEMA %I CASCADE', s); + END LOOP; + CREATE SCHEMA public; +END +$wipe$; +SQL + fi + printf '\\i %s\n' "$work_dir/backup/database.sql" + # Row-count checks run inside the transaction, so a mismatch rolls back the + # whole restore instead of leaving unverified data behind. + while IFS=$'\t' read -r table expected; do + [[ -n "$table" ]] || continue + cat < $expected THEN + RAISE EXCEPTION 'Row count mismatch for %: backup=% restored=%', '$table', $expected, actual; + END IF; +END +\$verify\$; +SQL + done < "$work_dir/backup/manifest.tsv" +} > "$plan_sql" + +if ! psql -X --single-transaction -v ON_ERROR_STOP=1 -q -f "$plan_sql" > "$work_dir/psql.log" 2>&1; then + cat "$work_dir/psql.log" >&2 + echo "Restore FAILED and was rolled back: the target database is unchanged." >&2 + [[ -n "${snapshot_file:-}" ]] && echo "A pre-restore snapshot is also available: $snapshot_file" >&2 + exit 1 +fi +echo "Restore completed and all $manifest_tables recorded public table row counts matched." diff --git a/scripts/pg-service.mjs b/scripts/pg-service.mjs index f2d0adc1..18201924 100644 --- a/scripts/pg-service.mjs +++ b/scripts/pg-service.mjs @@ -19,6 +19,12 @@ if (sslmode) entries.push(["sslmode", sslmode]); for (const [key, value] of entries) { if (/[\r\n]/.test(value)) throw new Error(`Invalid newline in PostgreSQL ${key}`); } -const escape = (value) => `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`; -const contents = `[flowfi_backup]\n${entries.map(([key, value]) => `${key}=${escape(value)}`).join("\n")}\n`; +// libpq service files are plain `key=value` lines: values are taken verbatim +// (only surrounding whitespace is trimmed) and quotes are NOT stripped, so +// quoting them would make libpq read e.g. port as the literal "'5432'". +// Newlines are rejected above, which is the only way to break out of a line. +for (const [key, value] of entries) { + if (value !== value.trim()) throw new Error(`PostgreSQL ${key} must not have leading/trailing whitespace`); +} +const contents = `[flowfi_backup]\n${entries.map(([key, value]) => `${key}=${value}`).join("\n")}\n`; writeFileSync(output, contents, { mode: 0o600, flag: "wx" }); \ No newline at end of file