#!/usr/bin/env python3 """ServerBike Reseller Public API: reference client (Python 3.8+, standard library only). No WHMCS, no ServerBike code: signing, transport, durable operation journal and polling are all here, so this file is a complete example of a reseller integration that does not use WHMCS. Credentials come from the environment and are never printed: SB_API_BASE https://bridge.serverbike.com SB_CREDENTIAL_ID the issued credential identifier SB_SECRET the issued 43-character secret (unpadded base64url of 32 bytes) SB_JOURNAL path of the operation journal (default ./serverbike-operations.jsonl) Rules this client follows (see RETRY_AND_ERRORS.md): * every request gets a fresh timestamp and nonce; a retry is re-signed, never replayed; * a business mutation's operation_uuid and exact body are written to the journal (fsync) BEFORE the first send; * after a timeout, a transport error, a non-JSON or edge (proxy) error, a 5xx or OUTCOME_UNKNOWN, the original operation_uuid is looked up; a mutation is never resent under a new UUID until the original is proven terminal; * reads may be retried after 429 (Retry-After) or a transport error; * no redirects are followed, no proxy is used, TLS certificate and hostname are always verified. Usage: serverbike_client.py [args] (run with -h for the list) """ import argparse import base64 import hashlib import hmac import http.client import json import os import secrets import ssl import sys import time import uuid from urllib.parse import urlsplit SCHEME = 'BRIDGE-HMAC-SHA256-V1' DOMAIN = 'reseller-public' EMPTY_SHA256 = hashlib.sha256(b'').hexdigest() USER_AGENT = 'ServerBike-Reference-Python/1.1.0' MAX_RESPONSE = 1024 * 1024 class Ambiguous(Exception): """The request may or may not have been processed (transport, edge or unknown outcome).""" def decode_secret(wire: str) -> bytes: if len(wire) != 43 or any(c not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_' for c in wire): raise ValueError('secret must be 43 unpadded base64url characters') raw = base64.urlsafe_b64decode(wire + '=') if len(raw) != 32 or base64.urlsafe_b64encode(raw).decode().rstrip('=') != wire: raise ValueError('non-canonical secret encoding') return raw def canonical_message(timestamp: str, nonce: str, method: str, raw_target: str, body: bytes) -> bytes: path, sep, query = raw_target.partition('?') canonical_query = ('?' + query) if sep else '-' return '\n'.join([SCHEME, DOMAIN, timestamp, nonce, method, path, canonical_query, hashlib.sha256(body).hexdigest()]).encode('ascii') def sign(secret: bytes, credential_id: str, method: str, raw_target: str, body: bytes, timestamp=None, nonce=None) -> dict: timestamp = str(int(time.time())) if timestamp is None else str(timestamp) nonce = nonce or base64.urlsafe_b64encode(secrets.token_bytes(16)).decode().rstrip('=') mac = hmac.new(secret, canonical_message(timestamp, nonce, method, raw_target, body), hashlib.sha256).hexdigest() return {'X-Reseller-Credential-Id': credential_id, 'X-Request-Timestamp': timestamp, 'X-Request-Nonce': nonce, 'X-Request-Signature': 'v1=' + mac} class Client: def __init__(self, base: str, credential_id: str, secret_wire: str, journal: str, timeout: float = 20.0): u = urlsplit(base) if u.scheme != 'https' or not u.hostname or u.path not in ('', '/') or u.query: raise ValueError('SB_API_BASE must be an https origin') self.host, self.port = u.hostname, u.port or 443 self.credential_id, self.secret = credential_id, decode_secret(secret_wire) self.journal, self.timeout = journal, timeout self.tls = ssl.create_default_context() self.tls.minimum_version = ssl.TLSVersion.TLSv1_2 # ---------------------------------------------------------------- transport def _send(self, method: str, target: str, body: bytes = b'', timeout: float = None): headers = sign(self.secret, self.credential_id, method, target, body) headers.update({'Accept': 'application/json', 'Accept-Encoding': 'identity', 'User-Agent': USER_AGENT}) if body: headers['Content-Type'] = 'application/json' conn = http.client.HTTPSConnection(self.host, self.port, timeout=timeout or self.timeout, context=self.tls) try: conn.request(method, target, body=body if body else None, headers=headers) resp = conn.getresponse() raw = resp.read(MAX_RESPONSE + 1) hdr = {k.lower(): v for k, v in resp.getheaders()} except (OSError, http.client.HTTPException) as e: raise Ambiguous('transport: %s' % type(e).__name__) from None finally: conn.close() if len(raw) > MAX_RESPONSE or hdr.get('content-encoding', 'identity').lower() != 'identity': raise Ambiguous('response too large or encoded') if 300 <= resp.status < 400: raise Ambiguous('redirect refused (%d)' % resp.status) try: doc = json.loads(raw.decode('utf-8')) except (UnicodeDecodeError, ValueError): # An edge or proxy page (HTML), a challenge (cf-mitigated) or a truncated body: never a Bridge answer. raise Ambiguous('non-JSON response %d%s ray=%s' % (resp.status, ' challenge' if 'cf-mitigated' in hdr else '', hdr.get('cf-ray', '-'))) return resp.status, hdr, doc def read(self, target: str, retries: int = 2): for attempt in range(retries + 1): try: status, hdr, doc = self._send('GET', target) except Ambiguous: if attempt == retries: raise time.sleep(2 ** attempt) continue if status == 429 and attempt < retries: time.sleep(min(30, max(1, int(hdr.get('retry-after', '2'))))) continue return status, doc raise Ambiguous('unreachable') # ---------------------------------------------------------------- journal (business mutations) def _journal(self, record: dict) -> None: with open(self.journal, 'a', encoding='utf-8') as f: f.write(json.dumps(record, sort_keys=True) + '\n') f.flush() os.fsync(f.fileno()) def mutate(self, target: str, payload: dict, lookup: str): """Send a durable mutation once. On ambiguity, poll `lookup` for the SAME operation_uuid.""" body = json.dumps(payload, separators=(',', ':')).encode('utf-8') self._journal({'at': int(time.time()), 'target': target, 'operation_uuid': payload.get('operation_uuid'), 'body': body.decode(), 'lookup': lookup}) try: # A Start can wait up to ~45 s for the provider's answer: allow 60 s before calling the outcome ambiguous. status, hdr, doc = self._send('POST', target, body, timeout=60.0) except Ambiguous as e: return {'ambiguous': str(e), 'lookup': lookup} code = (doc.get('error') or {}).get('code') if isinstance(doc, dict) else None if status in (500, 502, 503, 504) or code == 'OUTCOME_UNKNOWN': return {'ambiguous': code or str(status), 'lookup': lookup, 'retry_after': hdr.get('retry-after')} return {'status': status, 'body': doc} def resume(self, lookup: str, until=('committed', 'rejected'), timeout: int = 600): """Poll a lookup until a terminal status (never resends).""" deadline, delay = time.time() + timeout, 3 while True: status, doc = self.read(lookup) data = doc.get('data') or {} state = data.get('status') or data.get('phase') if status == 200 and (state in until or data.get('terminal') is True): return doc if time.time() > deadline: return doc time.sleep(delay) delay = min(delay * 2, 30) def env_client(args) -> Client: try: return Client(os.environ['SB_API_BASE'], os.environ['SB_CREDENTIAL_ID'], os.environ['SB_SECRET'], os.environ.get('SB_JOURNAL', 'serverbike-operations.jsonl')) except KeyError as e: sys.exit('missing environment variable %s' % e) def out(x) -> None: print(json.dumps(x, indent=2, sort_keys=True)) def main(argv=None) -> int: p = argparse.ArgumentParser(description='ServerBike Reseller Public API reference client') sub = p.add_subparsers(dest='cmd', required=True) for name in ('verify', 'account', 'catalog', 'services'): sub.add_parser(name) for name in ('service', 'runtime', 'activity', 'access', 'guest-access', 'commercial', 'status'): sub.add_parser(name).add_argument('service_uuid') sub.add_parser('lookup').add_argument('operation_uuid') sub.add_parser('settlement').add_argument('operation_uuid') q = sub.add_parser('purchase'); q.add_argument('product'); q.add_argument('term'); q.add_argument('image') q.add_argument('--op', help='retry the SAME intent under its original operation_uuid (after a lost or ambiguous reply)') q = sub.add_parser('renew'); q.add_argument('service_uuid'); q.add_argument('commercial_service_ref'); q.add_argument('term') q.add_argument('--op', help='retry the SAME intent under its original operation_uuid') q = sub.add_parser('terminate'); q.add_argument('service_uuid'); q.add_argument('commercial_service_ref') q = sub.add_parser('change', help='deferred plan change (upgrade)'); q.add_argument('service_uuid'); q.add_argument('commercial_service_ref') q.add_argument('target_product'); q.add_argument('target_term'); q.add_argument('target_image') q = sub.add_parser('power'); q.add_argument('service_uuid'); q.add_argument('action', choices=['start', 'stop', 'restart', 'poweroff']) q = sub.add_parser('power-op'); q.add_argument('service_uuid'); q.add_argument('operation_uuid') q = sub.add_parser('password', help='new password read from SB_NEW_PASSWORD (never argv)'); q.add_argument('service_uuid') q = sub.add_parser('password-op'); q.add_argument('service_uuid'); q.add_argument('operation_uuid') q = sub.add_parser('reinstall', help='DESTRUCTIVE: reinstall image_ref; new password read from SB_NEW_PASSWORD (never argv)') q.add_argument('service_uuid'); q.add_argument('image_ref') q.add_argument('--op', help='retry the SAME reinstall under its original operation_uuid (after an ambiguous reply)') q = sub.add_parser('reinstall-op'); q.add_argument('service_uuid'); q.add_argument('operation_uuid') q = sub.add_parser('plan-change'); q.add_argument('service_uuid'); q.add_argument('operation_uuid') q = sub.add_parser('console'); q.add_argument('service_uuid'); q.add_argument('origin') q.add_argument('--deliver', help='write the one-use console path to a NEW 0600 file for your portal (never printed)') q = sub.add_parser('reveal', help='writes the password to a new 0600 file; prints only the result'); q.add_argument('service_uuid'); q.add_argument('outfile') q = sub.add_parser('wait', help='poll a lookup path until terminal'); q.add_argument('path'); q.add_argument('--timeout', type=int, default=900) sub.add_parser('vectors', help='print the known-answer vectors (no network)') a = p.parse_args(argv) if a.cmd == 'vectors': out(vectors()) return 0 c = env_client(a) s = getattr(a, 'service_uuid', None) reads = {'verify': '/api/v1/auth/verify', 'account': '/api/v1/account/commercial', 'catalog': '/api/v1/catalog?limit=10', 'services': '/api/v1/services?limit=100'} per_service = {'service': '', 'runtime': '/runtime-state', 'activity': '/activity', 'access': '/access', 'guest-access': '/guest-access', 'commercial': '/commercial', 'status': '/operational-status'} if a.cmd in reads: status, doc = c.read(reads[a.cmd]); out({'http': status, **doc}); return 0 if a.cmd in per_service: status, doc = c.read('/api/v1/services/%s%s' % (s, per_service[a.cmd])); out({'http': status, **doc}); return 0 if a.cmd == 'lookup': status, doc = c.read('/api/v1/operations/' + a.operation_uuid); out({'http': status, **doc}); return 0 if a.cmd == 'settlement': status, doc = c.read('/api/v1/operations/%s/settlement' % a.operation_uuid); out({'http': status, **doc}); return 0 if a.cmd == 'power-op': status, doc = c.read('/api/v1/services/%s/power/operations/%s' % (s, a.operation_uuid)); out({'http': status, **doc}); return 0 if a.cmd == 'password-op': status, doc = c.read('/api/v1/services/%s/password/operations/%s' % (s, a.operation_uuid)); out({'http': status, **doc}); return 0 if a.cmd == 'reinstall-op': status, doc = c.read('/api/v1/services/%s/reinstall/operations/%s' % (s, a.operation_uuid)); out({'http': status, **doc}); return 0 if a.cmd == 'plan-change': status, doc = c.read('/api/v1/services/%s/plan-changes/%s' % (s, a.operation_uuid)); out({'http': status, **doc}); return 0 if a.cmd == 'wait': out(c.resume(a.path, until=('committed', 'rejected', 'complete', 'failed_definitely_not_sent', 'failed_provider_rejected'), timeout=a.timeout)); return 0 op = getattr(a, 'op', None) or str(uuid.uuid4()) if a.cmd == 'purchase': out(c.mutate('/api/v1/purchases', {'operation_uuid': op, 'external_product_ref': a.product, 'term_ref': a.term, 'requested_image_ref': a.image}, '/api/v1/operations/' + op)); return 0 if a.cmd == 'renew': out(c.mutate('/api/v1/renewals', {'operation_uuid': op, 'commercial_service_ref': a.commercial_service_ref, 'service_uuid': s, 'term_ref': a.term}, '/api/v1/operations/' + op)); return 0 if a.cmd == 'terminate': out(c.mutate('/api/v1/commercial-terminations', {'operation_uuid': op, 'commercial_service_ref': a.commercial_service_ref, 'service_uuid': s}, '/api/v1/operations/' + op)); return 0 if a.cmd == 'change': out(c.mutate('/api/v1/commercial-changes', {'operation_uuid': op, 'commercial_service_ref': a.commercial_service_ref, 'service_uuid': s, 'target_external_product_ref': a.target_product, 'target_term_ref': a.target_term, 'target_requested_image_ref': a.target_image}, '/api/v1/services/%s/plan-changes/%s' % (s, op))); return 0 if a.cmd == 'power': out(c.mutate('/api/v1/services/%s/power/%s' % (s, a.action), {'operation_uuid': op}, '/api/v1/services/%s/power/operations/%s' % (s, op))); return 0 if a.cmd == 'password': pw = os.environ.get('SB_NEW_PASSWORD') if not pw: sys.exit('set SB_NEW_PASSWORD') r = c.mutate('/api/v1/services/%s/password' % s, {'operation_uuid': op, 'new_password': pw}, '/api/v1/services/%s/password/operations/%s' % (s, op)) out(r); return 0 if a.cmd == 'reinstall': pw = os.environ.get('SB_NEW_PASSWORD') if not pw: sys.exit('set SB_NEW_PASSWORD') out(c.mutate('/api/v1/services/%s/reinstall' % s, {'operation_uuid': op, 'image_ref': a.image_ref, 'new_password': pw}, '/api/v1/services/%s/reinstall/operations/%s' % (s, op))); return 0 if a.cmd == 'console': status, hdr, doc = c._send('POST', '/api/v1/services/%s/console-sessions' % s, json.dumps({'origin': a.origin}, separators=(',', ':')).encode()) data = doc.get('data') or {} if 'console_path' in data and a.deliver: fd = os.open(a.deliver, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, 'w') as f: json.dump({'console_path': data['console_path'], 'expires_at': data['expires_at']}, f) if 'console_path' in data: data = dict(data, console_path=data['console_path'][:24] + '...(one-use ticket, not printed)') out({'http': status, 'data': data, 'error': doc.get('error')}); return 0 if a.cmd == 'reveal': fd = os.open(a.outfile, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) status, hdr, doc = c._send('POST', '/api/v1/services/%s/access/initial-credential' % s, b'{"confirm":true}') data = doc.get('data') or {} with os.fdopen(fd, 'w') as f: if data.get('result') == 'revealed': f.write(data['password'] + '\n') out({'http': status, 'result': data.get('result'), 'login_username': data.get('login_username'), 'error': doc.get('error')}); return 0 return 2 def vectors() -> list: """Known-answer vectors with SYNTHETIC material only (secret bytes 00..1f).""" wire = base64.urlsafe_b64encode(bytes(range(32))).decode().rstrip('=') secret = decode_secret(wire) cases = [ ('GET', '/api/v1/auth/verify', b''), ('GET', '/api/v1/catalog?limit=10', b''), ('POST', '/api/v1/purchases', b'{"operation_uuid":"0b7f6f1e-2c3d-4e5f-8a9b-0c1d2e3f4a5b","external_product_ref":"prd_example","term_ref":"term:monthly","requested_image_ref":"ubuntu-24.04"}'), ('POST', '/api/v1/services/123/actions?b=2&a=1&a=0', b'{"action":"restart"}'), ('GET', '/api/v1/test', b''), ] out_ = [] for method, target, body in cases: h = sign(secret, 'rescred_EXAMPLE', method, target, body, 1787850000, 'AAECAwQFBgcICQoLDA0ODw') out_.append({'secret_wire': wire, 'credential_id': 'rescred_EXAMPLE', 'timestamp': '1787850000', 'nonce': 'AAECAwQFBgcICQoLDA0ODw', 'method': method, 'target': target, 'body': body.decode(), 'body_sha256': hashlib.sha256(body).hexdigest(), 'canonical_message': canonical_message('1787850000', 'AAECAwQFBgcICQoLDA0ODw', method, target, body).decode(), 'signature': h['X-Request-Signature']}) return out_ if __name__ == '__main__': sys.exit(main())