Skip to content
VPS, Dedicated Servers and Colocation across ServerBike service locations

Developer reference

Examples and test vectors

A Python reference client, three signing examples and known-answer vectors.

Public API 1.1.1Not SDKs
Documentation menu
Official API documentation · version 1.1.1View raw README.md

Examples (synthetic credentials only)

PathWhat
python/serverbike_client.pyComplete reference client, Python 3.8+ standard library: signing, transport rules, durable operation journal, lookup-based recovery, every route. python3 serverbike_client.py -h.
node/serverbike_sign.mjsSigner + minimal request, Node.js 18+.
php/serverbike_sign.phpSigner + minimal request, PHP 8.1+ with ext-curl.
go/serverbike_sign.goSigner, Go 1.20+.
vectors.jsonKnown-answer vectors (canonical message and signature) for all of the above.

Check every implementation against the vectors:

Shell
python3 python/serverbike_client.py vectors | diff - vectors.json && echo "python OK"
node node/serverbike_sign.mjs vectors vectors.json
php php/serverbike_sign.php vectors vectors.json
(cd go && go run serverbike_sign.go ../vectors.json)

Calling the API needs your real credential in the environment (SB_API_BASE, SB_CREDENTIAL_ID, SB_SECRET) and a registered source address. Never put the secret in a command line, a browser or a log.

Source files

One reference client and three signing examples, shown exactly as published. They are examples, not SDKs or packages. Copy a file, save it from its raw link or download the whole bundle.

Python reference client

Python 3.8+, standard library only. Covers every route.

examples/python/serverbike_client.py18,167 bytesDownloadRaw
serverbike_client.pyPython
#!/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 <command> [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())

Node.js signing example

Node.js 18+. Signs and sends one minimal request.

examples/node/serverbike_sign.mjs3,699 bytesDownloadRaw
serverbike_sign.mjsNode.js
// ServerBike Reseller Public API: BRIDGE-HMAC-SHA256-V1 signer and minimal client (Node.js 18+, no dependencies).
// Usage:  node serverbike_sign.mjs vectors ../vectors.json      (checks the known-answer vectors)
//         SB_API_BASE=... SB_CREDENTIAL_ID=... SB_SECRET=... node serverbike_sign.mjs get /api/v1/auth/verify
import { createHash, createHmac, randomBytes } from 'node:crypto';
import { readFileSync } from 'node:fs';
import https from 'node:https';

export function decodeSecret(wire) {
  if (!/^[A-Za-z0-9_-]{43}$/.test(wire)) throw new Error('secret must be 43 unpadded base64url characters');
  const raw = Buffer.from(wire, 'base64url');
  if (raw.length !== 32 || raw.toString('base64url') !== wire) throw new Error('non-canonical secret');
  return raw;
}

export function canonicalMessage(timestamp, nonce, method, rawTarget, body) {
  const i = rawTarget.indexOf('?');
  const path = i < 0 ? rawTarget : rawTarget.slice(0, i);
  const query = i < 0 ? '-' : '?' + rawTarget.slice(i + 1);
  const bodyHash = createHash('sha256').update(body).digest('hex');
  return ['BRIDGE-HMAC-SHA256-V1', 'reseller-public', timestamp, nonce, method, path, query, bodyHash].join('\n');
}

export function sign(secret, credentialId, method, rawTarget, body, timestamp, nonce) {
  timestamp = timestamp ?? String(Math.floor(Date.now() / 1000));
  nonce = nonce ?? randomBytes(16).toString('base64url');
  const mac = createHmac('sha256', secret).update(canonicalMessage(timestamp, nonce, method, rawTarget, body)).digest('hex');
  return { 'X-Reseller-Credential-Id': credentialId, 'X-Request-Timestamp': timestamp, 'X-Request-Nonce': nonce, 'X-Request-Signature': 'v1=' + mac };
}

export function request(method, rawTarget, bodyText = '') {
  const base = new URL(process.env.SB_API_BASE);
  const body = Buffer.from(bodyText, 'utf8');
  const headers = { ...sign(decodeSecret(process.env.SB_SECRET), process.env.SB_CREDENTIAL_ID, method, rawTarget, body),
    Accept: 'application/json', 'Accept-Encoding': 'identity' };
  if (body.length) headers['Content-Type'] = 'application/json';
  return new Promise((resolve, reject) => {
    // path is passed verbatim: the signed raw target is exactly what goes on the wire.
    const req = https.request({ host: base.hostname, port: base.port || 443, method, path: rawTarget, headers, minVersion: 'TLSv1.2', timeout: 20000 }, (res) => {
      const chunks = []; res.on('data', (c) => chunks.push(c));
      res.on('end', () => resolve({ status: res.statusCode, body: Buffer.concat(chunks).toString('utf8') }));
    });
    req.on('timeout', () => req.destroy(new Error('timeout: outcome unknown for a POST, look it up')));
    req.on('error', reject);
    if (body.length) req.write(body);
    req.end();
  });
}

