| 1 | """Bind mobile history to the actual guest provider. Never print raw configuration.""" |
| 2 | import hashlib |
| 3 | import hmac |
| 4 | import json |
| 5 | import os |
| 6 | from pathlib import Path |
| 7 | import runpy |
| 8 | import secrets |
| 9 | import shutil |
| 10 | import subprocess |
| 11 | import sys |
| 12 | import tempfile |
| 13 | import uuid |
| 14 | from urllib.parse import urlsplit |
| 15 | |
| 16 | |
| 17 | class Unverified(Exception): |
| 18 | pass |
| 19 | |
| 20 | |
| 21 | class Changed(Exception): |
| 22 | pass |
| 23 | |
| 24 | |
| 25 | class Verified(Exception): |
| 26 | def __init__(self, config): |
| 27 | self.config = str(config) |
| 28 | |
| 29 | |
| 30 | def single_turn_notice(): |
| 31 | print(json.dumps({"type": "system", "subtype": "cage_identity_single_turn"}), flush=True) |
| 32 | |
| 33 | |
| 34 | def read_settings(path): |
| 35 | with open(path, "rb") as stream: |
| 36 | payload = stream.read(1024 * 1024 + 1) |
| 37 | if len(payload) > 1024 * 1024: |
| 38 | raise Unverified() |
| 39 | value = json.loads(payload) |
| 40 | if not isinstance(value, dict): |
| 41 | raise Unverified() |
| 42 | return value |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | CCS_PROBE = """ |
| 50 | import json, os, sys |
| 51 | args = sys.argv[1:] |
| 52 | if os.environ['CAGE_CAPTURE_ID'] not in args: |
| 53 | sys.exit(1) |
| 54 | settings = {} |
| 55 | source = None |
| 56 | if '--settings' in args: |
| 57 | index = args.index('--settings') |
| 58 | source = args[index + 1] |
| 59 | if source.lstrip().startswith('{'): |
| 60 | settings = json.loads(source) |
| 61 | else: |
| 62 | with open(source, 'rb') as f: |
| 63 | content = f.read(1048577) |
| 64 | if len(content) > 1048576: sys.exit(1) |
| 65 | settings = json.loads(content) |
| 66 | del args[index:index + 2] |
| 67 | print('CAGE_CCS_CAPTURE:' + json.dumps([args, settings, source, dict(os.environ)])) |
| 68 | """ |
| 69 | |
| 70 | |
| 71 | def ccs_launch(profile, args, id_index): |
| 72 | probe_id = str(uuid.uuid4()) |
| 73 | probe_args = args.copy() |
| 74 | probe_args[id_index] = probe_id |
| 75 | with tempfile.TemporaryDirectory(prefix="cage-ccs-launch-") as directory: |
| 76 | probe = Path(directory) / "claude" |
| 77 | probe.write_text("#!" + sys.executable + " -I\n" + CCS_PROBE) |
| 78 | probe.chmod(0o700) |
| 79 | env = dict(os.environ, CCS_CLAUDE_PATH=str(probe), CAGE_CAPTURE_ID=probe_id) |
| 80 | result = subprocess.run(["ccs", profile, *probe_args], env=env, stdin=subprocess.DEVNULL, |
| 81 | stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=20) |
| 82 | records = [line.removeprefix(b"CAGE_CCS_CAPTURE:") for line in result.stdout.splitlines() |
| 83 | if line.startswith(b"CAGE_CCS_CAPTURE:")] |
| 84 | if result.returncode or len(records) != 1 or len(records[0]) > 2 << 20: |
| 85 | raise Unverified() |
| 86 | passed, settings, source, env = json.loads(records[0]) |
| 87 | if (not isinstance(passed, list) or not isinstance(env, dict) or |
| 88 | not isinstance(settings, dict) or env.get("CCS_PROFILE_TYPE") != "settings" or |
| 89 | not isinstance(source, str) or not os.path.isabs(source) or not os.path.isfile(source)): |
| 90 | |
| 91 | |
| 92 | raise Unverified() |
| 93 | |
| 94 | |
| 95 | extra = passed[len(probe_args):] |
| 96 | if passed[:len(probe_args)] != probe_args or len(extra) % 2: |
| 97 | raise Unverified() |
| 98 | if any(flag not in ("--disallowedTools", "--disallowed-tools", "--append-system-prompt", "--append-system-prompt-file") |
| 99 | or not value or value.startswith("-") for flag, value in zip(extra[::2], extra[1::2])): |
| 100 | raise Unverified() |
| 101 | env.pop("CAGE_CAPTURE_ID", None) |
| 102 | env.pop("CCS_CLAUDE_PATH", None) |
| 103 | return args + extra, settings, env |
| 104 | |
| 105 | |
| 106 | def merged_settings(user, profile): |
| 107 | result = dict(user) |
| 108 | for key, value in profile.items(): |
| 109 | if key == "env": |
| 110 | result[key] = {**result.get(key, {}), **value} |
| 111 | elif key not in result or result[key] == value: |
| 112 | result[key] = value |
| 113 | else: |
| 114 | |
| 115 | |
| 116 | raise Unverified() |
| 117 | return result |
| 118 | |
| 119 | |
| 120 | def route_values(env): |
| 121 | return {k: v for k, v in env.items() if k.startswith(("ANTHROPIC_", "CLAUDE_")) |
| 122 | or k.lower() in ("https_proxy", "http_proxy", "all_proxy", "no_proxy", "node_extra_ca_certs", |
| 123 | "ssl_cert_file", "ssl_cert_dir", "node_tls_reject_unauthorized", |
| 124 | "home", "xdg_config_home", "appdata", "userprofile")} |
| 125 | |
| 126 | |
| 127 | def windows_registry_settings(): |
| 128 | if os.name != "nt": |
| 129 | return [] |
| 130 | import winreg |
| 131 | result = [] |
| 132 | for hive in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER): |
| 133 | for view in (winreg.KEY_WOW64_64KEY, winreg.KEY_WOW64_32KEY): |
| 134 | try: |
| 135 | with winreg.OpenKey(hive, r"SOFTWARE\Policies\ClaudeCode", 0, winreg.KEY_READ | view) as key: |
| 136 | text, kind = winreg.QueryValueEx(key, "Settings") |
| 137 | if kind not in (winreg.REG_SZ, winreg.REG_EXPAND_SZ) or not isinstance(text, str) or len(text.encode()) > 1 << 20: |
| 138 | raise Unverified() |
| 139 | if kind == winreg.REG_EXPAND_SZ: |
| 140 | text = winreg.ExpandEnvironmentStrings(text) |
| 141 | policy = json.loads(text) |
| 142 | if not isinstance(policy, dict): |
| 143 | raise Unverified() |
| 144 | if policy not in result: |
| 145 | result.append(policy) |
| 146 | except FileNotFoundError: |
| 147 | pass |
| 148 | except (OSError, ValueError): |
| 149 | raise Unverified() |
| 150 | return result |
| 151 | |
| 152 | |
| 153 | def validate_shared_mcp(args, extra_paths=(), config_env=None, workspace=None): |
| 154 | |
| 155 | |
| 156 | sources = [] |
| 157 | index = 0 |
| 158 | while index < len(args): |
| 159 | value = args[index] |
| 160 | if value in ("--channels", "--dangerously-load-development-channels") or value.startswith(("--channels=", "--dangerously-load-development-channels=")): |
| 161 | raise Unverified() |
| 162 | if value == "--mcp-config": |
| 163 | index += 1 |
| 164 | start = index |
| 165 | while index < len(args) and not args[index].startswith("-"): |
| 166 | sources.append(args[index]); index += 1 |
| 167 | if index == start: |
| 168 | raise Unverified() |
| 169 | continue |
| 170 | if value.startswith("--mcp-config="): |
| 171 | sources.append(value.split("=", 1)[1]) |
| 172 | index += 1 |
| 173 | for item in sources: |
| 174 | data = json.loads(item) if item.lstrip().startswith("{") else read_settings(Path(item)) |
| 175 | if not isinstance(data, dict) or not isinstance(data.get("mcpServers", {}), dict) or "cage" in data.get("mcpServers", {}): |
| 176 | raise Unverified() |
| 177 | for filename in extra_paths: |
| 178 | if Path(filename).exists(): |
| 179 | data = read_settings(Path(filename)) |
| 180 | if not isinstance(data.get("mcpServers", {}), dict) or "cage" in data.get("mcpServers", {}): |
| 181 | raise Unverified() |
| 182 | if config_env is not None: |
| 183 | |
| 184 | |
| 185 | directory = config_env.get("CLAUDE_CONFIG_DIR") |
| 186 | filename = Path(directory) / ".claude.json" if directory else Path.home() / ".claude.json" |
| 187 | if filename.exists(): |
| 188 | data = read_settings(filename) |
| 189 | servers = data.get("mcpServers", {}) |
| 190 | if not isinstance(servers, dict) or "cage" in servers: |
| 191 | raise Unverified() |
| 192 | projects = data.get("projects", {}) |
| 193 | if not isinstance(projects, dict): |
| 194 | raise Unverified() |
| 195 | if workspace is not None: |
| 196 | target = os.path.normcase(str(Path(workspace).resolve())) |
| 197 | for path, project in projects.items(): |
| 198 | if os.path.normcase(str(Path(path).resolve())) != target: |
| 199 | continue |
| 200 | if not isinstance(project, dict): |
| 201 | raise Unverified() |
| 202 | servers = project.get("mcpServers", {}) |
| 203 | if not isinstance(servers, dict) or "cage" in servers: |
| 204 | raise Unverified() |
| 205 | |
| 206 | |
| 207 | def managed_settings(): |
| 208 | |
| 209 | |
| 210 | |
| 211 | directory = Path(os.environ.get("ProgramFiles", "C:/Program Files")) / "ClaudeCode" if os.name == "nt" else Path("/etc/claude-code") |
| 212 | paths = [directory / "managed-settings.json"] |
| 213 | paths.extend(sorted((directory / "managed-settings.d").glob("*.json"))) |
| 214 | policies = [] |
| 215 | values = windows_registry_settings() |
| 216 | values.extend(read_settings(path) for path in paths if path.exists()) |
| 217 | for policy in values: |
| 218 | permissions = policy.get("permissions", {}) |
| 219 | if (policy.keys() - {"permissions", "tui", "channelsEnabled"} or not isinstance(permissions, dict) |
| 220 | or permissions.keys() - {"defaultMode"}): |
| 221 | raise Unverified() |
| 222 | |
| 223 | policies.append({key: value for key, value in policy.items() if key != "channelsEnabled"}) |
| 224 | return policies |
| 225 | |
| 226 | |
| 227 | def shared_channels_disabled(): |
| 228 | directory = Path(os.environ.get("ProgramFiles", "C:/Program Files")) / "ClaudeCode" if os.name == "nt" else Path("/etc/claude-code") |
| 229 | policies = windows_registry_settings() |
| 230 | for path in [directory / "managed-settings.json", *sorted((directory / "managed-settings.d").glob("*.json"))]: |
| 231 | if path.exists(): |
| 232 | policies.append(read_settings(path)) |
| 233 | return any(policy.get("channelsEnabled") is False for policy in policies) |
| 234 | |
| 235 | |
| 236 | def freeze_settings(env, settings, snapshot): |
| 237 | config = Path(env.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude") |
| 238 | if not config.is_absolute(): |
| 239 | raise Unverified() |
| 240 | user_file = config / "settings.json" |
| 241 | settings = merged_settings(read_settings(user_file) if user_file.exists() else {}, settings) |
| 242 | settings_env = settings.get("env", {}) |
| 243 | if not isinstance(settings_env, dict) or not all(isinstance(v, str) for v in settings_env.values()): |
| 244 | raise Unverified() |
| 245 | |
| 246 | |
| 247 | if settings.get("apiKeyHelper") or (config / "remote-settings.json").exists(): |
| 248 | raise Unverified() |
| 249 | policies = managed_settings() |
| 250 | route_env, route_settings = route_values(env), route_values(settings_env) |
| 251 | effective = {**route_env, **route_settings} |
| 252 | if (any(v and k.endswith("_FILE_DESCRIPTOR") for k, v in effective.items()) or |
| 253 | effective.get("NODE_TLS_REJECT_UNAUTHORIZED") == "0" or |
| 254 | any(effective.get(k) for k in ("ANTHROPIC_PROFILE", "ANTHROPIC_CONFIG_DIR", "ANTHROPIC_FEDERATION_RULE_ID")) or |
| 255 | any(k in route_settings and route_settings[k] != env.get(k) for k in |
| 256 | ("HOME", "XDG_CONFIG_HOME", "APPDATA", "USERPROFILE", "CLAUDE_CONFIG_DIR"))): |
| 257 | raise Unverified() |
| 258 | |
| 259 | |
| 260 | |
| 261 | snapshot.write(json.dumps(settings).encode()) |
| 262 | snapshot.flush() |
| 263 | snapshot.seek(0) |
| 264 | fd = snapshot.fileno() |
| 265 | |
| 266 | |
| 267 | os.set_inheritable(fd, os.name != "nt") |
| 268 | source = str(Path(snapshot.name).resolve()) if os.name == "nt" else "/dev/fd/" + str(fd) |
| 269 | flags = ["--setting-sources", "", "--settings", source] |
| 270 | return config, settings, route_env, route_settings, flags, policies |
| 271 | |
| 272 | |
| 273 | def replace_settings(args, flags): |
| 274 | position = args.index("--setting-sources") |
| 275 | if args[position + 1] != "user": |
| 276 | raise Unverified() |
| 277 | return [*args[:position], *flags, *args[position + 2:]] |
| 278 | |
| 279 | |
| 280 | def resolve(prefix, args, id_index, snapshot): |
| 281 | binary = shutil.which(os.environ.get("CCS_CLAUDE_PATH", "claude") if prefix[0] == "ccs" else "claude") |
| 282 | if not binary: |
| 283 | raise Unverified() |
| 284 | env, settings = dict(os.environ), {} |
| 285 | if prefix[0] == "ccs": |
| 286 | args, settings, env = ccs_launch(prefix[1], args, id_index) |
| 287 | return resolve_actual_context(binary, prefix, args, env, settings, snapshot) |
| 288 | |
| 289 | |
| 290 | def resolve_actual_context(binary, prefix, args, env, settings, snapshot): |
| 291 | config, settings, route_env, route_settings, flags, policies = freeze_settings(env, settings, snapshot) |
| 292 | effective = {**route_env, **route_settings} |
| 293 | fd = snapshot.fileno() |
| 294 | status = subprocess.run([binary, *flags, "auth", "status"], env=env, pass_fds=() if os.name == "nt" else (fd,), |
| 295 | stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=12) |
| 296 | snapshot.seek(0) |
| 297 | info = json.loads(status.stdout) |
| 298 | if not isinstance(info, dict) or status.returncode or not info.get("loggedIn") or info.get("apiProvider") != "firstParty": |
| 299 | raise Unverified() |
| 300 | reported_config = info.get("configDirectory") |
| 301 | if not isinstance(reported_config, str) or Path(reported_config).resolve() != config.resolve(): |
| 302 | raise Unverified() |
| 303 | method = info.get("authMethod") |
| 304 | explicit_key = method == "api_key" and info.get("apiKeySource") == "ANTHROPIC_API_KEY" and effective.get("ANTHROPIC_API_KEY") |
| 305 | explicit_token = method == "oauth_token" and (effective.get("ANTHROPIC_AUTH_TOKEN") or effective.get("CLAUDE_CODE_OAUTH_TOKEN")) |
| 306 | |
| 307 | |
| 308 | if not explicit_key and not explicit_token: |
| 309 | raise Unverified() |
| 310 | endpoint = urlsplit(effective.get("ANTHROPIC_BASE_URL") or "https://api.anthropic.com") |
| 311 | if endpoint.scheme not in ("http", "https") or not endpoint.hostname or endpoint.hostname.rstrip(".") == "api.anthropic.com": |
| 312 | |
| 313 | |
| 314 | raise Unverified() |
| 315 | |
| 316 | |
| 317 | material = [prefix, str(config.resolve()), method, route_env, route_settings, settings] |
| 318 | if policies: |
| 319 | material.append(policies) |
| 320 | return binary, replace_settings(args, flags), env, material |
| 321 | |
| 322 | |
| 323 | def official_turn(helper_path, account, args, snapshot, sid, resume, verify_only=False): |
| 324 | |
| 325 | |
| 326 | helper = runpy.run_path(helper_path) |
| 327 | env = helper["cli_environment"](helper["profile"](account)) |
| 328 | config, settings, route_env, route_settings, flags, policies = freeze_settings(env, {}, snapshot) |
| 329 | harmless_env = {"CLAUDE_CONFIG_DIR", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", |
| 330 | "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS", "CLAUDE_CODE_MAX_OUTPUT_TOKENS", |
| 331 | "ANTHROPIC_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", |
| 332 | "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL"} |
| 333 | ordinary_settings = {"$schema", "env", "model", "permissions", "hooks", "statusLine", "attribution", |
| 334 | "language", "effortLevel", "alwaysThinkingEnabled", "includeCoAuthoredBy", |
| 335 | "respectGitignore", "spinnerTipsEnabled", "enabledPlugins", "outputStyle", |
| 336 | "disableAllHooks", "includeGitInstructions", "autoUpdatesChannel", |
| 337 | "theme", "skipDangerousModePermissionPrompt", "tui", "autoMemoryDirectory", "autoMemoryEnabled"} |
| 338 | familiar_settings = not (settings.keys() - ordinary_settings) |
| 339 | for route in (route_env, route_settings): |
| 340 | for key, value in route.items(): |
| 341 | if not value: |
| 342 | continue |
| 343 | if key == "ANTHROPIC_BASE_URL": |
| 344 | if value.rstrip("/") != "https://api.anthropic.com": |
| 345 | raise Changed() |
| 346 | elif key.startswith(("ANTHROPIC_", "CLAUDE_")) and key not in harmless_env: |
| 347 | raise Unverified() |
| 348 | subject = env.get("CAGE_CLAUDE_SUBJECT") |
| 349 | if not subject: |
| 350 | raise Unverified() |
| 351 | def bind_subscription(reading): |
| 352 | |
| 353 | |
| 354 | proven = familiar_settings and str(reading.get("plan") or "").lower() in ("pro", "max") |
| 355 | material = ["official", account, str(config.resolve()), subject, route_env, route_settings, settings] if proven else None |
| 356 | if material is not None and policies: |
| 357 | material.append(policies) |
| 358 | bind(sid, resume, material) |
| 359 | if verify_only: |
| 360 | raise Verified(config) |
| 361 | if not proven: |
| 362 | single_turn_notice() |
| 363 | result = helper["main"](["run", account, *replace_settings(args, flags)], mobile_settings_fd=snapshot.fileno(), |
| 364 | verify_mobile=bind_subscription) |
| 365 | if result != 0: |
| 366 | raise Changed() |
| 367 | |
| 368 | |
| 369 | def bind(session_id, resume, material): |
| 370 | directory = Path(os.environ["CAGE_CLI_STATE_ROOT"]).parent / "mobile-cli-identities" if os.name == "nt" else Path.home() / ".local/share/cage/mobile-cli-identities" |
| 371 | directory.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 372 | path = directory / session_id |
| 373 | serialized = json.dumps(material, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() |
| 374 | def digest(salt): |
| 375 | return hmac.new(bytes.fromhex(salt), serialized, hashlib.sha256).hexdigest() if material is not None else "" |
| 376 | if not path.exists(): |
| 377 | if resume: |
| 378 | raise Changed() |
| 379 | salt = secrets.token_hex(32) |
| 380 | |
| 381 | with tempfile.NamedTemporaryFile(dir=directory, delete=False) as f: |
| 382 | name = f.name |
| 383 | f.write(json.dumps([salt, digest(salt)]).encode()) |
| 384 | f.flush() |
| 385 | os.fsync(f.fileno()) |
| 386 | try: |
| 387 | try: |
| 388 | os.link(name, path) |
| 389 | except FileExistsError: |
| 390 | pass |
| 391 | finally: |
| 392 | os.unlink(name) |
| 393 | salt, expected = json.loads(path.read_bytes()) |
| 394 | if not expected and resume: |
| 395 | raise Unverified() |
| 396 | if not hmac.compare_digest(expected, digest(salt)): |
| 397 | raise Changed() |
| 398 | |
| 399 | |
| 400 | def main(): |
| 401 | prefix_len = {"ccs": 2, "official": 3}.get(sys.argv[1], 1) |
| 402 | prefix, args = sys.argv[1:1 + prefix_len], sys.argv[1 + prefix_len:] |
| 403 | verify_only = "--cage-verify" in args |
| 404 | if verify_only: |
| 405 | args.remove("--cage-verify") |
| 406 | resume = "--resume" in args |
| 407 | index = args.index("--resume" if resume else "--session-id") + 1 |
| 408 | sid = str(uuid.UUID(args[index])) |
| 409 | if sid != args[index]: |
| 410 | raise Unverified() |
| 411 | with tempfile.TemporaryFile() as snapshot: |
| 412 | if prefix[0] == "official": |
| 413 | return official_turn(prefix[1], prefix[2], args, snapshot, sid, resume, verify_only) |
| 414 | try: |
| 415 | binary, flags, env, material = resolve(prefix, args, index, snapshot) |
| 416 | except (Unverified, OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError): |
| 417 | if resume: |
| 418 | raise Unverified() |
| 419 | bind(sid, False, None) |
| 420 | single_turn_notice() |
| 421 | os.execvp(prefix[0], [*prefix, *args]) |
| 422 | bind(sid, resume, material) |
| 423 | if verify_only: |
| 424 | raise Verified(Path(env.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude").resolve()) |
| 425 | os.execve(binary, [binary, *flags], env) |
| 426 | |
| 427 | |
| 428 | if __name__ == "__main__": |
| 429 | try: |
| 430 | main() |
| 431 | except Verified as result: |
| 432 | print(json.dumps({"config": result.config}), flush=True) |
| 433 | except (Changed, Unverified, OSError, ValueError, KeyError, TypeError, IndexError, subprocess.SubprocessError) as error: |
| 434 | subtype = "cage_identity_changed" if isinstance(error, Changed) else "cage_identity_unverified" |
| 435 | if subtype == "cage_identity_unverified" and "--resume" not in sys.argv: |
| 436 | subtype = "cage_identity_unverified_start" |
| 437 | print(json.dumps({"type": "system", "subtype": subtype}), flush=True) |
| 438 | sys.exit(2) |