返回 last30days-skill
permission_preflight.py
根目录 / skills / last30days / scripts / lib / permission_preflight.py
1 """Permission preflight contract and human renderer."""
2
3 from __future__ import annotations
4
5 import os
6 import platform
7 import shutil
8 from typing import Any
9 from urllib.parse import urlsplit
10
11 from . import corpus, env, providers as provider_endpoints, proxy
12
13
14 ENDPOINT_OVERRIDE_KEYS = {
15 "BROWSER_CDP_URL",
16 "BSKY_SEARCH_HOST",
17 "LAST30DAYS_AMAZON_DOMAIN",
18 "LAST30DAYS_API_BASE",
19 "LAST30DAYS_SEARXNG_URL",
20 "LAST30DAYS_YOUTUBE_SSH_HOST",
21 "OPENAI_BASE_URL",
22 "OPENROUTER_BASE_URL",
23 "SCRAPECREATORS_BASE_URL",
24 "XAI_BASE_URL",
25 "XIAOHONGSHU_API_BASE",
26 "YOUTUBE_PROXY",
27 "YT_PROXY",
28 }
29
30 _DEFAULT_AMAZON_DOMAIN = "https://www.amazon.com"
31
32 PROVIDER_CREDENTIALS = {
33 "google": "Google/Gemini API key",
34 "openai": "OpenAI API key",
35 "xai": "xAI API key",
36 "openrouter": "OpenRouter API key",
37 "perplexity": "Perplexity API key",
38 "scrapecreators": "ScrapeCreators API key",
39 "github": "GitHub token or gh auth",
40 # Presence for these keys is computed from config inside build(), never
41 # through diagnose.providers, whose key set is frozen by
42 # tests/test_diagnose_compat.py.
43 "x_bearer": "X API bearer token",
44 "x_cookies": "X browser cookies (AUTH_TOKEN/CT0)",
45 "brave": "Brave Search API key",
46 "exa": "Exa API key",
47 "serper": "Serper API key",
48 "parallel": "Parallel API key",
49 "bluesky": "Bluesky app password",
50 "truthsocial": "Truth Social token",
51 "apify": "Apify API token",
52 "xquik": "Xquik API key",
53 "brightdata": "Bright Data API key",
54 "groq": "Groq API key",
55 "deepline": "Deepline API key",
56 "hosted_api": "last30days hosted/proxy API key",
57 "publish_password": "HTML publish password",
58 }
59
60
61 def _has_secret(value: Any) -> bool:
62 return bool(str(value or "").strip()) and not proxy.is_sentinel(value)
63
64
65 def _config_or_env(config: dict[str, Any], key: str) -> str:
66 raw = config.get(key)
67 if raw is None:
68 raw = os.environ.get(key)
69 return str(raw or "").strip()
70
71
72 def _valid_hosted_api_base(value: str) -> bool:
73 if not value or any(ord(ch) < 0x20 or ord(ch) == 0x7F or ch.isspace() for ch in value):
74 return False
75 if not provider_endpoints.allowed_base_url_override(value):
76 return False
77 try:
78 parts = urlsplit(value)
79 _ = parts.port
80 except ValueError:
81 return False
82 if "\\" in parts.netloc:
83 return False
84 if parts.username is not None or parts.password is not None or "@" in parts.netloc:
85 return False
86 if parts.query or parts.fragment or "?" in value or "#" in value:
87 return False
88 return True
89
90
91 def _configured_corpus_dirs(config: dict[str, Any]) -> list[str]:
92 """Resolve configured corpus dirs respecting EXCLUDE_SOURCES (matches runtime hosted bypass)."""
93 if "corpus" in env.exclude_sources(config):
94 return []
95 cli_dirs = config.get("_CORPUS_DIRS")
96 if isinstance(cli_dirs, str):
97 cli_list: list[str] | None = [cli_dirs]
98 elif cli_dirs:
99 cli_list = [str(item) for item in cli_dirs if str(item).strip()]
100 else:
101 cli_list = None
102 raw = config.get("LAST30DAYS_CORPUS_DIRS")
103 if not cli_list and not raw:
104 return []
105 return [str(path) for path in corpus.resolve_directories(cli_list, raw)]
106
107
108 def _planned_corpus_dirs(
109 configured_dirs: list[str],
110 requested_sources: list[str] | None = None,
111 ) -> list[str]:
112 if requested_sources and "corpus" not in requested_sources:
113 return []
114 return list(configured_dirs)
115
116
117 def _active_secret_stores(config_source: str) -> list[str]:
118 stores: list[str] = []
119 if config_source == "keychain":
120 stores.append("keychain")
121 elif (
122 platform.system() == "Darwin"
123 and not _truthy(os.environ.get(env.KEYCHAIN_DISABLE_ENV))
124 and shutil.which("security")
125 ):
126 stores.append("keychain")
127 if config_source == "pass":
128 stores.append("pass")
129 elif shutil.which("pass"):
130 stores.append("pass")
131 return stores
132
133
134 def _truthy(value: Any) -> bool:
135 if value is None:
136 return False
137 return str(value).strip().lower() in {"1", "true", "yes", "on"}
138
139
140 def _status(value: bool) -> str:
141 return "available" if value else "unavailable"
142
143
144 def _write_key(write: dict[str, str]) -> tuple[str, str]:
145 return str(write.get("kind") or ""), str(write.get("path") or "")
146
147
148 def _dedupe_writes(writes: list[dict[str, str]]) -> list[dict[str, str]]:
149 deduped: list[dict[str, str]] = []
150 seen: set[tuple[str, str]] = set()
151 for write in writes:
152 key = _write_key(write)
153 if key in seen:
154 continue
155 seen.add(key)
156 deduped.append(write)
157 return deduped
158
159
160 def _conditional_x_cookie_routes(config: dict[str, Any]) -> list[str]:
161 if (
162 not env.x_policy(config).cookie_discovery
163 or env.cookie_access_denied(config)
164 or (config.get("AUTH_TOKEN") and config.get("CT0"))
165 ):
166 return []
167 from . import agentcookie, chrome_cdp
168
169 routes = []
170 if agentcookie.is_available(config):
171 routes.append("agentcookie (if available)")
172 if chrome_cdp.cookie_access_allowed(config) and any(
173 not endpoint.strip().lower().startswith(("https://", "wss://"))
174 for endpoint in chrome_cdp.candidate_endpoints(config)
175 ):
176 routes.append("Chrome CDP (if available)")
177 return routes if routes and env.x_extras_enabled(config) else []
178
179
180 def build(
181 config: dict[str, Any],
182 diagnose: dict[str, Any],
183 *,
184 planned_save_dir: str | None = None,
185 report_on_save_dir: str | None = None,
186 requested_sources: list[str] | None = None,
187 deep_research: bool = False,
188 local_only_run: bool = False,
189 ) -> dict[str, Any]:
190 """Build a stable, secret-free permission preflight object."""
191 browser = dict(diagnose.get("browser_cookies") or {})
192 browser_mode = str(browser.get("mode") or "off")
193 browser_browsers = []
194 if browser_mode in {"read", "plan_only"}:
195 browser_browsers = list(browser.get("browsers") or [])
196 if (
197 (not requested_sources or "reddit" in requested_sources)
198 and "reddit" not in env.exclude_sources(config)
199 and not env.reddit_scrapecreators_primary(config)
200 ):
201 allowed, _ = env.reddit_session_gate({**config, "_BROWSER_COOKIE_MODE": "read"})
202 if allowed:
203 reddit_browser = str(config[env.REDDIT_FROM_BROWSER_VAR]).strip().lower()
204 if reddit_browser not in browser_browsers:
205 browser_browsers.append(reddit_browser)
206 browser_browsers.extend(_conditional_x_cookie_routes(config))
207 browser_status = "enabled_by_config" if browser_browsers else "off"
208
209 ignored_project_config = diagnose.get("ignored_project_config")
210 config_source = str(diagnose.get("config_source") or "env_only")
211 project_config_active = config_source.startswith("project:")
212 if project_config_active:
213 project_status = "trusted_active"
214 elif ignored_project_config:
215 project_status = "ignored_untrusted"
216 else:
217 project_status = "not_active"
218
219 local_writes = list(diagnose.get("local_writes") or [])
220 if planned_save_dir is not None:
221 local_writes = [write for write in local_writes if write.get("kind") != "report"]
222 if planned_save_dir:
223 local_writes.append({"kind": "report", "path": str(planned_save_dir)})
224 local_writes = _dedupe_writes([dict(write) for write in local_writes])
225 local_write_paths = {str(write.get("path") or "") for write in local_writes}
226 conditional_writes: list[dict[str, str]] = []
227 if report_on_save_dir and not planned_save_dir and str(report_on_save_dir) not in local_write_paths:
228 conditional_writes.append({"kind": "report_on_save", "path": str(report_on_save_dir)})
229 conditional_writes = _dedupe_writes(conditional_writes)
230
231 api_base = _config_or_env(config, "LAST30DAYS_API_BASE")
232 raw_hosted_key = config.get("LAST30DAYS_API_KEY")
233 if raw_hosted_key is None:
234 raw_hosted_key = env.read_secret_env("LAST30DAYS_API_KEY")
235 hosted_api_key_present = _has_secret(raw_hosted_key)
236 proxy_mode = _config_or_env(config, "LAST30DAYS_API_MODE").lower() == "proxy"
237 configured_corpus_dirs = _configured_corpus_dirs(config)
238 corpus_dirs = _planned_corpus_dirs(configured_corpus_dirs, requested_sources)
239 hosted_base_valid = bool(api_base) and _valid_hosted_api_base(api_base)
240 hosted_mode = bool(
241 hosted_base_valid
242 and hosted_api_key_present
243 and not proxy_mode
244 and not configured_corpus_dirs
245 and not deep_research
246 and not local_only_run
247 )
248
249 providers = dict(diagnose.get("providers") or {})
250 credentials = {
251 "google": {
252 "present": bool(
253 providers.get("google")
254 or _has_secret(config.get("GOOGLE_API_KEY"))
255 or _has_secret(config.get("GEMINI_API_KEY"))
256 or _has_secret(config.get("GOOGLE_GENAI_API_KEY"))
257 ),
258 "label": PROVIDER_CREDENTIALS["google"],
259 },
260 "openai": {"present": bool(providers.get("openai")), "label": PROVIDER_CREDENTIALS["openai"]},
261 "xai": {
262 "present": (
263 _has_secret(config.get("XAI_API_KEY"))
264 if "XAI_API_KEY" in config
265 else bool(providers.get("xai"))
266 ),
267 "label": PROVIDER_CREDENTIALS["xai"],
268 },
269 "openrouter": {"present": bool(providers.get("openrouter")), "label": PROVIDER_CREDENTIALS["openrouter"]},
270 "perplexity": {"present": bool(providers.get("perplexity")), "label": PROVIDER_CREDENTIALS["perplexity"]},
271 "scrapecreators": {
272 "present": (
273 _has_secret(config.get("SCRAPECREATORS_API_KEY"))
274 if "SCRAPECREATORS_API_KEY" in config
275 else bool(diagnose.get("has_scrapecreators"))
276 ),
277 "label": PROVIDER_CREDENTIALS["scrapecreators"],
278 },
279 "github": {"present": bool(diagnose.get("has_github")), "label": PROVIDER_CREDENTIALS["github"]},
280 "x_bearer": {
281 "present": _has_secret(config.get("X_BEARER_TOKEN")),
282 "label": PROVIDER_CREDENTIALS["x_bearer"],
283 },
284 "x_cookies": {
285 "present": _has_secret(config.get("AUTH_TOKEN")) or _has_secret(config.get("CT0")),
286 "label": PROVIDER_CREDENTIALS["x_cookies"],
287 },
288 "brave": {"present": _has_secret(config.get("BRAVE_API_KEY")), "label": PROVIDER_CREDENTIALS["brave"]},
289 "exa": {"present": _has_secret(config.get("EXA_API_KEY")), "label": PROVIDER_CREDENTIALS["exa"]},
290 "serper": {"present": _has_secret(config.get("SERPER_API_KEY")), "label": PROVIDER_CREDENTIALS["serper"]},
291 "parallel": {"present": _has_secret(config.get("PARALLEL_API_KEY")), "label": PROVIDER_CREDENTIALS["parallel"]},
292 "bluesky": {
293 "present": _has_secret(config.get("BSKY_APP_PASSWORD")),
294 "label": PROVIDER_CREDENTIALS["bluesky"],
295 },
296 "truthsocial": {
297 "present": _has_secret(config.get("TRUTHSOCIAL_TOKEN")),
298 "label": PROVIDER_CREDENTIALS["truthsocial"],
299 },
300 "apify": {"present": _has_secret(config.get("APIFY_API_TOKEN")), "label": PROVIDER_CREDENTIALS["apify"]},
301 "xquik": {"present": _has_secret(config.get("XQUIK_API_KEY")), "label": PROVIDER_CREDENTIALS["xquik"]},
302 "brightdata": {
303 "present": _has_secret(config.get("BRIGHTDATA_API_KEY")),
304 "label": PROVIDER_CREDENTIALS["brightdata"],
305 },
306 "groq": {"present": _has_secret(config.get("GROQ_API_KEY")), "label": PROVIDER_CREDENTIALS["groq"]},
307 "deepline": {
308 "present": _has_secret(config.get("DEEPLINE_API_KEY")),
309 "label": PROVIDER_CREDENTIALS["deepline"],
310 },
311 "hosted_api": {"present": hosted_api_key_present, "label": PROVIDER_CREDENTIALS["hosted_api"]},
312 "publish_password": {
313 "present": _has_secret(config.get("LAST30DAYS_PUBLISH_PASSWORD")),
314 "label": PROVIDER_CREDENTIALS["publish_password"],
315 },
316 }
317
318 active_endpoint_overrides: list[str] = []
319 rejected_provider_overrides: list[str] = []
320 for key in sorted(ENDPOINT_OVERRIDE_KEYS):
321 if key == "LAST30DAYS_API_BASE":
322 value = api_base
323 if not value:
324 continue
325 if not hosted_base_valid:
326 rejected_provider_overrides.append(key)
327 else:
328 active_endpoint_overrides.append(key)
329 continue
330 value = str(config.get(key) or "").strip()
331 if not value:
332 continue
333 if key == "LAST30DAYS_AMAZON_DOMAIN" and value.rstrip("/").lower() == _DEFAULT_AMAZON_DOMAIN:
334 continue
335 if (
336 key in provider_endpoints.PROVIDER_BASE_URL_KEYS
337 and not provider_endpoints.allowed_base_url_override(value)
338 ):
339 rejected_provider_overrides.append(key)
340 else:
341 active_endpoint_overrides.append(key)
342 ignored_endpoint_overrides = sorted(
343 set(diagnose.get("ignored_endpoint_overrides") or []) | set(rejected_provider_overrides)
344 )
345 external_commands = {
346 name: {"status": _status(bool(available))}
347 for name, available in sorted((diagnose.get("external_commands") or {}).items())
348 }
349
350 action_items: list[str] = []
351 if ignored_project_config:
352 action_items.append("Project config was ignored; set LAST30DAYS_TRUST_PROJECT_CONFIG=1 to trust it.")
353 # get_config() already emptied these, so the provider flags above read them
354 # as absent. Name them anyway: the user's setup is broken in a way the
355 # presence booleans alone describe as "nothing configured".
356 templated_keys = env.templated_config_keys(config)
357 if templated_keys:
358 action_items.append(
359 "Unsubstituted config template(s) count as unset: "
360 + _format_names(templated_keys)
361 + ". Replace each with a real value or remove it."
362 )
363 if rejected_provider_overrides:
364 action_items.append(
365 "Provider endpoint override(s) ignored: "
366 + _format_names(rejected_provider_overrides)
367 + ". Use HTTPS, or HTTP on loopback."
368 )
369
370 secret_stores = _active_secret_stores(config_source)
371 available_sources = ["hosted"] if hosted_mode else list(diagnose.get("available_sources") or [])
372
373 return {
374 "status": "action_needed" if action_items else "ready",
375 "safe": bool(diagnose.get("safe")),
376 "local_reads": {
377 "config_source": config_source,
378 "secret_stores": secret_stores,
379 "corpus_dirs": corpus_dirs,
380 "project_config": {
381 "status": project_status,
382 "trusted": bool(project_config_active),
383 "ignored_path": ignored_project_config,
384 "ignored_keys": list(diagnose.get("ignored_project_config_keys") or []),
385 },
386 "browser_cookies": {
387 "status": browser_status,
388 "mode": browser_mode,
389 "browsers": browser_browsers,
390 "reads_values": bool(browser.get("reads_values", False)),
391 },
392 },
393 "local_writes": local_writes,
394 "conditional_writes": conditional_writes,
395 "external_commands": external_commands,
396 "credentials": credentials,
397 "network": {
398 "available_sources": available_sources,
399 "hosted_mode": hosted_mode,
400 "native_search": bool(diagnose.get("native_search")),
401 "endpoint_overrides": active_endpoint_overrides,
402 "ignored_endpoint_overrides": ignored_endpoint_overrides,
403 },
404 "action_items": action_items,
405 }
406
407
408 def _format_names(names: list[str]) -> str:
409 return ", ".join(names) if names else "none"
410
411
412 def render_text(preflight: dict[str, Any]) -> str:
413 """Render the permission preflight as concise user-facing text."""
414 lines: list[str] = ["last30days preflight"]
415 status = preflight.get("status")
416 if status == "ready":
417 lines.append("Status: Ready to research with safe defaults.")
418 else:
419 lines.append("Status: Ready, with item(s) to review.")
420
421 reads = preflight.get("local_reads") or {}
422 project = reads.get("project_config") or {}
423 browser = reads.get("browser_cookies") or {}
424 writes = list(preflight.get("local_writes") or [])
425 conditional_writes = list(preflight.get("conditional_writes") or [])
426 commands = preflight.get("external_commands") or {}
427 credentials = preflight.get("credentials") or {}
428 network = preflight.get("network") or {}
429
430 lines.append("")
431 lines.append("Local reads:")
432 lines.append(f"- Config source: {reads.get('config_source') or 'env_only'}")
433 secret_stores = list(reads.get("secret_stores") or [])
434 if secret_stores:
435 lines.append("- Secret stores: " + _format_names(secret_stores))
436 corpus_dirs = list(reads.get("corpus_dirs") or [])
437 if corpus_dirs:
438 lines.append("- Corpus directories: " + _format_names(corpus_dirs))
439 if project.get("status") == "ignored_untrusted":
440 ignored_keys = _format_names(list(project.get("ignored_keys") or []))
441 lines.append(f"- Project config: ignored untrusted file ({ignored_keys})")
442 elif project.get("status") == "trusted_active":
443 lines.append("- Project config: trusted and active")
444 else:
445 lines.append("- Project config: not active")
446 if browser.get("status") == "enabled_by_config":
447 read_note = (
448 "; cookie values were read"
449 if browser.get("reads_values")
450 else "; preflight did not read cookie values"
451 )
452 lines.append(
453 "- Browser cookies: enabled by config for "
454 + _format_names(list(browser.get("browsers") or []))
455 + read_note
456 )
457 else:
458 lines.append("- Browser cookies: off; no browser stores will be read")
459
460 lines.append("")
461 lines.append("Local writes:")
462 if writes:
463 for write in writes:
464 lines.append(f"- {write.get('kind', 'file')}: {write.get('path')}")
465 else:
466 lines.append("- none planned")
467 for write in conditional_writes:
468 kind = write.get("kind", "file")
469 if kind == "engine_cache_on_first_use":
470 lines.append(f"- MCP engine cache (first use may initialize it): {write.get('path')}")
471 elif kind == "native_core_on_first_run":
472 lines.append(
473 "- Native Rust core binary (first live run may download from GitHub Releases "
474 f"with SHA-256 verification and execute): {write.get('path')}"
475 )
476 elif kind.endswith("_on_save"):
477 label = kind.removesuffix("_on_save").replace("_", " ").capitalize()
478 lines.append(f"- {label} (if saved): {write.get('path')}")
479 else:
480 lines.append(f"- {kind} (conditional): {write.get('path')}")
481
482 present_credentials = [
483 str(info.get("label") or name)
484 for name, info in credentials.items()
485 if info.get("present")
486 ]
487 lines.append("")
488 lines.append("Credentials:")
489 lines.append("- Present: " + _format_names(present_credentials))
490 lines.append("- Values are not printed or written by preflight")
491
492 unavailable_commands = [
493 name for name, info in commands.items() if info.get("status") == "unavailable"
494 ]
495 lines.append("")
496 if unavailable_commands:
497 lines.append("Optional commands unavailable: " + _format_names(unavailable_commands))
498 else:
499 lines.append("Optional commands: available")
500
501 endpoint_overrides = list(network.get("endpoint_overrides") or [])
502 ignored_endpoint_overrides = list(network.get("ignored_endpoint_overrides") or [])
503 lines.append("")
504 lines.append("Network:")
505 if network.get("hosted_mode"):
506 lines.append("- Hosted mode: active (LAST30DAYS_API_BASE)")
507 lines.append("- Available sources: " + _format_names(list(network.get("available_sources") or [])))
508 if endpoint_overrides:
509 lines.append("- Endpoint overrides active: " + _format_names(endpoint_overrides))
510 if ignored_endpoint_overrides:
511 lines.append("- Endpoint overrides ignored: " + _format_names(ignored_endpoint_overrides))
512
513 action_items = list(preflight.get("action_items") or [])
514 lines.append("")
515 if action_items:
516 lines.append("Next:")
517 for item in action_items:
518 lines.append(f"- {item}")
519 else:
520 lines.append("Next: run research normally, or configure optional sources if you need more coverage.")
521
522 return "\n".join(lines) + "\n"
523
523 lines PYTHON