if (process.argv[1] && process.argv[1].endsWith('serverbike_sign.mjs')) {
  const [cmd, a, b] = process.argv.slice(2);
  if (cmd === 'vectors') {
    let ok = 0;
    for (const v of JSON.parse(readFileSync(a, 'utf8'))) {
      const h = sign(decodeSecret(v.secret_wire), v.credential_id, v.method, v.target, Buffer.from(v.body, 'utf8'), v.timestamp, v.nonce);
      if (h['X-Request-Signature'] !== v.signature || canonicalMessage(v.timestamp, v.nonce, v.method, v.target, Buffer.from(v.body)) !== v.canonical_message) {
        console.error('MISMATCH', v.method, v.target); process.exit(1);
      }
      ok++;
    }
    console.log(`node: ${ok} vectors OK`);
  } else if (cmd === 'get') {
    console.log(await request('GET', a));
  } else if (cmd === 'post') {
    console.log(await request('POST', a, b ?? ''));
  } else {
    console.error('usage: vectors <file> | get <target> | post <target> <json>'); process.exit(2);
  }
}

PHP signing example

PHP 8.1+ with ext-curl. Signs and sends one minimal request.

examples/php/serverbike_sign.php3,812 bytesDownloadRaw
serverbike_sign.phpPHP
<?php
// ServerBike Reseller Public API: BRIDGE-HMAC-SHA256-V1 signer and minimal client (PHP 8.1+, ext-curl; no framework).
// Usage:  php serverbike_sign.php vectors ../vectors.json
//         SB_API_BASE=... SB_CREDENTIAL_ID=... SB_SECRET=... php serverbike_sign.php get /api/v1/auth/verify
declare(strict_types=1);

function sb_decode_secret(string $wire): string
{
    if (preg_match('/\A[A-Za-z0-9_-]{43}\z/D', $wire) !== 1) throw new InvalidArgumentException('secret must be 43 unpadded base64url characters');
    $raw = base64_decode(strtr($wire, '-_', '+/'), true);
    if ($raw === false || strlen($raw) !== 32 || rtrim(strtr(base64_encode($raw), '+/', '-_'), '=') !== $wire) throw new InvalidArgumentException('non-canonical secret');
    return $raw;
}

function sb_canonical(string $ts, string $nonce, string $method, string $target, string $body): string
{
    $q = strpos($target, '?');
    $path = $q === false ? $target : substr($target, 0, $q);
    $query = $q === false ? '-' : '?' . substr($target, $q + 1);
    return implode("\n", ['BRIDGE-HMAC-SHA256-V1', 'reseller-public', $ts, $nonce, $method, $path, $query, hash('sha256', $body)]);
}

function sb_sign(string $secret, string $credentialId, string $method, string $target, string $body, ?string $ts = null, ?string $nonce = null): array
{
    $ts ??= (string) time();
    $nonce ??= rtrim(strtr(base64_encode(random_bytes(16)), '+/', '-_'), '=');
    return ['X-Reseller-Credential-Id' => $credentialId, 'X-Request-Timestamp' => $ts, 'X-Request-Nonce' => $nonce,
        'X-Request-Signature' => 'v1=' . hash_hmac('sha256', sb_canonical($ts, $nonce, $method, $target, $body), $secret)];
}

function sb_request(string $method, string $target, string $body = ''): array
{
    $headers = sb_sign(sb_decode_secret((string) getenv('SB_SECRET')), (string) getenv('SB_CREDENTIAL_ID'), $method, $target, $body);
    $lines = ['Accept: application/json', 'Accept-Encoding: identity'];
    foreach ($headers as $k => $v) $lines[] = "$k: $v";
    if ($body !== '') $lines[] = 'Content-Type: application/json';
    $ch = curl_init(rtrim((string) getenv('SB_API_BASE'), '/') . $target);
    curl_setopt_array($ch, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $lines, CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => false, CURLOPT_PROXY => '', CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2, CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_TIMEOUT => 20]);
    if ($body !== '') curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    $resp = curl_exec($ch);
    $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    if ($resp === false) throw new RuntimeException('transport error: outcome unknown for a POST, look it up');
    return ['status' => $status, 'body' => $resp];
}

