import base64 import json import os from pathlib import Path import secrets import subprocess from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import padding ROOT = Path(__file__).resolve().parents[1] STORE = Path.home() / 'tangled.org/zzstoatzz.io/secrets/prod.yaml' CONFIG = Path.home() / '.config/agents-mcp' transfer = ROOT / 'encrypted-tunnel.json' if transfer.exists(): envelope = json.loads(transfer.read_text()) keyfile = CONFIG / 'transfer-key.pem' key = serialization.load_pem_private_key(keyfile.read_bytes(), password=None) secret = key.decrypt(base64.b64decode(envelope['encryptedSecret']), padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) state = {'tunnel_id': envelope['tunnelId'], 'account_id': envelope['accountId'], 'tunnel_secret': base64.b64encode(secret).decode(), 'jwt_signing_key': secrets.token_urlsafe(48)} subprocess.run(['sops', 'set', '--value-stdin', str(STORE), '["agents_mcp"]'], input=json.dumps(state), text=True, check=True, stdout=subprocess.DEVNULL) keyfile.unlink() transfer.unlink() else: state = json.loads(subprocess.check_output(['sops', '-d', '--extract', '["agents_mcp"]', '--output-type', 'json', str(STORE)])) def write_private(name, value): path = CONFIG / name if path.exists() and path.read_text() == value: print(name + ': already current') return fd = os.open(path, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0o600) with os.fdopen(fd, 'w') as f: f.write(value) os.chmod(path, 0o600) print(name + ': updated') write_private('tunnel.json', json.dumps({'AccountTag': state['account_id'], 'TunnelID': state['tunnel_id'], 'TunnelSecret': state['tunnel_secret']})) write_private('server.env', 'SESSIONS_MCP_BASE_URL=https://agents.zzstoatzz.io\nSESSIONS_MCP_ALLOWED_DIDS=did:plc:xbtmt2zjwlrfegqvch7fboei\nSESSIONS_MCP_JWT_SIGNING_KEY=' + state['jwt_signing_key'] + '\n') write_private('cloudflared.yml', f"tunnel: {state['tunnel_id']}\ncredentials-file: {CONFIG / 'tunnel.json'}\ningress:\n - hostname: agents.zzstoatzz.io\n service: http://127.0.0.1:8766\n - service: http_status:404\n")