#!/usr/bin/env python3 """Proton command line: create, connect to, and manage your Proton computers. Install: curl -fsSL https://app.proton.computer/install.sh | sh Requires Python 3.8+ and OpenSSH. Uses only the Python standard library. """ import argparse import contextlib import fcntl import hashlib import json import os import pathlib import re import socket import subprocess import sys import tempfile import time import urllib.error import urllib.parse import urllib.request import uuid import webbrowser VERSION = '0.1.5' API = 'https://app.proton.computer' KEY_TYPES = ('ssh-ed25519 ', 'ecdsa-sha2-nistp256 ', 'ssh-rsa ') def config_dir(): base = os.environ.get('XDG_CONFIG_HOME') or str(pathlib.Path.home() / '.config') return pathlib.Path(base) / 'proton' class Failure(Exception): pass class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, *args, **kwargs): return None class Client: def __init__(self, url=API, token=None, host=None): parsed = urllib.parse.urlsplit(url) local = parsed.scheme == 'http' and parsed.hostname == '127.0.0.1' and host if not (parsed.scheme == 'https' or local) or parsed.username or parsed.query or parsed.path not in {'', '/'}: raise Failure('PROTON_API_URL must be an HTTPS origin') self.url, self.token, self.host = url.rstrip('/'), token, host self.opener = urllib.request.build_opener(NoRedirect()) def request(self, path, body=None, *, key=None, auth=True): headers = {'Accept': 'application/json', 'User-Agent': 'proton-cli/' + VERSION} if self.host: headers['Host'] = self.host if auth: if not self.token: raise Failure('not signed in; run: proton login') headers['Authorization'] = 'Bearer ' + self.token data = None if body is not None: data = json.dumps(body).encode() headers['Content-Type'] = 'application/json' if key: headers['Idempotency-Key'] = key request = urllib.request.Request(self.url + '/api' + path, data=data, headers=headers, method='GET' if body is None else 'POST') try: with self.opener.open(request, timeout=30) as response: return json.loads(response.read(4 << 20)) except urllib.error.HTTPError as error: try: message = json.loads(error.read(65536))['error']['message'] except (ValueError, KeyError, TypeError): message = 'HTTP %d' % error.code if error.code == 401: message += ' (run: proton login)' failure = Failure(message) failure.status = error.code raise failure from None except (urllib.error.URLError, OSError, ValueError) as error: raise Failure('could not reach Proton: %s' % getattr(error, 'reason', error)) from None def credentials_path(): return config_dir() / 'credentials.json' def load_credentials(): try: return json.loads(credentials_path().read_text()) except (OSError, ValueError): return {} def save_credentials(value): path = credentials_path() path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) temporary = path.with_suffix('.tmp') fd = os.open(str(temporary), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, 'w') as handle: json.dump(value, handle) os.replace(str(temporary), str(path)) def client(args): saved = load_credentials() url = os.environ.get('PROTON_API_URL') or saved.get('api') or API return Client(url, os.environ.get('PROTON_TOKEN') or saved.get('token')) @contextlib.contextmanager def create_intent(api): """Pin accepted bytes before an uncertain network effect, per CLI session. The digest scopes retries without writing a credential. No timeout silently discards an unresolved paid create. A filesystem failure prevents dispatch. """ if not isinstance(api.url, str) or not isinstance(api.token, str): yield None # Dependency-injected clients may supply their own persistence. return scope = hashlib.sha256((api.url+'\0'+api.token).encode()).hexdigest() path = config_dir()/('create-'+scope+'.json') path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) fd = os.open(str(path.with_suffix('.lock')), os.O_CREAT|os.O_RDWR|os.O_NOFOLLOW, 0o600) try: try: fcntl.flock(fd, fcntl.LOCK_EX|fcntl.LOCK_NB) except BlockingIOError: raise Failure('Another Create request is in progress in this CLI session') from None try: read_fd = os.open(str(path), os.O_RDONLY|os.O_NOFOLLOW) with os.fdopen(read_fd) as handle: prior = json.load(handle) if not isinstance(prior,dict) or set(prior) != {'body','terms','key'} or not isinstance(prior['body'],dict) or not isinstance(prior['terms'],dict) or not isinstance(prior['key'],str): raise ValueError('invalid intent') except FileNotFoundError: prior = None except (OSError,ValueError): raise Failure('Cannot read pending Create request; resolve '+str(path)+' before creating another computer') from None def save(value): temporary_fd, temporary = tempfile.mkstemp(prefix='create-', dir=str(path.parent)) try: with os.fdopen(temporary_fd,'w') as handle: json.dump(value,handle);handle.flush();os.fsync(handle.fileno()) os.replace(temporary,str(path)) finally: if os.path.exists(temporary):os.unlink(temporary) yield {'prior':prior,'save':save,'clear':lambda:path.unlink(missing_ok=True)} finally: os.close(fd) def confirm(question, assume): if assume: return True if not sys.stdin.isatty(): raise Failure(question + ' Re-run with --yes to confirm non-interactively.') return input(question + ' [y/N] ').strip().lower() in {'y', 'yes'} def runtime_price(monthly_microusd=20000000): whole, fraction = divmod(monthly_microusd, 1000000) amount = str(whole) + (('.%06d' % fraction).rstrip('0') if fraction else '') return '$%s per 730 running hours (about one month), billed per running second from your shared Cube balance' % amount def machine_spec(machine): disk = ('%d GB' % (machine['proton_units'] * 15) if machine.get('sizing_version') == 'units-v1' else '≈%d GB' % round(machine['disk_gib'] * 2**30 / 1e9)) return '%d shared vCPUs · %g GB guaranteed RAM (up to %g GB) · %s disk' % ( machine['vcpus'], machine.get('floor_mib', 2048) / 1024, machine['ceiling_mib'] / 1024, disk) def machine_price(terms): if terms.get('billing_version', 'runtime-v1') not in {'runtime-v1','running-paused-v1'} or (terms.get('billing_version','runtime-v1') == 'runtime-v1' and terms.get('paused_monthly_microusd',0) != 0): raise Failure('Computer pricing is unavailable; refresh before accepting charges') price = runtime_price(terms.get('monthly_microusd', 20000000)) if terms.get('billing_version', 'runtime-v1') == 'running-paused-v1': paused = terms.get('paused_monthly_microusd') if type(paused) is not int or paused <= 0: raise Failure('Computer pricing is unavailable; refresh before accepting charges') running = terms.get('monthly_microusd', 20000000)/1e6 return '$%g per 730 running hours ($%.4f/hour); $%g per 730 paused hours ($%.4f/hour), prorated by time from your shared Cube balance. Restart is subject to capacity' % (running, running/730, paused/1e6, paused/1e6/730) return price + '. Stopped computers are not charged' def billing_consent(api, args, monthly_microusd=20000000, *, terms=None): billing = api.request('/billing') if not billing.get('enabled'): return {} terms = terms or {'monthly_microusd':monthly_microusd} if not confirm('This computer costs ' + machine_price(terms) + '. Continue?', args.yes): raise Failure('cancelled') return {'billing_accepted': True, **({'accepted_billing_version':terms['billing_version']} if terms.get('billing_version') == 'running-paused-v1' else {})} def list_machines(api): data=api.request('/machines') if data.get('unavailable_providers'): print('Some computers are temporarily unavailable; showing reachable hosts.',file=sys.stderr) return data['machines'] def find(api, name): machines = list_machines(api) for machine in machines: if name in {machine['name'], machine['id']}: return machine names = ', '.join(m['name'] for m in machines) or 'none' raise Failure('no computer named %r (yours: %s)' % (name, names)) def wait(api, operation, quiet=False): deadline = time.time() + 20 * 60 shown = None while time.time() < deadline: op = api.request('/operations/' + operation['id'])['operation'] if op['status'] != shown and not quiet: print(' %s: %s' % (op['action'], op['status']), file=sys.stderr) shown = op['status'] if op['status'] == 'succeeded': return op if op['status'] not in {'queued', 'running'}: raise Failure('%s %s: %s' % (op['action'], op['status'], op.get('error') or 'see proton show')) time.sleep(3) raise Failure('Observation timed out; the operation may still be running. Use: proton wait '+operation['id']) def read_key(path): candidates = [pathlib.Path(path).expanduser()] if path else [ pathlib.Path.home() / '.ssh' / name for name in ('id_ed25519.pub', 'id_ecdsa.pub', 'id_rsa.pub')] for candidate in candidates: if candidate.is_file(): if candidate.suffix != '.pub': raise Failure('%s looks like a private key; pass the .pub file' % candidate) key = candidate.read_text().strip() if not key.startswith(KEY_TYPES) or '\n' in key: raise Failure('%s is not a single OpenSSH public key' % candidate) return key if path: raise Failure('no public key at ' + path) raise Failure('no SSH key found. Create one with: ssh-keygen -t ed25519 (or pass --key PATH.pub)') def endpoint(machine): ssh = machine.get('public_ssh') if machine['state'] != 'running' or not ssh or not ssh.get('enabled'): raise Failure('%s is %s; SSH is available while it is running (proton start %s)' % (machine['name'], machine['state'], machine['name'])) return ssh def known_hosts(ssh): """Pin the API-reported host key so the first connection needs no trust prompt.""" path = config_dir() / 'known_hosts' if not ssh.get('host_key'): return None entry = '[%s]:%d' % (ssh['hostname'], ssh['port']) path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) try: lines = [line for line in path.read_text().splitlines() if line.split(' ', 1)[0] != entry] except OSError: lines = [] lines.append(entry + ' ' + ssh['host_key']) path.write_text('\n'.join(lines) + '\n') return path def ssh_options(ssh): pinned = known_hosts(ssh) if pinned is None: return ['-o', 'StrictHostKeyChecking=ask'] return ['-o', 'UserKnownHostsFile=' + str(pinned), '-o', 'StrictHostKeyChecking=yes'] def cmd_login(args): api = Client(os.environ.get('PROTON_API_URL') or API) host = re.sub(r'[^A-Za-z0-9._-]', '', socket.gethostname())[:40] or 'unknown' device = api.request('/cli/device', {'client': 'proton CLI on ' + host}, auth=False) link = api.url + '/cli?code=' + device['user_code'] print('Sign in to Proton in your browser:\n\n %s\n\nConfirm this code matches: %s\n' % (link, device['user_code'])) if not args.no_browser: try: webbrowser.open(link) except Exception: pass interval, deadline = device['interval'], time.time() + device['expires_in'] while time.time() < deadline: time.sleep(interval) result = api.request('/cli/token', {'device_code': device['device_code']}, auth=False) if result['status'] == 'slow_down': interval += 5 elif result['status'] == 'approved': save_credentials({'api': api.url, 'token': result['access_token'], 'email': result.get('email', '')}) print('Signed in as %s.' % (result.get('email') or 'your Proton account')) return raise Failure('sign-in timed out; run proton login again') def cmd_logout(args): api = client(args) try: api.request('/cli/logout', {}) except Failure as error: print('warning: ' + str(error), file=sys.stderr) try: credentials_path().unlink() except FileNotFoundError: pass print('Signed out.') def cmd_whoami(args): me = client(args).request('/me') print(me.get('email') or me['id']) def cmd_balance(args): b = client(args).request('/billing') if not b.get('enabled'): print('Billing is not active yet.') return if not b.get('available'): print('No prepaid Cube balance. Add credit: https://app.cube.computer/billing') else: print('Shared Cube balance: $%.2f' % (int(b['balance_microusd']) / 1e6)) print('Proton runtime: %.2f hours · deducted $%.4f' % (b['runtime_seconds'] / 3600, int(b['charged_microusd']) / 1e6)) if b.get('paused_seconds'): print('Proton paused time: %.2f hours' % (b['paused_seconds']/3600)) print('Use proton show NAME to see each computer\'s running and paused prices.') def cmd_list(args): machines = list_machines(client(args)) if args.json: print(json.dumps(machines, indent=2)) return if not machines: print('No computers yet. Create one with: proton create NAME') return rows = [('NAME', 'STATE', 'SSH')] for m in machines: s = m.get('public_ssh') rows.append((m['name'], m['state'], 'ssh -p %d ubuntu@%s' % (s['port'], s['hostname']) if s and s.get('enabled') else '—')) width = [max(len(r[i]) for r in rows) for i in range(2)] for r in rows: print('%-*s %-*s %s' % (width[0], r[0], width[1], r[1], r[2])) def cmd_show(args): api = client(args) d = api.request('/machines/' + find(api, args.name)['id']) if args.json: print(json.dumps(d, indent=2)) return m, s = d['machine'], d['machine'].get('public_ssh') print('%s (%s)\n id: %s\n spec: %s\n price: %s' % (m['name'], m['state'], m['id'], machine_spec(m), machine_price(m))) if s and s.get('enabled'): print(' ssh: ssh -p %d ubuntu@%s\n host: %s' % (s['port'], s['hostname'], s.get('fingerprint') or 'unknown')) if m.get('error'): print(' error: ' + m['error']) for op in d['operations'][:5]: print(' %s %s %s' % (time.strftime('%Y-%m-%d %H:%M', time.localtime(op['created'])), op['action'], op['status'])) def cmd_diagnose(args): api = client(args) machine = find(api, args.name) detail = api.request('/machines/' + machine['id']) try: metrics = api.request('/metrics') except Failure as error: metrics = {'error': str(error), 'guests': []} report = {'machine': detail['machine'], 'operations': detail['operations'], 'telemetry_at': metrics.get('at'), 'telemetry_error': metrics.get('error',''), 'telemetry': next((g for g in metrics.get('guests',[]) if g['uuid']==machine['id']), None)} if args.json: print(json.dumps(report, indent=2)) return m = report['machine'] print('%s: %s' % (machine['name'], m['state'])) print('Public SSH: '+('enabled' if (m.get('public_ssh') or {}).get('enabled') else 'unavailable')) print('Machine detail: '+(m.get('error') or 'none')) print('Telemetry: '+(report['telemetry_error'] or ('available' if report['telemetry'] else 'no fresh reading'))) if report['telemetry']: print(json.dumps(report['telemetry'], indent=2)) for op in report['operations'][:5]: print('%s %s %s: %s' % (op['id'],op['action'],op['status'],op.get('error') or '')) def cmd_recover(args): api = client(args) machine = find(api, args.name) detail = api.request('/machines/' + machine['id']) pending = next((o for o in detail['operations'] if o['status'] in {'queued','running'}), None) if pending and pending['action'] not in {'create','start','restart','reconcile'}: raise Failure('another machine operation is in progress: '+pending['id']) if pending: op = pending elif detail['machine']['state'] not in {'error','unknown'}: print(json.dumps({'machine':detail['machine'],'recovery_needed':False},indent=2) if args.json else machine['name']+': no failed operation to recover; use proton diagnose for details') return else: key = args.request_key or str(uuid.uuid4()) print('Request key: '+key, file=sys.stderr) op = api.request('/machines/'+machine['id']+'/reconcile', {}, key=key)['operation'] print('Operation: '+op['id'], file=sys.stderr) if not args.no_wait: op = wait(api,op,quiet=args.json) print(json.dumps({'operation':op},indent=2) if args.json else machine['name']+': '+op['status']) def cmd_wait(args): api = client(args) op = wait(api,{'id':args.operation},quiet=args.json) print(json.dumps({'operation':op},indent=2) if args.json else op['id']+': '+op['status']) def cmd_create(args): api = client(args) with create_intent(api) as intent: prior = intent['prior'] if intent else None if prior: body, selected, key = prior['body'], prior['terms'], prior['key'] if args.name != body.get('name') or (args.units is not None and args.units != body.get('units')): raise Failure('A Create request is pending. Retry its original name, size and accepted pricing before creating another computer') # The saved terms remain authoritative even if rollout changed. billing_consent(api, args, selected['monthly_microusd'], terms=selected) print('Retrying pending Create with its original accepted pricing.', file=sys.stderr) else: units = args.units config = api.request('/config', auth=False) sizing_enabled = config.get('units_enabled', False) if units is None and sizing_enabled: units = 4 if units is not None and not sizing_enabled: raise Failure('vCPU sizing is not enabled on this server') body = {'name': args.name, 'ssh_keys': [read_key(args.key)]} selected = dict(vcpus=4, floor_mib=2048, ceiling_mib=65536, disk_gib=50, monthly_microusd=20000000) if units is not None: body['units'] = units selected.update(proton_units=units, sizing_version='units-v1', vcpus=units, floor_mib=units*2048, ceiling_mib=units*2048+16384, monthly_microusd=units*6000000) pricing = config.get('pricing', {'billing_version':'runtime-v1'}) selected.update(billing_version=pricing['billing_version'],paused_monthly_microusd=(units or 0)*pricing.get('paused_vcpu_monthly_microusd',0)) body.update(billing_consent(api, args, selected['monthly_microusd'], terms=selected)) key = str(uuid.uuid4()) if intent: intent['save']({'body':body,'terms':selected,'key':key}) try: op = api.request('/machines', body, key=key)['operation'] except Failure as error: if intent and 400 <= getattr(error,'status',0) < 500: intent['clear']() raise if intent: intent['clear']() print('Creating %s (%s · %s)…' % (args.name, machine_spec(selected), machine_price(selected)), file=sys.stderr) if args.no_wait: return wait(api, op) print('Ready. Connect with: proton ssh ' + args.name) def lifecycle(verb): def run(args): api = client(args) machine = find(api, args.name) if verb == 'stop': print('Pausing retains your files. '+machine_price(machine), file=sys.stderr) body = billing_consent(api, args, machine.get('monthly_microusd', 20000000), terms=machine) if verb in {'start', 'restart'} else {} op = api.request('/machines/%s/%s' % (machine['id'], verb), body, key=str(uuid.uuid4()))['operation'] if args.no_wait: print('%s: %s requested' % (machine['name'], verb)) return wait(api, op) print('%s: %s complete' % (machine['name'], verb)) return run def cmd_delete(args): api = client(args) machine = find(api, args.name) if not args.yes: if not sys.stdin.isatty(): raise Failure('deletion is permanent; re-run with --yes to confirm non-interactively') typed = input('Permanently delete %s and its disk? Type its name to confirm: ' % machine['name']).strip() if typed != machine['name']: raise Failure('cancelled') op = api.request('/machines/%s/delete' % machine['id'], {'confirm_name': machine['name'], 'purge_disk': True}, key=str(uuid.uuid4()))['operation'] if not args.no_wait: wait(api, op) print('Deleted %s.' % machine['name']) def cmd_keys(args): api = client(args) machine = find(api, args.name) keys = [read_key(path) for path in args.key] if args.key else [read_key(None)] op = api.request('/machines/%s/authorize-key' % machine['id'], {'ssh_keys': keys}, key=str(uuid.uuid4()))['operation'] wait(api, op) print('Replaced SSH keys on %s.' % machine['name']) def cmd_ssh(args): machine = find(client(args), args.name) ssh = endpoint(machine) extra = args.command[1:] if args.command[:1] == ['--'] else args.command command = ['ssh', '-p', str(ssh['port'])] + ssh_options(ssh) + ['ubuntu@' + ssh['hostname']] + extra try: return subprocess.call(command) except FileNotFoundError: raise Failure('OpenSSH client not found; install ssh and try again') from None def cmd_ssh_config(args): machine = find(client(args), args.name) ssh = endpoint(machine) pinned = known_hosts(ssh) lines = ['Host proton-' + machine['name'], ' HostName ' + ssh['hostname'], ' User ubuntu', ' Port %d' % ssh['port']] if pinned: lines += [' UserKnownHostsFile ' + str(pinned), ' StrictHostKeyChecking yes'] print('\n'.join(lines)) def parser(): p = argparse.ArgumentParser(prog='proton', description='Manage your Proton computers. https://proton.computer') p.add_argument('--version', action='version', version='proton ' + VERSION) sub = p.add_subparsers(dest='command', metavar='COMMAND') sub.required = True def add(name, function, help_text, *, machine=False, consent=False, wait=False, json_output=False, aliases=()): s = sub.add_parser(name, aliases=list(aliases), help=help_text, description=help_text) if machine: s.add_argument('name', help='computer name or ID') if consent: s.add_argument('-y', '--yes', action='store_true', help='skip confirmation prompts') if wait: s.add_argument('--no-wait', action='store_true', help='return once the request is accepted') if json_output: s.add_argument('--json', action='store_true', help='print raw JSON') s.set_defaults(func=function) return s add('login', cmd_login, 'sign in through your browser').add_argument( '--no-browser', action='store_true', help='print the sign-in link without opening a browser') add('logout', cmd_logout, 'sign out and revoke this session') add('whoami', cmd_whoami, 'show the signed-in account') add('balance', cmd_balance, 'show your shared Cube balance and Proton usage') add('list', cmd_list, 'list your computers', json_output=True, aliases=('ls',)) add('show', cmd_show, 'show a computer', machine=True, json_output=True) add('diagnose', cmd_diagnose, 'inspect state, memory telemetry, SSH publication, and recent operations', machine=True, json_output=True, aliases=('diagnostics',)) add('recover', cmd_recover, 'check and recover without restarting or recreating the computer', machine=True, wait=True, json_output=True, aliases=('reconcile',)).add_argument('--request-key',help='reuse this key after an uncertain request') add('wait', cmd_wait, 'wait for an existing operation', json_output=True).add_argument('operation') create = add('create', cmd_create, 'create a computer', machine=True, consent=True, wait=True) create.add_argument('--key', help='SSH public key file (default: ~/.ssh/id_ed25519.pub)') create.add_argument('--vcpus', dest='units', type=int, choices=range(2,33), metavar='2..32', help='select shared vCPUs; $6 per vCPU per 730 running hours; includes 2 GB RAM and 15 GB storage per vCPU') create.add_argument('--units', dest='units', type=int, choices=range(2,33), help=argparse.SUPPRESS) add('start', lifecycle('start'), 'start a stopped computer', machine=True, consent=True, wait=True) add('stop', lifecycle('stop'), 'pause a computer and retain its files; accepted pricing determines paused charges', machine=True, wait=True) add('restart', lifecycle('restart'), 'restart a computer', machine=True, consent=True, wait=True) add('delete', cmd_delete, 'permanently delete a computer and its disk', machine=True, consent=True, wait=True) add('keys', cmd_keys, 'replace the SSH public keys on a running computer', machine=True).add_argument( '--key', action='append', help='public key file; repeat for several keys') add('ssh', cmd_ssh, 'open an SSH session (extra arguments run as a command)', machine=True).add_argument( 'command', nargs=argparse.REMAINDER, help='optional command to run') add('ssh-config', cmd_ssh_config, 'print an ~/.ssh/config block for Codex, Claude, or editors', machine=True) return p def main(argv=None): args = parser().parse_args(argv) try: return args.func(args) or 0 except Failure as error: print('proton: ' + str(error), file=sys.stderr) return 1 except KeyboardInterrupt: return 130 if __name__ == '__main__': sys.exit(main())