import { createHash, createHmac, randomBytes } from 'node:crypto';
import { open } from 'node:fs/promises';
import { basename } from 'node:path';
import { parseArgs } from 'node:util';
const usage = `Usage: node request.mjs [METHOD REQUEST_TARGET] [--json FILE | --file FILE --file-type TYPE] [--idempotency-key KEY]
Default: GET /api/v3/private/ping
Environment: EXCHANGER_API_ORIGIN, EXCHANGER_API_TOKEN, EXCHANGER_API_HMAC_SECRET`;
function encodeComponent(value) {
return encodeURIComponent(value).replace(/[!'()*]/g, (character) =>
`%${character.charCodeAt(0).toString(16).toUpperCase()}`,
);
}
function canonicalQuery(search) {
if (!search) {
return '';
}
const entries = search.slice(1).split('&');
if (entries.length > 50) {
throw new Error('The example accepts at most 50 query fields.');
}
const names = [];
const pairs = [];
for (const entry of entries) {
const separator = entry.indexOf('=');
if (separator < 1 || entry.includes(';')) {
throw new Error('Use name=value query pairs separated by &. Encode a literal semicolon as %3B.');
}
const name = decodeURIComponent(entry.slice(0, separator).replaceAll('+', ' '));
const value = decodeURIComponent(entry.slice(separator + 1).replaceAll('+', ' '));
if (!/^[A-Za-z0-9_-]+(?:\[[A-Za-z0-9_-]+\]){0,6}$/.test(name)) {
throw new Error('Use query names such as filter[status_id][0], with explicit indexes for lists.');
}
if (names.some((previous) => name === previous || name.startsWith(`${previous}[`) || previous.startsWith(`${name}[`))) {
throw new Error('Give each query field a unique name and avoid scalar and nested forms of the same name.');
}
names.push(name);
pairs.push(`${encodeComponent(name)}=${encodeComponent(value)}`);
}
return pairs.sort().join('&');
}
async function readRequestFile(filename, limit, sizeLabel) {
const file = await open(filename, 'r');
try {
const stat = await file.stat();
if (!stat.isFile() || stat.size < 1 || stat.size > limit) {
throw new Error(`Use a nonempty local file of at most ${sizeLabel}.`);
}
const buffer = Buffer.alloc(stat.size + 1);
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
if (bytesRead !== stat.size) {
throw new Error('Could not read the file at its original size.');
}
return buffer.subarray(0, bytesRead);
} finally {
await file.close();
}
}
async function jsonBytes(filename) {
const bytes = await readRequestFile(filename, 1_048_576, '1 MiB');
try {
JSON.parse(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes));
} catch {
throw new Error('Use a valid UTF-8 JSON file without a byte order mark.');
}
return bytes;
}
async function request() {
const { values, positionals } = parseArgs({
allowPositionals: true,
options: {
json: { type: 'string' },
file: { type: 'string' },
'file-type': { type: 'string' },
'idempotency-key': { type: 'string' },
help: { type: 'boolean' },
},
});
if (values.help) {
console.error(usage);
return;
}
if (positionals.length !== 0 && positionals.length !== 2) {
throw new Error(usage);
}
const [method = 'GET', target = '/api/v3/private/ping'] = positionals;
if (!['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
throw new Error('Use an uppercase GET, POST, PUT, PATCH, or DELETE method.');
}
const hasJson = values.json !== undefined;
const hasFile = values.file !== undefined;
const fileType = values['file-type'];
if (hasJson && hasFile) {
throw new Error('Choose either --json or --file.');
}
if (method === 'GET' && hasJson) {
throw new Error('Use --json only with a method that supports a request body.');
}
if (hasFile && (method !== 'POST' || !fileType || !/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i.test(fileType))) {
throw new Error('Use --file with POST and set --file-type, for example application/pdf.');
}
if (!hasFile && fileType !== undefined) {
throw new Error('Use --file-type together with --file.');
}
const { EXCHANGER_API_ORIGIN: address, EXCHANGER_API_TOKEN: token, EXCHANGER_API_HMAC_SECRET: secret } = process.env;
if (!address || !token || !secret || !/^[!-~]+$/.test(token)) {
throw new Error('Set EXCHANGER_API_ORIGIN, EXCHANGER_API_TOKEN, and EXCHANGER_API_HMAC_SECRET.');
}
const origin = new URL(address);
if (origin.protocol !== 'https:' || origin.href !== `${origin.origin}/`) {
throw new Error('Use the direct HTTPS origin of your exchanger, without a path, credentials, or parameters.');
}
if (!target.startsWith('/api/v3/private/') || /[\u0000-\u0020\u007f#\\]/.test(target)) {
throw new Error('Use an origin-relative /api/v3/private/ path with an optional percent-encoded query.');
}
const url = new URL(target, origin);
if (url.pathname !== target.split('?', 1)[0] || url.pathname.includes('//')) {
throw new Error('Use the exact API path without relative segments or repeated slashes.');
}
const query = canonicalQuery(url.search);
const suppliedKey = values['idempotency-key'];
const key = suppliedKey?.trim() ?? '';
if (suppliedKey !== undefined && !/^[A-Za-z0-9._:-]{8,191}$/.test(key)) {
throw new Error('Use an idempotency key of 8 to 191 characters from A-Z, a-z, 0-9, dot, underscore, colon, and hyphen.');
}
let body;
let bytesToSign = '';
if (hasJson) {
bytesToSign = await jsonBytes(values.json);
body = bytesToSign;
} else if (hasFile) {
bytesToSign = await readRequestFile(values.file, 10_485_760, '10 MiB');
body = new FormData();
body.append('file', new Blob([bytesToSign], { type: fileType }), basename(values.file));
}
const bodyHash = createHash('sha256').update(bytesToSign).digest('hex');
const timestamp = String(Math.floor(Date.now() / 1000));
const nonce = randomBytes(16).toString('hex');
const canonical = ['v2', method, url.pathname, query, bodyHash, timestamp, nonce, key].join('\n');
const signature = createHmac('sha256', secret).update(canonical).digest('hex');
const headers = new Headers({
Accept: 'application/json',
Authorization: `Bearer ${token}`,
'X-Api-Signature-Version': 'v2',
'X-Api-Timestamp': timestamp,
'X-Api-Nonce': nonce,
'X-Api-Signature': `sha256=${signature}`,
});
if (hasJson) {
headers.set('Content-Type', 'application/json');
}
if (key !== '') {
headers.set('Idempotency-Key', key);
}
const response = await fetch(url, { method, headers, body, redirect: 'error', signal: AbortSignal.timeout(10_000) });
const responseBody = Buffer.from(await response.arrayBuffer());
process.stdout.write(responseBody);
console.error(`HTTP ${response.status}`);
let envelope;
try {
envelope = JSON.parse(responseBody.toString('utf-8'));
} catch {
throw new Error('Expected a JSON response from Exchanger API.');
}
if (!response.ok || envelope?.state !== 0) {
process.exitCode = 1;
}
}
try {
await request();
} catch (error) {
console.error(error.message);
process.exitCode = 1;
}