// Cytrongift API client for Node 18+ (fetch and WebCrypto, no dependencies). // // CYTRON_API_KEY=ck_... CYTRON_API_SECRET=cs_... node client.mjs [base_url] // // Signs every request with the application key, exchanges the signature for a Bearer token // and reads the balance twice: once over the signature, once over the token. import { createHmac } from 'node:crypto'; export class CytronApi { #base; #key; #secret; #token = ''; constructor(base, key, secret) { this.#base = base.replace(/\/+$/, ''); this.#key = key; this.#secret = secret; } // One request. The signature covers METHOD, PATH (without /v1), TIMESTAMP and the raw body. async request(method, path, body = null, bearer = false) { method = method.toUpperCase(); const raw = body === null ? '' : JSON.stringify(body); const headers = { Accept: 'application/json' }; if (raw !== '') { headers['Content-Type'] = 'application/json'; } if (bearer && this.#token) { headers.Authorization = 'Bearer ' + this.#token; } else { const ts = String(Math.floor(Date.now() / 1000)); const cleanPath = '/' + new URL(path, 'https://x').pathname.replace(/^\/+/, ''); headers['X-Api-Key'] = this.#key; headers['X-Timestamp'] = ts; headers['X-Signature'] = createHmac('sha256', this.#secret).update(`${method}\n${cleanPath}\n${ts}\n${raw}`).digest('hex'); } const res = await fetch(this.#base + path, { method, headers, body: raw === '' ? undefined : raw }); const data = await res.json(); if (typeof data !== 'object' || data === null) { throw new Error(`HTTP ${res.status}: not a JSON envelope`); } return data; } // Exchange the signature for a Bearer token and keep it for later calls. async auth(ttl = 3600) { const answer = await this.request('POST', '/auth', { ttl }); if (answer.ok) { this.#token = answer.data.access_token; } return answer; } } if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) { const cytron = new CytronApi(process.argv[2] || 'https://api.cytrongift.com/v1', process.env.CYTRON_API_KEY || '', process.env.CYTRON_API_SECRET || ''); const steps = [ ['health', () => cytron.request('GET', '/health')], ['config', () => cytron.request('GET', '/config')], ['stats', () => cytron.request('GET', '/stats')], ['offers', () => cytron.request('GET', '/catalog/offers?limit=5')], ['balance', () => cytron.request('GET', '/account/balance')], ['auth', () => cytron.auth()], ['balance_jwt', () => cytron.request('GET', '/account/balance', null, true)], ]; for (const [name, call] of steps) { const answer = await call(); console.log(name.padEnd(12), answer.ok ? 'ok' : `error ${answer.error?.id} ${answer.error?.desc}`); if (!answer.ok) { process.exit(1); } } }