/** Small HTTP client for MoShi Partner API v1. No automatic retries or secrets in errors. */ import { randomBytes } from 'node:crypto'; // Persist this token with the command in your original-system ledger BEFORE claiming. export const createLeaseToken = () => randomBytes(32).toString('base64url'); export class PartnerApiError extends Error { constructor({ status = 0, code = 'TRANSPORT_ERROR', message = '请求未确认,请查询原命令或原请求结果。', requestId, traceId, retryAfter } = {}) { super(message); this.name = 'PartnerApiError'; this.status = status; this.code = code; if (requestId) this.request_id = requestId; if (traceId) this.trace_id = traceId; if (retryAfter !== undefined) this.retry_after_seconds = retryAfter; } } export class VendorClient { #url; #key; #fetch; #timeout; constructor({ baseUrl, apiKey, fetchImpl = globalThis.fetch, timeoutMs = 15000 }) { let url; try { url = new URL(baseUrl); } catch { throw new TypeError('baseUrl 必须是有效 URL。'); } const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname); if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) throw new TypeError('正式接入必须使用 HTTPS。'); if (url.username || url.password || url.search || url.hash || (url.pathname !== '/' && url.pathname !== '')) throw new TypeError('baseUrl 仅填写服务根地址,不含凭据、路径、查询或片段。'); if (typeof apiKey !== 'string' || apiKey.length < 16 || /[\r\n]/.test(apiKey)) throw new TypeError('请通过安全配置提供接入密钥。'); if (!Number.isInteger(timeoutMs) || timeoutMs < 250 || timeoutMs > 60000) throw new TypeError('timeoutMs 范围为 250 到 60000 毫秒。'); if (typeof fetchImpl !== 'function') throw new TypeError('需要 fetch 实现。'); this.#url = url.origin; this.#key = apiKey; this.#fetch = fetchImpl; this.#timeout = timeoutMs; } async #request(method, path, body) { const requestId = body?.request_id || body?.result_id; let response; try { response = await this.#fetch(`${this.#url}/api/partner/v1${path}`, { method, redirect: 'error', signal: AbortSignal.timeout(this.#timeout), headers: { Authorization: `Bearer ${this.#key}`, Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), }); } catch { // Do not expose fetch errors; they can contain credentials or request details. throw new PartnerApiError({ requestId }); } const traceId = response.headers?.get('X-Request-Id') || undefined; const retryHeader = response.headers?.get('Retry-After'); const retryAfter = retryHeader && /^[0-9]+$/.test(retryHeader) ? Number(retryHeader) : undefined; let data; try { data = await response.json(); } catch { throw new PartnerApiError({ status: response.status, code: 'INVALID_RESPONSE', message: '返回内容不是有效 JSON,请查询原请求结果。', requestId, traceId, retryAfter }); } if (!response.ok || data?.status === 'failed' && data?.code) { throw new PartnerApiError({ status: response.status, code: data?.code || 'HTTP_ERROR', message: '接入请求被拒绝,请按错误代码核对并查询原请求结果。', requestId, traceId, retryAfter }); } return data; } pageQuery({limit=50,cursor}={}) { if(!Number.isInteger(limit)||limit<1||limit>100)throw new TypeError('limit 范围为 1 到 100。'); if(cursor!==undefined&&(typeof cursor!=='string'||!cursor.length))throw new TypeError('cursor 必须为上页返回的非空字符串。'); return new URLSearchParams({limit:String(limit),...(cursor===undefined?{}:{cursor})}).toString(); } sos(options) { return this.#request('GET', '/sos?'+this.pageQuery(options)); } acknowledgeSos(alertId, payload) { return this.#request('POST', `/sos/${encodeURIComponent(alertId)}/acknowledge`, payload); } tasks(operatorExternalId,options) { return this.#request('GET', `/tasks?operator_external_id=${encodeURIComponent(operatorExternalId)}&${this.pageQuery(options)}`); } taskAction(payload) { return this.#request('POST', '/tasks/actions', payload); } info() { return this.#request('GET', '/info'); } syncCatalog(payload) { return this.#request('POST', '/catalog', payload); } syncState(payload) { return this.#request('POST', '/state', payload); } notify(payload) { return this.#request('POST', '/notifications', payload); } commands({ limit = 50 } = {}) { if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new TypeError('limit 范围为 1 到 100。'); return this.#request('GET', `/commands?limit=${limit}`); } command(commandId) { return this.#request('GET', `/commands/${encodeURIComponent(commandId)}`); } claim(commandId, workerId, leaseToken) { if (typeof leaseToken !== 'string' || !/^[A-Za-z0-9_-]{32,128}$/.test(leaseToken)) throw new TypeError('领取前必须持久化随机 lease_token(32 到 128 个 base64url 字符)。'); return this.#request('POST', `/commands/${encodeURIComponent(commandId)}/claim`, { worker_id: workerId, lease_token: leaseToken }); } report(commandId, payload) { return this.#request('POST', `/commands/${encodeURIComponent(commandId)}/result`, payload); } events({ after = 0, limit = 50 } = {}) { if (!Number.isInteger(after) || after < 0 || !Number.isInteger(limit) || limit < 1 || limit > 300) throw new TypeError('事件游标必须是非负整数,limit 范围为 1 到 300。'); return this.#request('GET', `/events?after=${after}&limit=${limit}`); } }