if (PHP_SAPI === 'cli' && realpath($argv[0]) === __FILE__) {
    $cmd = $argv[1] ?? '';
    if ($cmd === 'vectors') {
        $n = 0;
        foreach (json_decode((string) file_get_contents($argv[2]), true, 8, JSON_THROW_ON_ERROR) as $v) {
            $h = sb_sign(sb_decode_secret($v['secret_wire']), $v['credential_id'], $v['method'], $v['target'], $v['body'], $v['timestamp'], $v['nonce']);
            if ($h['X-Request-Signature'] !== $v['signature'] || sb_canonical($v['timestamp'], $v['nonce'], $v['method'], $v['target'], $v['body']) !== $v['canonical_message']) {
                fwrite(STDERR, "MISMATCH {$v['method']} {$v['target']}\n"); exit(1);
            }
            $n++;
        }
        echo "php: $n vectors OK\n";
    } elseif ($cmd === 'get' || $cmd === 'post') {
        print_r(sb_request(strtoupper($cmd), $argv[2], $argv[3] ?? ''));
    } else {
        fwrite(STDERR, "usage: vectors <file> | get <target> | post <target> <json>\n"); exit(2);
    }
}

Go signing example

Go 1.20+. Signs a request.

examples/go/serverbike_sign.go2,895 bytesDownloadRaw
serverbike_sign.goGo
// ServerBike Reseller Public API: BRIDGE-HMAC-SHA256-V1 signer (Go 1.20+, standard library only).
// Usage: go run serverbike_sign.go ../vectors.json
package main

import (
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"regexp"
	"strconv"
	"strings"
	"time"
)

