返回 last30days-skill
box_chrome_login.py
根目录 / skills / last30days / scripts / box_chrome_login.py
1 #!/usr/bin/env python3
2 """Extras-host X login helper: print (or ``--exec``) the box-chrome launch.
3
4 On extra hosts (Linux, a Darwin Mac mini, a Darwin agentcookie sink, or
5 ``AGENTCOOKIE=on``) the local Chrome cookie store cannot be decrypted, so the
6 only way to hand bird a live X session is to launch a throwaway Chrome with a
7 remote-debugging port, let the human log in, and read the pair over CDP. This
8 helper prints the exact, host-correct launch command — or launches it with
9 ``--exec`` — and refuses to do anything on a MacBook (which keeps its Keychain /
10 Firefox / Safari extract path).
11
12 Contract, matching the rest of the feature:
13 * **Extras only.** On a MacBook (and any non-extras host) it prints "no launch
14 needed" and never spawns a browser, even with ``--exec``. An official-only
15 host (``LAST30DAYS_HOST=grok-bot``, see ``env.x_policy``) gets the same
16 no-launch recipe with a neutral note, even on Linux or a Mac mini.
17 * Launch on the last30days extras NUX port ``18800``
18 (``SAND_CHROME_REMOTE_DEBUG_PORT=18800``) so ``chrome_cdp`` finds it. This is
19 NOT box-chrome's built-in default (``9222`` + the display number).
20 * Uses the host ``box-chrome`` wrapper (which sets ``--class=box-chrome``);
21 never assembles a raw ``google-chrome-stable`` flag soup and never launches
22 raw Chrome with a custom ``--class`` (a raw Chrome with ``--class=l30d-…``
23 failed live where ``box-chrome`` succeeded). No special user-agent is
24 required. If ``box-chrome`` is missing it tells the user to sign into a
25 remote-debugging Chrome and pin ``BROWSER_CDP_URL``.
26 * Reads NO cookies and prints NO cookie values. It never writes to the ``.env``.
27 """
28
29 from __future__ import annotations
30
31 import argparse
32 import json
33 import os
34 import shlex
35 import shutil
36 import stat
37 import subprocess
38 import sys
39 from pathlib import Path
40 from typing import Any, Dict, List, Optional
41
42 SCRIPT_DIR = Path(__file__).parent.resolve()
43 sys.path.insert(0, str(SCRIPT_DIR))
44
45 from lib import chrome_cdp, env # noqa: E402
46
47 # The last30days extras NUX port — single source of truth is chrome_cdp.
48 EXTRAS_CDP_PORT = chrome_cdp._BOX_CHROME_PORT
49 LOGIN_URL = "https://x.com/login"
50 BOX_CHROME_BIN = "box-chrome"
51 # Printed on an official-only host instead of the MacBook note. Names no
52 # cookie mechanism: this host searches X through official access only.
53 OFFICIAL_HOST_NOTE = (
54 "No launch needed: this host searches X through official access and "
55 "does not use a browser login window."
56 )
57
58
59 def _ancestor_chain(path: Path) -> List[Path]:
60 """Return existing/planned ancestors of ``path`` from filesystem root down to ``path.parent``."""
61 return list(reversed(path.parents))
62
63
64 def _check_trusted_ancestor(anc: Path, *, is_immediate_parent: bool, uid: int) -> None:
65 """Verify an existing ancestor directory cannot be tampered with by another local user."""
66 st = os.lstat(anc)
67 if stat.S_ISLNK(st.st_mode):
68 # Never allow a symlink at the immediate parent or owned by a non-root user.
69 if is_immediate_parent or os.name == "nt" or st.st_uid != 0:
70 raise OSError(f"Refusing symlink in profile path: {anc}")
71 # Allow root-owned system symlinks strictly above the immediate parent
72 # (e.g., macOS /var -> private/var) only when the target dir is also trusted.
73 try:
74 st = os.stat(anc)
75 except FileNotFoundError as exc:
76 raise OSError(f"Refusing broken symlink in profile path: {anc}") from exc
77 if not stat.S_ISDIR(st.st_mode):
78 raise OSError(f"Ancestor in profile path is not a directory: {anc}")
79 if os.name == "nt":
80 return
81
82 mode = stat.S_IMODE(st.st_mode)
83 other_writable = bool(mode & 0o022)
84 is_sticky = bool(mode & stat.S_ISVTX)
85
86 if is_immediate_parent:
87 if st.st_uid != uid:
88 raise PermissionError(
89 f"Profile parent directory is not owned by uid {uid}: {anc}"
90 )
91 if other_writable:
92 raise PermissionError(
93 f"Profile parent directory is writable by group or others: {anc}"
94 )
95 return
96
97 if st.st_uid not in (0, uid):
98 raise PermissionError(
99 f"Profile ancestor directory has untrusted owner: {anc}"
100 )
101 # A root-owned sticky directory (e.g., /tmp with mode 1777) prevents other
102 # non-root users from replacing a uid-owned child directory beneath it; any
103 # other group/world-writable ancestor allows path substitution.
104 if other_writable and not (st.st_uid == 0 and is_sticky):
105 raise PermissionError(
106 f"Profile ancestor directory is writable by group or others: {anc}"
107 )
108
109
110 def _is_safe_owner_dir(path: Path) -> bool:
111 """True when ``path`` is an existing owner-only dir inside a trusted ancestor chain."""
112 try:
113 if ".." in path.parts:
114 return False
115 st = os.lstat(path)
116 if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode):
117 return False
118 uid = os.getuid() if os.name != "nt" else 0
119 if os.name != "nt":
120 if st.st_uid != uid:
121 return False
122 if stat.S_IMODE(st.st_mode) & 0o077:
123 return False
124 for anc in _ancestor_chain(path):
125 _check_trusted_ancestor(anc, is_immediate_parent=False, uid=uid)
126 canonical = path.resolve(strict=True)
127 for anc in _ancestor_chain(canonical):
128 _check_trusted_ancestor(anc, is_immediate_parent=False, uid=uid)
129 except OSError:
130 return False
131 return True
132
133
134 def _default_profile_dir() -> str:
135 """Return an owner-only per-user runtime/cache profile path (never a fixed /tmp path)."""
136 xdg_runtime = (os.environ.get("XDG_RUNTIME_DIR") or "").strip()
137 if xdg_runtime and os.path.isabs(xdg_runtime):
138 runtime_path = Path(xdg_runtime)
139 if _is_safe_owner_dir(runtime_path):
140 return str(runtime_path / "last30days-x-chrome")
141 xdg_cache = (os.environ.get("XDG_CACHE_HOME") or "").strip()
142 if xdg_cache and os.path.isabs(xdg_cache):
143 cache_candidate = Path(xdg_cache)
144 if _is_safe_owner_dir(cache_candidate):
145 return str(cache_candidate / "last30days" / "x-chrome")
146 return str(Path.home() / ".cache" / "last30days" / "x-chrome")
147
148
149 DEFAULT_PROFILE_DIR = _default_profile_dir()
150
151
152 def _harden_owned_dir_0700(path: Path, uid: int) -> tuple[int, int]:
153 """Verify non-symlink ownership and enforce mode 0700 on ``path``, returning ``(st_dev, st_ino)``."""
154 st = os.lstat(path)
155 if stat.S_ISLNK(st.st_mode):
156 raise OSError(f"Refusing symlink directory: {path}")
157 if not stat.S_ISDIR(st.st_mode):
158 raise OSError(f"Path is not a directory: {path}")
159 if os.name == "nt":
160 return (st.st_dev, st.st_ino)
161 if st.st_uid != uid:
162 raise PermissionError(f"Directory is not owned by uid {uid}: {path}")
163 if hasattr(os, "O_DIRECTORY") and hasattr(os, "fchmod"):
164 open_flags = os.O_RDONLY | os.O_DIRECTORY | getattr(os, "O_NOFOLLOW", 0)
165 fd = os.open(str(path), open_flags)
166 try:
167 fst = os.fstat(fd)
168 if not stat.S_ISDIR(fst.st_mode):
169 raise OSError(f"Path is not a directory: {path}")
170 if fst.st_uid != uid:
171 raise PermissionError(f"Directory is not owned by uid {uid}: {path}")
172 if stat.S_IMODE(fst.st_mode) != 0o700:
173 os.fchmod(fd, 0o700)
174 fst = os.fstat(fd)
175 if stat.S_IMODE(fst.st_mode) != 0o700:
176 raise PermissionError(
177 f"Could not enforce 0700 permissions on directory: {path}"
178 )
179 return (fst.st_dev, fst.st_ino)
180 finally:
181 os.close(fd)
182 if stat.S_IMODE(st.st_mode) != 0o700:
183 os.chmod(str(path), 0o700)
184 st = os.lstat(path)
185 if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode):
186 raise OSError(f"Directory changed unexpectedly: {path}")
187 if st.st_uid != uid:
188 raise PermissionError(f"Directory is not owned by uid {uid}: {path}")
189 if stat.S_IMODE(st.st_mode) != 0o700:
190 raise PermissionError(f"Could not enforce 0700 permissions on directory: {path}")
191 return (st.st_dev, st.st_ino)
192
193
194 def _ensure_private_profile_dir(profile_dir: str) -> str:
195 """Create and verify a non-symlink, owner-only (0o700) profile dir; return canonical path."""
196 if not profile_dir or not profile_dir.strip():
197 raise OSError("Profile directory path must not be empty")
198
199 raw_path = Path(profile_dir)
200 if ".." in raw_path.parts:
201 raise OSError(f"Refusing traversal segments in profile directory: {profile_dir}")
202 target = raw_path if raw_path.is_absolute() else Path(os.path.abspath(profile_dir))
203
204 uid = os.getuid() if os.name != "nt" else 0
205 ancestors = _ancestor_chain(target)
206 if not ancestors:
207 raise OSError(f"Refusing root as profile directory: {profile_dir}")
208
209 # Phase 1 (read-only): validate every existing unresolved ancestor AND the
210 # full resolved ancestor chain of the deepest existing ancestor BEFORE
211 # creating any directories or changing any permissions.
212 deepest_existing: Optional[Path] = None
213 deepest_idx = -1
214 for idx, anc in enumerate(ancestors):
215 is_immediate = idx == len(ancestors) - 1
216 try:
217 _check_trusted_ancestor(anc, is_immediate_parent=is_immediate, uid=uid)
218 except FileNotFoundError:
219 break
220 deepest_existing = anc
221 deepest_idx = idx
222
223 if deepest_existing is None:
224 raise FileNotFoundError(
225 f"No existing ancestor directory for profile path: {profile_dir}"
226 )
227
228 resolved_existing = deepest_existing.resolve(strict=True)
229 resolved_chain = _ancestor_chain(resolved_existing) + [resolved_existing]
230 deepest_is_immediate = deepest_idx == len(ancestors) - 1
231 for idx, anc in enumerate(resolved_chain):
232 _check_trusted_ancestor(
233 anc,
234 is_immediate_parent=(deepest_is_immediate and idx == len(resolved_chain) - 1),
235 uid=uid,
236 )
237
238 # Phase 2: create any missing per-user intermediate directories beneath the
239 # verified existing prefix with explicit 0700 mode.
240 for idx in range(deepest_idx + 1, len(ancestors)):
241 anc = ancestors[idx]
242 is_immediate = idx == len(ancestors) - 1
243 os.makedirs(str(anc), mode=0o700, exist_ok=True)
244 _harden_owned_dir_0700(anc, uid)
245 _check_trusted_ancestor(anc, is_immediate_parent=is_immediate, uid=uid)
246
247 try:
248 os.lstat(target)
249 except FileNotFoundError:
250 os.makedirs(str(target), mode=0o700, exist_ok=True)
251
252 verified_id = _harden_owned_dir_0700(target, uid)
253
254 # Resolve the full canonical path (expanding any root-owned system symlinks
255 # like macOS /var -> /private/var), validate every resolved ancestor from /
256 # downward, and confirm canonical still refers to the exact verified inode.
257 canonical = target.resolve(strict=True)
258 canonical_ancestors = _ancestor_chain(canonical)
259 if not canonical_ancestors:
260 raise OSError(f"Refusing root as profile directory: {profile_dir}")
261 for idx, anc in enumerate(canonical_ancestors):
262 _check_trusted_ancestor(
263 anc, is_immediate_parent=(idx == len(canonical_ancestors) - 1), uid=uid
264 )
265
266 cst = os.lstat(canonical)
267 if stat.S_ISLNK(cst.st_mode) or not stat.S_ISDIR(cst.st_mode):
268 raise OSError(f"Resolved profile path is not a directory: {canonical}")
269 if os.name != "nt":
270 if cst.st_uid != uid:
271 raise PermissionError(
272 f"Resolved profile directory is not owned by uid {uid}: {canonical}"
273 )
274 if stat.S_IMODE(cst.st_mode) != 0o700:
275 raise PermissionError(
276 f"Resolved profile directory does not have mode 0700: {canonical}"
277 )
278 if (cst.st_dev, cst.st_ino) != verified_id:
279 raise OSError(f"Profile directory changed during verification: {canonical}")
280
281 return str(canonical)
282
283
284 def build_recipe(
285 config: Dict[str, Any],
286 *,
287 profile_dir: Optional[str] = None,
288 url: str = LOGIN_URL,
289 ) -> Dict[str, Any]:
290 """Return the gated launch recipe. Never spawns, never reads cookies.
291
292 Keys: ``applies`` (extras host?), ``box_chrome`` (path or None), ``port``,
293 ``profile_dir``, ``url``, ``env`` (launch env overrides or None),
294 ``command`` (argv or None), ``note`` (human guidance).
295 """
296 profile_dir = _default_profile_dir() if profile_dir is None else profile_dir
297 # Official-only host (LAST30DAYS_HOST=grok-bot): the same no-launch
298 # recipe as a MacBook, checked BEFORE the extras signals so a Linux or
299 # Mac mini Grok Bot computer never gets a launch command. The note is
300 # neutral on purpose. A LAST30DAYS_X_BACKEND=bird pin re-enables
301 # discovery through env.x_policy, and with it this helper.
302 if not env.x_policy(config).cookie_discovery:
303 return {
304 "applies": False,
305 "box_chrome": None,
306 "port": EXTRAS_CDP_PORT,
307 "profile_dir": profile_dir,
308 "url": url,
309 "env": None,
310 "command": None,
311 "note": OFFICIAL_HOST_NOTE,
312 }
313
314 if not env.x_extras_enabled(config):
315 return {
316 "applies": False,
317 "box_chrome": None,
318 "port": EXTRAS_CDP_PORT,
319 "profile_dir": profile_dir,
320 "url": url,
321 "env": None,
322 "command": None,
323 "note": (
324 "This host uses the standard browser-cookie path (Keychain / "
325 "Firefox / Safari extract). No box-chrome login is needed; "
326 "run `setup --allow-browser-cookies` as usual."
327 ),
328 }
329
330 box = shutil.which(BOX_CHROME_BIN)
331 if box:
332 return {
333 "applies": True,
334 "box_chrome": box,
335 "port": EXTRAS_CDP_PORT,
336 "profile_dir": profile_dir,
337 "url": url,
338 "env": {
339 "CHROME_USER_DATA_DIR": profile_dir,
340 "SAND_CHROME_REMOTE_DEBUG_PORT": str(EXTRAS_CDP_PORT),
341 },
342 "command": [box, "--new-window", url],
343 "note": (
344 "Launch this throwaway login Chrome, wait for the x.com login "
345 "page, then hand the desktop to the human to type. Do NOT drive "
346 "the page. After they sign in, pin "
347 f"BROWSER_CDP_URL=http://127.0.0.1:{EXTRAS_CDP_PORT} in .env "
348 "(never AUTH_TOKEN/CT0) and run `setup --allow-browser-cookies`."
349 ),
350 }
351
352 return {
353 "applies": True,
354 "box_chrome": None,
355 "port": EXTRAS_CDP_PORT,
356 "profile_dir": profile_dir,
357 "url": url,
358 "env": None,
359 "command": None,
360 "note": (
361 "box-chrome is not on PATH. Do not assemble a raw google-chrome "
362 "command or launch raw Chrome with a custom --class (that is what "
363 "failed live; box-chrome sets --class=box-chrome). Sign into x.com "
364 "in a Chrome that already exposes a remote-debugging port, then pin "
365 "BROWSER_CDP_URL to that endpoint in .env and run "
366 "`setup --allow-browser-cookies`."
367 ),
368 }
369
370
371 def render_recipe(recipe: Dict[str, Any]) -> str:
372 """Human-readable recipe. Contains no cookie values (none are read)."""
373 lines: List[str] = []
374 if not recipe["applies"]:
375 if recipe["note"] == OFFICIAL_HOST_NOTE:
376 lines.append("[login helper] No launch needed on this host.")
377 else:
378 lines.append("[box-chrome login] Not an extras host.")
379 lines.append(recipe["note"])
380 return "\n".join(lines)
381
382 if recipe["command"] is None:
383 lines.append("[box-chrome login] Extras host, but box-chrome is unavailable.")
384 lines.append(recipe["note"])
385 return "\n".join(lines)
386
387 helper_cmd = [sys.executable or "python3", str(Path(__file__).resolve()), "--exec"]
388 if recipe["profile_dir"] != _default_profile_dir():
389 helper_cmd.extend(["--profile-dir", str(recipe["profile_dir"])])
390 if recipe["url"] != LOGIN_URL:
391 helper_cmd.extend(["--url", str(recipe["url"])])
392 launch_line = " ".join(shlex.quote(part) for part in helper_cmd)
393 lines.append(
394 "[box-chrome login] Extras host. Launch the throwaway login Chrome "
395 "via --exec (verifies trusted 0700 profile dir):"
396 )
397 lines.append("")
398 lines.append(f" {launch_line}")
399 lines.append("")
400 lines.append(
401 f"Launches {recipe['command'][0]} with "
402 f"SAND_CHROME_REMOTE_DEBUG_PORT={recipe['port']} and "
403 f"CHROME_USER_DATA_DIR={recipe['profile_dir']}."
404 )
405 lines.append(recipe["note"])
406 lines.append(
407 "For this first-run harvest, set AGENTCOOKIE=off so a sidecar can't mix "
408 "a different pair; leave AGENTCOOKIE unset again after success."
409 )
410 return "\n".join(lines)
411
412
413 def _parse_args(argv: List[str]) -> argparse.Namespace:
414 parser = argparse.ArgumentParser(
415 description="Print or launch the host-gated box-chrome X login helper."
416 )
417 parser.add_argument("--exec", dest="do_exec", action="store_true")
418 parser.add_argument("--json", dest="as_json", action="store_true")
419 parser.add_argument("--profile-dir", dest="profile_dir", default=None)
420 parser.add_argument("--url", dest="url", default=LOGIN_URL)
421 return parser.parse_args(argv)
422
423
424 def main(argv: Optional[List[str]] = None) -> int:
425 args = _parse_args(list(sys.argv[1:] if argv is None else argv))
426
427 config = env.get_config() # default policy: no cookie reads, no discovery
428 recipe = build_recipe(config, profile_dir=args.profile_dir, url=args.url)
429
430 if args.as_json:
431 printable = {k: v for k, v in recipe.items() if k != "box_chrome"}
432 printable["box_chrome_present"] = recipe["box_chrome"] is not None
433 print(json.dumps(printable))
434 else:
435 print(render_recipe(recipe))
436
437 if args.do_exec:
438 # Refuse to spawn on a non-extras host, or when box-chrome is missing.
439 if not recipe["applies"] or not recipe["command"]:
440 return 0
441 try:
442 verified_profile_dir = _ensure_private_profile_dir(recipe["profile_dir"])
443 except OSError as exc:
444 print(
445 f"[box-chrome login] unsafe or unusable profile directory: "
446 f"{type(exc).__name__}: {exc}",
447 file=sys.stderr,
448 )
449 return 1
450 launch_env = os.environ.copy()
451 launch_env.update(recipe["env"])
452 launch_env["CHROME_USER_DATA_DIR"] = verified_profile_dir
453 try:
454 subprocess.Popen(recipe["command"], env=launch_env)
455 except OSError as exc:
456 print(f"[box-chrome login] failed to launch: {type(exc).__name__}: {exc}",
457 file=sys.stderr)
458 return 1
459 return 0
460
461
462 if __name__ == "__main__":
463 raise SystemExit(main())
464
464 lines PYTHON