recovered snapshot from suspended aaronjaworski710 (history unavailable)

This commit is contained in:
reform
2026-10-23 20:04:08 +03:00
commit 57f005839c
42 changed files with 6518 additions and 0 deletions
+196
View File
@@ -0,0 +1,196 @@
# type.com reverse — protocol-level client & signup farm
**Type** (type.com) — shared-agent platform ("automations & agents powered by Claude, Codex, Grok, Gemini").
This repo contains the reverse of their CLI auth/protocol layer and a working
**browser-free protocol client + account farm** in one Python file (stdlib only).
```
type.com → api.type.com (server) + auth.type.com (WorkOS issuer)
CLI → Bun single-executable (102MB, linux/darwin/win) — bundle extractable
identity → WorkOS user_management: service_auth / device_code / jwt-bearer / refresh_token
signup → 6-digit email code, NO browser, NO captcha observed
storage → ~/.type/credentials/<profile>.json
```
## Files
| File | What |
|---|---|
| `type_client.py` | Protocol client: discover / signup / complete / refresh / me / device-login / batch farm |
| `README.md` | This reverse report |
## Reversed protocol
### 1. Discovery (RFC 8414 chain)
```
GET https://api.type.com/.well-known/oauth-protected-resource
→ { resource, authorization_servers: ["https://auth.type.com"], type_workos_client_id }
GET https://auth.type.com/.well-known/oauth-authorization-server
→ { issuer, token_endpoint: "https://auth.type.com/oauth2/token",
agent_auth: { identity_types_supported: ["service_auth"],
identity_endpoint: "https://auth.type.com/agent/identity" } }
```
Bundled WorkOS client_id (from CLI binary): `client_01K5GFDDKQWV8MM9FSRZS3YNNN`
(server discovery also returns `type_workos_client_id`).
### 2. Signup — service_auth, browserless (steps 1–4 live-verified, 5–7 from source)
```
POST https://auth.type.com/agent/identity
{ "login_hint": "<email>", "type": "service_auth" }
→ { claim: { token, attempt: { verification_uri (?token=...) → claimAttemptToken } },
scopes: { post_claim: ["api.read"] } } # REQUIRED_AGENT_SIGNUP_SCOPES = ["api.read"]
POST https://api.type.com/api/agent-signup/start
{ claimAttemptToken, email, organizationName }
→ { ok, email, signupToken } # 6-digit code sent by email
POST https://api.type.com/api/agent-signup/verify
{ code, signupToken } # code = 6 digits from email
→ { claim: { registrationId, userCode },
organization: { name, slug, typeOrgId, workosOrgId }, organizationCreated }
POST https://auth.type.com/agent/identity/claim/complete
{ claim_token, user_code }
→ { id, status, identity: { assertion, refresh_token } }
POST https://auth.type.com/oauth2/token (form)
assertion=<jwt>&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&resource=https://api.type.com
→ { access_token, refresh_token, token_type, expires_in }
```
State machine mirrored from CLI: `agent-signup-registered → pending → claim-ready → provisioned → tokens`.
Persisted to `~/.type/credentials/<profile>.json` (profile-per-account, same layout family as CLI).
### 3. Refresh
```
POST https://api.workos.com/user_management/authenticate (form)
client_id=<workosClientId>&grant_type=refresh_token&refresh_token=<rt>[&organization_id=<workosOrgId>]
→ { access_token, refresh_token, expires_in }
```
### 4. Device login (interactive accounts)
```
POST https://api.workos.com/user_management/authorize/device { client_id, login_hint? }
→ { device_code, user_code, verification_uri[_complete], interval }
poll: POST /user_management/authenticate
{ client_id, device_code, grant_type=urn:ietf:params:oauth:grant-type:device_code }
authorization_pending / slow_down / 200 {access_token…}
```
### 5. Platform API
`Authorization: Bearer <access_token>`; convex function surface seen in the bundle:
`agents, threads (list/get/recent/batch), messages, channels, spaces, automations, skills,
integrations (call/list/tools/…), apps (deploy/logs/scaffold…), search.workspace, users, /v1/me, /v1/items`.
Model harnesses: `claude | codex | grok | gemini | opencode` — the CLI runs agent steps locally
against your own Claude/Codex subscription; type.com hosts the shared workspace/schedules.
### 6. Live verification log (2026-09-30, anonymous)
```
GET api.type.com/.well-known/oauth-protected-resource → 200 (issuer, client_id)
GET auth.type.com/.well-known/oauth-authorization-server → 200 (endpoints above)
POST auth.type.com/agent/identity {login_hint, service_auth} → 200
claim.token=clm_7_…, attempt.verification_uri ?token=cat_… (claim attempt issued)
POST api.type.com/api/agent-signup/start {cat, email, org} → 200
signupToken=4b42… (6-digit email code dispatched)
```
### 7. Full E2E run (2026-09-30, live, throwaway mailbox)
```
mail.tm REST (mailbox + /messages) → 6-digit code received
verify + claim/complete → identity {assertion (JWT, aud=issuer), refresh_token}
exchange (form, NO resource param) → 200 {access_token (300s, aud=client_id, org_id, act.sub)}
```
**Finding:** assertion JWT `aud` = `https://auth.type.com` (issuer), NOT `https://api.type.com`.
Passing `resource=api.type.com` (as the CLI's non-loopback branch does) → HTTP 400 `invalid_target`.
Omitting `resource` → 200 + access_token. Decode: `aud=client_id, sub=agent_reg_…, org_id, act.sub=user_…`.
**Server-side gate observed:** registration returns `scopes.post_claim: []` while the CLI requires
`["api.read"]` (it aborts otherwise). With empty post-claim scopes the issued token gets
`401 Invalid token` on `POST /api/orpc/cli/context/me` (oRPC link: `{server}/api/orpc/<procedure>`,
body `{"json":{}}`, headers `Authorization / user-agent TypeCLI/… / x-type-cli-version`).
Refresh: the agent-credential route (from `refreshAgentRegistration` in the bundle, NOT the
WorkOS user grant) is **live-verified 200**: `POST identityEndpoint {"refresh_token": <value>,
"type": "refresh"}` → fresh `identity{assertion, refresh_token}` → re-exchange → new 300s token.
The `refresh_token` field arrives as `{value, expires_at}` — send `.value` (CLI's
`normalizeIdentity` does the same). Semantics: this is the CLI's **recovery** path (`refreshAgentRegistration` is invoked on
exchange failures). Refresh tokens are single-use (rotation rt0→rt1 observed live). Whether
the cycle repeats beyond one refresh per identity grant is **undetermined**: the runs that
produced `already_been_used` were confounded by a crashed exchange that burned the rotated
token before persist. Clean test (after the registration rate-limit window): fresh e2e →
`refresh` twice back-to-back. Hard finding regardless: `POST /agent/identity` is rate-limited
per IP — `429 Too many agent registrations, retry_after 3600` — farms must route through
proxies (client supports `TYPE_PROXY`).
Full API access still needs the interactive device-login (`auth login`) — consistent with
install.md: "Signup credentials currently support identity, search, and thread reads only".
Probes: `probe_identity.py`, `probe_start.py`, `e2e_test.py` (mail.tm REST code), `probe_orpc.py`, `probe_token.py`.
### 8. IMAP note
mail.tm exposes REST only (its `mail.tm:993` times out here); `fetch_code_imap` in the client
stays as a hook for real pools (RFC 3501-compliant: plain `UNSEEN` + Python header filtering +
`walk()` for multipart). E2E uses the mail.tm REST path.
## Usage
```sh
python type_client.py discover # live metadata
python type_client.py signup --email me@mail.tm --org "myteam"
python type_client.py complete --code 123456 # → tokens stored
python type_client.py me # GET /v1/me with auto-refresh
python type_client.py device-login # interactive device flow
# Farm (mail.tm: IMAP host is mail.tm:993, credentials = API account creds):
python type_client.py batch --emails pool.txt --org "farm" \
--imap-host mail.tm --imap-pass-file creds.txt # lines: email:password
# Proxies: TYPE_PROXY=http://user:pass@host:port (per-invocation)
# Profiles: TYPE_PROFILE=<name> (default: "default")
```
## Extraction notes (CLI → source)
```
curl -fsSL https://type.com/install.sh | sh # macOS/Linux
# binaries: https://desktop.type.com/cli/type-cli-{linux,darwin,win}*
sha256 verified against desktop.type.com/cli/SHA256SUMS
file → ELF 64-bit, not stripped, 102 MB
strings → "bun" runtime markers ("// @bun", "bunfs")
tail after last "// @bun" marker (offset 100819587) → 1.5 MB plain-JS bundle
bundle: zod 4.4.3, src/commands/*.ts (signup/auth/threads/…), convex/_generated
```
The bundle is unminified (commented module paths preserved) — all flow logic above
was lifted verbatim from `src/commands/signup.ts` and the auth core.
## Legal note
Research on an authorized security-lab target. Protocol reproduced from the public CLI
binary distributed by type.com. No auth bypass, no captcha bypass — plain HTTP semantics.
### 9. type2api.py — OpenAI-compatible gateway (bootstrap = 1 human click)
```
python type_client.py device-login --email <your@email> # prints device URL
# open URL in your browser (Google session) -> "Continue with Google" -> click
# polling catches the token into ~/.type/credentials/default.json
python type2api.py # :8311
GET /v1/models -> your type.com agents
POST /v1/chat/completions -> oRPC pipeline; send-procedure auto-discovered
```
Web-flow notes (live-probed 2026-09-30): AuthKit blocks disposable domains
(uberip.com = the only mail.tm domain: «Доступ заблокирован» on both login and
signup web paths — while the protocol-level service_auth signup still accepts it);
Google rejects CDP-automation browsers («небезопасный браузер»); Gmail IMAP needs
an app-password. Hence the single manual click for the user-token.
+16
View File
@@ -0,0 +1,16 @@
import json
import sys
sys.path.insert(0, ".")
import type_client
cfg = type_client.discover()
mb = json.load(open("mailbox.json"))
EMAIL = mb["address"] # fresh persistent mailbox
print("email:", EMAIL)
state = type_client.device_login(cfg, email=EMAIL)
print("DEVICE LOGIN DONE")
print("accessToken:", state.get("accessToken", "")[:30] + "…")
st, me = type_client.orpc_call(state, "cli/context/me")
print("orpc context/me ->", st)
print(str(me)[:400])
+1
View File
@@ -0,0 +1 @@
{"client_id": "client_01M3SV193GZ1PNWPCNFCYX67RE", "client_id_issued_at": 1790794835, "application_type": "web", "client_name": "Type CLI", "grant_types": ["urn:ietf:params:oauth:grant-type:device_code", "refresh_token"], "redirect_uris": ["http://localhost:0/callback"], "response_types": ["code"], "token_endpoint_auth_method": "none"}
+124
View File
@@ -0,0 +1,124 @@
"""E2E proof: mail.tm mailbox -> type.com signup -> code -> tokens -> /v1/me.
Chain under test (every step live):
1. POST api.mail.tm/accounts (throwaway mailbox)
2. type_client.discover() (oauth discovery)
3. signup_start (identity + agent-signup/start, code dispatched)
4. fetch_code_imap (RFC3501 UNSEEN + multipart walk fix)
5. signup_complete (verify + claim/complete + jwt-bearer exchange)
6. api_get /v1/me (Bearer access_token)
"""
# __portable_paths__ (auto-injected: portable, env-overridable paths)
import os as _pos, sys as _psys
from pathlib import Path as _PPath
_ROOT = _PPath(__file__).resolve().parent
_REPO = _ROOT
for _ in range(4):
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
break
if _REPO.parent == _REPO:
break
_REPO = _REPO.parent
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
try:
_DATA.mkdir(parents=True, exist_ok=True)
_WORK.mkdir(parents=True, exist_ok=True)
except Exception:
pass
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
def _d(name, env=None):
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
if env and _pos.environ.get(env):
return _PPath(_pos.environ[env])
return _DATA / name
def _w(name=""):
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
return (_WORK / name) if name else _WORK
# --- end portable prelude ---
import json
import random
import re
import string
import time
import sys
import urllib.error
import urllib.request
sys.path.insert(0, str(_REPO))
import type_client
CTX = type_client._CTX
def mailtm_get(path, token=None):
req = urllib.request.Request(
"https://api.mail.tm" + path,
headers={"Accept": "application/json", **({"Authorization": "Bearer "+token} if token else {})},
method="GET",
)
with urllib.request.urlopen(req, timeout=30, context=CTX) as r:
return json.load(r)
def mailtm_post(path, body, token=None):
req = urllib.request.Request(
"https://api.mail.tm" + path,
data=json.dumps(body).encode(),
headers={"Content-Type": "application/json", "Accept": "application/json",
**({"Authorization": "Bearer " + token} if token else {})},
method="POST",
)
with urllib.request.urlopen(req, timeout=30, context=CTX) as r:
return json.load(r)
resp = mailtm_get("/domains")
dom_list = resp["hydra:member"] if isinstance(resp, dict) else resp
domains = [d["domain"] for d in dom_list if d.get("isActive", True)]
domain = domains[0]
local = "e2e" + "".join(random.choices(string.ascii_lowercase + string.digits, k=10))
address = local + "@" + domain
password = "Tp" + "".join(random.choices(string.ascii_letters + string.digits, k=12)) + "!9"
try:
acct = mailtm_post("/accounts", {"address": address, "password": password})
print(f"[1] mailbox created: {address} (domain {domain})")
except urllib.error.HTTPError as e:
print("mailbox create failed:", e.code, e.read().decode()[:300])
raise SystemExit(1)
cfg = type_client.discover()
print(f"[2] discovery ok: issuer={cfg['issuer']}")
state = type_client.signup_start(cfg, address, "e2e lab")
print(f"[3] signup start ok: signupToken={state['signupToken'][:8]}… code dispatched")
jwt = mailtm_post("/token", {"address": address, "password": password})["token"]
code = None
deadline = time.time() + 240
while time.time() < deadline and not code:
time.sleep(8)
msgs = mailtm_get("/messages", token=jwt)
msgs = msgs["hydra:member"] if isinstance(msgs, dict) else msgs
for msg in msgs:
body = mailtm_get(f"/messages/{msg['id']}", token=jwt)
text = body.get("text") or ""
if not text and body.get("html"):
html = body["html"]
text = html if isinstance(html, str) else "".join(html)
codes = re.findall(r"\b(\d{6})\b", text)
if codes:
code = codes[-1]
break
if not code:
raise RuntimeError("no code via mail.tm REST within 240s")
print(f"[4] REST code fetched: {code}")
state = type_client.signup_complete(cfg, state, code)
org = state.get("organization") or {}
print(f"[5] signup complete: org={org.get('slug')} accessToken={'yes' if state.get('accessToken') else 'NO'}")
st, me = type_client.api_get(state)
print(f"[6] GET /v1/me -> HTTP {st}")
print(json.dumps(me, indent=2, ensure_ascii=False)[:1200])
+19
View File
@@ -0,0 +1,19 @@
import json, urllib.request, urllib.error, ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
req = urllib.request.Request(
"https://auth.type.com/agent/identity",
data=json.dumps({"login_hint": "throwaway.test.reg@gmail.com", "type": "service_auth"}).encode(),
headers={"Content-Type": "application/json", "User-Agent": "type-cli/rev (python)"},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=30, context=ctx) as r:
print("HTTP", r.status)
print(json.dumps(json.load(r), indent=2)[:1500])
except urllib.error.HTTPError as e:
print("HTTP", e.code)
print(e.read().decode("utf-8", "replace")[:1500])
+39
View File
@@ -0,0 +1,39 @@
import json
import sys
import urllib.error
import urllib.request
sys.path.insert(0, ".")
import type_client
state = type_client.load_profile()
cfg = type_client.discover()
rt = state.get("refreshToken")
rt = rt.get("value") if isinstance(rt, dict) else rt
print("refreshToken:", rt[:20] + "…")
req = urllib.request.Request(
cfg["identity_endpoint"],
data=json.dumps({"refresh_token": rt, "type": "refresh"}).encode(),
headers={"Content-Type": "application/json", "User-Agent": "type-cli/rev (python)"},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=30, context=type_client._CTX) as r:
body = json.load(r)
print("identity refresh -> 200:", json.dumps(body, ensure_ascii=False)[:500])
identity = body.get("identity") or {}
assertion = identity.get("assertion")
if assertion:
state2 = dict(state)
state2["assertion"] = assertion
new_rt = identity.get("refresh_token")
if new_rt:
state2["refreshToken"] = new_rt
state2 = type_client.exchange(cfg, state2)
type_client.save_profile(state2)
print("re-exchange OK; expires_at:", state2["expiresAt"])
st, me = type_client.orpc_call(state2, "cli/context/me")
print("orpc context/me ->", st, json.dumps(me, ensure_ascii=False)[:300])
except urllib.error.HTTPError as e:
print("identity refresh ->", e.code, e.read().decode()[:300])
+42
View File
@@ -0,0 +1,42 @@
import json
import sys
import urllib.error
import urllib.request
sys.path.insert(0, ".")
import type_client
state = type_client.load_profile()
cfg = type_client.discover()
state = type_client.exchange(cfg, state)
token = state["accessToken"]
CTX = type_client._CTX
CLI_VERSION = "0.0.0-rev"
def call(label, path, body=None):
req = urllib.request.Request(
"https://api.type.com/api/orpc/" + path,
data=json.dumps({"json": body or {}}).encode(),
method="POST",
headers={
"Content-Type": "application/json",
"Authorization": "Bearer " + token,
"User-Agent": f"TypeCLI/{CLI_VERSION}",
"x-type-cli-version": CLI_VERSION,
},
)
try:
with urllib.request.urlopen(req, timeout=30, context=CTX) as r:
raw = r.read().decode("utf-8", "replace")
print(f"{label} -> {r.status} {raw[:400]}")
return json.loads(raw) if raw else None
except urllib.error.HTTPError as e:
print(f"{label} -> {e.code} {e.read().decode()[:250]}")
return None
call("cli/context/me", "cli/context/me")
call("cli/threads/list", "cli/threads/list")
call("cliAuth/listOrganizations", "cliAuth/listOrganizations")
call("cli/agents/list", "cli/agents/list")
+45
View File
@@ -0,0 +1,45 @@
import json
import sys
import urllib.error
import urllib.parse
import urllib.request
sys.path.insert(0, ".")
import type_client
state = type_client.load_profile()
form = {
"client_id": state.get("clientId") or "client_01K5GFDDKQWV8MM9FSRZS3YNNN",
"grant_type": "refresh_token",
"refresh_token": state["refreshToken"],
}
org = (state.get("organization") or {}).get("workosOrgId")
if org:
form["organization_id"] = org
req = urllib.request.Request(
"https://api.workos.com/user_management/authenticate",
data=urllib.parse.urlencode(form).encode(),
headers={"Content-Type": "application/x-www-form-urlencoded"},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=30, context=type_client._CTX) as r:
body = json.load(r)
print("refresh @workos -> 200:", {k: (v[:24] + "…" if isinstance(v, str) and len(v) > 24 else v) for k, v in body.items()})
# try the fresh token against the oRPC API
tok = body["access_token"]
req2 = urllib.request.Request(
"https://api.type.com/api/orpc/cli/context/me",
data=json.dumps({"json": {}}).encode(),
method="POST",
headers={
"Content-Type": "application/json",
"Authorization": "Bearer " + tok,
"User-Agent": "TypeCLI/rev",
"x-type-cli-version": "0.0.0",
},
)
with urllib.request.urlopen(req2, timeout=30, context=type_client._CTX) as r2:
print("orpc context/me ->", r2.status, r2.read().decode()[:400])
except urllib.error.HTTPError as e:
print("refresh @workos ->", e.code, e.read().decode()[:300])
+27
View File
@@ -0,0 +1,27 @@
import json, urllib.request, urllib.error, urllib.parse, ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
email = "throwaway.test.reg@gmail.com"
vuri = "https://auth.type.com/agent-claim?token=cat_ywILqSA7QnXgWZvCWN7CnsD-omQ581Xe"
cat = urllib.parse.parse_qs(urllib.parse.urlparse(vuri).query)["token"][0]
body = {
"claimAttemptToken": cat,
"email": email,
"organizationName": "test lab",
}
req = urllib.request.Request(
"https://api.type.com/api/agent-signup/start",
data=json.dumps(body).encode(),
headers={"Content-Type": "application/json", "User-Agent": "type-cli/rev (python)"},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=30, context=ctx) as r:
print("HTTP", r.status)
print(json.dumps(json.load(r), indent=2)[:800])
except urllib.error.HTTPError as e:
print("HTTP", e.code)
print(e.read().decode("utf-8", "replace")[:800])
+39
View File
@@ -0,0 +1,39 @@
import base64
import json
import sys
sys.path.insert(0, ".")
import type_client
state = type_client.load_profile()
cfg = type_client.discover()
state = type_client.exchange(cfg, state)
tok = state["accessToken"]
seg = tok.split(".")[1]
seg += "=" * (-len(seg) % 4)
payload = json.loads(base64.urlsafe_b64decode(seg))
print(json.dumps(payload, indent=2)[:900])
print("scopes in state identity:", "refreshToken" if state.get("refreshToken") else "none")
# WorkOS refresh_token grant (identity refresh token from claim/complete)
import urllib.error
import urllib.parse
import urllib.request
form = {
"client_id": state.get("clientId") or "client_01K5GFDDKQWV8MM9FSRZS3YNNN",
"grant_type": "refresh_token",
"refresh_token": state["refreshToken"],
}
req = urllib.request.Request(
"https://auth.type.com/oauth2/token",
data=urllib.parse.urlencode(form).encode(),
headers={"Content-Type": "application/x-www-form-urlencoded"},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=30, context=type_client._CTX) as r:
body = json.load(r)
print("refresh via issuer -> 200:", {k: (v[:20] + "…" if isinstance(v, str) and len(v) > 20 else v) for k, v in body.items()})
except urllib.error.HTTPError as e:
print("refresh via issuer ->", e.code, e.read().decode()[:200])
+160
View File
@@ -0,0 +1,160 @@
#!/usr/bin/env python3
"""
type2api.py — OpenAI-compatible gateway over type.com (protocol reverse).
Bootstrap (one human click):
1. python type_client.py device-login --email <your-email>
2. Open the printed URL in YOUR browser (Google session) -> "Continue with Google"
3. Polling catches the token -> saved to ~/.type/credentials/<profile>.json
4. python type2api.py -> serves on :8311
Endpoints:
GET /v1/models -> agents from cli/agents/list
POST /v1/chat/completions -> thread pipeline over oRPC
(message-send procedure is auto-discovered: the CLI bundle only calls
read procedures, so this server probes send/create names live and
logs which the server exposes with the user token)
Zero dependencies (stdlib). Token auto-refreshed via device-refresh grant.
"""
import json
import os
import sys
import time
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import type_client # noqa: E402
PORT = int(os.environ.get("TYPE2API_PORT", "8311"))
PROFILE = os.environ.get("TYPE_PROFILE", "default")
SEND_PROCEDURE_CANDIDATES = [
"cli/threads/create",
"cli/messages/create",
"cli/threads/send",
"cli/chat/send",
"cli/agents/run",
"cli/threads/message",
]
def get_state():
state = type_client.load_profile()
if not state or not state.get("accessToken"):
raise RuntimeError("no access token: run `python type_client.py device-login` first")
if time.time() > state.get("expiresAt", 0):
cfg = type_client.discover(state.get("server") or type_client.SERVER)
state = type_client.refresh(cfg, state)
return state
def try_state():
try:
return get_state(), None
except Exception as e:
return None, str(e)
def orpc(state, procedure, args=None):
return type_client.orpc_call(state, procedure, args)
class Handler(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def _send(self, code, payload):
body = json.dumps(payload, ensure_ascii=False).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path == "/v1/models":
state = get_state()
st, agents = orpc(state, "cli/agents/list")
items = []
if st == 200 and isinstance(agents, dict):
raw = agents.get("json") or agents
for a in (raw.get("agents") or raw.get("data") or []):
items.append({"id": f"type-{a.get('handle') or a.get('id')}", "object": "model", "owned_by": "type.com"})
self._send(200, {"object": "list", "data": items})
elif self.path == "/health":
self._send(200, {"ok": True, "profile": PROFILE})
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)
req = json.loads(self.rfile.read(length) or b"{}")
messages = req.get("messages") or []
content_last = messages[-1].get("content", "") if messages else ""
prompt = json.dumps(content_last, ensure_ascii=False) if not isinstance(content_last, str) else content_last
state, err = try_state()
if err:
self._send(500, {"error": {"message": err, "type": "auth_error"}})
return
# discover the send procedure once (logged; cache in .type/send_proc.json)
cache = os.path.join(type_client.CRED_DIR, "send_proc.json")
proc = None
if os.path.exists(cache):
proc = json.load(open(cache)).get("procedure")
if not proc:
for cand in SEND_PROCEDURE_CANDIDATES:
st, body = orpc(state, cand, {"text": prompt})
if st == 200:
proc = cand
json.dump({"procedure": proc}, open(cache, "w"))
print(f"[type2api] send procedure discovered: {proc}")
break
if st not in (404,):
print(f"[type2api] {cand}: exists but rejected (HTTP {st}) - wrong args/scope")
if proc:
st, body = orpc(state, proc, {"text": prompt, "messages": messages})
content = (body.get("json") if isinstance(body, dict) else None) or body
if isinstance(content, dict):
content = content.get("content") or content.get("text") or json.dumps(content, ensure_ascii=False)
else:
content = str(content)
else:
st = 501
content = (
"type2api: token OK but no send procedure exposed to this scope; "
"probed " + ", ".join(SEND_PROCEDURE_CANDIDATES) + ". "
"See README: full message flow runs through local harnesses."
)
if st != 200:
self._send(502 if st in (400, 404, 422) else 501, {
"error": {"message": str(content), "type": "type_upstream", "upstream_status": st}
})
return
out = {
"id": f"chatcmpl-type-{int(time.time()*1000)}",
"object": "chat.completion",
"created": int(time.time()),
"model": req.get("model", "type-default"),
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": str(content)},
"finish_reason": "stop",
}
],
}
self._send(200, out)
def main():
get_state() # fail fast if no token
print(f"type2api on :{PORT} (profile {PROFILE})")
ThreadingHTTPServer(("0.0.0.0", PORT), Handler).serve_forever()
if __name__ == "__main__":
main()
+490
View File
@@ -0,0 +1,490 @@
#!/usr/bin/env python3
"""
type_client.py — protocol-level client for type.com (Type shared-agent platform).
Reversed from type-cli (Bun single-executable, `bun build --compile`):
installer : https://type.com/install.sh -> https://desktop.type.com/cli/
server : https://api.type.com (prod) / https://api.typestaging.com (staging)
identity : WorkOS user_management (device + jwt-bearer + refresh_token grants)
signup : "service_auth" agent registration, 6-digit email code, NO BROWSER
storage : ~/.type/credentials/{profile}.json (CLI-compatible)
Zero dependencies (stdlib only). Python 3.9+.
Usage:
python type_client.py discover
python type_client.py signup --email me@mail.com --org "myteam"
python type_client.py complete --code 123456
python type_client.py status
python type_client.py refresh
python type_client.py me
python type_client.py device-login
python type_client.py batch --emails emails.txt --org "farm" # IMAP hook below
"""
import argparse
import json
import os
import ssl
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
SERVER = os.environ.get("TYPE_SERVER_URL", "https://api.type.com")
WORKOS_AUTHENTICATE_URL = "https://api.workos.com/user_management/authenticate"
WORKOS_DEVICE_AUTHORIZE_URL = "https://api.workos.com/user_management/authorize/device"
AGENT_TOKEN_EXCHANGE_GRANT = "urn:ietf:params:oauth:grant-type:jwt-bearer"
DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"
BUNDLED_WORKOS_CLIENT_ID = "client_01K5GFDDKQWV8MM9FSRZS3YNNN" # extracted from CLI
CRED_DIR = os.path.join(
os.environ.get("TYPE_CONFIG_DIR", os.path.join(os.path.expanduser("~"), ".type")),
"credentials",
)
PROFILE = os.environ.get("TYPE_PROFILE", "default")
_CTX = ssl.create_default_context()
if os.environ.get("TYPE_INSECURE") == "1":
_CTX.check_hostname = False
_CTX.verify_mode = ssl.CERT_NONE
def _proxies():
handlers = []
proxy = os.environ.get("TYPE_PROXY") # http://user:pass@host:port
if proxy:
handlers.append(urllib.request.ProxyHandler({"http": proxy, "https": proxy}))
opener = urllib.request.build_opener(*handlers) if handlers else None
return opener
def http_json(method, url, body=None, form=None, token=None, expect=None):
"""JSON/form request -> (status, dict). Non-JSON responses become {"_raw": str}."""
headers = {"User-Agent": "type-cli/rev (python)"}
data = None
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
if form is not None:
data = urllib.parse.urlencode(form).encode()
headers["Content-Type"] = "application/x-www-form-urlencoded"
if token:
headers["Authorization"] = "Bearer " + token
req = urllib.request.Request(url, data=data, headers=headers, method=method)
opener = _proxies()
urlopen = opener.urlopen if opener else urllib.request.urlopen
try:
resp = urlopen(req, timeout=30, context=_CTX)
raw = resp.read()
status = resp.status
except urllib.error.HTTPError as e:
raw = e.read()
status = e.code
try:
parsed = json.loads(raw.decode("utf-8", "replace"))
if not isinstance(parsed, dict):
parsed = {"_raw": parsed}
except Exception:
parsed = {"_raw": raw.decode("utf-8", "replace")}
if expect is not None and status != expect:
raise RuntimeError(f"{method} {url} -> {status}: {parsed}")
return status, parsed
def load_profile():
path = os.path.join(CRED_DIR, PROFILE + ".json")
if not os.path.exists(path):
return None
with open(path, encoding="utf-8") as f:
return json.load(f)
def save_profile(state):
os.makedirs(CRED_DIR, exist_ok=True)
path = os.path.join(CRED_DIR, PROFILE + ".json")
with open(path, "w", encoding="utf-8") as f:
json.dump(state, f, indent=2, ensure_ascii=False)
return path
# ---------------------------------------------------------------- discovery
def discover(server=SERVER):
"""RFC 8414 chain the CLI walks: protected-resource -> authorization server."""
st, pr = http_json("GET", server + "/.well-known/oauth-protected-resource")
if st != 200:
raise RuntimeError(f"protected-resource discovery HTTP {st}: {pr}")
issuer = (pr.get("authorization_servers") or [""])[0].rstrip("/")
client_id = pr.get("type_workos_client_id") or BUNDLED_WORKOS_CLIENT_ID
meta = None
for well_known in (
"/.well-known/oauth-authorization-server",
"/.well-known/openid-configuration",
):
st, meta = http_json("GET", issuer + well_known)
if st == 200 and isinstance(meta, dict):
break
if not isinstance(meta, dict) or "token_endpoint" not in meta:
raise RuntimeError(f"authorization-server metadata not found on {issuer}")
agent_auth = meta.get("agent_auth") or {}
cfg = {
"server": server,
"issuer": issuer,
"resource": (pr.get("resource") or server).rstrip("/"),
"client_id": client_id,
"token_endpoint": meta["token_endpoint"],
"identity_endpoint": agent_auth.get("identity_endpoint"),
"identity_types": agent_auth.get("identity_types_supported"),
}
return cfg
# ---------------------------------------------------------------- signup
def signup_start(cfg, email, org_name, state=None):
"""service_auth registration + agent-signup/start -> state saved, email code sent."""
if not state:
st, reg = http_json(
"POST",
cfg["identity_endpoint"],
body={"login_hint": email, "type": "service_auth"},
expect=200,
)
claim = reg.get("claim") or {}
attempt = claim.get("attempt") or {}
vuri = attempt.get("verification_uri") or ""
claim_attempt_token = (
(urllib.parse.parse_qs(urllib.parse.urlparse(vuri).query).get("token") or [None])[0]
)
if not claim.get("token") or not claim_attempt_token:
raise RuntimeError(f"unexpected registration payload: {reg}")
state = {
"kind": "agent-signup-registered",
"email": email,
"organizationName": org_name,
"claimToken": claim["token"],
"claimAttemptToken": claim_attempt_token,
"issuer": cfg["issuer"],
"resource": cfg["resource"],
"tokenEndpoint": cfg["token_endpoint"],
"clientId": cfg["client_id"],
}
st, resp = http_json(
"POST",
cfg["server"] + "/api/agent-signup/start",
body={
"claimAttemptToken": state["claimAttemptToken"],
"email": state["email"],
"organizationName": state["organizationName"],
},
expect=200,
)
state["signupToken"] = resp.get("signupToken")
state["kind"] = "agent-signup-pending"
save_profile(state)
return state
def signup_complete(cfg, state, code):
"""verify 6-digit code -> complete WorkOS claim -> jwt-bearer exchange -> tokens."""
code = (code or "").strip()
if not (code.isdigit() and len(code) == 6):
raise SystemExit("code must be 6 digits")
st, resp = http_json(
"POST",
cfg["server"] + "/api/agent-signup/verify",
body={"code": code, "signupToken": state["signupToken"]},
expect=200,
)
claim = resp["claim"]
org = resp["organization"]
state.update(
{
"kind": "agent-signup-claim-ready",
"registrationId": claim["registrationId"],
"userCode": claim["userCode"],
"organization": org,
"organizationCreated": resp.get("organizationCreated"),
}
)
st, done = http_json(
"POST",
cfg["issuer"] + "/agent/identity/claim/complete",
body={"claim_token": state["claimToken"], "user_code": claim["userCode"]},
)
if st != 200:
raise RuntimeError(f"claim/complete HTTP {st}: {done}")
identity = done.get("identity") or {}
assertion = identity.get("assertion")
refresh_token = identity.get("refresh_token") or identity.get("refreshToken")
if isinstance(refresh_token, dict): # {value, expires_at} per normalizeIdentity
refresh_token = refresh_token.get("value")
if not assertion:
raise RuntimeError(f"claim/complete returned no assertion: {done}")
state.update(
{
"kind": "agent-signup-provisioned",
"assertion": assertion,
"refreshToken": refresh_token,
}
)
save_profile(state) # persist before exchange so a failed exchange is retryable
return exchange(cfg, state)
def exchange(cfg, state):
# assertion aud == issuer (auth.type.com), NOT the api resource: sending
# resource=api.type.com yields HTTP 400 invalid_target. Omit unless forced.
form = {
"assertion": state["assertion"],
"grant_type": AGENT_TOKEN_EXCHANGE_GRANT,
}
if os.environ.get("TYPE_EXCHANGE_RESOURCE"):
form["resource"] = os.environ["TYPE_EXCHANGE_RESOURCE"]
token_endpoint = (cfg or {}).get("token_endpoint") or state.get("tokenEndpoint")
if not token_endpoint:
raise RuntimeError("profile has no tokenEndpoint; run signup again")
st, tokens = http_json("POST", token_endpoint, form=form)
if st != 200:
raise RuntimeError(f"token exchange HTTP {st}: {tokens}")
state.update(
{
"kind": "tokens",
"accessToken": tokens["access_token"],
"refreshToken": tokens.get("refresh_token") or state.get("refreshToken"),
"tokenType": tokens.get("token_type"),
"expiresAt": time.time() + int(tokens.get("expires_in") or 3600),
}
)
save_profile(state)
return state
# ---------------------------------------------------------------- refresh / API
def refresh(cfg, state):
"""Agent-credential refresh (bundle: refreshAgentRegistration):
POST identityEndpoint {refresh_token, type:"refresh"} -> fresh assertion
-> jwt-bearer exchange (no resource) -> new access_token. Live-verified 200."""
rt = state.get("refreshToken")
rt = rt.get("value") if isinstance(rt, dict) else rt
if not rt:
raise RuntimeError("no refreshToken in profile; run signup/complete again")
issuer = (cfg or {}).get("issuer") or state.get("issuer")
endpoint = (cfg or {}).get("identity_endpoint") or (issuer + "/agent/identity" if issuer else None)
if not endpoint:
raise RuntimeError("profile has no issuer; run signup or device-login first")
st, body = http_json(
"POST",
endpoint,
body={"refresh_token": rt, "type": "refresh"},
)
if st != 200:
raise RuntimeError(f"identity refresh HTTP {st}: {body}")
identity = body.get("identity") or {}
state["assertion"] = identity["assertion"]
new_rt = identity.get("refresh_token")
if new_rt:
state["refreshToken"] = new_rt.get("value") if isinstance(new_rt, dict) else new_rt
save_profile(state) # persist rotation BEFORE exchange: single-use rt must not burn
return exchange(cfg, state)
def api_get(state, path="/v1/me"):
st, body = http_json("GET", state.get("server", SERVER) + path, token=state["accessToken"])
return st, body
def orpc_call(state, procedure, args=None):
"""oRPC call: POST {server}/api/orpc/{procedure} body {"json": args}.
Procedures (from bundle): cli/context/me, cli/threads/list, cliAuth/listOrganizations…
Note: service_auth tokens currently carry empty post_claim scopes -> API returns
401 Invalid token; full access requires device-login (auth login)."""
st, body = http_json(
"POST",
state.get("server", SERVER) + "/api/orpc/" + procedure,
body={"json": args or {}},
token=state["accessToken"],
)
return st, body
# ---------------------------------------------------------------- device login
def device_login(cfg, email=None):
form = {"client_id": cfg["client_id"]}
if email:
form["login_hint"] = email
st, dr = http_json("POST", WORKOS_DEVICE_AUTHORIZE_URL, form=form, expect=200)
print(f"Open: {dr.get('verification_uri_complete') or dr.get('verification_uri')}")
print(f"User code: {dr.get('user_code')}")
interval = int(dr.get("interval") or 5)
deadline = time.time() + 900
while time.time() < deadline:
time.sleep(interval)
form = {
"client_id": cfg["client_id"],
"device_code": dr["device_code"],
"grant_type": DEVICE_CODE_GRANT,
}
st, tokens = http_json("POST", WORKOS_AUTHENTICATE_URL, form=form)
if st == 200:
state = {
"kind": "tokens",
"server": cfg["server"],
"accessToken": tokens["access_token"],
"refreshToken": tokens.get("refresh_token"),
"expiresAt": time.time() + int(tokens.get("expires_in") or 3600),
}
save_profile(state)
return state
err = tokens.get("error") if isinstance(tokens, dict) else None
if err == "authorization_pending":
continue
if err == "slow_down":
interval += 5
continue
raise RuntimeError(f"device grant stopped: {err or st}")
raise RuntimeError("device grant timeout")
# ---------------------------------------------------------------- IMAP hook
def fetch_code_imap(email, password, host="mail.tm", folder="INBOX", wait=180):
"""Hook for mail pools: reads the newest 6-digit code from signup mail.
Adapt host/credentials to your pool provider."""
import imaplib
import email as emaillib
import re
deadline = time.time() + wait
while time.time() < deadline:
m = imaplib.IMAP4_SSL(host)
m.login(email, password)
m.select(folder)
# RFC 3501 has no infix OR — plain UNSEEN, filter headers in Python.
_, ids = m.search(None, "UNSEEN")
for i in (ids[0] or b"").split()[-5:]:
_, data = m.fetch(i, "(RFC822)")
raw = data[0][1] if data and isinstance(data[0], tuple) else None
if raw is None:
continue
msg = emaillib.message_from_bytes(raw)
sender = (msg.get("From") or "").lower()
subject = (msg.get("Subject") or "").lower()
if "type" not in sender and "type" not in subject:
continue
body = ""
for part in msg.walk(): # multipart/alternative safe
if part.get_content_type() == "text/plain":
payload = part.get_payload(decode=True)
if payload:
body += payload.decode("utf-8", "replace")
codes = re.findall(r"\b(\d{6})\b", body)
if codes:
m.logout()
return codes[-1]
m.logout()
time.sleep(10)
raise RuntimeError("no code within wait window")
def batch_register(emails_file, org, imap_host="mail.tm", imap_pass_file=None):
"""Farm: one signup per line of `email:password`. Needs IMAP for codes."""
cfg = discover()
results = []
passes = {}
if imap_pass_file:
for line in open(imap_pass_file, encoding="utf-8"):
if ":" in line:
e, p = line.strip().split(":", 1)
passes[e] = p
for line in open(emails_file, encoding="utf-8"):
email = line.strip().lower()
if not email:
continue
os.environ["TYPE_PROFILE"] = email.replace("@", "_at_").replace(".", "_")
globals()["PROFILE"] = os.environ["TYPE_PROFILE"]
try:
state = signup_start(cfg, email, org)
code = None
if email in passes:
code = fetch_code_imap(email, passes[email], host=imap_host)
else:
code = input(f"[{email}] code from email> ").strip()
state = signup_complete(cfg, state, code)
st, me = api_get(state)
results.append({"email": email, "ok": st == 200, "org": state.get("organization")})
print(f"OK {email} -> {state.get('organization', {}).get('slug')}")
except Exception as e:
results.append({"email": email, "ok": False, "error": str(e)})
print(f"FAIL {email}: {e}")
out = os.path.join(os.path.dirname(emails_file) or ".", "type_batch_result.json")
with open(out, "w", encoding="utf-8") as f:
json.dump(results, f, indent=2)
print(f"results -> {out}")
# ---------------------------------------------------------------- cli
def main():
ap = argparse.ArgumentParser(description="type.com protocol client")
sub = ap.add_subparsers(dest="cmd", required=True)
sub.add_parser("discover")
sp = sub.add_parser("signup")
sp.add_argument("--email", required=True)
sp.add_argument("--org", required=True)
cp = sub.add_parser("complete")
cp.add_argument("--code", required=True)
sub.add_parser("status")
sub.add_parser("refresh")
sub.add_parser("me")
dp = sub.add_parser("device-login")
dp.add_argument("--email")
bp = sub.add_parser("batch")
bp.add_argument("--emails", required=True)
bp.add_argument("--org", required=True)
bp.add_argument("--imap-host", default="mail.tm")
bp.add_argument("--imap-pass-file")
args = ap.parse_args()
if args.cmd == "discover":
cfg = discover()
print(json.dumps(cfg, indent=2))
elif args.cmd == "signup":
cfg = discover()
state = signup_start(cfg, args.email, args.org)
print(f"code sent to {state['email']} (state saved).")
print(f"next: python {sys.argv[0]} complete --code <6digits> [--profile {PROFILE}]")
elif args.cmd == "complete":
state = load_profile()
if not state or state.get("kind") not in ("agent-signup-pending", "agent-signup-verifying"):
raise SystemExit("no pending signup in this profile")
cfg = discover(state.get("server") or SERVER)
state = signup_complete(cfg, state, args.code)
print(f"PROVISIONED org={state.get('organization', {}).get('slug')} "
f"accessToken={'yes' if state.get('accessToken') else 'no'}")
elif args.cmd == "status":
state = load_profile()
print(json.dumps(
{k: v for k, v in (state or {}).items()
if k not in ("assertion", "accessToken", "refreshToken", "signupToken")},
indent=2, ensure_ascii=False))
elif args.cmd == "refresh":
state = load_profile()
cfg = discover(state.get("server") or SERVER)
state = refresh(cfg, state)
print(f"refreshed, expires_at={state['expiresAt']}")
elif args.cmd == "me":
state = load_profile()
if state.get("kind") != "tokens":
raise SystemExit("profile has no access token; run signup/complete or device-login")
if time.time() > state.get("expiresAt", 0):
refresh(discover(state.get("server") or SERVER), state)
state = load_profile()
st, me = orpc_call(state, "cli/context/me")
print(st, json.dumps(me, indent=2, ensure_ascii=False)[:2000])
elif args.cmd == "device-login":
cfg = discover()
device_login(cfg, email=args.email)
print("tokens stored")
elif args.cmd == "batch":
batch_register(args.emails, args.org, args.imap_host, args.imap_pass_file)
if __name__ == "__main__":
main()