ci/cd(backend): offline test suite + Dockerize + audit-grade deploy (b + c)

Closes the "backend has zero CI + manual SSH deploy" audit finding for the indexer.

Part B — CI-runnable tests (the integration-tests/*.live.test.js need a live chain and
are excluded, not stubbed): extract injectable cores (indexer.js: DB+HTTP+decode, no
@pezkuwi import; council.js: createApp factory for the council/KYC routes). New node:test
suite (19/19, fully offline) — in-memory sqlite, dependency-injected chain stub, an
in-memory fake-supabase, and REAL @pezkuwi keyring signatures proving 401 bad-sig /
400 msg-mismatch / 200 valid / 409 dup / 403 non-member / threshold auto-execute. Backend
job now runs npm ci + npm test and is in ci-gate (failing tests block merge). Fixed a
latent bug: block indexing now awaits each insert (was fire-and-forget forEach). Added
runtime deps server.js imported but were missing from package.json (@supabase/supabase-js,
pino, pino-http) — server.js could not have `npm ci`-run before.

Part C — Dockerfile (non-root, HEALTHCHECK /health, sqlite state on a /data VOLUME kept
out of the image) + backend deploy pipeline mirroring the web one: build+push to GHCR,
cosign keyless sign + verify, ssh deploy with the DB volume preserved across deploys,
/health poll, auto-rollback to previous SHA, same Telegram CEO approval gate, main/tags
only, never fork PRs. New secrets documented in backend/DEPLOY.md (BACKEND_VPS_HOST/USER/
SSH_KEY). DB_PATH env (default ./transactions.db) lets prod point at the volume.

Note for owner: if server.js (council/KYC bootstrap) is legacy/unused, its newly-added
deps can be dropped instead.
This commit is contained in:
Satoshi Qazi Muhammed committed 2026-07-25 11:01:47 -07:00
1 parent 20a5602167
commit 80d273ff11
14 files changed
+1847 -324

No files matched your search

+32 -124
View File
@@ -1,134 +1,42 @@
import express from 'express';
import cors from 'cors';
import { open } from 'sqlite';
import sqlite3 from 'sqlite3';
import { ApiPromise, WsProvider } from '@pezkuwi/api';
import dotenv from 'dotenv';
// Indexer service bootstrap.
//
// Thin wiring layer: connects to the live chain and feeds decoded blocks into
// the injectable core in ./indexer.js (which holds all the DB + HTTP logic and
// is unit-tested offline). Keeping the @pezkuwi/api connection isolated here
// means the testable core never touches the network.
dotenv.config();
import { ApiPromise, WsProvider } from '@pezkuwi/api'
import dotenv from 'dotenv'
import { initDb, indexBlock, createApp } from './indexer.js'
const app = express();
const port = process.env.PORT || 3001;
const WS_ENDPOINT = process.env.WS_ENDPOINT || 'wss://rpc.pezkuwichain.io';
dotenv.config()
app.use(cors());
app.use(express.json());
// Initialize Database
async function initDb() {
const db = await open({
filename: './transactions.db',
driver: sqlite3.Database
});
await db.exec(`
CREATE TABLE IF NOT EXISTS transfers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
hash TEXT UNIQUE,
sender TEXT,
receiver TEXT,
amount TEXT,
asset_id INTEGER DEFAULT NULL,
symbol TEXT,
block_number INTEGER,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
return db;
}
const port = process.env.PORT || 3001
const WS_ENDPOINT = process.env.WS_ENDPOINT || 'wss://rpc.pezkuwichain.io'
// Start Indexing
async function startIndexer(db) {
console.log(`Connecting to Pezkuwi Node: ${WS_ENDPOINT}`);
const provider = new WsProvider(WS_ENDPOINT);
const api = await ApiPromise.create({ provider });
async function startIndexer (db) {
console.log(`Connecting to Pezkuwi Node: ${WS_ENDPOINT}`)
const provider = new WsProvider(WS_ENDPOINT)
const api = await ApiPromise.create({ provider })
console.log('Connected! Listening for new blocks...');
console.log('Connected! Listening for new blocks...')
api.rpc.chain.subscribeNewHeads(async (header) => {
const blockNumber = header.number.toNumber();
const blockHash = await api.rpc.chain.getBlockHash(blockNumber);
const signedBlock = await api.rpc.chain.getBlock(blockHash);
signedBlock.block.extrinsics.forEach(async (ex) => {
const { method: { method, section }, signer } = ex;
// 1. Handle Native HEZ Transfers
if (section === 'balances' && (method === 'transfer' || method === 'transferKeepAlive')) {
const [dest, value] = ex.method.args;
await saveTransfer(db, {
hash: ex.hash.toHex(),
sender: signer.toString(),
receiver: dest.toString(),
amount: value.toString(),
asset_id: null,
symbol: 'HEZ',
block_number: blockNumber
});
}
// 2. Handle Asset Transfers (PEZ, USDT)
if (section === 'assets' && method === 'transfer') {
const [id, dest, value] = ex.method.args;
const assetId = id.toNumber();
const symbol = assetId === 1 ? 'PEZ' : assetId === 1000 ? 'USDT' : `ASSET-${assetId}`;
await saveTransfer(db, {
hash: ex.hash.toHex(),
sender: signer.toString(),
receiver: dest.toString(),
amount: value.toString(),
asset_id: assetId,
symbol: symbol,
block_number: blockNumber
});
}
});
});
}
async function saveTransfer(db, tx) {
try {
await db.run(
`INSERT OR IGNORE INTO transfers (hash, sender, receiver, amount, asset_id, symbol, block_number)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
[tx.hash, tx.sender, tx.receiver, tx.amount, tx.asset_id, tx.symbol, tx.block_number]
);
console.log(`Indexed ${tx.symbol} Transfer: ${tx.hash.slice(0, 10)}...`);
} catch (err) {
console.error('DB Insert Error:', err);
}
}
// API Routes
async function startServer(db) {
app.get('/api/history/:address', async (req, res) => {
const { address } = req.params;
try {
const history = await db.all(
`SELECT * FROM transfers
WHERE sender = ? OR receiver = ?
ORDER BY block_number DESC LIMIT 50`,
[address, address]
);
res.json(history);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.get('/api/stats', async (req, res) => {
const stats = await db.get('SELECT COUNT(*) as total FROM transfers');
res.json(stats);
});
app.listen(port, () => {
console.log(`Indexer API running at http://localhost:${port}`);
});
api.rpc.chain.subscribeNewHeads(async (header) => {
const blockNumber = header.number.toNumber()
const blockHash = await api.rpc.chain.getBlockHash(blockNumber)
const signedBlock = await api.rpc.chain.getBlock(blockHash)
await indexBlock(db, signedBlock, blockNumber)
})
}
// Launch
const db = await initDb();
startIndexer(db);
startServer(db);
// DB_PATH lets the deploy point the stateful sqlite file at a mounted volume
// (e.g. /data/transactions.db); defaults to the historical ./transactions.db.
const db = await initDb(process.env.DB_PATH || './transactions.db')
startIndexer(db)
const app = createApp(db)
app.listen(port, () => {
console.log(`Indexer API running at http://localhost:${port}`)
})