"""Python 3, standard library. APP_ORIGIN + BEARER; create HOST [A|CNAME], list, verify ID, remove ID.""" import json import os import re import sys import urllib.error import urllib.parse import urllib.request base = os.environ['APP_ORIGIN'].rstrip('/') parts = urllib.parse.urlsplit(base) if parts.scheme != 'https' and parts.hostname not in ('localhost', '127.0.0.1'): raise SystemExit('Owner credentials require HTTPS.') action = sys.argv[1] if len(sys.argv) > 1 else 'list' value = sys.argv[2] if len(sys.argv) > 2 else '' if action not in ('create', 'list', 'verify', 'remove'): raise SystemExit('Use create, list, verify or remove.') if action in ('verify', 'remove') and not re.fullmatch(r'dom_[a-f0-9]{32}', value): raise SystemExit('Supply the returned bindingId.') suffix = '/' + value + '/verify' if action == 'verify' else '/' + value if action == 'remove' else '' data = json.dumps({'hostname': value, 'recordType': sys.argv[3] if len(sys.argv) > 3 else 'A'}).encode() if action == 'create' else None request = urllib.request.Request(base + '/api/domains' + suffix, data=data, method='GET' if action == 'list' else 'DELETE' if action == 'remove' else 'POST', headers={'Authorization': 'Bearer ' + os.environ['BEARER'], 'Content-Type': 'application/json'}) class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None try: with urllib.request.build_opener(NoRedirect).open(request, timeout=30) as response: print(response.read().decode()) except urllib.error.HTTPError as error: print(error.read().decode(), file=sys.stderr) raise SystemExit(1)