File size: 3,761 Bytes
37d21bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""Bridge the host's OpenCode V2 credential API to the pinned V1 container.

Never copy the host database or include CLI output in exceptions: exports contain secrets.
"""
import json
from pathlib import Path
import re
import shutil
import subprocess
import fcntl


def valid_auth(content):
    return isinstance(content, dict) and bool(content) and all(
        isinstance(v, dict) and (v.get("key") or v.get("access") and v.get("refresh"))
        for v in content.values())


class OpenCodeLogin:
    def __init__(self, folder, provider):
        self.folder, self.provider = Path(folder), provider
        binary = shutil.which("opencode")
        self.v2 = False
        if binary:
            try:
                result = subprocess.run([binary, "--version"], capture_output=True, text=True, timeout=30)
                version = re.search(r"(?:^|\s)v?(\d+)\.", result.stdout)
                self.v2 = result.returncode == 0 and bool(version) and int(version[1]) >= 2
            except (OSError, subprocess.SubprocessError):
                pass
        self.binary = binary

    def command(self, *args, content=None):
        try:
            result = subprocess.run([self.binary, "auth", *args], input=content, capture_output=True, text=True, timeout=30)
        except (OSError, subprocess.SubprocessError):
            raise RuntimeError("OpenCode credential API is unavailable; check `opencode auth list`.") from None
        if result.returncode:
            raise RuntimeError("OpenCode credential API failed; check `opencode auth list`.")
        return result.stdout

    def account(self):
        try:
            entries = json.loads(self.command("export", self.provider))
            active = [e for e in entries if isinstance(e, dict) and e.get("integrationID") == self.provider and e.get("active") is True]
            if len(active) == 1 and active[0].get("id") and valid_auth({self.provider: active[0].get("value")}):
                return active[0]
        except (ValueError, TypeError):
            pass
        raise RuntimeError(f"No usable active OpenCode account for {self.provider}; check `opencode auth list`.")

    def encode(self, account):
        value = dict(account["value"])
        # V2 calls API-key credentials "key"; the pinned V1 runtime calls them "api".
        if value.get("type") == "key":
            value["type"] = "api"
        return json.dumps({self.provider: value}, sort_keys=True).encode()

    def read(self):
        if not self.v2:
            return (self.folder / "auth.json").read_bytes()
        account = self.account()
        if not hasattr(self, "account_id"):
            self.account_id = account["id"]
        return self.encode(account)

    def persist(self, fresh, initial):
        data = Path(fresh).read_bytes()
        content = json.loads(data)
        if not valid_auth(content) or set(content) != {self.provider}:
            return "invalid_refresh_not_persisted"
        if content == json.loads(initial):
            return "unchanged"
        # All campaign sessions use this lock. Re-export before import so a user
        # login or account switch observed meanwhile is never overwritten.
        with (self.folder / ".benchmark-auth.lock").open("a") as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            current = self.account()
            if current["id"] != self.account_id or json.loads(self.encode(current)) != json.loads(initial):
                return "concurrent_login_preserved"
            value = dict(content[self.provider])
            if value.get("type") == "api":
                value["type"] = "key"
            self.command("import", content=json.dumps([{**current, "value": value}]))
        return "refreshed_credentials_persisted"