/** Dependency-free GateProxy reseller API v1.2 client for Node 18+. */ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; const RETRY = new Set([429, 502, 503, 504]); const KEY_RE = /^[A-Za-z0-9_\-:.]{8,64}$/; export class GateProxyError extends Error { constructor(status, code, message, requestId = null, body = null) { super(code + ": " + message); this.name = "GateProxyError"; this.status = status; this.code = code; this.requestId = requestId; this.body = body; } } const clean = (value) => Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined && v !== null)); const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const enc = (value) => encodeURIComponent(String(value)); export class GateProxy { constructor(apiKey, { baseUrl = "https://api.gateproxy.store", timeout = 100000, maxRetries = 2 } = {}) { this.apiKey = apiKey; this.baseUrl = baseUrl.replace(/\/$/, ""); this.timeout = timeout; this.maxRetries = Math.max(0, Number(maxRetries) || 0); } _key(value) { if (value === undefined || value === null) value = randomBytes(24).toString("base64url"); if (!KEY_RE.test(value)) throw new TypeError("idempotencyKey must be 8-64 allowed characters"); return value; } async _request(method, path, { query, body, idempotencyKey, auth = true, text = false } = {}) { const params = new URLSearchParams(); for (const [key, value] of Object.entries(clean(query || {}))) { if (Array.isArray(value)) value.forEach((item) => params.append(key, String(item))); else params.set(key, String(value)); } const queryString = params.toString(); if (queryString) path += "?" + queryString; const headers = { Accept: text ? "text/csv, text/plain" : "application/json" }; if (auth) headers.Authorization = "Bearer " + this.apiKey; if (idempotencyKey !== undefined) headers["Idempotency-Key"] = this._key(idempotencyKey); let payload; if (body !== undefined) { headers["Content-Type"] = "application/json"; payload = JSON.stringify(body); } const canRetry = method === "GET" || (method === "POST" && idempotencyKey !== undefined); const attempts = canRetry ? this.maxRetries + 1 : 1; for (let attempt = 0; attempt < attempts; attempt++) { let response; try { response = await fetch(this.baseUrl + path, { method, headers, body: payload, signal: AbortSignal.timeout(this.timeout) }); } catch (error) { throw new GateProxyError(0, "network_error", error.message); } const raw = await response.text(); let parsed = null; if (raw) { try { parsed = JSON.parse(raw); } catch { parsed = { raw }; } } if (response.ok) return text ? raw : parsed; if (RETRY.has(response.status) && attempt + 1 < attempts) { const header = Number(response.headers.get("retry-after")); const seconds = Number.isFinite(header) ? header : 2 ** attempt; await sleep(Math.min(30, Math.max(0, seconds)) * 1000); continue; } const error = parsed?.error || {}; throw new GateProxyError(response.status, error.code || "http_error", error.message || response.statusText, error.request_id || null, parsed); } } health() { return this._request("GET", "/v1/health", { auth: false }); } status() { return this._request("GET", "/v1/status", { auth: false }); } me() { return this._request("GET", "/v1/me"); } balance() { return this._request("GET", "/v1/balance"); } products() { return this._request("GET", "/v1/products"); } product(product) { return this._request("GET", "/v1/products/" + enc(product)); } createOrder(product, plan, { idempotencyKey, clientReference, metadata, maxPriceUsd, quoteId, wait = true } = {}) { const key = this._key(idempotencyKey); const body = clean({ product, plan, max_price_usd: maxPriceUsd, quote_id: quoteId, client_reference: clientReference, metadata }); return this._request("POST", "/v1/orders", { query: { wait }, body, idempotencyKey: key }); } createBatch(product, plan, quantity, { idempotencyKey, clientReference, metadata, maxPriceUsd } = {}) { const body = clean({ product, plan, quantity, max_price_usd: maxPriceUsd, client_reference: clientReference, metadata }); return this._request("POST", "/v1/orders/batch", { body, idempotencyKey: this._key(idempotencyKey) }); } listOrders(filters = {}) { return this._request("GET", "/v1/orders", { query: filters }); } async *iterOrders(filters = {}) { const params = { ...filters }; while (true) { const page = await this.listOrders(params); for (const order of page.orders || []) yield order; if (!page.next_before) return; params.before = page.next_before; } } getOrder(id) { return this._request("GET", "/v1/orders/" + enc(id)); } orderUsage(id) { return this._request("GET", "/v1/orders/" + enc(id) + "/usage"); } resetOrderPassword(id) { return this._request("POST", "/v1/orders/" + enc(id) + "/reset-password", { body: {} }); } disableOrder(id) { return this._request("POST", "/v1/orders/" + enc(id) + "/disable", { body: {} }); } enableOrder(id) { return this._request("POST", "/v1/orders/" + enc(id) + "/enable", { body: {} }); } orderProxies(id, params = {}) { return this._request("GET", "/v1/orders/" + enc(id) + "/proxies", { query: params, text: params.output === "text" }); } createQuote(product, plan, quantity) { return this._request("POST", "/v1/quotes", { body: clean({ product, plan, quantity }) }); } getQuote(id) { return this._request("GET", "/v1/quotes/" + enc(id)); } listTransactions(filters = {}) { return this._request("GET", "/v1/transactions", { query: filters }); } exportOrdersCsv(filters = {}) { return this._request("GET", "/v1/orders/export.csv", { query: filters, text: true }); } exportTransactionsCsv(filters = {}) { return this._request("GET", "/v1/transactions/export.csv", { query: filters, text: true }); } stats(filters = {}) { return this._request("GET", "/v1/stats", { query: filters }); } statement(month) { return this._request("GET", "/v1/statements/" + enc(month)); } listKeys() { return this._request("GET", "/v1/keys"); } createKey(mode, name, expiresInDays) { return this._request("POST", "/v1/keys", { body: clean({ mode, name, expires_in_days: expiresInDays }) }); } rotateKey(id, graceHours) { return this._request("POST", "/v1/keys/" + enc(id) + "/rotate", { body: clean({ grace_hours: graceHours }) }); } deleteKey(id) { return this._request("DELETE", "/v1/keys/" + enc(id)); } getWebhook() { return this._request("GET", "/v1/webhook"); } setWebhook(url) { return this._request("POST", "/v1/webhook", { body: { url } }); } updateWebhook({ events, lowBalanceUsd, lowTrafficPercent } = {}) { return this._request("PATCH", "/v1/webhook", { body: clean({ events, low_balance_usd: lowBalanceUsd, low_traffic_percent: lowTrafficPercent }) }); } deleteWebhook() { return this._request("DELETE", "/v1/webhook"); } testWebhook() { return this._request("POST", "/v1/webhook/test", { body: {} }); } listWebhookDeliveries(filters = {}) { return this._request("GET", "/v1/webhook/deliveries", { query: filters }); } resendWebhookDelivery(id) { return this._request("POST", "/v1/webhook/deliveries/" + enc(id) + "/resend", { body: {} }); } depositInfo() { return this._request("GET", "/v1/deposits/info"); } verifyDeposit(reference, method = "binance") { return this._request("POST", "/v1/deposits/verify", { body: { method, reference } }); } createRestockAlert(product, plan) { return this._request("POST", "/v1/restock-alerts", { body: { product, plan } }); } } export function verifyWebhook(secret, rawBody, header, tolerance = 300) { try { const parts = Object.fromEntries(header.split(",").map((part) => part.split(/=(.*)/s, 2))); const timestamp = Number(parts.t); if (!Number.isInteger(timestamp) || Math.abs(Date.now() / 1000 - timestamp) > tolerance) return false; const expected = Buffer.from(createHmac("sha256", secret).update(parts.t + ".").update(rawBody).digest("hex"), "hex"); const supplied = Buffer.from(parts.v1, "hex"); return expected.length === supplied.length && timingSafeEqual(expected, supplied); } catch { return false; } }