// Node.js >=22, no third-party dependencies. Single demo trader only.
// Production platforms must replace Basic auth with their verified user/session
// and persist user ownership + API order ID in a transactional database.
import http from 'node:http';
import {createHash, createHmac, timingSafeEqual} from 'node:crypto';
import {readFile, mkdir, writeFile, rename} from 'node:fs/promises';
import path from 'node:path';
const required = name => {
const value = process.env[name];
if (!value) throw new Error(`Missing ${name}`);
return value;
};
const base = new URL(required('QR_API_BASE').replace(/\/$/, ''));
if (base.protocol !== 'https:' || base.pathname !== '/api/v1' || base.username ||
base.password || base.search || base.hash) throw new Error('Invalid HTTPS API base');
const key = required('QR_API_KEY');
const siteUser = required('SITE_USERNAME');
const sitePassword = required('SITE_PASSWORD');
const siteOrigin = new URL(required('SITE_ORIGIN')).origin;
if (!siteOrigin.startsWith('https://')) throw new Error('SITE_ORIGIN must use HTTPS');
const webhookSecret = required('QR_WEBHOOK_SECRET');
const filename = process.env.PRIVATE_STATE_FILE ?? 'private/qr-state.json';
await mkdir(path.dirname(filename), {recursive: true, mode: 0o700});
let state;
try { state = JSON.parse(await readFile(filename, 'utf8')); }
catch (error) {
if (error.code !== 'ENOENT') throw new Error('Private state could not be read');
state = {orders: {}, seen: {}, latest: {}};
}
let persistence = Promise.resolve();
const persist = () => {
const operation = persistence.catch(() => {}).then(async () => {
const temporary = filename + '.tmp';
await writeFile(temporary, JSON.stringify(state), {mode: 0o600, flush: true});
await rename(temporary, filename);
});
persistence = operation;
return operation;
};
async function bytes(stream, limit) {
const parts = [];
let size = 0;
for await (const chunk of stream) {
size += chunk.length;
if (size > limit) throw new Error('Body exceeds size limit');
parts.push(Buffer.from(chunk));
}
return Buffer.concat(parts);
}
async function upstream(method, endpoint, body, idempotencyKey, image = false) {
// The API origin is configuration, never a URL supplied by a browser/webhook.
const uri = new URL(base.href + endpoint);
if (uri.origin !== base.origin || !uri.pathname.startsWith('/api/v1/')) throw new Error('Unsafe API URL');
const response = await fetch(uri, {method, redirect: 'error',
signal: AbortSignal.timeout(30000), headers: {
Authorization: `Bearer ${key}`, Accept: image ? 'image/png' : 'application/json',
...(body ? {'Content-Type': 'application/json'} : {}),
...(idempotencyKey ? {'Idempotency-Key': idempotencyKey} : {})},
body: body ? JSON.stringify(body) : undefined});
const content = await bytes(response.body, image ? 10 * 1024 * 1024 : 1024 * 1024);
if (!response.ok) {
const error = new Error('API request failed');
error.status = response.status;
try { error.code = JSON.parse(content).error.code; } catch {}
throw error; // do not log request headers, secret or upstream raw body
}
if (image) {
if (response.headers.get('content-type')?.split(';')[0] !== 'image/png' ||
!content.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10]))) {
throw new Error('Invalid QR image');
}
return content;
}
return JSON.parse(content);
}
function authorized(request) {
const actual = request.headers.authorization ?? '';
const expected = 'Basic ' + Buffer.from(`${siteUser}:${sitePassword}`).toString('base64');
return timingSafeEqual(createHash('sha256').update(actual).digest(),
createHash('sha256').update(expected).digest());
}
function json(response, status, value) {
response.writeHead(status, {'Content-Type': 'application/json', 'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff'}).end(JSON.stringify(value));
}
const page = `
Получение QR
Получить QR
Обязательно проверьте корректность введённых данных. В случае предоставления фейковых данных ваш кабинет и баланс будут заморожены. ФИО указывайте полностью, без сокращений. Для каждой заявки указывайте фактического плательщика.
Перейти к оплате
`;
async function webhook(request, response) {
const raw = await bytes(request, 65536);
const timestamp = request.headers['x-qr-timestamp'] ?? '';
const signature = request.headers['x-qr-signature'] ?? '';
const now = Math.floor(Date.now() / 1000);
if (!/^\d+$/.test(timestamp) || Math.abs(now - Number(timestamp)) > 300 ||
!/^sha256=[a-f0-9]{64}$/.test(signature)) return json(response, 401, {error: 'invalid_signature'});
const expected = 'sha256=' + createHmac('sha256', webhookSecret).update(timestamp + '.').update(raw).digest('hex');
if (!timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) return json(response, 401, {error: 'invalid_signature'});
const event = JSON.parse(raw);
if (event.id !== request.headers['x-qr-event-id'] || event.type !== 'order.updated' ||
!Number.isSafeInteger(event.sequence) || event.sequence < 1 || typeof event.data?.id !== 'string') {
return json(response, 400, {error: 'invalid_event'});
}
// Persist before 2xx. Multiple workers need DB unique(event_id) and an atomic
// conditional sequence update in the same transaction as business credit.
if (!Object.hasOwn(state.seen, event.id)) {
state.seen[event.id] = event.created_at;
if (!state.latest[event.data.id] || state.latest[event.data.id].sequence < event.sequence) {
state.latest[event.data.id] = {sequence: event.sequence, data: event.data};
}
}
await persist();
response.writeHead(204).end();
}
const server = http.createServer(async (request, response) => {
try {
const route = new URL(request.url, 'http://localhost');
if (request.method === 'POST' && route.pathname === '/qr-webhook') return await webhook(request, response);
if (!authorized(request)) {
response.writeHead(401, {'WWW-Authenticate': 'Basic realm="Demo trader"'}).end();
return;
}
if (request.method === 'GET' && route.pathname === '/') {
response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff'}).end(page);
return;
}
if (request.method === 'POST' && route.pathname === '/orders') {
if (request.headers.origin && request.headers.origin !== siteOrigin) {
return json(response, 403, {error: 'invalid_origin'});
}
const input = JSON.parse(await bytes(request, 16384));
const local = input.client_order_id;
if (typeof local !== 'string' || !/^[a-f0-9-]{36}$/.test(local)) return json(response, 422, {error: 'invalid_order'});
const body = {external_id: `site:${local}`, full_name: input.full_name, bank: input.bank, amount_rub: input.amount_rub};
const previous = state.orders[local];
if (previous && (previous.owner !== siteUser || JSON.stringify(previous.body) !== JSON.stringify(body))) {
return json(response, 409, {error: 'order_data_changed'});
}
state.orders[local] ??= {owner: siteUser, body};
await persist(); // preserves identity even if POST times out
const result = await upstream('POST', '/orders', body, `site:${local}`);
state.orders[local].api_id = result.id;
await persist();
return json(response, 202, result);
}
const match = route.pathname.match(/^\/orders\/([a-f0-9-]{36})(\/qr)?$/);
if (request.method === 'GET' && match) {
const own = state.orders[match[1]];
if (!own || own.owner !== siteUser) return json(response, 404, {error: 'not_found'});
// Recover a lost create response using the SAME body and key.
if (!own.api_id) {
const recovered = await upstream('POST', '/orders', own.body, `site:${match[1]}`);
own.api_id = recovered.id;
await persist();
}
const order = await upstream('GET', `/orders/${own.api_id}`);
if (match[2]) {
const expected = `/api/v1/orders/${own.api_id}/qr`;
if (order.status !== 'ready' || order.qr_url !== expected) return json(response, 409, {error: 'qr_unavailable'});
const png = await upstream('GET', `/orders/${own.api_id}/qr`, null, null, true);
response.writeHead(200, {'Content-Type': 'image/png', 'Cache-Control': 'private, no-store'}).end(png);
return;
}
return json(response, 200, order);
}
json(response, 404, {error: 'not_found'});
} catch (error) {
// Raw fetch errors can include URLs. Return only a bounded stable code.
const code = /^[a-z][a-z0-9_]{0,63}$/.test(error.code ?? '') ? error.code : 'temporarily_unavailable';
json(response, error.status >= 400 && error.status <= 599 ? error.status : 503, {error: code});
}
});
server.requestTimeout = 15000;
server.listen(Number(process.env.PORT ?? 8080), '127.0.0.1', () => {
console.log('Demo backend listening on loopback; publish behind an HTTPS reverse proxy.');
});