recovered snapshot from suspended aaronjaworski710 (history unavailable)
This commit is contained in:
@@ -0,0 +1,114 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>type-toolkit — control plane</title>
|
||||
<style>
|
||||
:root{--bg:#0d1117;--panel:#161b22;--brd:#30363d;--fg:#c9d1d9;--dim:#8b949e;--acc:#58a6ff;--ok:#3fb950;--err:#f85149;--warn:#d29922}
|
||||
*{box-sizing:border-box;margin:0;padding:0}
|
||||
body{background:var(--bg);color:var(--fg);font:14px/1.5 -apple-system,'Segoe UI',Roboto,sans-serif;padding:24px}
|
||||
h1{font-size:20px;margin-bottom:4px}
|
||||
.sub{color:var(--dim);font-size:12px;margin-bottom:20px}
|
||||
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:14px;margin-bottom:20px}
|
||||
.card{background:var(--panel);border:1px solid var(--brd);border-radius:8px;padding:16px}
|
||||
.card h2{font-size:12px;text-transform:uppercase;color:var(--dim);letter-spacing:.5px;margin-bottom:10px}
|
||||
.big{font-size:26px;font-weight:600}
|
||||
.big.ok{color:var(--ok)}.big.err{color:var(--err)}.big.w{color:var(--warn)}
|
||||
.row{display:flex;justify-content:space-between;padding:3px 0;font-size:13px}
|
||||
.row span:last-child{color:var(--dim)}
|
||||
.bar{display:flex;gap:10px;margin-bottom:20px;flex-wrap:wrap}
|
||||
button{background:#21262d;border:1px solid var(--brd);color:var(--fg);border-radius:6px;padding:8px 16px;font-size:13px;cursor:pointer}
|
||||
button:hover{border-color:var(--acc);color:var(--acc)}
|
||||
button:disabled{opacity:.45;cursor:wait}
|
||||
input{background:#0d1117;border:1px solid var(--brd);color:var(--fg);border-radius:6px;padding:8px 10px;font-size:13px}
|
||||
table{width:100%;border-collapse:collapse;font-size:13px}
|
||||
th{ text-align:left;color:var(--dim);font-size:11px;text-transform:uppercase;padding:8px 10px;border-bottom:1px solid var(--brd)}
|
||||
td{padding:8px 10px;border-bottom:1px solid #21262d}
|
||||
.tag{display:inline-block;padding:2px 8px;border-radius:10px;font-size:11px}
|
||||
.tag.ok{background:#0d2818;color:var(--ok)}.tag.err{background:#2d0b0e;color:var(--err)}
|
||||
.log{background:#0d1117;border:1px solid var(--brd);border-radius:8px;padding:12px;font:12px/1.6 Consolas,monospace;max-height:320px;overflow-y:auto;white-space:pre-wrap}
|
||||
.log .t{color:var(--dim)}
|
||||
.log .ok{color:var(--ok)}.log .err{color:var(--err)}
|
||||
.note{background:#1f2937;border-left:3px solid var(--warn);padding:10px 14px;border-radius:0 6px 6px 0;margin-bottom:20px;font-size:12px;color:#e3b341}
|
||||
a{color:var(--acc);text-decoration:none}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>type-toolkit</h1>
|
||||
<div class="sub">type.com agent platform — autoreg / pool / OpenAI-compat gateway. <a href="http://127.0.0.1:8311/health" target="_blank">gateway :8311</a></div>
|
||||
|
||||
<div class="note">oRPC API закрыт сервером для agent-токенов (401 Invalid token, aud-политика). Пул, авторег и ротация identity работают полностью — см. FINDINGS.md.</div>
|
||||
|
||||
<div class="grid">
|
||||
<div class="card"><h2>Gateway :8311</h2><div class="big" id="gw">—</div></div>
|
||||
<div class="card"><h2>Аккаунтов в пуле</h2><div class="big" id="cnt">—</div></div>
|
||||
<div class="card"><h2>С токеном</h2><div class="big" id="tok">—</div></div>
|
||||
<div class="card"><h2>Обновлено</h2><div class="big w" id="now" style="font-size:14px">—</div></div>
|
||||
</div>
|
||||
|
||||
<div class="bar">
|
||||
<button id="btn-reg" onclick="autoreg()">+ Зарегать акк</button>
|
||||
<input id="org" value="reform-org" placeholder="org name" style="width:140px">
|
||||
<button id="btn-refr" onclick="refresh()">Обновить токены</button>
|
||||
<button onclick="load()">Обновить данные</button>
|
||||
</div>
|
||||
|
||||
<table id="tbl"><thead><tr>
|
||||
<th>email</th><th>org</th><th>создан</th><th>посл. refresh</th><th>статус</th><th>token</th>
|
||||
</tr></thead><tbody></tbody></table>
|
||||
|
||||
<h2 style="font-size:12px;text-transform:uppercase;color:var(--dim);margin:20px 0 8px">Лог</h2>
|
||||
<div class="log" id="log"></div>
|
||||
|
||||
<script>
|
||||
async function load(){
|
||||
try{
|
||||
const s = await (await fetch('/api/status')).json();
|
||||
const gw = document.getElementById('gw');
|
||||
gw.textContent = s.gateway.up ? 'UP' : 'DOWN';
|
||||
gw.className = 'big ' + (s.gateway.up ? 'ok' : 'err');
|
||||
document.getElementById('cnt').textContent = s.pool.count;
|
||||
const tok = document.getElementById('tok');
|
||||
tok.textContent = s.pool.with_token;
|
||||
tok.className = 'big ' + (s.pool.with_token ? 'ok' : 'w');
|
||||
document.getElementById('now').textContent = s.now;
|
||||
const lg = document.getElementById('log');
|
||||
lg.innerHTML = s.log.map(l=>{
|
||||
const m = l.match(/\[(\d+:\d+:\d+)\]\s(.*)/);
|
||||
const t = m?m[1]:''; const txt=(m?m[2]:l)||'';
|
||||
const cls = /OK/.test(txt)?'ok':( /FAIL|ERR/.test(txt)?'err':'');
|
||||
return `<span class="t">[${t}]</span> <span class="${cls}">${txt}</span>`;
|
||||
}).join('\n');
|
||||
lg.scrollTop = lg.scrollHeight;
|
||||
}catch(e){ console.error(e); }
|
||||
}
|
||||
async function accounts(){
|
||||
try{
|
||||
const a = await (await fetch('/api/accounts')).json();
|
||||
document.querySelector('#tbl tbody').innerHTML = a.map(x=>`<tr>
|
||||
<td>${x.email||''}</td><td>${x.org||''}</td><td>${x.created_at||''}</td>
|
||||
<td>${x.last_refresh||''}</td>
|
||||
<td>${x.last_status?`<span class="tag ${/^refresh|^exchange/.test(x.last_status)?'ok':'err'}">${x.last_status}</span>`:''}</td>
|
||||
<td>${x.access_token_len||0}b</td></tr>`).join('') || '<tr><td colspan=6 style="color:var(--dim)">пусто</td></tr>';
|
||||
}catch(e){ console.error(e); }
|
||||
}
|
||||
async function autoreg(){
|
||||
const b = document.getElementById('btn-reg'); b.disabled = true; b.textContent = 'Регистрирую…';
|
||||
try{
|
||||
const r = await (await fetch('/api/autoreg', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({org: document.getElementById('org').value})})).json();
|
||||
if(!r.ok) alert('Ошибка: ' + r.error);
|
||||
}catch(e){ alert('Сбой: ' + e); }
|
||||
b.disabled = false; b.textContent = '+ Зарегать акк';
|
||||
load(); accounts();
|
||||
}
|
||||
async function refresh(){
|
||||
const b = document.getElementById('btn-refr'); b.disabled = true; b.textContent = 'Обновляю…';
|
||||
try{ await fetch('/api/refresh', {method:'POST'}); }catch(e){}
|
||||
b.disabled = false; b.textContent = 'Обновить токены';
|
||||
load(); accounts();
|
||||
}
|
||||
load(); accounts();
|
||||
setInterval(()=>{load(); accounts();}, 10000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,239 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
gateway.py - OpenAI-compatible gateway over the type.com agent pool.
|
||||
Port 8311. Stdlib only. Pool-aware: rotates accounts from server/pool.json,
|
||||
auto-refreshes identity (rotating refresh_token) before use.
|
||||
|
||||
Endpoints:
|
||||
GET /v1/models -> static agent catalog (pool-backed)
|
||||
GET /health -> {"ok", "pool", "upstream_mode"}
|
||||
POST /v1/chat/completions -> oRPC bridge (cli/messages/send etc.)
|
||||
Upstream api.type.com currently rejects agent tokens with
|
||||
401 Invalid token (aud=client, server policy - see FINDINGS.md),
|
||||
so completions return the upstream status verbatim.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
ROOT = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
POOL_PATH = os.path.join(ROOT, "pool.json")
|
||||
PORT = int(os.environ.get("TYPE2API_PORT", "8311"))
|
||||
UA = "TypeCLI/1.0.0"
|
||||
TOKEN_TTL = 3600
|
||||
|
||||
POOL_LOCK = threading.Lock()
|
||||
_ROBIN = {"i": 0}
|
||||
STATS = {"requests": 0, "upstream_401": 0, "upstream_200": 0, "refreshes": 0}
|
||||
|
||||
|
||||
def log(msg):
|
||||
print("[gateway %s] %s" % (time.strftime("%H:%M:%S"), msg), flush=True)
|
||||
|
||||
|
||||
def api(method, url, body=None, form=None, headers=None, timeout=30):
|
||||
h = {"Content-Type": "application/json", "User-Agent": UA}
|
||||
if headers:
|
||||
h.update(headers)
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
if form is not None:
|
||||
data = urllib.parse.urlencode(form).encode()
|
||||
h["Content-Type"] = "application/x-www-form-urlencoded"
|
||||
req = urllib.request.Request(url, data=data, headers=h, method=method)
|
||||
try:
|
||||
r = urllib.request.urlopen(req, timeout=timeout)
|
||||
raw = r.read()
|
||||
status = r.status
|
||||
except urllib.error.HTTPError as e:
|
||||
raw = e.read()
|
||||
status = e.code
|
||||
except Exception as e:
|
||||
return 0, {"error": str(e)}
|
||||
try:
|
||||
parsed = json.loads(raw or b"{}")
|
||||
except Exception:
|
||||
parsed = {"_raw": raw.decode("utf-8", "replace")[:300]}
|
||||
return status, parsed
|
||||
|
||||
|
||||
def load_pool():
|
||||
if not os.path.exists(POOL_PATH):
|
||||
return []
|
||||
try:
|
||||
with open(POOL_PATH, encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def save_pool(pool):
|
||||
tmp = POOL_PATH + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(pool, f, indent=1)
|
||||
os.replace(tmp, POOL_PATH)
|
||||
|
||||
|
||||
def refresh_account(acct):
|
||||
"""Identity refresh (rotating rt) + jwt-bearer exchange. Live-verified flow."""
|
||||
rt = acct.get("refresh_token")
|
||||
if not rt:
|
||||
raise RuntimeError("no refresh_token for %s" % acct.get("email"))
|
||||
st, body = api("POST", "https://auth.type.com/agent/identity",
|
||||
body={"refresh_token": rt, "type": "refresh"})
|
||||
if st != 200:
|
||||
raise RuntimeError("identity refresh %s: %s" % (st, str(body)[:120]))
|
||||
ident = body.get("identity") or {}
|
||||
new_rt = (ident.get("refresh_token") or {}).get("value")
|
||||
if ident.get("assertion"):
|
||||
acct["assertion"] = ident["assertion"]
|
||||
if new_rt:
|
||||
acct["refresh_token"] = new_rt
|
||||
st2, tok = api("POST", acct.get("token_endpoint", "https://auth.type.com/oauth2/token"),
|
||||
form={"assertion": acct["assertion"],
|
||||
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer"})
|
||||
at = tok.get("access_token")
|
||||
if not at:
|
||||
raise RuntimeError("exchange %s: %s" % (st2, str(tok)[:120]))
|
||||
acct["access_token"] = at
|
||||
acct["access_token_len"] = len(at)
|
||||
acct["last_refresh"] = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
acct["last_status"] = "refresh:%s/exchange:%s" % (st, st2)
|
||||
acct["token_expires_at"] = time.time() + TOKEN_TTL
|
||||
STATS["refreshes"] += 1
|
||||
return acct
|
||||
|
||||
|
||||
def pick_account():
|
||||
"""Round-robin a pool account with a live-ish token; refresh if stale."""
|
||||
with POOL_LOCK:
|
||||
pool = load_pool()
|
||||
usable = [a for a in pool if a.get("refresh_token")]
|
||||
if not usable:
|
||||
raise RuntimeError("pool empty: POST http://127.0.0.1:8312/api/autoreg first")
|
||||
acct = usable[_ROBIN["i"] % len(usable)]
|
||||
_ROBIN["i"] += 1
|
||||
if time.time() > acct.get("token_expires_at", 0):
|
||||
refresh_account(acct)
|
||||
with POOL_LOCK:
|
||||
pool = load_pool()
|
||||
for i, a in enumerate(pool):
|
||||
if a.get("email") == acct["email"]:
|
||||
pool[i] = acct
|
||||
save_pool(pool)
|
||||
return acct
|
||||
|
||||
|
||||
def orpc(acct, procedure, args=None):
|
||||
return api("POST", "https://api.type.com/api/orpc/" + procedure,
|
||||
body={"json": args or {}},
|
||||
headers={"Authorization": "Bearer " + acct["access_token"]})
|
||||
|
||||
|
||||
SEND_PROCEDURE_CANDIDATES = [
|
||||
"cli/threads/create", "cli/messages/create", "cli/threads/send",
|
||||
"cli/chat/send", "cli/agents/run", "cli/threads/message",
|
||||
]
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def _send(self, code, payload):
|
||||
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self):
|
||||
if self.path == "/health":
|
||||
with POOL_LOCK:
|
||||
pool = load_pool()
|
||||
self._send(200, {
|
||||
"ok": True,
|
||||
"port": PORT,
|
||||
"pool": {"count": len(pool), "with_token": sum(1 for a in pool if a.get("access_token"))},
|
||||
"stats": STATS,
|
||||
"upstream_mode": "agent-pool (oRPC gated server-side: 401 Invalid token)",
|
||||
})
|
||||
elif self.path == "/v1/models":
|
||||
self._send(200, {"object": "list", "data": [
|
||||
{"id": "type-agent", "object": "model", "owned_by": "type.com"},
|
||||
{"id": "type-default", "object": "model", "owned_by": "type.com"},
|
||||
]})
|
||||
else:
|
||||
self._send(404, {"error": {"message": "not found"}})
|
||||
|
||||
def do_POST(self):
|
||||
if self.path != "/v1/chat/completions":
|
||||
self._send(404, {"error": {"message": "not found"}})
|
||||
return
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
try:
|
||||
req = json.loads(self.rfile.read(length) or b"{}")
|
||||
except Exception:
|
||||
req = {}
|
||||
STATS["requests"] += 1
|
||||
messages = req.get("messages") or []
|
||||
last = messages[-1].get("content", "") if messages else ""
|
||||
prompt = last if isinstance(last, str) else json.dumps(last, ensure_ascii=False)
|
||||
try:
|
||||
acct = pick_account()
|
||||
except Exception as e:
|
||||
self._send(500, {"error": {"message": str(e), "type": "pool_error"}})
|
||||
return
|
||||
# probe live procedures with the account token
|
||||
last_err = None
|
||||
for proc in SEND_PROCEDURE_CANDIDATES:
|
||||
st, body = orpc(acct, proc, {"text": prompt})
|
||||
if st == 200:
|
||||
STATS["upstream_200"] += 1
|
||||
content = body
|
||||
if isinstance(content, dict):
|
||||
content = content.get("json") or content.get("content") or json.dumps(content, ensure_ascii=False)
|
||||
out = {
|
||||
"id": "chatcmpl-type-%d" % int(time.time() * 1000),
|
||||
"object": "chat.completion", "created": int(time.time()),
|
||||
"model": req.get("model", "type-agent"),
|
||||
"choices": [{"index": 0, "message": {"role": "assistant", "content": str(content)},
|
||||
"finish_reason": "stop"}],
|
||||
}
|
||||
self._send(200, out)
|
||||
return
|
||||
last_err = (st, body)
|
||||
if st == 404:
|
||||
continue
|
||||
break
|
||||
STATS["upstream_401"] += 1
|
||||
st, body = last_err or (0, {"error": "no procedure"})
|
||||
self._send(502, {
|
||||
"error": {
|
||||
"message": "type.com oRPC rejected agent token: HTTP %s %s" % (
|
||||
st, json.dumps(body, ensure_ascii=False)[:300]),
|
||||
"type": "type_upstream",
|
||||
"upstream_status": st,
|
||||
"note": "api.type.com requires aud=https://api.type.com (user token). "
|
||||
"Agent tokens get 401 by server policy. See FINDINGS.md.",
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
def main():
|
||||
log("gateway on :%d, pool=%s" % (PORT, POOL_PATH))
|
||||
ThreadingHTTPServer(("0.0.0.0", PORT), Handler).serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,362 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
manager.py - type-toolkit control plane: autoreg API + account pool + dashboard.
|
||||
Port 8312. Stdlib only.
|
||||
|
||||
Endpoints:
|
||||
GET / dashboard (dashboard.html)
|
||||
GET /api/status {gateway, pool summary, log tail}
|
||||
GET /api/accounts pool (redacted - no tokens)
|
||||
POST /api/autoreg {"org": "reform-org"} -> register 1 account (60-180s)
|
||||
POST /api/refresh refresh all accounts (identity refresh + jwt-bearer exchange)
|
||||
|
||||
Autoreg flow (live-verified 2026-09-30):
|
||||
mail.tm account -> auth.type.com/agent/identity (service_auth)
|
||||
-> api.type.com/api/agent-signup/start -> email code via mail.tm
|
||||
-> agent-signup/verify -> agent/identity/claim/complete
|
||||
-> oauth2/token jwt-bearer exchange -> access_token
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import string
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
ROOT = os.path.dirname(os.path.abspath(__file__))
|
||||
POOL_PATH = os.path.join(ROOT, "pool.json")
|
||||
DASH_PATH = os.path.join(ROOT, "dashboard.html")
|
||||
GATEWAY_URL = os.environ.get("TYPE2API_URL", "http://127.0.0.1:8311")
|
||||
PORT = int(os.environ.get("TYPE_MANAGER_PORT", "8312"))
|
||||
UA = "TypeCLI/1.0.0"
|
||||
|
||||
POOL_LOCK = threading.Lock()
|
||||
LOG = []
|
||||
|
||||
|
||||
def log(msg):
|
||||
LOG.append("[%s] %s" % (time.strftime("%H:%M:%S"), msg))
|
||||
del LOG[:-200]
|
||||
print(msg, flush=True)
|
||||
|
||||
|
||||
def api(method, url, body=None, form=None, headers=None, timeout=30):
|
||||
h = {"Content-Type": "application/json", "User-Agent": UA}
|
||||
if headers:
|
||||
h.update(headers)
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
if form is not None:
|
||||
data = urllib.parse.urlencode(form).encode()
|
||||
h["Content-Type"] = "application/x-www-form-urlencoded"
|
||||
req = urllib.request.Request(url, data=data, headers=h, method=method)
|
||||
try:
|
||||
r = urllib.request.urlopen(req, timeout=timeout)
|
||||
raw = r.read()
|
||||
status = r.status
|
||||
except urllib.error.HTTPError as e:
|
||||
raw = e.read()
|
||||
status = e.code
|
||||
except Exception as e:
|
||||
return 0, {"error": str(e)}
|
||||
try:
|
||||
parsed = json.loads(raw or b"{}")
|
||||
except Exception:
|
||||
parsed = {"_raw": raw.decode("utf-8", "replace")[:300]}
|
||||
return status, parsed
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- pool
|
||||
def load_pool():
|
||||
if not os.path.exists(POOL_PATH):
|
||||
return []
|
||||
try:
|
||||
with open(POOL_PATH, encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def save_pool(pool):
|
||||
tmp = POOL_PATH + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(pool, f, indent=1)
|
||||
os.replace(tmp, POOL_PATH)
|
||||
|
||||
|
||||
def redact(acct):
|
||||
return {
|
||||
"email": acct.get("email"),
|
||||
"org": (acct.get("org") or {}).get("slug") if isinstance(acct.get("org"), dict) else acct.get("org"),
|
||||
"created_at": acct.get("created_at"),
|
||||
"last_refresh": acct.get("last_refresh"),
|
||||
"last_status": acct.get("last_status"),
|
||||
"access_token_len": acct.get("access_token_len") or len(acct.get("access_token") or ""),
|
||||
"has_refresh": bool(acct.get("refresh_token")),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- autoreg (full_reg.py flow)
|
||||
def autoreg_one(org="reform-org"):
|
||||
user = "tt" + "".join(random.choices(string.ascii_lowercase + string.digits, k=6))
|
||||
# dynamic mail.tm domain (hardcoded domains go stale -> 422 ConstraintViolation)
|
||||
st, doms = api("GET", "https://api.mail.tm/domains")
|
||||
dom = None
|
||||
if st == 200 and isinstance(doms, dict):
|
||||
for d in doms.get("hydra:member", []):
|
||||
if d.get("isActive"):
|
||||
dom = d.get("domain")
|
||||
break
|
||||
if not dom:
|
||||
raise RuntimeError("mail.tm domains unavailable: %s" % str(doms)[:120])
|
||||
email = user + "@" + dom
|
||||
mpwd = "Tp" + "".join(random.choices(string.ascii_letters + string.digits, k=12)) + "!"
|
||||
|
||||
st, acc = api("POST", "https://api.mail.tm/accounts", body={"address": email, "password": mpwd})
|
||||
if st not in (200, 201):
|
||||
raise RuntimeError("mail.tm create %s: %s" % (st, str(acc)[:150]))
|
||||
st, tok = api("POST", "https://api.mail.tm/token", body={"address": email, "password": mpwd})
|
||||
mt = tok.get("token")
|
||||
if not mt:
|
||||
raise RuntimeError("mail.tm no token: %s" % str(tok)[:150])
|
||||
log("mail created %s" % email)
|
||||
|
||||
st, reg = api("POST", "https://auth.type.com/agent/identity",
|
||||
body={"type": "service_auth", "login_hint": email})
|
||||
claim = reg.get("claim") or {}
|
||||
if not claim.get("token"):
|
||||
raise RuntimeError("service_auth %s: %s" % (st, str(reg)[:200]))
|
||||
cat = urllib.parse.parse_qs(
|
||||
urllib.parse.urlparse(claim["attempt"]["verification_uri"]).query)["token"][0]
|
||||
log("claim ok (HTTP %s)" % st)
|
||||
|
||||
st, s = api("POST", "https://api.type.com/api/agent-signup/start",
|
||||
body={"claimAttemptToken": cat, "email": email, "organizationName": org})
|
||||
if not s.get("signupToken"):
|
||||
raise RuntimeError("signup/start %s: %s" % (st, str(s)[:200]))
|
||||
log("signup started, waiting for email code")
|
||||
|
||||
code = None
|
||||
for _ in range(30):
|
||||
time.sleep(6)
|
||||
st, msgs = api("GET", "https://api.mail.tm/messages",
|
||||
headers={"Authorization": "Bearer " + mt})
|
||||
lst = msgs.get("hydra:member", msgs if isinstance(msgs, list) else [])
|
||||
for m in lst:
|
||||
frm = (m.get("from") or {}).get("address", "")
|
||||
if "type" in (frm + m.get("subject", "")).lower():
|
||||
st2, full = api("GET", "https://api.mail.tm/messages/" + m["id"],
|
||||
headers={"Authorization": "Bearer " + mt})
|
||||
body_text = full.get("text", "") or json.dumps(full.get("html", []))
|
||||
codes = re.findall(r"\b(\d{6})\b", body_text)
|
||||
if codes:
|
||||
code = codes[-1]
|
||||
break
|
||||
if code:
|
||||
break
|
||||
if not code:
|
||||
raise RuntimeError("no email code within 180s")
|
||||
log("email code %s" % code)
|
||||
|
||||
st, v = api("POST", "https://api.type.com/api/agent-signup/verify",
|
||||
body={"code": code, "signupToken": s["signupToken"]})
|
||||
uc = (v.get("claim") or {}).get("userCode")
|
||||
if not uc:
|
||||
raise RuntimeError("verify %s: %s" % (st, str(v)[:200]))
|
||||
log("verified, org=%s" % ((v.get("organization") or {}).get("slug")))
|
||||
|
||||
st, done = api("POST", "https://auth.type.com/agent/identity/claim/complete",
|
||||
body={"claim_token": claim["token"], "user_code": uc})
|
||||
ident = done.get("identity") or {}
|
||||
if not ident.get("assertion"):
|
||||
raise RuntimeError("claim/complete %s: %s" % (st, str(done)[:200]))
|
||||
log("identity issued")
|
||||
|
||||
st, tok2 = api("POST", "https://auth.type.com/oauth2/token", form={
|
||||
"assertion": ident["assertion"],
|
||||
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
|
||||
})
|
||||
at = tok2.get("access_token")
|
||||
log("exchange HTTP %s, token len %d" % (st, len(at or "")))
|
||||
if not at:
|
||||
raise RuntimeError("exchange %s: %s" % (st, str(tok2)[:200]))
|
||||
|
||||
return {
|
||||
"email": email,
|
||||
"mail_pwd": mpwd,
|
||||
"mt_token": mt,
|
||||
"assertion": ident.get("assertion"),
|
||||
"refresh_token": (ident.get("refresh_token") or {}).get("value"),
|
||||
"token_endpoint": "https://auth.type.com/oauth2/token",
|
||||
"org": v.get("organization"),
|
||||
"user_created": v.get("organizationCreated"),
|
||||
"created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"last_refresh": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"last_status": "exchange:%s" % st,
|
||||
"access_token_len": len(at),
|
||||
"access_token": at,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- refresh (live-verified flow)
|
||||
def refresh_one(acct):
|
||||
rt = acct.get("refresh_token")
|
||||
if not rt:
|
||||
raise RuntimeError("no refresh_token")
|
||||
st, body = api("POST", "https://auth.type.com/agent/identity",
|
||||
body={"refresh_token": rt, "type": "refresh"})
|
||||
if st != 200:
|
||||
raise RuntimeError("identity refresh %s: %s" % (st, str(body)[:150]))
|
||||
ident = body.get("identity") or {}
|
||||
new_rt = (ident.get("refresh_token") or {}).get("value")
|
||||
if ident.get("assertion"):
|
||||
acct["assertion"] = ident["assertion"]
|
||||
if new_rt:
|
||||
acct["refresh_token"] = new_rt
|
||||
st2, tok = api("POST", acct.get("token_endpoint", "https://auth.type.com/oauth2/token"),
|
||||
form={
|
||||
"assertion": acct["assertion"],
|
||||
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
|
||||
})
|
||||
at = tok.get("access_token")
|
||||
if not at:
|
||||
raise RuntimeError("exchange %s: %s" % (st2, str(tok)[:150]))
|
||||
acct["access_token"] = at
|
||||
acct["access_token_len"] = len(at)
|
||||
acct["last_refresh"] = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
acct["last_status"] = "refresh:%s/exchange:%s" % (st, st2)
|
||||
return acct
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- http
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def _send(self, code, payload, ctype="application/json; charset=utf-8"):
|
||||
if isinstance(payload, (dict, list)):
|
||||
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
elif isinstance(payload, str):
|
||||
body = payload.encode("utf-8")
|
||||
else:
|
||||
body = payload
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self):
|
||||
if self.path in ("/", "/index.html", "/dashboard"):
|
||||
try:
|
||||
with open(DASH_PATH, "rb") as f:
|
||||
self._send(200, f.read(), "text/html; charset=utf-8")
|
||||
except Exception as e:
|
||||
self._send(500, {"error": str(e)})
|
||||
elif self.path == "/api/status":
|
||||
st, gw = api("GET", GATEWAY_URL + "/health", timeout=5)
|
||||
with POOL_LOCK:
|
||||
pool = load_pool()
|
||||
self._send(200, {
|
||||
"gateway": {"up": st == 200, "port": 8311, "body": gw},
|
||||
"pool": {
|
||||
"count": len(pool),
|
||||
"with_token": sum(1 for a in pool if a.get("access_token")),
|
||||
},
|
||||
"log": LOG[-30:],
|
||||
"now": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
})
|
||||
elif self.path == "/api/accounts":
|
||||
with POOL_LOCK:
|
||||
pool = load_pool()
|
||||
self._send(200, [redact(a) for a in pool])
|
||||
elif self.path.split("?")[0] == "/files":
|
||||
# agent-visible file browser (repo dir only; secrets redacted)
|
||||
qs = urllib.parse.urlparse(self.path).query
|
||||
q = urllib.parse.parse_qs(qs)
|
||||
rel = (q.get("path") or [""])[0].replace("\\", "/").lstrip("/")
|
||||
base = os.path.dirname(ROOT) # type-toolkit dir
|
||||
target = os.path.normpath(os.path.join(base, rel))
|
||||
if not target.startswith(base):
|
||||
self._send(403, {"error": "outside whitelist"})
|
||||
return
|
||||
secret_names = {"pool.json", "acct.json", "api_token.json"}
|
||||
try:
|
||||
if os.path.isdir(target):
|
||||
entries = []
|
||||
for name in sorted(os.listdir(target)):
|
||||
if name in ("__pycache__", ".git"):
|
||||
continue
|
||||
p = os.path.join(target, name)
|
||||
entries.append({"name": name, "dir": os.path.isdir(p),
|
||||
"size": os.path.getsize(p) if os.path.isfile(p) else 0})
|
||||
self._send(200, {"path": rel or ".", "type": "dir", "entries": entries})
|
||||
elif os.path.isfile(target):
|
||||
if os.path.basename(target) in secret_names or os.path.getsize(target) > 2 * 1024 * 1024:
|
||||
self._send(200, {"path": rel, "type": "secret-or-big",
|
||||
"note": "content withheld (credentials file or >2MB)"})
|
||||
else:
|
||||
with open(target, "rb") as f:
|
||||
self._send(200, {"path": rel, "type": "file",
|
||||
"content": f.read().decode("utf-8", errors="replace")})
|
||||
else:
|
||||
self._send(404, {"error": "not found"})
|
||||
except Exception as e:
|
||||
self._send(500, {"error": str(e)})
|
||||
else:
|
||||
self._send(404, {"error": "not found"})
|
||||
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
req = {}
|
||||
if length:
|
||||
try:
|
||||
req = json.loads(self.rfile.read(length) or b"{}")
|
||||
except Exception:
|
||||
req = {}
|
||||
if self.path == "/api/autoreg":
|
||||
org = (req.get("org") or "reform-org").strip() or "reform-org"
|
||||
try:
|
||||
acct = autoreg_one(org)
|
||||
with POOL_LOCK:
|
||||
pool = load_pool()
|
||||
pool.append(acct)
|
||||
save_pool(pool)
|
||||
log("autoreg OK %s -> %s" % (acct["email"], redact(acct)["org"]))
|
||||
self._send(200, {"ok": True, "account": redact(acct)})
|
||||
except Exception as e:
|
||||
log("autoreg FAIL: %s" % e)
|
||||
self._send(500, {"ok": False, "error": str(e)})
|
||||
elif self.path == "/api/refresh":
|
||||
with POOL_LOCK:
|
||||
pool = load_pool()
|
||||
results = []
|
||||
for a in pool:
|
||||
try:
|
||||
refresh_one(a)
|
||||
results.append({"email": a["email"], "ok": True})
|
||||
log("refresh OK %s" % a["email"])
|
||||
except Exception as e:
|
||||
a["last_status"] = "error:%s" % str(e)[:80]
|
||||
results.append({"email": a["email"], "ok": False, "error": str(e)})
|
||||
log("refresh FAIL %s: %s" % (a["email"], str(e)[:100]))
|
||||
with POOL_LOCK:
|
||||
save_pool(pool)
|
||||
self._send(200, results)
|
||||
else:
|
||||
self._send(404, {"error": "not found"})
|
||||
|
||||
|
||||
def main():
|
||||
log("manager on :%d (gateway %s)" % (PORT, GATEWAY_URL))
|
||||
ThreadingHTTPServer(("0.0.0.0", PORT), Handler).serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user