File size: 1,822 Bytes
6b86af2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
import json
from pathlib import Path

ROOT = Path('/data/appdata/kiro-stack')
GO_CONFIG = ROOT / 'kiro-go' / 'data' / 'config.json'
GW_ENV = ROOT / 'kiro-gateway' / '.env'


def load_env(path: Path):
    out = {}
    lines = []
    if path.exists():
        lines = path.read_text(encoding='utf-8').splitlines()
        for line in lines:
            s = line.strip()
            if not s or s.startswith('#') or '=' not in line:
                continue
            k, v = line.split('=', 1)
            out[k.strip()] = v.strip().strip('"')
    return out, lines


def quote(v: str) -> str:
    return '"' + v.replace('"', '\\"') + '"'


def main():
    data = json.loads(GO_CONFIG.read_text(encoding='utf-8'))
    accounts = data.get('accounts', [])

    env_map, lines = load_env(GW_ENV)
    primary = env_map.get('REFRESH_TOKEN', '')

    tokens = []
    seen = set()
    for a in accounts:
        if not a.get('enabled', False):
            continue
        token = (a.get('refreshToken') or '').strip()
        if not token:
            continue
        if token == primary:
            continue
        if token in seen:
            continue
        seen.add(token)
        tokens.append(token)

    joined = ','.join(tokens)
    kv = f'KIRO_REFRESH_TOKENS={quote(joined)}'

    replaced = False
    new_lines = []
    for line in lines:
        if line.startswith('KIRO_REFRESH_TOKENS='):
            new_lines.append(kv)
            replaced = True
        else:
            new_lines.append(line)

    if not replaced:
        if new_lines and new_lines[-1].strip() != '':
            new_lines.append('')
        new_lines.append(kv)

    GW_ENV.write_text('\n'.join(new_lines) + '\n', encoding='utf-8')
    print(f'synced_tokens={len(tokens)}')


if __name__ == '__main__':
    main()