var wireRe = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`)

// DecodeSecret turns the issued 43-character unpadded base64url secret into its 32 key bytes.
func DecodeSecret(wire string) ([]byte, error) {
	if !wireRe.MatchString(wire) {
		return nil, errors.New("secret must be 43 unpadded base64url characters")
	}
	raw, err := base64.RawURLEncoding.DecodeString(wire)
	if err != nil || len(raw) != 32 || base64.RawURLEncoding.EncodeToString(raw) != wire {
		return nil, errors.New("non-canonical secret")
	}
	return raw, nil
}

// CanonicalMessage builds the exact bytes that are signed (LF-separated, no trailing LF).
func CanonicalMessage(timestamp, nonce, method, rawTarget string, body []byte) string {
	path, query := rawTarget, "-"
	if i := strings.IndexByte(rawTarget, '?'); i >= 0 {
		path, query = rawTarget[:i], "?"+rawTarget[i+1:]
	}
	sum := sha256.Sum256(body)
	return strings.Join([]string{"BRIDGE-HMAC-SHA256-V1", "reseller-public", timestamp, nonce, method, path, query, hex.EncodeToString(sum[:])}, "\n")
}

// Sign returns the four request headers. Pass empty timestamp/nonce for fresh values.
func Sign(secret []byte, credentialID, method, rawTarget string, body []byte, timestamp, nonce string) map[string]string {
	if timestamp == "" {
		timestamp = strconv.FormatInt(time.Now().Unix(), 10)
	}
	if nonce == "" {
		b := make([]byte, 16)
		_, _ = rand.Read(b)
		nonce = base64.RawURLEncoding.EncodeToString(b)
	}
	m := hmac.New(sha256.New, secret)
	m.Write([]byte(CanonicalMessage(timestamp, nonce, method, rawTarget, body)))
	return map[string]string{"X-Reseller-Credential-Id": credentialID, "X-Request-Timestamp": timestamp,
		"X-Request-Nonce": nonce, "X-Request-Signature": "v1=" + hex.EncodeToString(m.Sum(nil))}
}

func main() {
	if len(os.Args) != 2 {
		fmt.Fprintln(os.Stderr, "usage: go run serverbike_sign.go <vectors.json>")
		os.Exit(2)
	}
	data, err := os.ReadFile(os.Args[1])
	if err != nil {
		panic(err)
	}
	var vs []map[string]string
	if err := json.Unmarshal(data, &vs); err != nil {
		panic(err)
	}
	for _, v := range vs {
		secret, err := DecodeSecret(v["secret_wire"])
		if err != nil {
			panic(err)
		}
		h := Sign(secret, v["credential_id"], v["method"], v["target"], []byte(v["body"]), v["timestamp"], v["nonce"])
		if h["X-Request-Signature"] != v["signature"] || CanonicalMessage(v["timestamp"], v["nonce"], v["method"], v["target"], []byte(v["body"])) != v["canonical_message"] {
			fmt.Fprintln(os.Stderr, "MISMATCH", v["method"], v["target"])
			os.Exit(1)
		}
	}
	fmt.Printf("go: %d vectors OK\n", len(vs))
}

Known-answer test vectors

Synthetic material only (credential rescred_EXAMPLE). Check your signer against these offline.

examples/vectors.json3,391 bytesDownloadRaw
vectors.jsonJSON
[
  {
    "body": "",
    "body_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    "canonical_message": "BRIDGE-HMAC-SHA256-V1\nreseller-public\n1787850000\nAAECAwQFBgcICQoLDA0ODw\nGET\n/api/v1/auth/verify\n-\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    "credential_id": "rescred_EXAMPLE",
    "method": "GET",
    "nonce": "AAECAwQFBgcICQoLDA0ODw",
    "secret_wire": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8",
    "signature": "v1=52ab049c2545d42eb9e25914a788659902bff5fb77e39d765c1a69213ec37ab7",
    "target": "/api/v1/auth/verify",
    "timestamp": "1787850000"
  },
  {
    "body": "",
    "body_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    "canonical_message": "BRIDGE-HMAC-SHA256-V1\nreseller-public\n1787850000\nAAECAwQFBgcICQoLDA0ODw\nGET\n/api/v1/catalog\n?limit=10\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    "credential_id": "rescred_EXAMPLE",
    "method": "GET",
    "nonce": "AAECAwQFBgcICQoLDA0ODw",
    "secret_wire": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8",
    "signature": "v1=0511cf41afda8fcb12aff4a3d6f62624e9da4e17883d23841bc19f9a53e03753",
    "target": "/api/v1/catalog?limit=10",
    "timestamp": "1787850000"
  },
  {
    "body": "{\"operation_uuid\":\"0b7f6f1e-2c3d-4e5f-8a9b-0c1d2e3f4a5b\",\"external_product_ref\":\"prd_example\",\"term_ref\":\"term:monthly\",\"requested_image_ref\":\"ubuntu-24.04\"}",
    "body_sha256": "b464d7f3cc5d5ad0c74cf178e18b1d5c41650bba9251034dd1b23bc8138c2b94",
    "canonical_message": "BRIDGE-HMAC-SHA256-V1\nreseller-public\n1787850000\nAAECAwQFBgcICQoLDA0ODw\nPOST\n/api/v1/purchases\n-\nb464d7f3cc5d5ad0c74cf178e18b1d5c41650bba9251034dd1b23bc8138c2b94",
    "credential_id": "rescred_EXAMPLE",
    "method": "POST",
    "nonce": "AAECAwQFBgcICQoLDA0ODw",
    "secret_wire": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8",
    "signature": "v1=e4e7c68e303138604000c7ed285c0a1cb3fb512dee1036baac1a0754be20077b",
    "target": "/api/v1/purchases",
    "timestamp": "1787850000"
  },
  {
    "body": "{\"action\":\"restart\"}",
    "body_sha256": "77573c4687af1b5834c15bcf2d7c30324168fb044ca9157def799dddfdd3d825",
    "canonical_message": "BRIDGE-HMAC-SHA256-V1\nreseller-public\n1787850000\nAAECAwQFBgcICQoLDA0ODw\nPOST\n/api/v1/services/123/actions\n?b=2&a=1&a=0\n77573c4687af1b5834c15bcf2d7c30324168fb044ca9157def799dddfdd3d825",
    "credential_id": "rescred_EXAMPLE",
    "method": "POST",
    "nonce": "AAECAwQFBgcICQoLDA0ODw",
    "secret_wire": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8",
    "signature": "v1=e8f8836f29cbd8f993469f2b5ed4d7f52609250f6bd437979f104228fc14e2ca",
    "target": "/api/v1/services/123/actions?b=2&a=1&a=0",
    "timestamp": "1787850000"
  },
  {
    "body": "",
    "body_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    "canonical_message": "BRIDGE-HMAC-SHA256-V1\nreseller-public\n1787850000\nAAECAwQFBgcICQoLDA0ODw\nGET\n/api/v1/test\n-\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    "credential_id": "rescred_EXAMPLE",
    "method": "GET",
    "nonce": "AAECAwQFBgcICQoLDA0ODw",
    "secret_wire": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8",
    "signature": "v1=68d54a7c424ecdeae0209e2823878a52c7bfe33ce3f79c9ece417ea078a59e15",
    "target": "/api/v1/test",
    "timestamp": "1787850000"
  }
]