From 8044e88be4ee052dccb0526314b2af8e1582c8eb Mon Sep 17 00:00:00 2001 From: reform Date: Fri, 23 Oct 2026 20:02:14 +0300 Subject: [PATCH] recovered from aaronjaworski710 --- .env.example | 117 + .github/ISSUE_TEMPLATE/bug_report.md | 42 + .github/ISSUE_TEMPLATE/feature_request.md | 19 + .github/PULL_REQUEST_TEMPLATE.md | 14 + .github/workflows/ci.yml | 233 + .github/workflows/deploy.yml | 298 + .gitignore | 85 + ARCHITECTURE.md | 245 + CHANGELOG.md | 338 + CONTRIBUTING.md | 82 + DISCLAIMER.md | 46 + LICENSE | 21 + Makefile | 71 + README.md | 159 + SECURITY.md | 77 + account_backup.py | 199 + apps/README.md | 53 + apps/__init__.py | 0 apps/cli/README.md | 13 + apps/control_api/__init__.py | 11 + apps/control_api/__main__.py | 22 + apps/control_api/accounts_ops.py | 167 + apps/control_api/app.py | 115 + apps/control_api/auth.py | 95 + apps/control_api/config_io.py | 409 ++ apps/control_api/imports_ops.py | 428 ++ apps/control_api/mail_ops.py | 339 + apps/control_api/nodes_ops.py | 2021 ++++++ apps/control_api/overview.py | 57 + apps/control_api/passwords.py | 67 + apps/control_api/process_registry.py | 235 + apps/control_api/progress.py | 654 ++ apps/control_api/rate_limit.py | 47 + apps/control_api/routes_accounts.py | 32 + apps/control_api/routes_auth.py | 106 + apps/control_api/routes_config.py | 56 + apps/control_api/routes_import.py | 90 + apps/control_api/routes_mail.py | 116 + apps/control_api/routes_nodes.py | 192 + apps/control_api/routes_ops.py | 105 + apps/control_api/routes_runs.py | 58 + apps/control_api/runs.py | 387 + apps/control_api/schemas.py | 87 + apps/control_api/sessions.py | 84 + apps/control_api/settings.py | 195 + apps/control_api/system_ops.py | 177 + apps/control_api/users.py | 122 + apps/gui/README.md | 13 + apps/web/index.html | 12 + apps/web/package-lock.json | 4147 +++++++++++ apps/web/package.json | 24 + apps/web/src/App.jsx | 137 + apps/web/src/api/client.js | 217 + apps/web/src/lib/format.js | 90 + apps/web/src/lib/http.js | 22 + apps/web/src/lib/http.test.js | 52 + apps/web/src/lib/providers.js | 56 + apps/web/src/lib/providers.test.js | 81 + apps/web/src/lib/useBusy.js | 17 + apps/web/src/lib/useBusy.test.jsx | 62 + apps/web/src/lib/useConfigForm.js | 130 + apps/web/src/main.jsx | 7 + apps/web/src/pages/Accounts/AccountsPage.jsx | 278 + apps/web/src/pages/LoginGate.jsx | 83 + apps/web/src/pages/Register/RegForm.jsx | 333 + apps/web/src/pages/Register/RegisterPage.jsx | 562 ++ apps/web/src/pages/Register/RunProgress.jsx | 292 + .../web/src/pages/Register/progressRender.jsx | 252 + apps/web/src/pages/Resources/ImportTab.jsx | 187 + apps/web/src/pages/Resources/MailTab.jsx | 317 + apps/web/src/pages/Resources/MailTab.test.jsx | 120 + .../web/src/pages/Resources/ResourcesPage.jsx | 68 + .../Resources/mail/DefaultDomainsCard.jsx | 72 + .../pages/Resources/mail/MailCredImport.jsx | 67 + .../pages/Resources/mail/MailPoolProbe.jsx | 722 ++ .../Resources/mail/MailProviderPanels.jsx | 175 + apps/web/src/pages/Resources/mail/domains.js | 24 + .../src/pages/Resources/mail/domains.test.js | 29 + .../pages/Resources/nodes/CatalogPanel.jsx | 356 + .../src/pages/Resources/nodes/ClashPanel.jsx | 564 ++ .../src/pages/Resources/nodes/clashFilters.js | 76 + .../Resources/nodes/clashFilters.test.js | 51 + apps/web/src/pages/RunLogs/LogsPage.jsx | 305 + apps/web/src/pages/Settings/SettingsPage.jsx | 424 ++ .../src/pages/Settings/SettingsPage.test.jsx | 123 + apps/web/src/store/feedback.js | 40 + apps/web/src/store/run.js | 12 + apps/web/src/store/session.js | 11 + apps/web/src/styles/accounts.css | 105 + apps/web/src/styles/base.css | 223 + apps/web/src/styles/components.css | 383 + apps/web/src/styles/logs.css | 105 + apps/web/src/styles/resources.css | 309 + apps/web/src/styles/run-progress.css | 376 + apps/web/src/styles/run.css | 277 + apps/web/src/styles/settings.css | 96 + apps/web/src/styles/tokens.css | 27 + apps/web/src/ui/Bar.jsx | 12 + apps/web/src/ui/Button.jsx | 22 + apps/web/src/ui/Card.jsx | 7 + apps/web/src/ui/Chip.jsx | 13 + apps/web/src/ui/Drawer.jsx | 21 + apps/web/src/ui/Field.jsx | 8 + apps/web/src/ui/Kpi.jsx | 9 + apps/web/src/ui/LogDetails.jsx | 11 + apps/web/src/ui/OpsFeedbackBar.jsx | 47 + apps/web/src/ui/PageHeader.jsx | 13 + apps/web/src/ui/ProviderPoolStatus.jsx | 37 + apps/web/src/ui/Select.jsx | 23 + apps/web/src/ui/StatusDot.jsx | 4 + apps/web/src/ui/Tabs.jsx | 19 + apps/web/src/ui/ToastHost.jsx | 13 + apps/web/src/ui/index.js | 15 + apps/web/vite.config.js | 24 + apps/web/vitest.config.js | 11 + config.example.json | 301 + config.simple.example.json | 45 + cpa_auths/.gitkeep | 1 + cpa_export.py | 1206 ++++ cpa_xai/__init__.py | 88 + cpa_xai/accounts.py | 121 + cpa_xai/browser_confirm.py | 2102 ++++++ cpa_xai/grpcweb.py | 107 + cpa_xai/mint.py | 762 ++ cpa_xai/oauth_device.py | 348 + cpa_xai/pkce_mint.py | 631 ++ cpa_xai/probe.py | 596 ++ cpa_xai/protocol_mint.py | 290 + cpa_xai/proxyutil.py | 71 + cpa_xai/refresh.py | 564 ++ cpa_xai/schema.py | 155 + cpa_xai/writer.py | 333 + docs/ADDING_PROVIDER.md | 73 + docs/DEVELOPED.md | 118 + docs/IP-ISOLATION-QUALITY-DESIGN.md | 109 + docs/LAYOUT.md | 20 + docs/archive/README.md | 10 + .../plans/2026-07-16-chatgpt-code-align.md | 1061 +++ .../plans/2026-07-16-cpa-mid-tier-probe.md | 832 +++ .../2026-07-17-nodes-target-preflight.md | 40 + .../2026-07-16-chatgpt-code-align-design.md | 297 + .../2026-07-16-cpa-mid-tier-probe-design.md | 190 + ...026-07-17-nodes-target-preflight-design.md | 117 + ...26-07-17-register-profile-config-design.md | 252 + docs/grok-register-deploy-experience.md | 37 + ...2026-07-21-console-ui-v1-progress-merge.md | 1074 +++ .../plans/2026-07-21-web-control-plane.md | 512 ++ .../plans/2026-07-22-console-ui-refactor.md | 1224 ++++ .../2026-07-26-console10-refactor-batch1.md | 633 ++ .../2026-07-26-console10-refactor-batch2.md | 55 + .../plans/2026-07-28-email-ip-correlation.md | 1707 +++++ ...2026-08-01-outlook-register-integration.md | 2259 ++++++ ...-21-console-ui-v1-progress-merge-design.md | 661 ++ .../2026-07-21-web-control-plane-design.md | 310 + .../2026-07-22-console-ui-refactor-design.md | 142 + .../2026-07-24-mail-pool-probe-design.md | 315 + .../2026-07-28-email-ip-correlation-design.md | 154 + ...2026-08-01-outlook-register-site-design.md | 190 + examples/README.md | 9 + examples/minimal_pipeline.py | 37 + grok_register_ttk.py | 6360 +++++++++++++++++ mail_assets/.gitkeep | 0 mail_assets/README.md | 36 + mail_credentials.example.txt | 11 + mail_pool_probe.py | 1491 ++++ mise.toml | 37 + node_score.py | 598 ++ nodes.example.json | 19 + nodes.example.txt | 6 + preflight-clash-nodes.sh | 109 + profiles/chatgpt-cf.example.yaml | 59 + profiles/chatgpt-gmail.example.yaml | 41 + profiles/chatgpt-tinyhost.example.yaml | 47 + profiles/grok-tinyhost.example.yaml | 68 + profiles/mimo-tinyhost.example.yaml | 54 + profiles/outlook-live-nobind.example.yaml | 47 + profiles/outlook-live-nobind.yaml | 36 + profiles/outlook-live-tzmatch.yaml | 43 + profiles/typesafe-tinyhost.example.yaml | 51 + providers/README.md | 23 + providers/__init__.py | 0 providers/_template/.env.example | 4 + providers/_template/README.md | 33 + providers/_template/run-register.sh | 16 + providers/chatgpt/.env.example | 25 + providers/chatgpt/README.md | 152 + providers/chatgpt/__init__.py | 1 + providers/chatgpt/protocol/__init__.py | 5 + providers/chatgpt/protocol/constants.py | 73 + providers/chatgpt/protocol/flow.py | 1124 +++ providers/chatgpt/protocol/sentinel.py | 148 + providers/chatgpt/protocol/session.py | 101 + providers/chatgpt/run-register.sh | 69 + providers/grok/README.md | 34 + providers/mimo/.env.example | 7 + providers/mimo/README-PXED.md | 30 + providers/mimo/README.md | 124 + providers/mimo/inject_cpa_openai.py | 472 ++ providers/mimo/package.json | 34 + providers/mimo/run-register.sh | 138 + providers/mimo/scripts/register-one.js | 1074 +++ providers/mimo/scripts/smoke-browser.js | 33 + providers/mimo/smoke.sh | 46 + providers/typesafe/.env.example | 15 + providers/typesafe/README.md | 80 + providers/typesafe/__init__.py | 1 + providers/typesafe/protocol/__init__.py | 5 + providers/typesafe/protocol/constants.py | 24 + providers/typesafe/protocol/flow.py | 564 ++ providers/typesafe/protocol/session.py | 74 + providers/typesafe/run-register.sh | 58 + providers/typesafe/smoke.sh | 140 + proxy_bridge.py | 233 + proxy_rotate.py | 1488 ++++ pyproject.toml | 56 + register.sh | 333 + register_cli.py | 2595 +++++++ register_core/README.md | 108 + register_core/__init__.py | 46 + register_core/__main__.py | 3 + register_core/cli.py | 401 ++ register_core/config/__init__.py | 11 + register_core/config/loader.py | 488 ++ register_core/config/schema.py | 180 + register_core/contracts.py | 290 + register_core/decode/__init__.py | 10 + register_core/decode/adapters.py | 44 + register_core/decode/base.py | 27 + register_core/decode/extract.py | 104 + register_core/decode/registry.py | 27 + register_core/email/__init__.py | 13 + register_core/email/base.py | 41 + register_core/email/composite.py | 104 + register_core/email/mail_proxy.py | 30 + register_core/email/registry.py | 65 + register_core/email/sources/__init__.py | 1 + register_core/email/sources/cloudflare.py | 139 + register_core/email/sources/duckmail.py | 72 + register_core/email/sources/gmail_imap.py | 114 + register_core/email/sources/legacy_grok.py | 96 + register_core/email/sources/temp_mail.py | 283 + register_core/email/sources/tinyhost.py | 234 + register_core/errors.py | 44 + register_core/mailbox/__init__.py | 10 + register_core/mailbox/adapters.py | 40 + register_core/mailbox/base.py | 22 + register_core/mailbox/registry.py | 28 + register_core/nodes/README.md | 151 + register_core/nodes/__init__.py | 34 + register_core/nodes/catalog.py | 111 + register_core/nodes/cli.py | 450 ++ register_core/nodes/convert/__init__.py | 31 + register_core/nodes/convert/cli_import.py | 231 + register_core/nodes/convert/parsers.py | 349 + register_core/nodes/convert/pipeline.py | 522 ++ register_core/nodes/convert/types.py | 51 + register_core/nodes/convert/uri.py | 262 + register_core/nodes/convert/validate.py | 161 + register_core/nodes/core_runtime.py | 333 + register_core/nodes/health.py | 292 + register_core/nodes/manager.py | 715 ++ register_core/nodes/models.py | 225 + register_core/nodes/targets.py | 108 + register_core/pipeline.py | 607 ++ register_core/providers/__init__.py | 13 + register_core/providers/base.py | 29 + register_core/providers/chatgpt_adapter.py | 370 + register_core/providers/grok_adapter.py | 292 + register_core/providers/mimo_adapter.py | 304 + register_core/providers/outlook_adapter.py | 453 ++ register_core/providers/outlook_browser.py | 539 ++ register_core/providers/outlook_captcha.py | 202 + register_core/providers/outlook_identity.py | 108 + register_core/providers/outlook_oauth.py | 369 + register_core/providers/outlook_recovery.py | 212 + register_core/providers/registry.py | 63 + register_core/providers/typesafe_adapter.py | 396 + register_core/sink/__init__.py | 6 + register_core/sink/base.py | 13 + register_core/sink/jsonl_sink.py | 44 + register_core/sink/multi.py | 15 + register_core/strategy/__init__.py | 5 + register_core/strategy/burn.py | 196 + register_core/strategy/engine.py | 268 + register_core/tools/__init__.py | 1 + register_core/tools/poll_otp.py | 126 + register_core/util/__init__.py | 1 + register_core/util/egress.py | 150 + register_core/util/files.py | 30 + register_core/util/mail_inject.py | 141 + register_core/util/process.py | 123 + register_core/util/proxy.py | 947 +++ register_core/util/secrets.py | 45 + register_core/verify/__init__.py | 9 + register_core/verify/base.py | 15 + register_core/verify/chatgpt_token.py | 68 + register_core/verify/grok_chat.py | 61 + register_core/verify/mimo_tts.py | 38 + register_core/verify/noop.py | 15 + register_core/verify/registry.py | 29 + register_core/verify/typesafe_key.py | 52 + register_universal.py | 75 + run-register-core.sh | 146 + run-register.sh | 70 + scripts/ab_fingerprint_light.sh | 212 + scripts/backfill_chat_stamps.py | 430 ++ scripts/backfill_cpa_xai_from_accounts.py | 288 + scripts/backup_registered_accounts.py | 45 + scripts/bootstrap_nodes_core.sh | 46 + scripts/build_web_console.sh | 14 + scripts/check_clash_egress.py | 91 + scripts/control_api_user.py | 72 + scripts/deploy_web_console10.sh | 187 + scripts/doctor_secrets.sh | 107 + scripts/export_cpa_xai_from_grok_auth.py | 94 + scripts/import_clash_to_nodes.py | 19 + scripts/import_cpa_auth_dir.py | 849 +++ scripts/import_nodes.py | 67 + scripts/launch_batch_supervisor.sh | 667 ++ scripts/probe_clash_nodes.py | 634 ++ scripts/probe_mail_pool.py | 351 + scripts/quality_milestone_watch.py | 107 + scripts/quality_sample_accounts.py | 381 + scripts/remint_expired_and_sync_authdir.py | 383 + scripts/run_control_api.sh | 81 + scripts/setup_simple.sh | 268 + scripts/smoke_diskfirst_one.sh | 209 + start-clash-for-grok.sh | 85 + tab_pool.py | 1164 +++ tests/conftest.py | 14 + ...test_outlook_control_plane_reachability.py | 139 + .../test_outlook_pipeline_gated.py | 103 + tests/unit/test_account_backup.py | 99 + .../test_batch_supervisor_cpa_milestones.py | 63 + tests/unit/test_browser_fingerprint_light.py | 402 ++ tests/unit/test_browser_recycle_slot_retry.py | 202 + tests/unit/test_browser_reliability_fixes.py | 507 ++ tests/unit/test_bulk_supervisor_disk_first.py | 84 + tests/unit/test_cdp_page_target_patch.py | 178 + tests/unit/test_chatgpt_error_kinds.py | 95 + tests/unit/test_chatgpt_protocol_steps.py | 640 ++ tests/unit/test_chatgpt_provider.py | 439 ++ tests/unit/test_control_api_accounts_ops.py | 218 + tests/unit/test_control_api_auth.py | 64 + tests/unit/test_control_api_config.py | 402 ++ tests/unit/test_control_api_import.py | 318 + tests/unit/test_control_api_login.py | 235 + tests/unit/test_control_api_mail.py | 419 ++ tests/unit/test_control_api_nodes.py | 508 ++ tests/unit/test_control_api_outlook.py | 52 + tests/unit/test_control_api_progress.py | 351 + tests/unit/test_control_api_runs.py | 707 ++ .../unit/test_control_api_sessions_ttl_cap.py | 101 + tests/unit/test_cpa_chat_entitlement_gate.py | 1633 +++++ tests/unit/test_cpa_one_click_chain.py | 250 + tests/unit/test_cpa_pkce_mint.py | 346 + tests/unit/test_cpa_refresh_persist.py | 344 + tests/unit/test_cpa_remote_inject.py | 239 + tests/unit/test_email_ip_correlation.py | 329 + tests/unit/test_email_ip_off_equivalence.py | 86 + tests/unit/test_email_providers_pool.py | 355 + tests/unit/test_env_config_overlay.py | 90 + tests/unit/test_fail_policy.py | 683 ++ tests/unit/test_gmail_imap_provider.py | 238 + tests/unit/test_hotmail_rest_code.py | 97 + tests/unit/test_mail_pool_probe.py | 690 ++ .../unit/test_mail_pool_weighted_sampling.py | 96 + tests/unit/test_mail_proxy_separation.py | 179 + tests/unit/test_mimo_cpa_openai_inject.py | 170 + tests/unit/test_mint_browser_lifecycle.py | 183 + tests/unit/test_mint_consent_allow.py | 182 + tests/unit/test_mint_consent_diag.py | 114 + tests/unit/test_mint_egress_hold.py | 110 + tests/unit/test_mint_stability.py | 360 + tests/unit/test_node_score.py | 185 + .../test_node_score_correlation_errors.py | 120 + tests/unit/test_nodes_convert.py | 235 + tests/unit/test_orphan_chrome_cleanup.py | 285 + tests/unit/test_otp_diagnostics.py | 43 + tests/unit/test_outlook_artifacts.py | 160 + tests/unit/test_outlook_browser.py | 392 + tests/unit/test_outlook_captcha.py | 253 + tests/unit/test_outlook_identity.py | 143 + tests/unit/test_outlook_import_export.py | 195 + tests/unit/test_outlook_oauth.py | 559 ++ tests/unit/test_outlook_provider.py | 689 ++ tests/unit/test_outlook_provider_registry.py | 40 + tests/unit/test_outlook_recovery.py | 228 + tests/unit/test_outlook_supervisor_markers.py | 103 + tests/unit/test_pipeline_proxy.py | 87 + tests/unit/test_probe_clash_rewrite.py | 158 + tests/unit/test_proxy_bridge.py | 155 + tests/unit/test_proxy_rotate.py | 442 ++ tests/unit/test_proxy_rotate_layer3_nudge.py | 234 + tests/unit/test_register_cli_attribution.py | 80 + tests/unit/test_register_core_layers.py | 868 +++ tests/unit/test_register_core_nodes.py | 1519 ++++ tests/unit/test_register_core_proxy.py | 344 + tests/unit/test_register_profile.py | 351 + tests/unit/test_register_strategy.py | 425 ++ tests/unit/test_router.py | 252 + tests/unit/test_simple_packaging.py | 153 + tests/unit/test_skeleton_layout.py | 58 + tests/unit/test_sso_normalize.py | 122 + tests/unit/test_temp_mail_source.py | 131 + tests/unit/test_typesafe_provider.py | 751 ++ turnstilePatch/content.js | 114 + turnstilePatch/manifest.json | 15 + uv.lock | 1175 +++ 409 files changed, 104886 insertions(+) create mode 100644 .env.example create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/deploy.yml create mode 100644 .gitignore create mode 100644 ARCHITECTURE.md create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 DISCLAIMER.md create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.md create mode 100644 SECURITY.md create mode 100644 account_backup.py create mode 100644 apps/README.md create mode 100644 apps/__init__.py create mode 100644 apps/cli/README.md create mode 100644 apps/control_api/__init__.py create mode 100644 apps/control_api/__main__.py create mode 100644 apps/control_api/accounts_ops.py create mode 100644 apps/control_api/app.py create mode 100644 apps/control_api/auth.py create mode 100644 apps/control_api/config_io.py create mode 100644 apps/control_api/imports_ops.py create mode 100644 apps/control_api/mail_ops.py create mode 100644 apps/control_api/nodes_ops.py create mode 100644 apps/control_api/overview.py create mode 100644 apps/control_api/passwords.py create mode 100644 apps/control_api/process_registry.py create mode 100644 apps/control_api/progress.py create mode 100644 apps/control_api/rate_limit.py create mode 100644 apps/control_api/routes_accounts.py create mode 100644 apps/control_api/routes_auth.py create mode 100644 apps/control_api/routes_config.py create mode 100644 apps/control_api/routes_import.py create mode 100644 apps/control_api/routes_mail.py create mode 100644 apps/control_api/routes_nodes.py create mode 100644 apps/control_api/routes_ops.py create mode 100644 apps/control_api/routes_runs.py create mode 100644 apps/control_api/runs.py create mode 100644 apps/control_api/schemas.py create mode 100644 apps/control_api/sessions.py create mode 100644 apps/control_api/settings.py create mode 100644 apps/control_api/system_ops.py create mode 100644 apps/control_api/users.py create mode 100644 apps/gui/README.md create mode 100644 apps/web/index.html create mode 100644 apps/web/package-lock.json create mode 100644 apps/web/package.json create mode 100644 apps/web/src/App.jsx create mode 100644 apps/web/src/api/client.js create mode 100644 apps/web/src/lib/format.js create mode 100644 apps/web/src/lib/http.js create mode 100644 apps/web/src/lib/http.test.js create mode 100644 apps/web/src/lib/providers.js create mode 100644 apps/web/src/lib/providers.test.js create mode 100644 apps/web/src/lib/useBusy.js create mode 100644 apps/web/src/lib/useBusy.test.jsx create mode 100644 apps/web/src/lib/useConfigForm.js create mode 100644 apps/web/src/main.jsx create mode 100644 apps/web/src/pages/Accounts/AccountsPage.jsx create mode 100644 apps/web/src/pages/LoginGate.jsx create mode 100644 apps/web/src/pages/Register/RegForm.jsx create mode 100644 apps/web/src/pages/Register/RegisterPage.jsx create mode 100644 apps/web/src/pages/Register/RunProgress.jsx create mode 100644 apps/web/src/pages/Register/progressRender.jsx create mode 100644 apps/web/src/pages/Resources/ImportTab.jsx create mode 100644 apps/web/src/pages/Resources/MailTab.jsx create mode 100644 apps/web/src/pages/Resources/MailTab.test.jsx create mode 100644 apps/web/src/pages/Resources/ResourcesPage.jsx create mode 100644 apps/web/src/pages/Resources/mail/DefaultDomainsCard.jsx create mode 100644 apps/web/src/pages/Resources/mail/MailCredImport.jsx create mode 100644 apps/web/src/pages/Resources/mail/MailPoolProbe.jsx create mode 100644 apps/web/src/pages/Resources/mail/MailProviderPanels.jsx create mode 100644 apps/web/src/pages/Resources/mail/domains.js create mode 100644 apps/web/src/pages/Resources/mail/domains.test.js create mode 100644 apps/web/src/pages/Resources/nodes/CatalogPanel.jsx create mode 100644 apps/web/src/pages/Resources/nodes/ClashPanel.jsx create mode 100644 apps/web/src/pages/Resources/nodes/clashFilters.js create mode 100644 apps/web/src/pages/Resources/nodes/clashFilters.test.js create mode 100644 apps/web/src/pages/RunLogs/LogsPage.jsx create mode 100644 apps/web/src/pages/Settings/SettingsPage.jsx create mode 100644 apps/web/src/pages/Settings/SettingsPage.test.jsx create mode 100644 apps/web/src/store/feedback.js create mode 100644 apps/web/src/store/run.js create mode 100644 apps/web/src/store/session.js create mode 100644 apps/web/src/styles/accounts.css create mode 100644 apps/web/src/styles/base.css create mode 100644 apps/web/src/styles/components.css create mode 100644 apps/web/src/styles/logs.css create mode 100644 apps/web/src/styles/resources.css create mode 100644 apps/web/src/styles/run-progress.css create mode 100644 apps/web/src/styles/run.css create mode 100644 apps/web/src/styles/settings.css create mode 100644 apps/web/src/styles/tokens.css create mode 100644 apps/web/src/ui/Bar.jsx create mode 100644 apps/web/src/ui/Button.jsx create mode 100644 apps/web/src/ui/Card.jsx create mode 100644 apps/web/src/ui/Chip.jsx create mode 100644 apps/web/src/ui/Drawer.jsx create mode 100644 apps/web/src/ui/Field.jsx create mode 100644 apps/web/src/ui/Kpi.jsx create mode 100644 apps/web/src/ui/LogDetails.jsx create mode 100644 apps/web/src/ui/OpsFeedbackBar.jsx create mode 100644 apps/web/src/ui/PageHeader.jsx create mode 100644 apps/web/src/ui/ProviderPoolStatus.jsx create mode 100644 apps/web/src/ui/Select.jsx create mode 100644 apps/web/src/ui/StatusDot.jsx create mode 100644 apps/web/src/ui/Tabs.jsx create mode 100644 apps/web/src/ui/ToastHost.jsx create mode 100644 apps/web/src/ui/index.js create mode 100644 apps/web/vite.config.js create mode 100644 apps/web/vitest.config.js create mode 100644 config.example.json create mode 100644 config.simple.example.json create mode 100644 cpa_auths/.gitkeep create mode 100644 cpa_export.py create mode 100644 cpa_xai/__init__.py create mode 100644 cpa_xai/accounts.py create mode 100644 cpa_xai/browser_confirm.py create mode 100644 cpa_xai/grpcweb.py create mode 100644 cpa_xai/mint.py create mode 100644 cpa_xai/oauth_device.py create mode 100644 cpa_xai/pkce_mint.py create mode 100644 cpa_xai/probe.py create mode 100644 cpa_xai/protocol_mint.py create mode 100644 cpa_xai/proxyutil.py create mode 100644 cpa_xai/refresh.py create mode 100644 cpa_xai/schema.py create mode 100644 cpa_xai/writer.py create mode 100644 docs/ADDING_PROVIDER.md create mode 100644 docs/DEVELOPED.md create mode 100644 docs/IP-ISOLATION-QUALITY-DESIGN.md create mode 100644 docs/LAYOUT.md create mode 100644 docs/archive/README.md create mode 100644 docs/archive/plans/2026-07-16-chatgpt-code-align.md create mode 100644 docs/archive/plans/2026-07-16-cpa-mid-tier-probe.md create mode 100644 docs/archive/plans/2026-07-17-nodes-target-preflight.md create mode 100644 docs/archive/specs/2026-07-16-chatgpt-code-align-design.md create mode 100644 docs/archive/specs/2026-07-16-cpa-mid-tier-probe-design.md create mode 100644 docs/archive/specs/2026-07-17-nodes-target-preflight-design.md create mode 100644 docs/archive/specs/2026-07-17-register-profile-config-design.md create mode 100644 docs/grok-register-deploy-experience.md create mode 100644 docs/superpowers/plans/2026-07-21-console-ui-v1-progress-merge.md create mode 100644 docs/superpowers/plans/2026-07-21-web-control-plane.md create mode 100644 docs/superpowers/plans/2026-07-22-console-ui-refactor.md create mode 100644 docs/superpowers/plans/2026-07-26-console10-refactor-batch1.md create mode 100644 docs/superpowers/plans/2026-07-26-console10-refactor-batch2.md create mode 100644 docs/superpowers/plans/2026-07-28-email-ip-correlation.md create mode 100644 docs/superpowers/plans/2026-08-01-outlook-register-integration.md create mode 100644 docs/superpowers/specs/2026-07-21-console-ui-v1-progress-merge-design.md create mode 100644 docs/superpowers/specs/2026-07-21-web-control-plane-design.md create mode 100644 docs/superpowers/specs/2026-07-22-console-ui-refactor-design.md create mode 100644 docs/superpowers/specs/2026-07-24-mail-pool-probe-design.md create mode 100644 docs/superpowers/specs/2026-07-28-email-ip-correlation-design.md create mode 100644 docs/superpowers/specs/2026-08-01-outlook-register-site-design.md create mode 100644 examples/README.md create mode 100644 examples/minimal_pipeline.py create mode 100644 grok_register_ttk.py create mode 100644 mail_assets/.gitkeep create mode 100644 mail_assets/README.md create mode 100644 mail_credentials.example.txt create mode 100644 mail_pool_probe.py create mode 100644 mise.toml create mode 100644 node_score.py create mode 100644 nodes.example.json create mode 100644 nodes.example.txt create mode 100644 preflight-clash-nodes.sh create mode 100644 profiles/chatgpt-cf.example.yaml create mode 100644 profiles/chatgpt-gmail.example.yaml create mode 100644 profiles/chatgpt-tinyhost.example.yaml create mode 100644 profiles/grok-tinyhost.example.yaml create mode 100644 profiles/mimo-tinyhost.example.yaml create mode 100644 profiles/outlook-live-nobind.example.yaml create mode 100644 profiles/outlook-live-nobind.yaml create mode 100644 profiles/outlook-live-tzmatch.yaml create mode 100644 profiles/typesafe-tinyhost.example.yaml create mode 100644 providers/README.md create mode 100644 providers/__init__.py create mode 100644 providers/_template/.env.example create mode 100644 providers/_template/README.md create mode 100644 providers/_template/run-register.sh create mode 100644 providers/chatgpt/.env.example create mode 100644 providers/chatgpt/README.md create mode 100644 providers/chatgpt/__init__.py create mode 100644 providers/chatgpt/protocol/__init__.py create mode 100644 providers/chatgpt/protocol/constants.py create mode 100644 providers/chatgpt/protocol/flow.py create mode 100644 providers/chatgpt/protocol/sentinel.py create mode 100644 providers/chatgpt/protocol/session.py create mode 100644 providers/chatgpt/run-register.sh create mode 100644 providers/grok/README.md create mode 100644 providers/mimo/.env.example create mode 100644 providers/mimo/README-PXED.md create mode 100644 providers/mimo/README.md create mode 100644 providers/mimo/inject_cpa_openai.py create mode 100644 providers/mimo/package.json create mode 100644 providers/mimo/run-register.sh create mode 100644 providers/mimo/scripts/register-one.js create mode 100644 providers/mimo/scripts/smoke-browser.js create mode 100644 providers/mimo/smoke.sh create mode 100644 providers/typesafe/.env.example create mode 100644 providers/typesafe/README.md create mode 100644 providers/typesafe/__init__.py create mode 100644 providers/typesafe/protocol/__init__.py create mode 100644 providers/typesafe/protocol/constants.py create mode 100644 providers/typesafe/protocol/flow.py create mode 100644 providers/typesafe/protocol/session.py create mode 100644 providers/typesafe/run-register.sh create mode 100644 providers/typesafe/smoke.sh create mode 100644 proxy_bridge.py create mode 100644 proxy_rotate.py create mode 100644 pyproject.toml create mode 100644 register.sh create mode 100644 register_cli.py create mode 100644 register_core/README.md create mode 100644 register_core/__init__.py create mode 100644 register_core/__main__.py create mode 100644 register_core/cli.py create mode 100644 register_core/config/__init__.py create mode 100644 register_core/config/loader.py create mode 100644 register_core/config/schema.py create mode 100644 register_core/contracts.py create mode 100644 register_core/decode/__init__.py create mode 100644 register_core/decode/adapters.py create mode 100644 register_core/decode/base.py create mode 100644 register_core/decode/extract.py create mode 100644 register_core/decode/registry.py create mode 100644 register_core/email/__init__.py create mode 100644 register_core/email/base.py create mode 100644 register_core/email/composite.py create mode 100644 register_core/email/mail_proxy.py create mode 100644 register_core/email/registry.py create mode 100644 register_core/email/sources/__init__.py create mode 100644 register_core/email/sources/cloudflare.py create mode 100644 register_core/email/sources/duckmail.py create mode 100644 register_core/email/sources/gmail_imap.py create mode 100644 register_core/email/sources/legacy_grok.py create mode 100644 register_core/email/sources/temp_mail.py create mode 100644 register_core/email/sources/tinyhost.py create mode 100644 register_core/errors.py create mode 100644 register_core/mailbox/__init__.py create mode 100644 register_core/mailbox/adapters.py create mode 100644 register_core/mailbox/base.py create mode 100644 register_core/mailbox/registry.py create mode 100644 register_core/nodes/README.md create mode 100644 register_core/nodes/__init__.py create mode 100644 register_core/nodes/catalog.py create mode 100644 register_core/nodes/cli.py create mode 100644 register_core/nodes/convert/__init__.py create mode 100644 register_core/nodes/convert/cli_import.py create mode 100644 register_core/nodes/convert/parsers.py create mode 100644 register_core/nodes/convert/pipeline.py create mode 100644 register_core/nodes/convert/types.py create mode 100644 register_core/nodes/convert/uri.py create mode 100644 register_core/nodes/convert/validate.py create mode 100644 register_core/nodes/core_runtime.py create mode 100644 register_core/nodes/health.py create mode 100644 register_core/nodes/manager.py create mode 100644 register_core/nodes/models.py create mode 100644 register_core/nodes/targets.py create mode 100644 register_core/pipeline.py create mode 100644 register_core/providers/__init__.py create mode 100644 register_core/providers/base.py create mode 100644 register_core/providers/chatgpt_adapter.py create mode 100644 register_core/providers/grok_adapter.py create mode 100644 register_core/providers/mimo_adapter.py create mode 100644 register_core/providers/outlook_adapter.py create mode 100644 register_core/providers/outlook_browser.py create mode 100644 register_core/providers/outlook_captcha.py create mode 100644 register_core/providers/outlook_identity.py create mode 100644 register_core/providers/outlook_oauth.py create mode 100644 register_core/providers/outlook_recovery.py create mode 100644 register_core/providers/registry.py create mode 100644 register_core/providers/typesafe_adapter.py create mode 100644 register_core/sink/__init__.py create mode 100644 register_core/sink/base.py create mode 100644 register_core/sink/jsonl_sink.py create mode 100644 register_core/sink/multi.py create mode 100644 register_core/strategy/__init__.py create mode 100644 register_core/strategy/burn.py create mode 100644 register_core/strategy/engine.py create mode 100644 register_core/tools/__init__.py create mode 100644 register_core/tools/poll_otp.py create mode 100644 register_core/util/__init__.py create mode 100644 register_core/util/egress.py create mode 100644 register_core/util/files.py create mode 100644 register_core/util/mail_inject.py create mode 100644 register_core/util/process.py create mode 100644 register_core/util/proxy.py create mode 100644 register_core/util/secrets.py create mode 100644 register_core/verify/__init__.py create mode 100644 register_core/verify/base.py create mode 100644 register_core/verify/chatgpt_token.py create mode 100644 register_core/verify/grok_chat.py create mode 100644 register_core/verify/mimo_tts.py create mode 100644 register_core/verify/noop.py create mode 100644 register_core/verify/registry.py create mode 100644 register_core/verify/typesafe_key.py create mode 100644 register_universal.py create mode 100644 run-register-core.sh create mode 100644 run-register.sh create mode 100644 scripts/ab_fingerprint_light.sh create mode 100644 scripts/backfill_chat_stamps.py create mode 100644 scripts/backfill_cpa_xai_from_accounts.py create mode 100644 scripts/backup_registered_accounts.py create mode 100644 scripts/bootstrap_nodes_core.sh create mode 100644 scripts/build_web_console.sh create mode 100644 scripts/check_clash_egress.py create mode 100644 scripts/control_api_user.py create mode 100644 scripts/deploy_web_console10.sh create mode 100644 scripts/doctor_secrets.sh create mode 100644 scripts/export_cpa_xai_from_grok_auth.py create mode 100644 scripts/import_clash_to_nodes.py create mode 100644 scripts/import_cpa_auth_dir.py create mode 100644 scripts/import_nodes.py create mode 100644 scripts/launch_batch_supervisor.sh create mode 100644 scripts/probe_clash_nodes.py create mode 100644 scripts/probe_mail_pool.py create mode 100644 scripts/quality_milestone_watch.py create mode 100644 scripts/quality_sample_accounts.py create mode 100644 scripts/remint_expired_and_sync_authdir.py create mode 100644 scripts/run_control_api.sh create mode 100644 scripts/setup_simple.sh create mode 100644 scripts/smoke_diskfirst_one.sh create mode 100644 start-clash-for-grok.sh create mode 100644 tab_pool.py create mode 100644 tests/conftest.py create mode 100644 tests/integration/test_outlook_control_plane_reachability.py create mode 100644 tests/integration/test_outlook_pipeline_gated.py create mode 100644 tests/unit/test_account_backup.py create mode 100644 tests/unit/test_batch_supervisor_cpa_milestones.py create mode 100644 tests/unit/test_browser_fingerprint_light.py create mode 100644 tests/unit/test_browser_recycle_slot_retry.py create mode 100644 tests/unit/test_browser_reliability_fixes.py create mode 100644 tests/unit/test_bulk_supervisor_disk_first.py create mode 100644 tests/unit/test_cdp_page_target_patch.py create mode 100644 tests/unit/test_chatgpt_error_kinds.py create mode 100644 tests/unit/test_chatgpt_protocol_steps.py create mode 100644 tests/unit/test_chatgpt_provider.py create mode 100644 tests/unit/test_control_api_accounts_ops.py create mode 100644 tests/unit/test_control_api_auth.py create mode 100644 tests/unit/test_control_api_config.py create mode 100644 tests/unit/test_control_api_import.py create mode 100644 tests/unit/test_control_api_login.py create mode 100644 tests/unit/test_control_api_mail.py create mode 100644 tests/unit/test_control_api_nodes.py create mode 100644 tests/unit/test_control_api_outlook.py create mode 100644 tests/unit/test_control_api_progress.py create mode 100644 tests/unit/test_control_api_runs.py create mode 100644 tests/unit/test_control_api_sessions_ttl_cap.py create mode 100644 tests/unit/test_cpa_chat_entitlement_gate.py create mode 100644 tests/unit/test_cpa_one_click_chain.py create mode 100644 tests/unit/test_cpa_pkce_mint.py create mode 100644 tests/unit/test_cpa_refresh_persist.py create mode 100644 tests/unit/test_cpa_remote_inject.py create mode 100644 tests/unit/test_email_ip_correlation.py create mode 100644 tests/unit/test_email_ip_off_equivalence.py create mode 100644 tests/unit/test_email_providers_pool.py create mode 100644 tests/unit/test_env_config_overlay.py create mode 100644 tests/unit/test_fail_policy.py create mode 100644 tests/unit/test_gmail_imap_provider.py create mode 100644 tests/unit/test_hotmail_rest_code.py create mode 100644 tests/unit/test_mail_pool_probe.py create mode 100644 tests/unit/test_mail_pool_weighted_sampling.py create mode 100644 tests/unit/test_mail_proxy_separation.py create mode 100644 tests/unit/test_mimo_cpa_openai_inject.py create mode 100644 tests/unit/test_mint_browser_lifecycle.py create mode 100644 tests/unit/test_mint_consent_allow.py create mode 100644 tests/unit/test_mint_consent_diag.py create mode 100644 tests/unit/test_mint_egress_hold.py create mode 100644 tests/unit/test_mint_stability.py create mode 100644 tests/unit/test_node_score.py create mode 100644 tests/unit/test_node_score_correlation_errors.py create mode 100644 tests/unit/test_nodes_convert.py create mode 100644 tests/unit/test_orphan_chrome_cleanup.py create mode 100644 tests/unit/test_otp_diagnostics.py create mode 100644 tests/unit/test_outlook_artifacts.py create mode 100644 tests/unit/test_outlook_browser.py create mode 100644 tests/unit/test_outlook_captcha.py create mode 100644 tests/unit/test_outlook_identity.py create mode 100644 tests/unit/test_outlook_import_export.py create mode 100644 tests/unit/test_outlook_oauth.py create mode 100644 tests/unit/test_outlook_provider.py create mode 100644 tests/unit/test_outlook_provider_registry.py create mode 100644 tests/unit/test_outlook_recovery.py create mode 100644 tests/unit/test_outlook_supervisor_markers.py create mode 100644 tests/unit/test_pipeline_proxy.py create mode 100644 tests/unit/test_probe_clash_rewrite.py create mode 100644 tests/unit/test_proxy_bridge.py create mode 100644 tests/unit/test_proxy_rotate.py create mode 100644 tests/unit/test_proxy_rotate_layer3_nudge.py create mode 100644 tests/unit/test_register_cli_attribution.py create mode 100644 tests/unit/test_register_core_layers.py create mode 100644 tests/unit/test_register_core_nodes.py create mode 100644 tests/unit/test_register_core_proxy.py create mode 100644 tests/unit/test_register_profile.py create mode 100644 tests/unit/test_register_strategy.py create mode 100644 tests/unit/test_router.py create mode 100644 tests/unit/test_simple_packaging.py create mode 100644 tests/unit/test_skeleton_layout.py create mode 100644 tests/unit/test_sso_normalize.py create mode 100644 tests/unit/test_temp_mail_source.py create mode 100644 tests/unit/test_typesafe_provider.py create mode 100644 turnstilePatch/content.js create mode 100644 turnstilePatch/manifest.json create mode 100644 uv.lock diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..e5139d9 --- /dev/null +++ b/.env.example @@ -0,0 +1,117 @@ +# Grok 注册机 - 环境变量模板 +# 复制为 .env 并填入真实值(.env 已 gitignore) +# 真实进程环境变量优先于 .env;.env 又覆盖 config.json 中同名开关(见 apply_env_config_overrides) + +# --- Hotmail / Outlook 邮箱池 --- +# 不要把 refresh_token / 密码写进 .env! +# 凭证文件格式见 mail_credentials.example.txt: +# email----password----ClientID----Token +# 单选(兼容):只启用一条邮箱链路 +EMAIL_PROVIDER=hotmail +# 多选(优先于 EMAIL_PROVIDER):逗号/空格分隔,注册时按策略轮用全部已选链路 +# 合法名:duckmail,yyds,cloudflare,cloudmail,hotmail,gmail +# (tinyhost 走 register_core profile,不在 legacy EMAIL_PROVIDERS 池内) +# EMAIL_PROVIDERS=duckmail,gmail,cloudflare +# 策略:round_robin(默认,每 attempt 轮询)| random | failover(失败才切下一家) +# EMAIL_PROVIDER_STRATEGY=round_robin +# DuckMail(第三方临邮 api.duckmail.sbs,非域名邮箱) +# 公开接口可无 key 创建;有 key 时写 DUCKMAIL_API_KEY(env 优先于 config.json) +# DUCKMAIL_API_KEY= +HOTMAIL_ACCOUNTS_FILE=mail_credentials.txt +# 批量资产目录(本地):mail_assets/hotmail.com_*.txt → 合并进 mail_credentials.txt + +# --- 代理 --- +PROXY=http://127.0.0.1:7890 +CPA_PROXY=http://127.0.0.1:7890 + +# --- 注册节点池 soft cooldown(与 hard quarantine 分离)--- +# risk=registration_disallowed 软冷却(不 quarantine);network 仍计 fail_count +# PER_USE 默认 0=关闭,避免小池饿死 +# REGISTER_NODES_COOLDOWN_RISK=600 +# REGISTER_NODES_COOLDOWN_NETWORK=120 +# REGISTER_NODES_COOLDOWN_PER_USE=0 +# REGISTER_NODES_MAX_FAIL=3 +# REGISTER_NODES_SKIP_FAILED=1 +# mail_miss / captcha / verify / fatal 永不 cool/quarantine 节点 + +# --- 邮件路径独立代理(ChatGPT / tinyhost HTTP 等)--- +# 默认直连;禁止把注册 PROXY_LIST 静默塞进邮件路径 +# CHATGPT_MAIL_PROXY= +# EMAIL_PROXY= +# MAIL_PROXY= + +# --- 代理/出口 IP 轮换(注册级,不动整机出口)--- +# 多账号冷 IP:优先 PROXY_ROTATE_MODE=list + PROXY_LIST(自控节点池) +# 单节点烟测/固定出口:clash + GROK_NODE/CLASH_PIN_NODE 钉住(on_start 不 advance) +# clash=仅专用组 GROK-REG 轮换(DOMAIN-SUFFIX 命中 x.ai/grok.com;主策略组不动) +PROXY_ROTATE_MODE=off +PROXY_ROTATE_EVERY=1 +# 节点双池策略(nodes.json tier:0=机房/普通,1=加宽/家宽/住宅) +# residential|加宽|家宽 = 只用 tier>=1 +# datacenter|机房|普通|非加宽 = 只用 tier==0 +# both|混用 = 两池都用(默认) +# REGISTER_NODES_POOL=both +# list 模式:逗号/分号/换行分隔,或 .txt/.list 文件路径 +PROXY_LIST= +# clash 模式:unix socket 或 http://host:port +CLASH_API=unix:///tmp/verge/verge-mihomo.sock +CLASH_PROXY_GROUP=GROK-REG +CLASH_DONOR_GROUP=宝可梦 +CLASH_RULE_DOMAINS=x.ai,grok.com,grok.x.ai,assets.grok.com +# 钉死 clash 节点名(与 config clash_pin_node 等价;start-clash-for-grok.sh 也读 GROK_NODE) +# GROK_NODE=GVPS-TUIC-googlevps +# CLASH_PIN_NODE= +# 进程结束自动恢复专用组原节点(绝不碰主组) +CLASH_RESTORE_ON_EXIT=true + +# --- 一键 CPA 远端注入 --- +CPA_REMOTE_INJECT=false +CPA_REMOTE_LIVE_REQUIRED=true +CPA_REMOTE_INJECT_REQUIRED=false +CPA_REMOTE_SSH_HOST=tebi-tunnel +CPA_REMOTE_SSH_USER= +CPA_REMOTE_LIVE_DIR=/root/.cli-proxy-api +CPA_REMOTE_AUTH_DIRS=/root/.cli-proxy-api,/personal/cpa/auths +CPA_REMOTE_AUTH_DIR=/personal/cpa/auths +CPA_REMOTE_CREDENTIALS_FILE=~/.ssh/bohrium_credentials +CPA_REMOTE_CREDENTIAL_ALIAS=tebi +# 也可用环境变量注入 SSH 密码(勿提交): +# CPA_REMOTE_SSHPASS= +# SSHPASS= +CPA_AUTH_DIR=./cpa_auths +CPA_AUTH_PRIORITY=1000 +CPA_EXPORT_ENABLED=true +CPA_PROTOCOL_ONLY=false +# OAuth grant: pkce (authorization-code, best-effort; empty SPA residual → device/browser) | device +CPA_PROTOCOL_FLOW=pkce +# PKCE fail → device flow for local disk only (product default true, matches mint.py / config.example). +# Device tokens often chat 403; entitlement_denied still hard-blocks tebi/live inject (no remint spin). +CPA_ALLOW_DEVICE_FLOW_FALLBACK=true +# free Build product gate: models-only is not enough; chat 403 = account entitlement (Manual-required) +CPA_PROBE_CHAT=true +CPA_PROBE_CHAT_REQUIRED=true +# chat gate transport: hybrid (default) | direct | cpa (cpa requires credential pin) +# CPA_PROBE_VIA=hybrid +# free Build 403 is NOT unlocked by code — do not soft-inject without chat_ok + +# --- CloudMail(email_provider=cloudmail 时)--- +CLOUDMAIL_URL= +CLOUDMAIL_ADMIN_EMAIL= +CLOUDMAIL_PASSWORD= + +# --- Gmail app-password IMAP(email_provider=gmail;CF 域名 catch-all → Gmail)--- +# 应用专用密码,不是登录密码;勿提交真实值 +# EMAIL_PROVIDER=gmail +# GMAIL_IMAP_USER=you@gmail.com +# GMAIL_IMAP_PASSWORD=xxxx xxxx xxxx xxxx +# GMAIL_IMAP_HOST=imap.gmail.com +# GMAIL_IMAP_PORT=993 +# GMAIL_IMAP_FOLDER=INBOX +# DEFAULT_DOMAINS=your-cf-domain.com + +# --- grok2api --- +GROK2API_APP_KEY= +GROK2API_REMOTE_BASE=http://127.0.0.1:8000/admin/api + +# --- 测试 --- +# GROK_REGISTER_LIVE=1 diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..fdd6bcc --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,42 @@ +--- +name: Bug report +about: Report a defect with enough offline-reproducible detail +title: "[bug] " +labels: bug +--- + +## Summary + + + +## Environment + +- OS: +- Python: +- Install method: `uv` / other +- Headed browser: yes / no +- Proxy configured: yes / no +- Email provider: hotmail / cloudmail / other + +## Steps to reproduce + +1. +2. +3. + +## Expected + +## Actual + +## Logs + + + +```text +paste redacted logs here +``` + +## Checklist + +- [ ] I did **not** paste real tokens or passwords +- [ ] I read DISCLAIMER.md / SECURITY.md diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..e5e60b4 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,19 @@ +--- +name: Feature request +about: Suggest an improvement +title: "[feat] " +labels: enhancement +--- + +## Problem + + + +## Proposal + +## Alternatives considered + +## Scope notes + +- Affects registration / CPA mint / mail / remote inject / docs / other: +- Willing to open a PR: yes / no diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..9edf9e7 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,14 @@ +## Summary + + + +## Test plan + +- [ ] `uv run python -m pytest -q` (offline) +- [ ] `uv run python -m py_compile …` if needed +- [ ] Live checks (if any): describe, do not paste secrets + +## Security + +- [ ] No `config.json` / credentials / `cpa_auths` / backups in this PR +- [ ] Logs in description are redacted diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..fffbe65 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,233 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + actions: read + +jobs: + test: + name: offline-tests + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install uv + uses: astral-sh/setup-uv@v5 + with: + enable-cache: true + + - name: Set up Python + run: uv python install 3.13 + + - name: Sync dependencies + run: uv sync --extra dev + + - name: Shell syntax (setup/doctor/hub) + run: | + bash -n scripts/setup_simple.sh + bash -n scripts/doctor_secrets.sh + bash -n scripts/build_web_console.sh + bash -n scripts/deploy_web_console10.sh + bash -n register.sh + bash -n providers/mimo/run-register.sh + bash -n providers/mimo/smoke.sh + bash -n providers/_template/run-register.sh + + - name: Syntax check + run: | + # I4: required paths must exist (fail CI if deleted); + # optional paths may be staged features and are skipped when absent. + set -euo pipefail + required=( + register_cli.py + grok_register_ttk.py + cpa_export.py + account_backup.py + tab_pool.py + proxy_bridge.py + proxy_rotate.py + mail_pool_probe.py + node_score.py + cpa_xai/__init__.py + cpa_xai/accounts.py + cpa_xai/browser_confirm.py + cpa_xai/mint.py + cpa_xai/oauth_device.py + cpa_xai/probe.py + cpa_xai/protocol_mint.py + cpa_xai/proxyutil.py + cpa_xai/schema.py + cpa_xai/writer.py + register_core/__init__.py + register_core/__main__.py + register_core/cli.py + register_core/contracts.py + register_core/errors.py + register_core/pipeline.py + register_core/email/__init__.py + register_core/providers/__init__.py + register_core/providers/grok_adapter.py + register_core/providers/mimo_adapter.py + register_core/verify/__init__.py + register_core/sink/jsonl_sink.py + register_core/util/process.py + register_core/util/secrets.py + register_core/verify/mimo_tts.py + register_core/verify/grok_chat.py + apps/control_api/app.py + apps/control_api/mail_ops.py + apps/control_api/nodes_ops.py + apps/control_api/accounts_ops.py + apps/control_api/system_ops.py + apps/control_api/process_registry.py + providers/mimo/inject_cpa_openai.py + scripts/backfill_cpa_xai_from_accounts.py + scripts/backup_registered_accounts.py + scripts/export_cpa_xai_from_grok_auth.py + scripts/remint_expired_and_sync_authdir.py + scripts/quality_milestone_watch.py + scripts/quality_sample_accounts.py + scripts/probe_mail_pool.py + ) + optional=( + # Keep empty or list experimental modules not yet always shipped. + ) + missing=0 + present=() + for f in "${required[@]}"; do + if [[ -f "$f" ]]; then + present+=("$f") + else + echo "ERROR: required file missing: $f" >&2 + missing=1 + fi + done + if [[ "$missing" -ne 0 ]]; then + exit 1 + fi + for f in "${optional[@]:-}"; do + [[ -z "$f" ]] && continue + if [[ -f "$f" ]]; then + present+=("$f") + else + echo "skip optional missing: $f" + fi + done + uv run python -m py_compile "${present[@]}" + + - name: Offline unit tests + env: + # Never run live mailbox / remote inject in CI + GROK_REGISTER_LIVE: "" + run: uv run python -m pytest -q + + - name: Secret path guard + run: | + set -euo pipefail + if git ls-files | grep -E '(^|/)(config\.json|\.env|mail_credentials\.txt|accounts_cli\.txt)$|mail_assets/hotmail|cpa_auths/xai-|^backups/|^logs/'; then + echo "Refusing tracked secret/runtime paths" >&2 + git ls-files | grep -E '(^|/)(config\.json|\.env|mail_credentials\.txt|accounts_cli\.txt)$|cpa_auths/xai-|^backups/|^logs/' >&2 + exit 1 + fi + echo "OK: no secret runtime paths tracked" + bash scripts/doctor_secrets.sh || test $? -eq 2 + + web-test: + name: web-unit-tests + runs-on: ubuntu-latest + timeout-minutes: 10 + # No main-only guard: console10 前端测试在 push 和 PR 上都要跑 + # (package-web 只在 main push 跑,PR 上前端曾经完全没有覆盖)。 + permissions: + contents: read + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: "22" + cache: npm + cache-dependency-path: apps/web/package-lock.json + + - name: Install deps + working-directory: apps/web + run: npm ci + + - name: Unit tests + working-directory: apps/web + run: npm test + + package-web: + name: package-console10 + runs-on: ubuntu-latest + timeout-minutes: 10 + needs: [test] + # M1: only package on main (PR CI still runs tests; deploy uses main artifacts) + if: github.ref == 'refs/heads/main' && github.event_name == 'push' + permissions: + contents: read + actions: write + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: "22" + cache: npm + cache-dependency-path: apps/web/package-lock.json + + - name: Web unit tests + working-directory: apps/web + run: | + npm ci + npm test + + - name: Build console10 + run: ./scripts/build_web_console.sh + + - name: Pack tarball + run: | + set -euo pipefail + mkdir -p artifacts + tar -C apps/web/dist -czf artifacts/console10-webroot.tgz . + # also keep a flat dist tree for artifact browsing + cp -a apps/web/dist artifacts/console10-dist + python - <<'PY' + from pathlib import Path + p = Path("artifacts/console10-webroot.tgz") + print(f"artifact_bytes={p.stat().st_size}") + assert p.stat().st_size > 1000, "web tarball too small" + idx = Path("artifacts/console10-dist/index.html") + assert idx.is_file(), "missing index.html in dist" + print("index_head:") + print(idx.read_text(encoding="utf-8", errors="replace")[:400]) + PY + + - name: Upload console10 artifact + uses: actions/upload-artifact@v4 + with: + name: console10-web + path: | + artifacts/console10-webroot.tgz + artifacts/console10-dist/** + if-no-files-found: error + retention-days: 14 diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..dfa90be --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,298 @@ +name: Deploy console10 + +# Deploy static SPA only — does NOT stop batch/coinbot. +# +# Triggers: +# - workflow_dispatch (manual; dry_run / rebuild / artifact options) +# - workflow_run: after successful CI on main (auto deploy that run's artifact) +# +# Required secrets (repo and/or Environment `pxed`): +# PXED_SSH_PRIVATE_KEY — deploy key private PEM +# PXED_HOST — ssh target (prefer direct host, e.g. user@pxed1497962.bohrium.tech) +# PXED_KNOWN_HOSTS — known_hosts lines (REQUIRED for real deploy) +# Optional: +# PXED_SSH_PORT — default 22 +# PXED_WEB — remote web root (default /data/grok-register/apps/web) +# +# Protection: job uses Environment `pxed`. + +on: + workflow_dispatch: + inputs: + ref: + description: "Git ref to build when not using artifact. Empty = this workflow SHA." + required: false + default: "" + type: string + use_latest_artifact: + description: "Prefer console10-web artifact from a successful main CI run." + required: false + default: true + type: boolean + remote_web: + description: "Override remote web root under /data/grok-register (empty = secret/default)." + required: false + default: "" + type: string + dry_run: + description: "Build/download only; do not scp/ssh." + required: false + default: false + type: boolean + workflow_run: + workflows: ["CI"] + types: [completed] + branches: [main] + +concurrency: + group: deploy-console10 + cancel-in-progress: false + +# I6: explicit least privilege (repo default may be read; workflow_run needs actions:read) +permissions: + contents: read + actions: read + +jobs: + deploy: + name: deploy-to-pxed + runs-on: ubuntu-latest + timeout-minutes: 20 + # C1: Environment gate + environment: pxed + permissions: + contents: read + actions: read + # Auto path: only on successful CI that was a push to main (not PR CI) + if: > + github.event_name == 'workflow_dispatch' || + (github.event_name == 'workflow_run' && + github.event.workflow_run.conclusion == 'success' && + github.event.workflow_run.event == 'push') + + steps: + - name: Resolve mode + id: mode + env: + EVENT_NAME: ${{ github.event_name }} + # workflow_run fields are empty on workflow_dispatch; inputs empty on workflow_run + WR_ID: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.id || '' }} + WR_SHA: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.head_sha || '' }} + WR_URL: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.html_url || '' }} + INPUT_REF: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || '' }} + INPUT_USE_ARTIFACT: ${{ github.event_name == 'workflow_dispatch' && (inputs.use_latest_artifact && 'true' || 'false') || 'true' }} + INPUT_DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && (inputs.dry_run && 'true' || 'false') || 'false' }} + INPUT_REMOTE_WEB: ${{ github.event_name == 'workflow_dispatch' && inputs.remote_web || '' }} + THIS_SHA: ${{ github.sha }} + run: | + set -euo pipefail + if [[ "$EVENT_NAME" == "workflow_run" ]]; then + echo "trigger=auto" >> "$GITHUB_OUTPUT" + echo "dry_run=false" >> "$GITHUB_OUTPUT" + echo "prefer_artifact=true" >> "$GITHUB_OUTPUT" + echo "ci_run_id=$WR_ID" >> "$GITHUB_OUTPUT" + echo "ref=$WR_SHA" >> "$GITHUB_OUTPUT" + echo "remote_web_input=" >> "$GITHUB_OUTPUT" + echo "Auto-deploy from CI run $WR_ID sha=$WR_SHA ($WR_URL)" + else + REF="$INPUT_REF" + if [[ -z "$REF" ]]; then + REF="$THIS_SHA" + fi + echo "trigger=manual" >> "$GITHUB_OUTPUT" + echo "dry_run=$INPUT_DRY_RUN" >> "$GITHUB_OUTPUT" + echo "prefer_artifact=$INPUT_USE_ARTIFACT" >> "$GITHUB_OUTPUT" + echo "ci_run_id=" >> "$GITHUB_OUTPUT" + echo "ref=$REF" >> "$GITHUB_OUTPUT" + echo "remote_web_input=$INPUT_REMOTE_WEB" >> "$GITHUB_OUTPUT" + echo "Manual deploy ref=$REF dry_run=$INPUT_DRY_RUN prefer_artifact=$INPUT_USE_ARTIFACT" + fi + + - name: Checkout (always — need deploy script) + uses: actions/checkout@v4 + with: + ref: ${{ steps.mode.outputs.ref }} + + - name: Sanitize remote web root + id: web + env: + PXED_WEB_SECRET: ${{ secrets.PXED_WEB }} + REMOTE_WEB_INPUT: ${{ steps.mode.outputs.remote_web_input }} + run: | + set -euo pipefail + # C2: never interpolate untrusted path into remote shell. + if [[ -n "${REMOTE_WEB_INPUT}" ]]; then + CANDIDATE="$REMOTE_WEB_INPUT" + elif [[ -n "${PXED_WEB_SECRET:-}" ]]; then + CANDIDATE="$PXED_WEB_SECRET" + else + CANDIDATE="/data/grok-register/apps/web" + fi + while [[ "$CANDIDATE" == */ && "$CANDIDATE" != / ]]; do + CANDIDATE="${CANDIDATE%/}" + done + case "$CANDIDATE" in + /data/grok-register|/data/grok-register/*) ;; + *) + echo "remote_web must be under /data/grok-register, got: $CANDIDATE" >&2 + exit 1 + ;; + esac + if [[ "$CANDIDATE" == *..* ]]; then + echo "remote_web must not contain .." >&2 + exit 1 + fi + if [[ ! "$CANDIDATE" =~ ^/data/grok-register(/[A-Za-z0-9._+-]+)*$ ]]; then + echo "remote_web has unsafe characters: $CANDIDATE" >&2 + exit 1 + fi + echo "remote_web=$CANDIDATE" >> "$GITHUB_OUTPUT" + echo "Using remote_web=$CANDIDATE" + + # I1: only accept runs that actually published console10-web; else rebuild. + - name: Obtain console10 tarball + id: tarball + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PREFER_ARTIFACT: ${{ steps.mode.outputs.prefer_artifact }} + CI_RUN_ID: ${{ steps.mode.outputs.ci_run_id }} + REPO: ${{ github.repository }} + run: | + set -euo pipefail + mkdir -p /tmp/console10-ci + OUT=/tmp/console10-ci/console10-webroot.tgz + got=0 + + download_from_run() { + local run_id="$1" + local dir + dir="$(mktemp -d /tmp/console10_art.XXXXXX)" + if ! gh run download "$run_id" --repo "$REPO" --name console10-web --dir "$dir" 2>/tmp/console10_dl.err; then + echo "download failed for run $run_id: $(cat /tmp/console10_dl.err 2>/dev/null || true)" + rm -rf "$dir" + return 1 + fi + local tgz + tgz=$(find "$dir" -name 'console10-webroot.tgz' | head -1) + if [[ -z "$tgz" || ! -s "$tgz" ]]; then + echo "run $run_id has console10-web name but missing tarball" + find "$dir" -maxdepth 4 -type f || true + rm -rf "$dir" + return 1 + fi + cp -f "$tgz" "$OUT" + rm -rf "$dir" + echo "Using artifact from CI run $run_id" + return 0 + } + + if [[ "$PREFER_ARTIFACT" == "true" ]]; then + if [[ -n "${CI_RUN_ID}" ]]; then + # auto path: this exact successful CI run + if download_from_run "$CI_RUN_ID"; then + got=1 + else + echo "CI run $CI_RUN_ID has no usable console10-web; will rebuild" + fi + else + # manual: scan recent successful CI runs for artifact name (I1) + mapfile -t RUN_IDS < <(gh run list \ + --repo "$REPO" \ + --branch main \ + --workflow CI \ + --json databaseId,conclusion,status \ + --limit 30 \ + --jq '.[] | select(.conclusion=="success" and .status=="completed") | .databaseId') + for run_id in "${RUN_IDS[@]:-}"; do + # confirm artifact exists before download + has=$(gh api "repos/$REPO/actions/runs/$run_id/artifacts" \ + --jq '[.artifacts[] | select(.name=="console10-web" and .expired==false)] | length') + if [[ "${has:-0}" -gt 0 ]]; then + if download_from_run "$run_id"; then + got=1 + break + fi + else + echo "skip CI run $run_id (no console10-web artifact)" + fi + done + fi + fi + + if [[ "$got" -eq 1 ]]; then + ls -la "$OUT" + echo "source=artifact" >> "$GITHUB_OUTPUT" + echo "path=$OUT" >> "$GITHUB_OUTPUT" + exit 0 + fi + + echo "Falling back to rebuild from ref ${{ steps.mode.outputs.ref }}" + echo "source=rebuild" >> "$GITHUB_OUTPUT" + echo "path=$OUT" >> "$GITHUB_OUTPUT" + + - name: Setup Node (rebuild fallback) + if: ${{ steps.tarball.outputs.source == 'rebuild' }} + uses: actions/setup-node@v4 + with: + node-version: "22" + cache: npm + cache-dependency-path: apps/web/package-lock.json + + - name: Build + pack (rebuild fallback) + if: ${{ steps.tarball.outputs.source == 'rebuild' }} + run: | + set -euo pipefail + ./scripts/build_web_console.sh + mkdir -p /tmp/console10-ci + tar -C apps/web/dist -czf /tmp/console10-ci/console10-webroot.tgz . + ls -la /tmp/console10-ci/console10-webroot.tgz + test -s /tmp/console10-ci/console10-webroot.tgz + + - name: Require deploy secrets + if: ${{ steps.mode.outputs.dry_run != 'true' }} + env: + PXED_SSH_PRIVATE_KEY: ${{ secrets.PXED_SSH_PRIVATE_KEY }} + PXED_HOST: ${{ secrets.PXED_HOST }} + PXED_KNOWN_HOSTS: ${{ secrets.PXED_KNOWN_HOSTS }} + run: | + set -euo pipefail + missing=0 + for name in PXED_SSH_PRIVATE_KEY PXED_HOST PXED_KNOWN_HOSTS; do + if [[ -z "${!name}" ]]; then + echo "Missing required secret: $name" >&2 + missing=1 + fi + done + if [[ "$missing" -ne 0 ]]; then + echo "Real deploy needs PXED_SSH_PRIVATE_KEY + PXED_HOST + PXED_KNOWN_HOSTS" >&2 + echo "Tip: manual dry_run=true builds/downloads without secrets." >&2 + exit 1 + fi + + # I3: single deploy script path + - name: Deploy via scripts/deploy_web_console10.sh + if: ${{ steps.mode.outputs.dry_run != 'true' }} + env: + PXED_SSH_PRIVATE_KEY: ${{ secrets.PXED_SSH_PRIVATE_KEY }} + PXED_HOST: ${{ secrets.PXED_HOST }} + PXED_SSH_PORT: ${{ secrets.PXED_SSH_PORT }} + PXED_KNOWN_HOSTS: ${{ secrets.PXED_KNOWN_HOSTS }} + PXED_WEB: ${{ steps.web.outputs.remote_web }} + CONSOLE10_TGZ: /tmp/console10-ci/console10-webroot.tgz + SKIP_BUILD: "1" + PRUNE_STALE_ASSETS: "1" + DRY_RUN: "0" + run: | + set -euo pipefail + chmod +x scripts/deploy_web_console10.sh + ./scripts/deploy_web_console10.sh + + - name: Dry-run summary + if: ${{ steps.mode.outputs.dry_run == 'true' }} + run: | + set -euo pipefail + ls -la /tmp/console10-ci/console10-webroot.tgz + echo "source=${{ steps.tarball.outputs.source }}" + echo "remote_web=${{ steps.web.outputs.remote_web }}" + echo "trigger=${{ steps.mode.outputs.trigger }}" + echo "dry_run=1 — skipped scp/ssh" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7b921c2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,85 @@ +__pycache__/ +*.pyc +*.pyo +*.pyd +.venv/ +venv/ +dist/ +.DS_Store +# node deps / Vite cache at repo root (only providers/* subtree deps are local) +node_modules/ +node_modules/** +# macOS AppleDouble sidecar files (break Chrome --load-extension if copied to host) +**/._* +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ + +# secrets / local runtime +config.json +config.local.json +config.json.bak* +.control_api_users.json +.control_api_users.json.tmp +.control_api_login.txt +.control_api_session_secret +.env +# Project-owned egress catalog (may contain proxy credentials) +nodes.json +nodes.txt +nodes.list +proxy_list.txt +nodes.json.tmp +# Embedded mihomo core + imported Clash YAML (secrets + large binary) +.nodes/ +accounts_*.txt +emails_used.txt +emails_error.txt +mail_credentials.txt +# keep directory structure; never track hotmail credential batches +mail_assets/* +!mail_assets/.gitkeep +!mail_assets/README.md +cpa_auths/* +!cpa_auths/.gitkeep +# Outlook private per-account refresh-token artifacts (0600, never commit) +outlook_auths/* +!outlook_auths/.gitkeep +cookies/ +screenshots/ +*.log +*.bak + +# register backups & secrets +backups/ +accounts_cli.txt +cpa_auths/*.json +logs/ + +# 第三方参照注册机(只读借鉴,勿提交) +/grok-register/ + +# Provider runtime (node_modules often on pxed /personal/*-register) +providers/*/node_modules/ +providers/*/output/ +providers/*/logs/ +providers/*/.env +providers/*/dist/ +!providers/_template/.env.example + +# local live harness ledgers (never commit) +_live_activation_*.txt +_live_activation_*.log +_live_activation_*.py +created_mailboxes.txt +# local nodes catalog backups (timestamped .bak copies) +nodes.json.bak.* +# underscore-prefixed one-off probe scripts (local ops, not for repo) +scripts/_* +output/ + +# console10 (Vite + Preact) local deps +apps/web/node_modules/ + +# local Claude session/scratch (never commit) +.claude/ diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..851fff1 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,245 @@ +# Architecture — ai-register-machine + +Production-oriented multi-provider register monorepo. Inspired by: + +- [ThinkerWen/ai-register](https://github.com/ThinkerWen/ai-register) — `register/` + shared `util` +- LiteLLM / LangChain — explicit layers, registry, partner/provider packages, Makefile + ARCHITECTURE +- Our additions — fail-fast, this-run attribution, black-box honesty, CPA OIDC/OpenAI gates, web control plane + +## Goals + +| Goal | Meaning | +|------|---------| +| **Usable** | One hub (`./register.sh`), one layered CLI (`python -m register_core`), web control plane | +| **Honest** | Success = this-run delta / RESULT_JSON; never historical tail alone | +| **Layered** | email / providers / verify / sink / pipeline contracts | +| **Product-local stacks** | Grok Python+Drission; MiMo Node+Playwright; ChatGPT in-process curl_cffi+EmailSource; typesafe in-process requests+EmailSource | +| **Safe defaults** | gitignore secrets, sink 0600, public redact, no mass alias farm | + +## Directory map + +```text +ai-register-machine/ +├── register.sh # hub: grok | mimo | chatgpt | typesafe | core | smoke | help +├── ARCHITECTURE.md # this file (canonical layout) +├── Makefile # test / syntax / doctor / help +├── pyproject.toml # uv + pytest +├── config.example.json # Grok production config template +├── config.simple.example.json # outsider quickstart +├── apps/ +│ ├── README.md # entrypoints map +│ ├── cli/ # thin docs for CLI paths +│ ├── control_api/ # FastAPI project control plane +│ ├── web/ # static operator UI (Overview/Config/Import/Runs) +│ └── gui/ # removed desktop TTK — pointer only +├── register_core/ # shared layers (contracts → pipeline) +│ ├── contracts.py +│ ├── errors.py +│ ├── pipeline.py +│ ├── cli.py +│ ├── nodes/ # project-owned egress catalog (no Clash) +│ ├── email/ # EmailSource registry + sources/* +│ ├── providers/ # adapter registry (black-box OK) +│ ├── verify/ +│ ├── sink/ +│ └── util/ # proxy rotation bridged to nodes + list mode +├── nodes.example.json # copy → nodes.json (gitignored credentials) +├── providers/ # product packages (runtime authority) +│ ├── README.md +│ ├── _template/ # copy-me skeleton for a new product +│ ├── mimo/ # Xiaomi MiMo (Node/Playwright) — production +│ ├── chatgpt/ # OpenAI platform protocol (curl_cffi + EmailSource) +│ ├── typesafe/ # typesafe.ai / jev console (Stytch magic-link) +│ └── grok/ # Grok layout notes (runtime still root paths) +├── docs/ +│ ├── ADDING_PROVIDER.md +│ └── LAYOUT.md +├── examples/ +│ └── minimal_pipeline.py +├── scripts/ # ops helpers (doctor, remint, setup) +├── tests/ # preferred home for new tests +│ ├── conftest.py +│ └── unit/ # layer unit tests live here when added +├── cpa_xai/ # Grok OIDC mint / chat probe (Grok product lib) +├── register_cli.py # Grok CLI production entry (legacy root path) +├── grok_register_ttk.py # Grok engine + mail channels (no desktop GUI) +├── scripts/run_control_api.sh # start web control plane +└── turnstilePatch/ # browser extension for Grok path +``` + +### Root-level runtime modules (legacy dependency surface — DO NOT MOVE) + +These stay at repo root because `register_core` / `register_cli.py` import them +lazily by bare name and production (pxed `/personal/grok-register`, batch +supervisor) runs with the repo root on `sys.path` but **not** `scripts/`. +Moving them breaks the lazy imports in a non-test environment. The tests that +exercise them also import by bare name (`import tab_pool as tp`, etc.). + +| Module | Imported by (lazy) | Purpose | +|--------|--------------------|---------| +| `proxy_bridge.py` | `register_core/util/proxy.py`, `register_core/nodes/models.py`, `register_core/nodes/cli.py` | proxy URL auth-strip / label helpers | +| `proxy_rotate.py` | `register_core/util/proxy.py` | list/clash proxy rotation | +| `cpa_export.py` | `register_cli.py`, `scripts/remint_expired_and_sync_authdir.py` | CPA auth export / remote inject | +| `account_backup.py` | `register_cli.py` | account backup | +| `node_score.py` | `mail_pool_probe.py` + tests | egress node scoring | +| `mail_pool_probe.py` | `apps/control_api` + tests | mail pool probe | +| `tab_pool.py` | tests (`import tab_pool as tp`) | browser/xvfb tab pool | + +If a module above is ever refactored into `register_core/`/`scripts/`, the lazy +import sites must be updated in the same commit and verified with the full +suite — do not move the file alone. Truly dead root scripts go to +`scripts/_archive/` (see `cf_mail_debug.py`, `optimization_checks.py`). + +## Layer dependency (one way) + +```text +hub / web control plane / apps + │ + ▼ + register_core.pipeline + │ + ├── providers (signup) + ├── email (allocate + OTP) [in-process only] + ├── verify (capability probe) + └── sink (JSONL 0600) + │ + ▼ + contracts + errors +``` + +Black-box providers (`grok`, `mimo`) **own mail internally**. Passing `--email-source=tinyhost` is rejected so we never pretend the pipeline controls their mailbox. + +In-process providers (`chatgpt`) **must** use `EmailSource` (default tinyhost). Protocol path: authorize PKCE → register → email OTP → create_account → oauth/token. Artifacts under `providers/chatgpt/output/` (gitignored). No silent production CPA inject. + +## Egress / nodes (project-owned) + +ChatGPT and other in-process providers **must not require Clash Verge UI / system TUN**. + +```text +REGISTER_EGRESS / --egress / nodes egress set + │ + ├─ core → project mihomo .nodes :17897 + ├─ clash → external Clash mixed port :7897 (+ optional API rotate) + ├─ list → nodes.json / PROXY_LIST only + ├─ direct → no proxy + └─ auto → healthy list → core → clash URL → direct + │ + ▼ + preflight (list/auto): L1 ipify (+ optional L2 business targets) → dual-pass pool + │ + ▼ + proxy_rotate → concrete URL per attempt + │ + ▼ + provider curl_cffi session (proxy=URL) + │ + ▼ + feedback: proxy/network fail → mark/quarantine/drop; success → clear fails +``` + +| Path | Authority | +|------|-----------| +| Switch | `register_core/util/egress.py` + `.nodes/config/egress.mode` | +| HTTP catalog | `nodes.json` + `register_core/nodes/` (import **merges** by URL) | +| Preflight + quarantine | `NodeManager.preflight/mark_result` + `util/proxy.preflight_nodes_for_register` | +| L2 targets | `register_core/nodes/targets.py` (provider map / env / extra) | +| Convert (opt-in) | `register_core/nodes/convert/` — parse/validate/pack only | +| Protocol YAML | `.nodes/config/runtime.yaml` (from `nodes import`) | +| Mini-core | `.nodes/bin/mihomo` via `nodes core start` (optional) | +| CLI | `python -m register_core nodes import\|validate\|list\|clear\|egress\|core …` | +| Import script | `scripts/import_nodes.py` (`import_clash_to_nodes.py` deprecated) | + +Primary backends: `list` \| `core` \| `direct`. Advanced: `auto` (healthy list → core → clash-if-set), `clash`. + +**Product contract (imported catalogs):** After `nodes import` writes `nodes.json`, each batch register with `egress=list|auto` **live-probes** the catalog (`REGISTER_NODES_PREFLIGHT=1` default) and seeds rotation with **healthy-only** URLs. Health has two layers: + +| Layer | Probe | Pass rule | Mutates `last_ok` | +|-------|-------|-----------|-------------------| +| **L1** egress | `api.ipify.org` | HTTP 2xx | Yes (catalog stamp) | +| **L2** target | provider business URL(s) | any HTTP status (transport OK) | No — filters pool only | + +Defaults: `grok`/`xai` → `https://accounts.x.ai/`; `chatgpt`/`openai` → `https://auth.openai.com/`; `mimo`/`xiaomi`/`mimo-tts` → `https://api.xiaomimimo.com/`. Override: `extra.probe_targets` / `REGISTER_NODES_PROBE_TARGETS` (set `0`/`none` to force L1-only). Pipeline stashes `provider` before preflight. Pool seed = L1∧L2 when targets set; L1-only when empty. Dead rows stay in the catalog but never enter the pool. Zero dual-pass (or L1-only when L2 off) on `list` (or `REGISTER_NODES_REQUIRED`) → FailFastError (no account burn). Operator `PROXY_LIST` / `CHATGPT_PROXY_LIST` owns the pool and skips catalog probe unless `force_nodes_preflight=1`. Optional convenience: `nodes import … --check` or `nodes check` (batch preflight remains the authority gate). Skip reasons are logged (`backend=*`, `REGISTER_NODES=0`, `explicit_proxy_list`, `preflight_disabled`). + +Dead nodes are quarantined after `REGISTER_NODES_MAX_FAIL`. Runtime proxy/network markers include empty response / connection reset language; never burn email domains on proxy RST. VLESS/SS/… need `egress=core`. Import/validate is **not** on the hot register path. + +## Production authority (do not invert) + +| Concern | Authority path | +|---------|----------------| +| Grok signup + mint + chat gate | `./register.sh grok` → `register_cli.py` / `grok_register_ttk.py` + `cpa_xai/` | +| **Grok production egress (pxed)** | **Clash mixed-port `127.0.0.1:7897`** via `run-register.sh` → `preflight-clash-nodes.sh` → `scripts/probe_clash_nodes.py` → `start-clash-for-grok.sh` | +| Grok catalog egress (list\|auto) | monorepo `nodes.json` + L1∧L2 `preflight_nodes_for_register` (separate backend; not the pxed Grok default until L2 pool non-empty for `accounts.x.ai`) | +| MiMo API key | `./register.sh mimo` → `providers/mimo/run-register.sh` | +| Layered orchestration only | `./register.sh core` → `python -m register_core` | +| CPA OpenAI inject (MiMo) | `providers/mimo/inject_cpa_openai.py` (local; never silent prod write) | + +### Dual egress backends (do not confuse) + +Two leaf-health preflights exist; both strip dead nodes before batch work, **backends differ**: + +| Backend | When | Entry | Probe | Healthy gate | +|---------|------|-------|-------|--------------| +| **Clash mixed-port (pxed Grok production)** | `bash run-register.sh` on host with mihomo | `preflight-clash-nodes.sh` | mihomo controller delay API (`scripts/probe_clash_nodes.py`) | rewrites register groups (`🎯Grok注册` …) to healthy-only, pins `GROK_NODE`, restarts mihomo on `:7897` | +| **nodes.json list\|auto** | `REGISTER_EGRESS=list\|auto` / ChatGPT / self-controlled `PROXY_LIST` path | `util/proxy.preflight_nodes_for_register` | L1 ipify (+ optional L2 business targets via `nodes/targets.py`) | dual-pass (or L1-only) pool into rotation; zero healthy → FailFastError | + +- `SKIP_CLASH_PREFLIGHT=1` skips the Clash path (local debug / non-Clash host only). +- Operator `PROXY_LIST` owns the pool and skips catalog probe unless `force_nodes_preflight=1` (see product contract above). +- Never treat Clash group rewrite as `nodes.json` authority, or vice versa. + +Root-level Grok modules (`register_cli.py`, `grok_register_ttk.py`, `cpa_xai/`, `proxy_*`) are **adapter targets** for `register_core/providers/grok_adapter`, reached via shell-out. Since migrate milestone A, the three `./register.sh` production entries (`grok | mimo | chatgpt`) route through the `register_core` Pipeline (attribution / strategy burn-cool / GrokChatVerifier·MimoTtsVerifier·ChatGPTTokenVerifier / JSONL sink). Egress ownership is backend-dependent and **declared in the profile**, not implicit: Grok/MiMo profiles pin `strategy.egress.mode: clash proxy 127.0.0.1:7897` so `profile_to_job` sets `extra["proxy"]` truthy and the grok/mimo adapter **force-sets the child `PROXY/CPA_PROXY`** from the attempt proxy (attempt proxy wins over ambient shell env — Pipeline owns the egress); Clash leaf health is still probed by `preflight-clash-nodes.sh` (Grok) / Node runner (MiMo), since `preflight_nodes_for_register` skips `clash` backend (the `nodes.json` L1/L2 catalog preflight is the separate `list|auto` backend). ChatGPT in-process selects mailbox by `CHATGPT_EMAIL_SOURCE` → matching profile (cf default `clash:7897`; tinyhost/gmail variants), with `CHATGPT_*` env overrides forwarded as `register_core` CLI flags. Grok and MiMo still shell out to legacy runners internally. Rollback per provider: `GROK_LEGACY=1` / `MIMO_LEGACY=1` / `CHATGPT_LEGACY=1`. In-process rewrites of Grok/MiMo (no shell-out) remain backlog (not started). `providers/grok/` documents the target package shape without breaking imports. + +## Dual production tracks (Grok bulk vs CLI shell) + +These are **intentional** dual authorities — not a temporary dual-track bug: + +| Track | Entry | When | Success criterion | +|-------|-------|------|-------------------| +| **CLI / single-shot** | `./register.sh grok N` → `run-register-core.sh` → register_core Pipeline → grok_adapter shell-out `register_cli --extra 1` | smoke、profile 编排、strategy/sink 统一归因 | register_core product exit (0/1/2) | +| **Disk-first smoke** | `scripts/smoke_diskfirst_one.sh` → flock + xvfb → `register_cli.py --extra 1` | 官方单发边界验证 | +1 complete `xai-*.json` (access+refresh) | +| **Bulk concurrent** | `scripts/launch_batch_supervisor.sh` → xvfb → **`register_cli.py --extra $chunk`** directly | 大批量产号(chunk/threads/soft browser recycle/Clash rotate) | **disk-first**:new complete `xai-*.json` with access+refresh (`mint_token_ok`) | + +Bulk deliberately bypasses register_core serial shell-out (adapter hard-codes `--extra 1` per attempt). Do **not** force bulk through Pipeline until B (in-process concurrent) exists. Supervisor / smoke freeze disk-first env: + +- `CPA_EXPORT_ENABLED=true` +- `CPA_PROBE_CHAT=false` +- `CPA_REMOTE_INJECT=false` + +**Mint stability (runtime hygiene):** ad-hoc `register_cli` takes non-blocking flock `/tmp/grok_register_cli.lock` (skip: `SKIP_REGISTER_CLI_LOCK=1` / `--no-cli-lock`) so dual Chromium/Xvfb cannot stall device-page clicks. Startup cleans PPID=1 orphan Drission Chromes and empty Xvfb (+ stale `/tmp/xvfb-run.*`). Browser mint early-aborts `device_click_stall` instead of full timeout; `SUMMARY_JSON` carries `mint_fail_reason` / `mint_fail_phase`. + +CPA inject is a **separate pipeline** (`scripts/import_cpa_auth_dir.py` / ops), never part of register product success when inject is off. + +## Registry pattern + +Factories live in `register_core/*/registry.py`: + +- `register_provider` / `get_provider` / `list_providers` +- `register_email_source` / `get_email_source` +- `get_verifier` + +New products: implement adapter → register factory → optional verifier → document in `providers/README.md`. + +## Success attribution (hard rule) + +1. Prefer structured `RESULT_JSON:` (or equivalent) from this process. +2. Else file **size offset before run** + append-only delta. +3. Exit 0 without this-run identity → **failure**. +4. Subprocess timeout → kill process group (`start_new_session` + `killpg`). + +## Hard safety contracts + +| Contract | Enforcement | +|----------|-------------| +| API key shape | `register_core.util.secrets` — single source; adapter/verify/inject/redact must agree | +| Grok product-ready | this-run **SSO** required (`ok=False` if email-only / pending). **Register main path (disk-first):** `cpa_probe_chat=false` → product success = `mint_token_ok` (complete auth on disk with refresh); chat probe / inject off. **Inject path (separate):** free Build live inject still requires **`chat_ok is True`** — models-only / token write alone never soft-pass inject | +| Mint honesty | `token_ok=True` after OIDC write; product `ok` follows configured probes (`product_batch_success`: disk-first → mint_token_ok; probe_chat on → chat_ok; inject on → remote_live_ok) | +| MiMo product-ready | this-run **secret** via RESULT_JSON or file delta (never historical tail) | +| CPA OpenAI inject | no default prod path; `--config`/`CPA_CONFIG` + prod requires `--i-understand-production` | +| Deploy path | `GROK_CODE_ROOT` or first existing `/personal/{ai-register-machine,register-machine,grok-register}` | + +## Non-goals (this skeleton) + +- Mass account farm / alias email expansion +- Unifying browser stacks into one framework +- Silent production CPA config mutation +- Desktop TTK GUI (removed; use `apps/control_api` + `apps/web`) +- Full multi-host fleet scheduler (control plane is one project root per process) diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..6301e22 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,338 @@ +# Changelog + +All notable changes to this project are documented in this file. + +Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +project versioning follows [Semantic Versioning](https://semver.org/). + +## [Unreleased] + +### Added + +- **typesafe.ai / jev console provider** (in-process): Stytch magic-link → + `/api/auth/callback` → `/api/api-keys`. Hub `./register.sh typesafe [count]`, + aliases `jev` / `typesafe-ai`. Default mailbox is tinyhost (full body). + Success = this-run `secret_kind=api_key`. Does **not** copy the original + 512/256 farm defaults. No CPA inject. pxed smoke 2026-09-22: `./register.sh + typesafe 1` → `CONTRACT_EXIT:0` this-run `api_key` (rsync to `/data/grok-register`; + not GitHub CI — §7 only deploys SPA). +- **typesafe probe-before-allocate**: GET+parse `console.typesafe.ai/login` + before tinyhost allocate (Clash preflight is skipped for `egress=clash`). + Hub `./register.sh smoke typesafe` is probe-only; `TYPESAFE_SMOKE_LIVE=1` + for n=1. Control-plane `StartRunRequest.product` accepts `typesafe`. + +### Changed + +- typesafe no longer appends full `api_key` to `accounts.jsonl`. Deliverable is + this-run `0600` `typesafe-*.json` under a `0700` output dir. Session parse + failures attach a short `$ACTION` HTML snippet. +- typesafe console probe now classifies 5xx as `network` / 4xx as `session` + (same as login GET) and forwards the parsed `$ACTION` into `register_one`, + so allocate is not followed by a second login GET unless magic-link POST + needs a refresh. Mailbox timeout stays `mail_miss`. Verifier `live=True` + is still shape-only (no spend). Magic-link extract parses query order. +- typesafe batch (`./register.sh typesafe N` with N>1): continue on + `mail_miss`/`network` (hard kinds still stop), in-process workers default 8 + capped at 32, unique `typesafe-*.json` names. Pipeline fan-out is only for + typesafe/chatgpt — grok `--threads` still belongs to the child runner. + pxed this-run 2026-09-22: `./register.sh typesafe 100` → `CONTRACT_EXIT:0` + ok=97 fail=3 (`mail_miss`×3) `stopped_reason=""`; 97 new `0600` + `typesafe-*.json`; no `accounts.jsonl` append; no CPA inject. +- typesafe mail poll with `sender_hint=typesafe` returns the Stytch URL + before any OTP-shaped token in the same body. Mail-miss diagnostics come + from this attempt's `MailMissError`, not the shared EmailSource slot + (n=100 workers were overwriting each other's wait stats). Deployment drift + is logged once per process. +- pxed this-run 2026-09-22 (after the mail-parse fix): `./register.sh typesafe + 100` → `CONTRACT_EXIT:0` ok=98 fail=2 (`session` / send_magic_link HTTP 500). + Then `./register.sh typesafe 1000` (8 workers, `--no-fail-fast`, + `rotate=off`) → `CONTRACT_EXIT:0` ok=976 fail=24 + (`mail_miss`×17, `session`×5, `oauth_callback`×2); 976 new `0600` + `typesafe-*.json`; no `accounts.jsonl` append; no CPA inject. +- README acknowledges the [LINUX DO](https://linux.do/) community. + +## [1.6.4] - 2026-07-16 + +### Added + +- **Register ↔ nodes adaptation**: preflight probe gate before batch registration + - `NodeManager.preflight` / `mark_result` / quarantine after `REGISTER_NODES_MAX_FAIL` + - `preflight_nodes_for_register` seeds healthy-only `proxy_list` for list/auto + - `report_attempt_proxy_result` feeds register outcomes back into catalog + live rotator + - Pipeline runs preflight once, then marks/drops dead proxies per attempt +- Heuristic `is_proxy_network_failure` — never quarantines mail_miss / captcha / registration_disallowed +- Fail-fast when `egress=list` has zero healthy nodes after probe +- Tests: preflight, quarantine, pipeline skip-dead, pool drop + +### Changed + +- `enabled_nodes(healthy_only=True)` now means `last_ok is True` only (register path) +- Hard-failed nodes excluded from rotation until they pass probe again + +## [1.6.3] - 2026-07-16 + +### Changed + +- **Purity pass for egress UX** + - `nodes import` **merges by URL** into `nodes.json` (add/update/keep); `--replace` for full overwrite + - Clash Verge profile scan is **opt-in** (`--from-clash-verge`), not default + - `nodes list` prints a **sample summary** by default (`--all` for full dump) + - `nodes clear --yes` empties HTTP catalog without touching protocol runtime + - `auto` egress only uses **known-healthy** (`last_ok=true`) catalog entries; unprobed bulk no longer blocks core + - Docs/CLI primary backends: `list|core|direct` (auto/clash advanced) + - Canonical script: `scripts/import_nodes.py`; `import_clash_to_nodes.py` deprecated alias + +### Added + +- Merge plan in import/dry-run JSON (`added`/`updated`/`kept`/`dropped`) +- Tests for merge/replace and auto healthy-list behavior + +## [1.6.2] - 2026-07-16 + +### Added + +- **Light node convert pipeline** (`register_core/nodes/convert/`): parse → validate → split → pack +- Inputs: Clash/mihomo YAML, V2Ray/Xray JSON outbounds, share URI lines (ss/vmess/vless/trojan/http/socks) +- CLI: `python -m register_core nodes import|validate` (dry-run, format force, no register-path weight) +- Legality report rejects missing type/server/port/uuid/…; dialable → `nodes.json`, protocol → `runtime.yaml` +- Compat: `scripts/import_clash_to_nodes.py` is a thin wrapper over the same pipeline +- Tests: `test_nodes_convert.py` + +### Notes + +- mihomo remains optional runtime for protocol nodes only; HTTP/SOCKS path needs no core +- Conversion is opt-in CLI — register pipeline only consumes artifacts + +## [1.6.1] - 2026-07-16 + +### Added + +- **Egress backend switch**: `core` | `clash` | `list` | `direct` | `auto` +- CLI: `python -m register_core nodes egress show|set|which` +- CLI/env: `--egress` / `REGISTER_EGRESS` / `CHATGPT_EGRESS` +- Persist preference: `.nodes/config/egress.mode` +- Tests cover clash vs core isolation and direct no-proxy + +## [1.6.0] - 2026-07-16 + +### Added + +- **Embedded mihomo mini-core** under `.nodes/bin/mihomo` + `.nodes/config/runtime.yaml` +- `register_core/nodes/core_runtime.py` + CLI: `nodes core start|stop|status|select|proxies|url` +- `scripts/import_clash_to_nodes.py` — copy Clash Verge YAMLs into project path and pack runtime +- `scripts/bootstrap_nodes_core.sh` — download official MetaCubeX mihomo for the host arch +- `util/proxy.py` can auto-start core and use `http://127.0.0.1:17897` when HTTP catalog empty + +### Notes + +- Protocol nodes (vless/ss/vmess/trojan/…) live in project runtime YAML; dialable HTTP/SOCKS still in `nodes.json` +- No dependency on Clash Verge UI / system TUN / `:7897` for ChatGPT path +- `.nodes/` is gitignored (binary + credentials) + +## [1.5.0] - 2026-07-16 + +### Added + +- **Project-owned node runtime** (`register_core/nodes/`): catalog (`nodes.json` / `nodes.txt`), health probe (`curl_cffi` → ipify), `NodeManager` rotation, CLI `python -m register_core nodes list|check|add|urls` +- `register_core/util/proxy.py` seeds list-mode pool from nodes catalog when `PROXY_LIST` empty +- Examples: `nodes.example.json`, `nodes.example.txt`; gitignore for credential catalogs +- Tests: `test_register_core_nodes.py` (catalog, manager, proxy util, pipeline wiring) + +### Changed + +- ChatGPT runner / adapter: **no default Clash `127.0.0.1:7897`** — egress from `nodes.json` / `PROXY_LIST` / explicit `CHATGPT_PROXY` +- Docs: ARCHITECTURE egress section; ChatGPT README + hub help describe nodes-first path + +### Notes + +- Operators supply HTTP/SOCKS proxy endpoints they control; Clash mode remains optional legacy for Grok browser only + +## [1.4.1] - 2026-07-15 + +### Added + +- **Self-controlled egress for layered providers**: `register_core/util/proxy.py` wires existing `proxy_rotate` **list** mode into `Pipeline` + `register_core` CLI + ChatGPT runner +- CLI: `--proxy`, `--proxy-list`, `--proxy-rotate {off,list,clash}`, `--proxy-rotate-every`, `--proxy-rotate-required` +- Env: `CHATGPT_PROXY_LIST` / `PROXY_LIST` auto-enables list mode (no Clash node selection) + +### Notes + +- Preferred path is **list** of explicit upstream URLs — register machine owns the node pool; Clash may only be a local forwarder, not a selector dependency +- Clash domain-group mode remains available for Grok browser paths; ChatGPT docs steer operators to list mode + +## [1.4.0] - 2026-07-15 + +### Added + +- **ChatGPT / OpenAI platform provider** (`providers/chatgpt/`): in-process protocol register via `curl_cffi` + Sentinel PoW + `EmailSource` (default `gmail_imap`); hub `./register.sh chatgpt` +- `register_core/providers/chatgpt_adapter.py` + `verify/chatgpt_token.py` (offline token shape gate) +- Unit tests: `test_chatgpt_provider.py` (attribution, redact, verifier, registry) +- Gmail OTP extractor: HTML strip + OpenAI “temporary verification code” patterns (was poisoned by CSS hex numbers) + +### Notes + +- ChatGPT path does **not** auto-inject tebi/CPA; secrets land in `providers/chatgpt/output/` (0600, gitignored) +- Live path verified through authorize → OTP validate; final `create_account` may still return `registration_disallowed` (IP/domain risk) — Manual-required + +## [1.3.0] - 2026-07-15 + +### Added + +- **Desktop GUI deep polish**: thread-safe `ui_queue` pump, form lock while running, validation focus/tab jump, log cap, copy log / open results, persist `register_count` +- **Desktop GUI redesign** (`grok_register_ttk.py`): Notebook tabs (基础 / 邮箱 / 进阶)、邮箱服务商字段动态显隐、右侧进度条与彩色日志 +- **Multi-provider hub**: `./register.sh` (`grok` / `mimo` / `core` / `smoke`) +- **`register_core/`** layered framework: contracts, email sources, provider adapters, verify, sink, pipeline, CLI +- **`providers/mimo/`**: Xiaomi MiMo API Key registration (Node/Playwright `register-one.js`, Geetest slide, tinyhost OTP) +- MiMo → CPA OpenAI-compat helper (optional, local): `providers/mimo/inject_cpa_openai.py` (does **not** touch production by default) +- Unit tests: `test_register_core_layers.py`, `test_mimo_cpa_openai_inject.py` +- Grok Gmail IMAP: HTTP CONNECT via configured proxy (container/no-public egress) +- Positioning docs vs [ThinkerWen/ai-register](https://github.com/ThinkerWen/ai-register): higher production usability, richer pipeline, **TTK UI** (form input + live log/status) +- **Monorepo skeleton** (inspired by ai-register product dirs + LiteLLM-style ARCHITECTURE/Makefile): + - `ARCHITECTURE.md`, `docs/LAYOUT.md`, `docs/ADDING_PROVIDER.md` + - `providers/_template/`, `providers/grok/README.md`, `providers/README.md` + - `apps/{cli,gui}/`, `examples/minimal_pipeline.py`, `tests/unit/`, `Makefile` + +### Changed + +- Project rename path: **`grok-register` → `register-machine` → `ai-register-machine`** (GitHub + package metadata) +- README highlights desktop UI (`grok_register_ttk.py`): count/threads/mail/proxy form, start/stop, status, scrolling logs, tutorial +- Fail-fast + this-run result attribution (no historical tail as success); public redact password/secret +- pytest `pythonpath` + `tests/` tree; gitignore all `providers/*/output|node_modules` + +### Fixed + +- Align `sk-` patterns across adapter / verifier / inject / redaction (hyphen & underscore vendor keys) +- Grok adapter no longer reports `ok=True` with empty SSO (`pending`); default Grok verifier requires SSO +- `inject_cpa_openai.py` no longer defaults to production CPA path; requires `--config`/`CPA_CONFIG` and `--i-understand-production` for prod +- `register.sh` / MiMo clash starter resolve monorepo root via `GROK_CODE_ROOT` and multi-name candidates (not hard-only `/personal/grok-register`) +- README no longer links a non-existent `v1.3.0` GitHub Release tag + +### Security + +- Jsonl sink `O_CREAT|0600`; black-box providers reject fake external `--email-source` +- Ignore MiMo runtime output / node_modules; never commit keys or mail ledgers +- Production CPA inject is opt-in with explicit ack (no silent default path) + +## [1.2.3] - 2026-07-13 + +### Added + +- `scripts/doctor_secrets.sh` — local secret hygiene (tracked paths, modes, cloud-sync path warn; never prints contents) +- CI: `bash -n` on setup/doctor scripts; py_compile quality scripts; run doctor_secrets in guard step +- README education banner + local secret hygiene; CONTRIBUTING ttk refactor caution + chat-gate rule + +### Changed + +- Package description emphasizes OIDC + chat gate (not Hotmail-only / not a quota farm) + +## [1.2.2] - 2026-07-13 + +### Fixed + +- Simple default email channel is **duckmail** (not hotmail four-segment) for lower onboarding friction +- `setup_simple.sh` doctor: Python/Chrome/proxy port, duckmail key / hotmail placeholder warnings; `uv sync` failure no longer aborts bootstrap +- README honest **最短路径** timing, 常见卡点 table, production inject key checklist +- Packaging tests: `bash -n`, setup smoke in temp dir (no overwrite) + +## [1.2.1] - 2026-07-13 + +### Added + +- Outsider-friendly packaging: `config.simple.example.json` + `scripts/setup_simple.sh` +- README quickstart (simple local path; tebi inject off by default) +- Product success table: chat probe required; `entitlement_denied` ≠ remint + +## [1.2.0] - 2026-07-13 + +### Added + +- One-click CPA chain: `cpa_auth_priority` end-to-end, multi remote auth-dirs (live + inventory) +- `cpa_remote_live_dir` / `cpa_remote_live_required` — **live inject is the product success gate** +- Free Build **chat entitlement gate**: default-on `/v1/responses` probe; 403 → `entitlement_denied`, skip live inject, remint ledger skip +- Transient chat probe retries + `chat_retryable` auth stamps; `entitlement_denied.jsonl` +- Auth proxy bridge for Chromium `user:pass` proxies; browser recycle modes; account slot retry +- `scripts/remint_expired_and_sync_authdir.py` for inventory remint without starting registration +- Offline tests for one-click dirs/priority, live-gate, and chat entitlement + +### Fixed + +- `account_slot_retry=0` no longer coerced to 3; no outer worker × slot multiplicative alias burn +- Mint browser no longer double-applies `--proxy-server` +- Proxy bridge failure hard-fails (no silent direct) +- Inventory-only remote inject no longer counts as one-click success when live was targeted +- Models-only 200 no longer counts as usable free Build when chat probe is on +- CI `py_compile` covers `proxy_bridge.py` and remint script + +### Security + +- Runtime mail/auth assets remain gitignored (`mail_credentials.txt`, `mail_assets/`) + +## [1.1.3] - 2026-07-12 + +### Fixed + +- Hard resource/config failures (Hotmail alias exhaustion, missing mail credentials, unconfigured providers) now **stop the whole batch immediately** instead of empty-loop retries +- `FatalRegisterError` + `_fatal_stop` event: workers exit without further account retries; process exit code `2` + +### Added + +- `classify_email_stage_failure` returns `fatal` for unrecoverable markers +- Offline tests for fatal classification and stop wiring + +## [1.1.2] - 2026-07-12 + +### Added + +- Startup cleanup of orphan Drission Chromes reparented to init/launchd (PPID=1) +- `tab_pool.cleanup_orphan_drission_chromes` / `TabPool.cleanup_orphans` with protect list +- Offline tests for Drission Chrome cmdline matching and dry-run cleanup + +### Notes + +- Success path still **reuses** the register browser (`clear_session`); cleanup only targets crashed leftovers, not the live worker Chrome. + +## [1.1.1] - 2026-07-12 + +### Fixed + +- SSO leading-dash normalize now applies at mint core, protocol extract/set, GUI ledger write, and shared `format_account_line` +- `existing_cpa_emails` / skip-existing match Hotmail plus-aliases against sanitized CPA filenames +- Official backfill script routes through `cpa_export` (remote inject + hooks); `--local-only` / `--no-remote` opt out +- Config booleans in `cpa_export` use `_config_bool` so string `"false"` is not truthy +- CI syntax-checks `grok_register_ttk.py` + +### Added + +- `format_account_line`, `email_match_keys`, `email_in_existing` helpers +- Offline tests for cookie extract normalize, plus-alias skip keys, `_config_bool` + +## [1.1.0] - 2026-07-12 + +### Added + +- Public project packaging for open-source release +- `LICENSE` (MIT), `DISCLAIMER.md`, `SECURITY.md`, `CONTRIBUTING.md` +- GitHub Actions CI (syntax + offline tests) +- Local account backup helpers (`account_backup.py`, `scripts/backup_registered_accounts.py`) +- Optional remote CPA auth inject after successful OIDC mint +- Hotmail/Outlook Office REST code fetch with IMAP fallback +- Protocol-first CPA OIDC mint (`cpa_xai/protocol_mint.py`) with browser fallback + +### Changed + +- README rebranded as **Grok 注册机** with full setup / ops docs +- Live Hotmail REST test gated behind `GROK_REGISTER_LIVE=1` +- Project package name aligned to `grok-register` + +### Security + +- Runtime secrets remain gitignored (`config.json`, accounts, CPA auths, backups, logs) + +## [1.0.0] - 2026-07-11 + +### Added + +- Chromium + DrissionPage registration core +- Hotmail four-field credential pool and plus-alias registration +- CPA export hook and `cpa_xai` OIDC tooling +- CLI (`register_cli.py`) and GUI (`grok_register_ttk.py`) entrypoints diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..3906ae8 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,82 @@ +# Contributing + +Thanks for considering a contribution. + +## Before you start + +1. Read [DISCLAIMER.md](DISCLAIMER.md) and [SECURITY.md](SECURITY.md). +2. Do **not** commit secrets or local runtime files. +3. Prefer small, focused pull requests. + +## Development setup + +```bash +git clone https://github.com/dengyie/ai-register-machine.git +cd ai-register-machine +# outsider path (Grok simple config) +bash scripts/setup_simple.sh +# or full template +uv sync --extra dev +cp config.example.json config.json +# optional: mail_credentials for live mail tests only +bash scripts/doctor_secrets.sh # hygiene; never prints secret contents +``` + +Python **3.13** is required (`requires-python` in `pyproject.toml`). Install via [uv](https://docs.astral.sh/uv/): `uv python install 3.13`. + +Repo layout (multi-provider) — see [ARCHITECTURE.md](ARCHITECTURE.md): + +- `register_cli.py` / `grok_register_ttk.py` / `cpa_xai/` — Grok production path (root until migrate) +- `providers/mimo/` — MiMo production path (Node) +- `providers/_template/` — copy-me for new products ([docs/ADDING_PROVIDER.md](docs/ADDING_PROVIDER.md)) +- `register_core/` — layered orchestration (not a browser rewrite) +- `./register.sh` / `Makefile` — unified hub + dev targets +- `apps/`, `docs/`, `examples/`, `tests/` — entry map, how-tos, samples, unit tests + +## Tests + +Offline (default, used by CI): + +```bash +make test # or: uv run python -m pytest -q +make test-unit +make syntax +bash -n scripts/setup_simple.sh scripts/doctor_secrets.sh register.sh +bash scripts/doctor_secrets.sh || test $? -eq 2 +``` + +Live Hotmail REST (needs real `mail_credentials.txt`, **not** for CI): + +```bash +GROK_REGISTER_LIVE=1 uv run python test_hotmail_rest_code.py +``` + +Syntax check (CI also compiles `grok_register_ttk.py` and scripts): + +```bash +uv run python -m py_compile register_cli.py grok_register_ttk.py cpa_export.py account_backup.py cpa_xai/*.py +``` + +## Coding guidelines + +- Match existing style; **avoid drive-by refactors in `grok_register_ttk.py`** (~5k lines). Prefer extract-with-tests if you must split; do not “clean up while here.” +- Keep changes scoped to the bug/feature +- Add or extend offline tests when fixing logic (prefer behavior tests over source-string contracts when practical) +- Never log raw passwords, refresh tokens, or access tokens +- Document user-facing config keys in `config.example.json` / `config.simple.example.json` comment keys +- **SSO handling:** only use `cpa_xai.accounts.normalize_sso_cookie` / `format_account_line`. Do not invent a second strip rule. Normalize must stay at mint core + ledger write (CLI/GUI). +- **CPA export path:** production register and default backfill go through `cpa_export.export_cpa_xai_for_account` so remote inject / backup hooks stay consistent. Do not reintroduce “mint only” as the default backfill path. +- **Chat gate:** free Build product success requires chat probe when enabled; `entitlement_denied` must not soft-pass or remint-spin. +- **Config booleans:** use `_config_bool` (or equivalent) so string `"false"` is false. + +## Pull requests + +- Describe **what** and **why** +- Note how you tested (offline / live) +- Confirm no secrets are included (`git status`, diff review) +- Link related issues when applicable + +## Issue reports + +Include OS, Python version, proxy yes/no, headed/headless, and redacted logs. +Do not paste SSO cookies, OIDC tokens, or mailbox refresh tokens. diff --git a/DISCLAIMER.md b/DISCLAIMER.md new file mode 100644 index 0000000..9b872f1 --- /dev/null +++ b/DISCLAIMER.md @@ -0,0 +1,46 @@ +# Disclaimer + +This project is provided for **education, research, and personal automation +experimentation** only. + +## Service terms + +Automating account registration, email verification, or API credential minting +may violate the Terms of Service of xAI, Microsoft, or other third parties. +You are solely responsible for ensuring your use complies with: + +- applicable laws and regulations +- third-party Terms of Service and Acceptable Use Policies +- local export, privacy, and anti-abuse rules + +## No warranty + +The software is provided **“AS IS”** under the MIT License, without warranty of +any kind. Authors and contributors are **not liable** for account bans, data +loss, service disruption, legal claims, or any other damages arising from use. + +## Prohibited / high-risk uses + +Do **not** use this project to: + +- mass-create accounts for spam, abuse, fraud, or resale +- bypass paid quotas, rate limits, or access controls for commercial scale +- attack, scrape, or degrade third-party services +- collect or distribute credentials you do not own + +## Credentials and privacy + +Runtime files may contain passwords, OAuth refresh tokens, SSO cookies, and +OIDC access tokens. Treat them as secrets: + +- never commit them to Git +- never paste them into public issues or screenshots +- rotate credentials immediately if leaked + +See [SECURITY.md](SECURITY.md). + +## Operator responsibility + +By running this software you accept full responsibility for configuration, +proxy/network setup, account ownership, and downstream use of any generated +tokens. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7f38187 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 dengyie + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..343d038 --- /dev/null +++ b/Makefile @@ -0,0 +1,71 @@ +# ai-register-machine — common developer targets +.PHONY: help test test-unit syntax doctor list core-list example clean build-web package-web + +ROOT := $(dir $(abspath $(lastword $(MAKEFILE_LIST)))) +PY := uv run python + +help: + @echo "ai-register-machine" + @echo " make test offline pytest (root + tests/)" + @echo " make test-unit skeleton + layer unit tests only" + @echo " make syntax bash -n + py_compile critical paths" + @echo " make doctor local secret hygiene (never prints secrets)" + @echo " make build-web Vite console10 → apps/web/dist" + @echo " make package-web tar apps/web/dist → /tmp/console10-webroot.tgz" + @echo " make list hub help + core list" + @echo " make example run examples/minimal_pipeline.py" + @echo " make clean caches only" + +test: + $(PY) -m pytest -q + +test-unit: + $(PY) -m pytest -q tests/unit test_register_core_layers.py + +syntax: + bash -n register.sh + bash -n run-register.sh + bash -n preflight-clash-nodes.sh + bash -n start-clash-for-grok.sh + bash -n providers/mimo/run-register.sh + bash -n providers/mimo/smoke.sh + bash -n providers/_template/run-register.sh + bash -n providers/typesafe/run-register.sh + bash -n providers/typesafe/smoke.sh + bash -n providers/chatgpt/run-register.sh + bash -n scripts/setup_simple.sh + bash -n scripts/doctor_secrets.sh + bash -n scripts/build_web_console.sh + bash -n scripts/deploy_web_console10.sh + $(PY) -m py_compile register_cli.py register_core/cli.py register_core/pipeline.py \ + register_core/providers/registry.py register_core/util/secrets.py \ + register_core/util/process.py register_core/verify/mimo_tts.py \ + register_core/verify/grok_chat.py providers/mimo/inject_cpa_openai.py \ + scripts/probe_clash_nodes.py mail_pool_probe.py \ + register_core/providers/typesafe_adapter.py register_core/verify/typesafe_key.py \ + providers/typesafe/protocol/flow.py providers/typesafe/protocol/session.py \ + providers/typesafe/protocol/constants.py apps/control_api/schemas.py +doctor: + bash scripts/doctor_secrets.sh || test $$? -eq 2 + +build-web: + bash scripts/build_web_console.sh + +package-web: build-web + tar -C apps/web/dist -czf /tmp/console10-webroot.tgz . + @ls -la /tmp/console10-webroot.tgz + @echo "upload/deploy via GitHub Actions preferred; local: DRY_RUN=1 ./scripts/deploy_web_console10.sh" + +list: + ./register.sh help + $(PY) -m register_core list + +core-list: + $(PY) -m register_core list + +example: + $(PY) examples/minimal_pipeline.py + +clean: + find . -type d -name __pycache__ -not -path './.venv/*' -prune -exec rm -rf {} + 2>/dev/null || true + rm -rf .pytest_cache diff --git a/README.md b/README.md new file mode 100644 index 0000000..d796d06 --- /dev/null +++ b/README.md @@ -0,0 +1,159 @@ +# universal-registrar + +Форк GoubaLab/ai-register-machine: веб-дашборд полностью переведён на русский (0 китайских символов в dist), +добавлен универсальный регистратор на 16 боевых провайдеров. + +## Quick start + +``` +pip install fastapi uvicorn pydantic +set REGISTER_PROJECT_ROOT= +python -m apps.control_api +``` +Открыть http://127.0.0.1:8787 (первый вход создаёт админа из CONTROL_API_BOOTSTRAP_*). +Фронтенд предсобран в apps/web/dist (пересборка: cd apps/web && npm i && npm run build). + +## Универсальный регистратор + +- Роутер: `register_universal.py list` — 16 провайдеров (vip7891, conol, vani, notion, kiro, type, llmtr, xkiro, omnirush, gname, abliteration, terrapolis, cleanapis, miarouter, treg, agentrouter). +- В UI: Register → product → выбрать ⚡-провайдера → kind переключится на register_sh → «Количество target» = N аккаунтов → Запустить. +- Пути к скриптам провайдеров: env `UNIVERSAL_REG_ROOT` (по умолчанию C:/Users/User), python: `UNIVERSAL_PYTHON`. +- Провайдер-скрипты в публичную репу НЕ входят (только роутер-контракт). + +--- + +# AI 通用注册机(ai-register-machine) + +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) +[![Python 3.13](https://img.shields.io/badge/python-3.13-blue.svg)](pyproject.toml) +[![LINUX DO](https://img.shields.io/badge/Community-LINUX%20DO-2563eb.svg?logo=linux&logoColor=white)](https://linux.do/) + +--- + +## 🌟 特别致谢与社区认可:LINUX DO + +> 🐧 **本项目深度认可并致谢 [LINUX DO (https://linux.do)](https://linux.do/) 社区,特此将 LINUX DO 列为首位致敬与致谢对象!** +> 本项目在多模型 Provider 协议逆向、邮箱收信通道适配、出口 IP 轮换以及生产级工程化落地中的大量思路、灵感与技巧,均汲取自 **LINUX DO** 社区全体佬友们的无私分享与真诚交流。致敬开源精神与纯粹的技术探索! + +--- + +面向大模型 API / Console 账号的现代化自动化注册机与凭据管理系统,集 **多线程并发、独立邮箱收信、有头/无头对抗、智能 IP 池轮换、增量真归因验收、CPA 批量导入与可视化 Web 控制面** 于一体。 + +--- + +## 🔥 核心项目特性 + +- ⚡ **多线程并发注册引擎**:内置统一 `Pipeline` 线程池调度系统,支持灵活自定义并发规模(`--threads`),提供智能软失败容错继续与硬性资源耗尽的 Fail-Fast 熔断机制。 +- 📬 **内置邮箱管理系统与 API**:抽象统一 `EmailSource` 接口层,深度集成多渠道邮箱自动分配与邮件/验证码精准轮询(tinyhost API、Hotmail/Outlook OAuth2+REST/IMAP、DuckMail API、CloudMail 等),严格保证一号一箱。 +- 🌐 **有头 / 无头双模浏览器驱动**:支持 Playwright 与 DrissionPage 双内核,高效应对 Cloudflare Turnstile 等人机验证;支持浏览器会话复用、崩溃自动清理与调试隔离。 +- 🔄 **智能 IP 池与出口隔离轮换**:深度集成 Clash Verge 控制器,支持专用策略组与域名级精准分流(轮换时不干扰整机主代理);同时支持自建 HTTP/SOCKS5 节点池(`proxy_list` / `nodes.json`)与实时健康度探针。 +- 🧪 **自动化批量测试与状态归因**:坚守「本轮真实增量交付」原则,杜绝使用历史账本尾巴充数;具备内置连通性探测(smoke probe)、`CONTRACT_EXIT` 验收契约及私钥凭据 `0600` 强隔离。 +- 🚀 **批量导入 CPA(CLIProxyAPI)**:支持从 SSO Cookie 自动进行 OIDC Device Flow 纯协议静默铸造,结合 Chat 模型探针进行 Healthy-Only 门禁筛选,并支持 SSH 远端自动热加载导入。 +- 🖥️ **可视化 Web 控制台(Control Plane)**:开箱即用的 FastAPI + Vite/Preact 现代化 Web 控制面,一站式管理配置热更、凭据导入、批次启停监控与实时日志流。 + +--- + +## 支持的 Provider 矩阵 + +| Provider | 命令入口 | 核心协议 / 驱动栈 | 产物契约与交付 | +|----------|----------|-------------------|----------------| +| **typesafe.ai / jev** | `./register.sh typesafe [count] [threads]` | Python + requests + Stytch Magic-Link | `typesafe-*.json` (0600 API Key) | +| **Grok / xAI** | `./register.sh grok [count] [threads]` | Python + DrissionPage + OIDC Device Flow | `accounts_cli.txt` (SSO) + `cpa_auths/` (OIDC) | +| **Xiaomi MiMo** | `./register.sh mimo` | Node + Playwright | `mimo-*.json` (`sk-` API Key,OpenAI 兼容) | +| **Outlook / Hotmail** | `./register.sh outlook [count]` | Python + Playwright + slidex | `outlook_auths/` (四段凭证与 OAuth Token) | +| **通用分层编排** | `./register.sh core run -p ` | `register_core/` 通用引擎 | Pipeline 驱动,支持自定义邮箱与验证器 | + +--- + +## ⚡ 快速开始(最短路径上手) + +### 1. 环境准备与配置 + +需要 **Python 3.13**,推荐使用 [uv](https://docs.astral.sh/uv/)。运行快速脚本将基于 `config.simple.example.json` 自动初始化 `config.json`(支持 `duckmail` 或 Hotmail 模式)并检查运行环境: + +```bash +git clone https://github.com/dengyie/ai-register-machine.git +cd ai-register-machine +bash scripts/setup_simple.sh +``` + +### 2. 核心命令速查 + +```bash +# 统一帮助入口 +./register.sh help + +# typesafe.ai 注册(支持并发多线程与软失败继续) +./register.sh typesafe 1 # 单次注册测试 +./register.sh typesafe 100 8 # 批量 100 个,8 线程并发 +./register.sh smoke typesafe # 控制台连通性探测 + +# Grok / xAI 注册 +./register.sh grok 1 1 # 注册 1 个号(推荐桌面有头模式) + +# Xiaomi MiMo TTS Key 注册 +./register.sh mimo + +# 通用 register_core 分层编排 +./register.sh core list +./register.sh core run -p typesafe -n 1 +``` + +### 3. Web 控制台(Control Plane) + +项目内置基于 FastAPI + Vite/Preact 的轻量级 Web 控制面,提供可视化配置、批次启停和实时日志: + +```bash +export CONTROL_API_SESSION_SECRET="$(openssl rand -hex 32)" +./scripts/run_control_api.sh +# 浏览器访问 http://127.0.0.1:8787(首次登录默认 admin / admin123) +``` + +--- + +## 📊 最新实测(pxed 生产机真机实测) + +所有实测严格遵守**「只计算本轮增量」**原则,不统计存量数据: + +### typesafe.ai 实测(1000 批次 · 2026-09-22) + +- **命令**:`./register.sh typesafe 1000`(8 线程,`--no-fail-fast`,超时 86400s) +- **环境**:pxed 生产机,Clash mixed-port `127.0.0.1:7897`(本批次 `rotate=off`),tinyhost 独立邮箱,收信直连 +- **结果**:**976 成功 / 24 失败**,`CONTRACT_EXIT:0`,全部跑完无中途崩溃 +- **交付物**:新增 976 个全新 `0600` `typesafe-*.json`,目录权限 `0700`,未向 `accounts.jsonl` 追加明文,未注入 CPA +- **失败归因**(全部为上游偶发软失败,不中断批次): + - `wait_magic_link` (17 次):tinyhost 180s 内未收到邮件(`no_mail` 偶发丢信) + - `send_magic_link` (5 次):上游接口 HTTP 500 + - `auth_callback` (2 次):上游接口 HTTP 401 +- **同日验证**:首轮 100 次实测 97 成功 / 3 失败;修复 magic-link 优先级后次轮 100 次实测 98 成功 / 2 失败。 + +--- + +## 🛡️ 安全、合规与常见卡点 + +- **合规声明**:Education / personal automation only; not a free-quota farm. 请勿用于违反第三方服务条款的滥用行为。本项目不提供任何破除付费限制或生成未获授权配额的功能。 +- **Grok 权限感知**:若遇到 `entitlement_denied`(或 chat 403),说明服务端未授予 free Build 权限,属于正常策略,**不要盲目 remint 空转**。 +- **密钥零追踪**:切勿提交 `config.json`、`mail_credentials.txt` 或 `cpa_auths/*.json`。运行 `bash scripts/doctor_secrets.sh` 随时检查本地密钥安全;所有私钥产物均严格设置 `0600` 文件权限,目录设置 `0700`。 + +### 常见卡点速查 + +| 现象 | 处理建议 | +|------|----------| +| doctor: proxy port closed | 检查本地代理是否启动,确认 `config.json` 中代理端口 | +| doctor: duckmail / placeholder | 填写真实 DuckMail Key 或有效邮箱凭证,替换模板占位符 | +| Turnstile 验证卡住 | 推荐使用桌面有头模式(`--no-headless`)及干净代理 IP | +| `entitlement_denied` | 该账号未获 xAI free Build 资格,无需重复尝试 | + +--- + +## 🐧 社区致谢与参考 + +- **[LINUX DO (https://linux.do)](https://linux.do/)**(🌟 **首位致谢对象**):特别感谢 LINUX DO 社区全体佬友的智慧结晶与开源分享,为自动化工程与逆向探索提供了无可替代的技术灵感。 +- **技术参考**:感谢社区开源项目 [ThinkerWen/ai-register](https://github.com/ThinkerWen/ai-register)、[Futureppo/typesafe_register](https://github.com/Futureppo/typesafe_register)、[daimon3332/OutlookRegister](https://github.com/daimon3332/OutlookRegister) 提供的架构与协议分析灵感。 + +--- + +## 📄 License + +本项目基于 [MIT License](LICENSE) 开源。 +Copyright (c) 2026 dengyie diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..eef9b63 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,77 @@ +# Security Policy + +## Supported versions + +Only the latest `main` branch is maintained. There is no long-term support +branch. + +## What is sensitive + +Never commit or publish: + +| Path / pattern | Contents | +|----------------|----------| +| `config.json` | proxies, remote hosts, feature flags, secrets | +| `.env` | environment secrets | +| `mail_credentials.txt` | mailbox password + Microsoft refresh_token | +| `mail_assets/` | imported Hotmail credential batches | +| `accounts_cli.txt` / `accounts_*.txt` | Grok password + SSO cookie | +| `cpa_auths/*.json` | OIDC access_token / refresh_token | +| `backups/` | full credential snapshots | +| `logs/` / `screenshots/` / `cookies/` | may embed PII or tokens | + +Templates are safe to share: `config.example.json`, `config.simple.example.json`, `mail_credentials.example.txt`, `.env.example`. + +## Local hygiene (operators) + +Runtime trees often hold **thousands** of tokens. Treat the working directory as a secrets vault: + +1. Prefer full-disk encryption; avoid putting this repo under iCloud/Dropbox/OneDrive sync of `mail_credentials.txt` / `cpa_auths/` / `backups/`. +2. Restrict permissions: `chmod 600 config.json .env mail_credentials.txt accounts_cli.txt` when present. +3. Before every commit: `bash scripts/doctor_secrets.sh` (prints **paths/modes only**, never file contents). Exit `1` = tracked/staged secrets; `2` = warnings (e.g. loose mode). +4. Never `git add -f` gitignored credential paths. CI also refuses known secret paths on `main`. +5. If leaked: rotate Microsoft refresh tokens, xAI/SSO sessions, CPA OIDC tokens, and any SSH passwords in inject credentials; invalidate remote live copies. + +## Reporting a vulnerability + +Please **do not** open a public issue for security problems that expose +credentials, remote access, or RCE-style bugs. + +Prefer one of: + +1. GitHub **private vulnerability report** on this repository (if enabled) +2. A private contact via the repository owner’s GitHub profile + +Include: + +- affected commit / tag +- reproduction steps (with redacted secrets) +- impact assessment + +We aim to acknowledge reports within a reasonable time; there is no bug bounty. + +## If secrets leak + +1. **Revoke / rotate immediately** + - Microsoft mailbox refresh_token / app password + - xAI / Grok session (SSO) by password reset or session revoke if available + - CPA / OIDC tokens (re-mint after rotation) + - SSH passwords / keys used for remote inject +2. Remove secrets from any fork, gist, chat log, or CI artifact +3. If the secret was pushed to Git history, rotate first, then rewrite or + abandon the tainted history; rotation matters more than history scrubbing +4. Check remote CPA auth-dir and delete leaked `xai-*.json` files + +## Safe defaults for contributors + +- Run offline tests only in CI (`GROK_REGISTER_LIVE` unset) +- Prefer dummy values in examples +- Never attach real `cpa_auths` or mail credentials to pull requests +- Redact emails and tokens in logs pasted into issues +- SSO normalize only strips a leading `-` when a JWT header (`eyJ`) is nearby; do not change this to blind `lstrip("-")` on arbitrary session values + +## Remote inject + +`cpa_remote_inject` may use `sshpass` and a credentials file. That password is +as sensitive as root on the target host. Prefer SSH keys + `ssh-agent` when +possible; keep credential files mode `600` outside the repo. diff --git a/account_backup.py b/account_backup.py new file mode 100644 index 0000000..fa8c753 --- /dev/null +++ b/account_backup.py @@ -0,0 +1,199 @@ +"""Local project backup for registered accounts + CPA auth files. + +Secrets stay under backups/ (gitignored). Safe to call after each success. +""" + +from __future__ import annotations + +import json +import os +import shutil +from datetime import datetime +from pathlib import Path +from typing import Any + +_ROOT = Path(__file__).resolve().parent +_BACKUP_ROOT = _ROOT / "backups" + + +def _project_root(root: str | Path | None = None) -> Path: + return Path(root).expanduser().resolve() if root else _ROOT + + +def _safe_copy(src: Path, dst: Path) -> bool: + if not src.is_file(): + return False + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(src, dst) + try: + os.chmod(dst, 0o600) + except OSError: + pass + return True + + +def _parse_accounts(accounts_file: Path) -> list[dict[str, Any]]: + rows: list[dict[str, Any]] = [] + if not accounts_file.is_file(): + return rows + for line in accounts_file.read_text(encoding="utf-8", errors="replace").splitlines(): + line = line.strip() + if not line or line.startswith("#"): + continue + parts = line.split("----") + email = (parts[0] or "").strip() + if not email: + continue + rows.append( + { + "email": email, + "has_password": len(parts) > 1 and bool(parts[1].strip()), + "has_sso": len(parts) > 2 and len(parts[2].strip()) > 20, + } + ) + return rows + + +def snapshot_registered_accounts( + root: str | Path | None = None, + *, + reason: str = "", + email: str | None = None, + make_timestamped: bool = True, + log_callback: Any = None, +) -> dict[str, Any]: + """Copy accounts ledger + CPA auths into backups/. + + Always refreshes backups/latest. + Optionally also writes backups/register_YYYYMMDD_HHMMSS. + """ + log = log_callback or (lambda _m: None) + proj = _project_root(root) + backup_root = proj / "backups" + backup_root.mkdir(parents=True, exist_ok=True) + + ts = datetime.now().strftime("%Y%m%d_%H%M%S") + targets: list[Path] = [] + latest = backup_root / "latest" + targets.append(latest) + stamped: Path | None = None + if make_timestamped: + stamped = backup_root / f"register_{ts}" + targets.append(stamped) + + sources = { + "accounts_cli.txt": proj / "accounts_cli.txt", + "emails_used.txt": proj / "emails_used.txt", + "emails_error.txt": proj / "emails_error.txt", + } + # also pick any accounts_*.txt snapshots from GUI runs + for p in sorted(proj.glob("accounts_*.txt")): + sources[p.name] = p + + cpa_src = proj / "cpa_auths" + cpa_files = sorted(cpa_src.glob("xai-*.json")) if cpa_src.is_dir() else [] + + written: list[str] = [] + for target in targets: + if target.exists(): + if target.is_dir(): + # refresh in place for latest; recreate for stamped + if target.name == "latest": + pass + else: + shutil.rmtree(target) + target.mkdir(parents=True, exist_ok=True) + else: + target.unlink() + target.mkdir(parents=True, exist_ok=True) + else: + target.mkdir(parents=True, exist_ok=True) + + for name, src in sources.items(): + if _safe_copy(src, target / name): + written.append(f"{target.name}/{name}") + + cpa_dst = target / "cpa_auths" + cpa_dst.mkdir(exist_ok=True) + # prune stale in latest to mirror current set + if target.name == "latest": + keep = {p.name for p in cpa_files} + for old in cpa_dst.glob("xai-*.json"): + if old.name not in keep: + try: + old.unlink() + except OSError: + pass + for p in cpa_files: + if _safe_copy(p, cpa_dst / p.name): + written.append(f"{target.name}/cpa_auths/{p.name}") + + accounts = _parse_accounts(proj / "accounts_cli.txt") + manifest = { + "created_at": ts, + "reason": reason or ("post_register" if email else "manual"), + "trigger_email": email or "", + "account_count": len(accounts), + "accounts": accounts, + "cpa_auth_files": [p.name for p in cpa_files], + "paths": { + "backup_dir": str(target), + "accounts_cli": "accounts_cli.txt", + "cpa_auths": "cpa_auths/", + }, + "note": "Contains credentials; keep out of git (backups/ is gitignored).", + } + man_path = target / "manifest.json" + man_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + try: + os.chmod(man_path, 0o600) + except OSError: + pass + + result = { + "ok": True, + "timestamp": ts, + "latest": str(latest), + "stamped": str(stamped) if stamped else "", + "account_count": len(_parse_accounts(proj / "accounts_cli.txt")), + "cpa_count": len(cpa_files), + "trigger_email": email or "", + "reason": reason or "", + "files": written[:20], + } + log( + f"[backup] accounts={result['account_count']} cpa={result['cpa_count']} " + f"-> {latest.name}" + + (f" + {stamped.name}" if stamped else "") + + (f" ({email})" if email else "") + ) + return result + + +def backup_after_success( + email: str, + *, + root: str | Path | None = None, + cpa_path: str | Path | None = None, + log_callback: Any = None, +) -> dict[str, Any]: + """Lightweight post-success backup: refresh latest only (no new timestamp dir). + + Prefer this on every register/mint success to avoid flooding backups/. + Full timestamped snapshot still available via snapshot_registered_accounts(). + """ + log = log_callback or (lambda _m: None) + proj = _project_root(root) + # ensure specific cpa file exists if path given + if cpa_path: + src = Path(cpa_path) + if src.is_file(): + # already under cpa_auths normally; snapshot will pick it up + pass + return snapshot_registered_accounts( + proj, + reason="success", + email=email, + make_timestamped=False, + log_callback=log, + ) diff --git a/apps/README.md b/apps/README.md new file mode 100644 index 0000000..e25a9e8 --- /dev/null +++ b/apps/README.md @@ -0,0 +1,53 @@ +# Apps (entrypoints) + +Thin map of user-facing entrypoints. Implementation may still live at repo root. + +| App | How to run | Notes | +|-----|------------|--------| +| **Hub** | `./register.sh help` | Multi-provider | +| **Grok CLI** | `./register.sh grok 1 1` | Production | +| **Web control plane** | `./scripts/run_control_api.sh` | Config / Import / Runs UI at `http://127.0.0.1:8787` | +| **MiMo** | `./register.sh mimo` | Node runtime | +| **Core** | `./register.sh core list` | Layered orchestration | + +## Web control plane + +```bash +export REGISTER_PROJECT_ROOT="$(pwd)" # optional; defaults to cwd +export CONTROL_API_HOST=127.0.0.1 +export CONTROL_API_PORT=8787 +# Recommended: stable session secret + optional script bearer +export CONTROL_API_SESSION_SECRET="$(openssl rand -hex 32)" +export CONTROL_API_TOKEN="$(openssl rand -hex 32)" # optional; for curl/scripts +# First start with empty user store auto-creates: +# username: admin +# password: admin123 +# Override: CONTROL_API_BOOTSTRAP_USER / CONTROL_API_BOOTSTRAP_PASSWORD +# Or set/change later: +# uv run python scripts/control_api_user.py set admin +./scripts/run_control_api.sh +``` + +Open `http://127.0.0.1:8787` → **login form**. Default credentials **`admin` / `admin123`** when `.control_api_users.json` does not exist yet. Session is HttpOnly cookie. + +- API: `/api/health`, `/api/auth/*`, `/api/overview`, `/api/config`, `/api/import/*`, `/api/runs/*`, `/api/nodes/*`, `/api/accounts/*`, `/api/ops/*` +- UI: **console10** Preact SPA — `cd apps/web && npm run build` (or `./scripts/build_web_console.sh`) writes `apps/web/dist`; FastAPI prefers `apps/web/dist` then falls back to flat `apps/web/`. + - **Packaging:** GitHub Actions `CI` job `package-console10` runs on **main push** only (after green tests) → artifact `console10-web` (14d). PR CI tests without packaging. + - **Deploy (auto + manual):** workflow **Deploy console10** (Environment `pxed`). + - **Auto:** after successful `CI` on `main` **push** (`workflow_run`), deploys that run’s artifact. + - **Manual:** Actions → Deploy console10 (`workflow_dispatch`); `dry_run` / rebuild / artifact options. + - Secrets: `PXED_SSH_PRIVATE_KEY` + `PXED_HOST` + `PXED_KNOWN_HOSTS` (optional `PXED_WEB`, `PXED_SSH_PORT`). Prefer direct host (not cloudflared alias). + - Path sanitized under `/data/grok-register`; stale Vite `assets/*` pruned; **single script** `scripts/deploy_web_console10.sh`. + - **Boundary (I5):** **static SPA only** under `PXED_WEB` (default `/data/grok-register/apps/web`). Does **not** deploy `control_api` / register core / supervisor, does **not** stop batch/coinbot. API code changes need a separate host update + careful control_api restart. + - Deploy key: scope write to `/data/grok-register/` (or web subdir) only when possible. + - **Local fallback:** `./scripts/deploy_web_console10.sh`. `SKIP_BUILD=1` / `CONSOLE10_TGZ=` / `DRY_RUN=1` / `PRUNE_STALE_ASSETS=1` supported. + - Dev: `cd apps/web && npm run dev` proxies `/api` → `:8787`. Legacy console9 under `apps/web/legacy/`. +- Auth (either): + - **Browser:** password login → signed cookie `control_session` + - **Scripts:** `Authorization: Bearer ` or `X-Control-Token` +- Operators file: `.control_api_users.json` (gitignored, mode 0600, scrypt hashes). Bootstrap is a **no-op** if this file already has users (production stays as configured). +- Login rate limit: 8 failures / 5 min per IP+username +- Default bind is localhost; use SSH tunnel for remote browser access +- Disable password login only for break-glass: `CONTROL_API_PASSWORD_LOGIN=0` (then rely on bearer or open) + +Subdir `gui/` only documents that the desktop TTK UI was removed. diff --git a/apps/__init__.py b/apps/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/cli/README.md b/apps/cli/README.md new file mode 100644 index 0000000..2c6fff1 --- /dev/null +++ b/apps/cli/README.md @@ -0,0 +1,13 @@ +# CLI + +```bash +./register.sh help +./register.sh grok [count] [threads] +./register.sh mimo [count] +./register.sh core list +./register.sh core run -p -n 1 +./register.sh smoke mimo +``` + +Grok full flags: `uv run python register_cli.py --help` +Core: `python -m register_core --help` diff --git a/apps/control_api/__init__.py b/apps/control_api/__init__.py new file mode 100644 index 0000000..2558bba --- /dev/null +++ b/apps/control_api/__init__.py @@ -0,0 +1,11 @@ +"""Project-owned Web control plane API.""" + +__all__ = ["create_app"] + + +def __getattr__(name: str): + if name == "create_app": + from apps.control_api.app import create_app + + return create_app + raise AttributeError(name) diff --git a/apps/control_api/__main__.py b/apps/control_api/__main__.py new file mode 100644 index 0000000..70f620c --- /dev/null +++ b/apps/control_api/__main__.py @@ -0,0 +1,22 @@ +"""python -m apps.control_api""" + +from __future__ import annotations + +import uvicorn + +from apps.control_api.settings import get_settings + + +def main() -> None: + s = get_settings() + uvicorn.run( + "apps.control_api.app:create_app", + factory=True, + host=s.host, + port=s.port, + log_level="info", + ) + + +if __name__ == "__main__": + main() diff --git a/apps/control_api/accounts_ops.py b/apps/control_api/accounts_ops.py new file mode 100644 index 0000000..8ebbfa6 --- /dev/null +++ b/apps/control_api/accounts_ops.py @@ -0,0 +1,167 @@ +"""List / inspect / delete product accounts under cpa_auths (disk-first pool).""" + +from __future__ import annotations + +import json +import time +from pathlib import Path +from typing import Any + +# Per-process mtime cache so paginated UI polls don't re-parse every auth JSON. +_SUMMARY_CACHE: dict[str, tuple[int, int, dict[str, Any]]] = {} + + +def _auth_dir(root: Path) -> Path: + return root / "cpa_auths" + + +def _safe_name(name: str) -> str: + base = Path(str(name or "")).name + if not base or base in {".", ".."} or "/" in str(name) or "\\" in str(name): + raise ValueError("invalid account name") + if not (base.startswith("xai-") and base.endswith(".json")): + raise ValueError("account file must be xai-*.json") + return base + + +def _summarize(path: Path) -> dict[str, Any]: + st = path.stat() + mtime_ns = int(getattr(st, "st_mtime_ns", int(st.st_mtime * 1_000_000_000))) + size = int(st.st_size) + cache_key = str(path) + hit = _SUMMARY_CACHE.get(cache_key) + if hit and hit[0] == mtime_ns and hit[1] == size: + return hit[2] + + email = "" + complete = False + has_access = False + has_refresh = False + disabled = False + expired = False + priority = None + auth_kind = None + last_refresh = None + err = None + try: + data = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(data, dict): + err = "not_object" + else: + email = str(data.get("email") or "") + at = data.get("access_token") + rt = data.get("refresh_token") + has_access = isinstance(at, str) and bool(at) + has_refresh = isinstance(rt, str) and bool(rt) + complete = has_access and has_refresh + disabled = bool(data.get("disabled")) + expired = bool(data.get("expired")) + priority = data.get("priority") + auth_kind = data.get("auth_kind") or data.get("type") + last_refresh = data.get("last_refresh") + except Exception as exc: + err = str(exc)[:200] + summary = { + "name": path.name, + "email": email or path.name.removeprefix("xai-").removesuffix(".json"), + "complete": complete, + "has_access": has_access, + "has_refresh": has_refresh, + "disabled": disabled, + "expired": expired, + "priority": priority, + "auth_kind": auth_kind, + "last_refresh": last_refresh, + "size": size, + "mtime": int(st.st_mtime), + "mtime_iso": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(st.st_mtime)), + "error": err, + } + _SUMMARY_CACHE[cache_key] = (mtime_ns, size, summary) + return summary + + +def list_accounts( + root: Path, + *, + q: str = "", + complete: str = "", + page: int = 1, + page_size: int = 50, +) -> dict[str, Any]: + d = _auth_dir(root) + if not d.is_dir(): + return { + "path": str(d), + "total": 0, + "complete": 0, + "page": 1, + "page_size": page_size, + "pages": 0, + "items": [], + } + paths = sorted(d.glob("xai-*.json"), key=lambda p: p.stat().st_mtime, reverse=True) + items = [_summarize(p) for p in paths] + # Drop cache entries for files that disappeared (bounded leak guard). + live = {str(p) for p in paths} + for k in list(_SUMMARY_CACHE.keys()): + if k.startswith(str(d)) and k not in live: + _SUMMARY_CACHE.pop(k, None) + + complete_n = sum(1 for it in items if it.get("complete")) + qq = (q or "").strip().lower() + if qq: + items = [ + it + for it in items + if qq in (it.get("email") or "").lower() or qq in (it.get("name") or "").lower() + ] + c = (complete or "").strip().lower() + if c in {"1", "true", "yes", "ok", "complete"}: + items = [it for it in items if it.get("complete")] + elif c in {"0", "false", "no", "incomplete"}: + items = [it for it in items if not it.get("complete")] + + total = len(items) + if page_size <= 0: + page = 1 + page_size = total or 1 + page_items = items + pages = 1 if total else 0 + else: + page = max(1, int(page or 1)) + page_size = max(1, min(500, int(page_size))) + pages = (total + page_size - 1) // page_size if total else 0 + if pages and page > pages: + page = pages + start = (page - 1) * page_size + page_items = items[start : start + page_size] + return { + "path": str(d), + "total": total, + "complete": complete_n if not qq and not c else sum(1 for it in items if it.get("complete")), + "disk_complete": complete_n, + "page": page, + "page_size": page_size, + "pages": pages, + "items": page_items, + } + + +def delete_account(root: Path, name: str) -> dict[str, Any]: + """Soft-delete: rename into cpa_auths/.trash/ with timestamp suffix (audit/backup).""" + base = _safe_name(name) + auth_dir = _auth_dir(root) + path = auth_dir / base + if not path.is_file(): + raise FileNotFoundError(base) + trash = auth_dir / ".trash" + trash.mkdir(parents=True, exist_ok=True) + stamp = time.strftime("%Y%m%dT%H%M%S") + dest = trash / f"{base}.{stamp}" + # Avoid clobber if two deletes land in the same second. + if dest.exists(): + dest = trash / f"{base}.{stamp}.{int(time.time() * 1000) % 1000}" + path.rename(dest) + _SUMMARY_CACHE.pop(str(path), None) + return {"ok": True, "deleted": base, "archived": dest.name, "archived_path": str(dest)} diff --git a/apps/control_api/app.py b/apps/control_api/app.py new file mode 100644 index 0000000..24f6c81 --- /dev/null +++ b/apps/control_api/app.py @@ -0,0 +1,115 @@ +"""FastAPI application factory for the project control plane.""" + +from __future__ import annotations + +from pathlib import Path + +from fastapi import Depends, FastAPI +from fastapi.responses import JSONResponse +from fastapi.staticfiles import StaticFiles + +from apps.control_api.auth import auth_is_required, require_auth +from apps.control_api.schemas import HealthOut, OverviewOut +from apps.control_api.settings import get_settings, log_auth_startup +from apps.control_api.users import ensure_bootstrap_user, has_any_user + + +def create_app() -> FastAPI: + app = FastAPI(title="ai-register-machine control API", version="1.1.0") + + @app.on_event("startup") + def _bootstrap_user() -> None: + s = get_settings() + # Always print ops-safe auth readiness (sources only, never secret values). + log_auth_startup(s) + if not s.password_login_enabled: + return + created = ensure_bootstrap_user( + s.project_root, + username=s.bootstrap_user, + password=s.bootstrap_password, + ) + if created: + # Do not log password; username only. + print(f"[control_api] bootstrap operator created: {created}", flush=True) + + @app.get("/api/health", response_model=HealthOut) + def health() -> HealthOut: + s = get_settings() + return HealthOut( + ok=True, + project_root=str(s.project_root), + token_required=bool(s.token), + password_login_enabled=s.password_login_enabled, + users_configured=has_any_user(s.project_root), + auth_required=auth_is_required(s.project_root), + ) + + @app.get("/api/overview", response_model=OverviewOut, dependencies=[Depends(require_auth)]) + def overview() -> OverviewOut: + from apps.control_api.overview import build_overview + + s = get_settings() + return OverviewOut(**build_overview(s.project_root)) + + try: + from apps.control_api.routes_auth import router as auth_router + + app.include_router(auth_router) + except ImportError: + pass + try: + from apps.control_api.routes_config import router as config_router + + app.include_router(config_router, dependencies=[Depends(require_auth)]) + except ImportError: + pass + try: + from apps.control_api.routes_runs import router as runs_router + + app.include_router(runs_router, dependencies=[Depends(require_auth)]) + except ImportError: + pass + try: + from apps.control_api.routes_import import router as import_router + + app.include_router(import_router, dependencies=[Depends(require_auth)]) + except ImportError: + pass + try: + from apps.control_api.routes_nodes import router as nodes_router + + app.include_router(nodes_router, dependencies=[Depends(require_auth)]) + except ImportError: + pass + try: + from apps.control_api.routes_accounts import router as accounts_router + + app.include_router(accounts_router, dependencies=[Depends(require_auth)]) + except ImportError: + pass + try: + from apps.control_api.routes_ops import router as ops_router + + app.include_router(ops_router, dependencies=[Depends(require_auth)]) + except ImportError: + pass + try: + from apps.control_api.routes_mail import router as mail_router + + app.include_router(mail_router, dependencies=[Depends(require_auth)]) + except ImportError: + pass + + web_root = Path(__file__).resolve().parents[1] / "web" + web_dist = web_root / "dist" + # Prefer Vite build (console10); fall back to flat static root / legacy. + web_dir = web_dist if (web_dist / "index.html").is_file() else web_root + if web_dir.is_dir() and (web_dir / "index.html").is_file(): + app.mount("/", StaticFiles(directory=str(web_dir), html=True), name="web") + + @app.exception_handler(ValueError) + async def _value_error(_request, exc: ValueError): + return JSONResponse(status_code=400, content={"detail": str(exc)}) + + return app diff --git a/apps/control_api/auth.py b/apps/control_api/auth.py new file mode 100644 index 0000000..124d97a --- /dev/null +++ b/apps/control_api/auth.py @@ -0,0 +1,95 @@ +"""Auth for control API: session cookie and/or bearer token.""" + +from __future__ import annotations + +import hmac + +from fastapi import Header, HTTPException, Request, status + +from apps.control_api.sessions import COOKIE_NAME, read_session_token +from apps.control_api.settings import get_settings +from apps.control_api.users import has_any_user + + +def session_username(request: Request) -> str | None: + settings = get_settings() + if not settings.session_secret: + return None + raw = request.cookies.get(COOKIE_NAME) + if not raw: + return None + payload = read_session_token( + raw, + secret=settings.session_secret, + max_age=settings.session_ttl_seconds, + ) + if not payload: + return None + user = payload.get("u") + return str(user) if user else None + + +def auth_is_required(project_root=None) -> bool: + """Gate API when bearer token is set OR password login mode is on.""" + settings = get_settings() + if settings.token: + return True + # Password mode: require session (even before first user — login returns 503). + return bool(settings.password_login_enabled) + + +def _bearer_ok( + authorization: str | None, + x_control_token: str | None, +) -> bool: + settings = get_settings() + if not settings.token: + return False + presented: str | None = None + if authorization and authorization.lower().startswith("bearer "): + presented = authorization[7:].strip() + elif x_control_token: + presented = x_control_token.strip() + if not presented: + return False + return hmac.compare_digest(presented, settings.token) + + +def require_token( + authorization: str | None = Header(default=None), + x_control_token: str | None = Header(default=None, alias="X-Control-Token"), +) -> None: + """Legacy dependency: bearer/X-Control-Token only.""" + settings = get_settings() + if not settings.token: + return + if _bearer_ok(authorization, x_control_token): + return + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="invalid or missing token", + ) + + +def require_auth( + request: Request, + authorization: str | None = Header(default=None), + x_control_token: str | None = Header(default=None, alias="X-Control-Token"), +) -> str | None: + """Accept valid session cookie OR bearer token. Returns username or 'token'.""" + settings = get_settings() + + if settings.token and _bearer_ok(authorization, x_control_token): + return "token" + + user = session_username(request) + if user: + return user + + if not auth_is_required(settings.project_root): + return None + + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="login required", + ) diff --git a/apps/control_api/config_io.py b/apps/control_api/config_io.py new file mode 100644 index 0000000..117e12b --- /dev/null +++ b/apps/control_api/config_io.py @@ -0,0 +1,409 @@ +"""Load / redact / save project config.json with backup-before-write. + +Console is the control plane: saving config also mirrors operational keys into +``.env`` so batch supervisors (which load ``.env``) follow the UI. +""" + +from __future__ import annotations + +import json +import re +import shutil +import time +from pathlib import Path +from typing import Any + +SECRET_KEY_SUBSTR = ( + "password", + "api_key", + "apikey", + "token", + "jwt", + "secret", + "credential", +) + + +def _is_comment_key(key: str) -> bool: + return key.startswith("//") or key.startswith("#") + + +def _is_secret_key(key: str) -> bool: + low = key.lower() + return any(s in low for s in SECRET_KEY_SUBSTR) + + +def load_config(root: Path) -> dict[str, Any]: + path = root / "config.json" + if not path.is_file(): + return {} + raw = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(raw, dict): + raise ValueError("config.json must be a JSON object") + return {k: v for k, v in raw.items() if not _is_comment_key(str(k))} + + +def redact_config(data: dict[str, Any]) -> dict[str, Any]: + out: dict[str, Any] = {} + for k, v in data.items(): + if _is_secret_key(str(k)) and isinstance(v, str) and v: + if len(v) <= 4: + out[k] = "***" + else: + out[k] = f"***{v[-4:]}" + else: + out[k] = v + return out + + +def _looks_masked(value: Any) -> bool: + return isinstance(value, str) and value.startswith("***") + + +# config.json key → .env / process env key (non-secret operational controls only). +# Secrets (api keys, passwords, tokens) stay out of console→.env sync. +CONFIG_TO_ENV: dict[str, str] = { + "email_provider": "EMAIL_PROVIDER", + "email_providers": "EMAIL_PROVIDERS", + "email_provider_strategy": "EMAIL_PROVIDER_STRATEGY", + "defaultDomains": "DEFAULT_DOMAINS", + "cloudflare_api_base": "CLOUDFLARE_API_BASE", + "cloudflare_auth_mode": "CLOUDFLARE_AUTH_MODE", + "hotmail_accounts_file": "HOTMAIL_ACCOUNTS_FILE", + "mail_timeout": "MAIL_TIMEOUT", + "mail_poll_interval": "MAIL_POLL_INTERVAL", + "proxy": "PROXY", + "cpa_proxy": "CPA_PROXY", + "cpa_probe_chat": "CPA_PROBE_CHAT", + "cpa_remote_inject": "CPA_REMOTE_INJECT", + "cpa_export_enabled": "CPA_EXPORT_ENABLED", + "proxy_rotate_mode": "PROXY_ROTATE_MODE", + "proxy_rotate_every": "PROXY_ROTATE_EVERY", + "proxy_list": "PROXY_LIST", +} + +ENV_TO_CONFIG: dict[str, str] = {v: k for k, v in CONFIG_TO_ENV.items()} + +# Empty string is a real "clear" for multi-select / free-form lists only. +# All other operational keys treat "" as "omit / keep existing" so a partial +# Register save cannot wipe PROXY (etc.) from .env or config.json. +# defaultDomains is clearable so Resources can intentionally empty the domain pool +# (Register never posts this key — omit keeps prior). +CLEARABLE_EMPTY_CONFIG_KEYS = frozenset( + { + "email_providers", + "proxy_list", + "defaultDomains", + } +) + + +_SAFE_ENV_KEY = re.compile(r"^[A-Z][A-Z0-9_]*$") + +# Allowlisted .env keys the control plane may write (sync + start_run inject). +ENV_ALLOWLIST = frozenset(CONFIG_TO_ENV.values()) | frozenset( + { + "CPA_BATCH_END_INJECT", + "CPA_BATCH_IMPORT_EVERY", + "CPA_BATCH_IMPORT_SIZE", + "CPA_BATCH_IMPORT_PAUSE", + "SKIP_CLASH_PREFLIGHT", + "NODE_SCORE", + "SUPERVISOR_CHUNK", + # Outlook live gate — the operator-controlled flag that turns on + # browser orchestration for the Outlook provider. A *name*, never a + # secret value; allowlisting lets the control plane pass it through + # start_run extra_env / .env sync so the gate can be turned on + # out-of-band without exposing proxy/email/token env vars (those are + # never allowlisted). + "GROK_REGISTER_OUTLOOK_LIVE", + } +) + + +def _format_env_value(value: Any) -> str | None: + """Serialize a config value for .env. None = clear/omit key.""" + if value is None: + return None + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, (list, tuple, set)): + parts = [str(x).strip() for x in value if str(x).strip()] + return ",".join(parts) if parts else "" + if isinstance(value, (int, float)) and not isinstance(value, bool): + return str(value) + text = str(value).strip() + return text + + +def _is_blank_config_value(value: Any) -> bool: + """True when a payload value should not overwrite sticky operational state.""" + if value is None: + return True + if isinstance(value, str) and not value.strip(): + return True + if isinstance(value, (list, tuple, set)) and not any(str(x).strip() for x in value): + return True + return False + + +def parse_env_file(env_path: Path) -> dict[str, str]: + """Parse simple KEY=value .env lines (no export/quotes expansion).""" + out: dict[str, str] = {} + if not env_path.is_file(): + return out + try: + text = env_path.read_text(encoding="utf-8") + except OSError: + return out + for raw in text.splitlines(): + line = raw.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, _, val = line.partition("=") + key = key.strip() + if not key or not _SAFE_ENV_KEY.match(key): + continue + out[key] = val + return out + + +def enrich_config_from_env(root: Path, cfg: dict[str, Any] | None = None) -> dict[str, Any]: + """Fill blank non-secret operational config fields from project ``.env``. + + Response-only helper for GET /api/config so the console shows the values + the batch actually runs with when config.json still has empty proxy/domains. + Does not write disk. + """ + data = dict(cfg if isinstance(cfg, dict) else load_config(root)) + env_map = parse_env_file(root / ".env") + if not env_map: + return data + for env_key, cfg_key in ENV_TO_CONFIG.items(): + if _is_secret_key(cfg_key): + continue + if env_key not in env_map: + continue + env_val = str(env_map.get(env_key) or "").strip() + if not env_val: + continue + cur = data.get(cfg_key) + if not _is_blank_config_value(cur): + continue + # Bool-ish env for known bool config keys. + if cfg_key in ("cpa_probe_chat", "cpa_remote_inject", "cpa_export_enabled"): + low = env_val.lower() + if low in ("1", "true", "yes", "on"): + data[cfg_key] = True + elif low in ("0", "false", "no", "off"): + data[cfg_key] = False + else: + data[cfg_key] = env_val + elif cfg_key in ("mail_timeout", "mail_poll_interval", "proxy_rotate_every"): + try: + data[cfg_key] = int(env_val) + except ValueError: + data[cfg_key] = env_val + elif cfg_key == "email_providers": + data[cfg_key] = [p.strip() for p in env_val.split(",") if p.strip()] + elif cfg_key == "proxy_list": + # PROXY_LIST may be comma or newline separated in env; keep string. + data[cfg_key] = env_val + else: + data[cfg_key] = env_val + return data + + +def config_to_env_map( + cfg: dict[str, Any] | None, + *, + only_keys: set[str] | list[str] | None = None, + skip_empty: bool = False, +) -> dict[str, str]: + """Map operational config keys → env strings. + + ``only_keys``: if set, only these config.json keys are considered (used on + save so a hotmail switch does not wipe unrelated PROXY/DEFAULT_DOMAINS). + ``skip_empty``: omit empty-string values (start_run inject must not clobber + a healthy process/env PROXY with config proxy=\"\"). + Sticky keys (everything except CLEARABLE_EMPTY_CONFIG_KEYS) never emit an + empty string even when skip_empty is False — only multi-select/list fields + may intentionally clear with ``KEY=``. + """ + out: dict[str, str] = {} + if not isinstance(cfg, dict): + return out + allow_cfg = set(only_keys) if only_keys is not None else None + for cfg_key, env_key in CONFIG_TO_ENV.items(): + if allow_cfg is not None and cfg_key not in allow_cfg: + continue + if env_key not in ENV_ALLOWLIST or not _SAFE_ENV_KEY.match(env_key): + continue + if cfg_key not in cfg: + continue + if _is_secret_key(cfg_key): + continue + formatted = _format_env_value(cfg.get(cfg_key)) + if formatted is None: + continue + if formatted == "": + # Intentional clear only for multi-select / free-form lists. + if skip_empty or cfg_key not in CLEARABLE_EMPTY_CONFIG_KEYS: + continue + out[env_key] = formatted + return out + + +def update_env_file( + env_path: Path, + updates: dict[str, str], + *, + backup: bool = True, +) -> dict[str, Any]: + """Upsert allowlisted KEY=value lines in ``.env``; preserve comments/unknown keys. + + Empty string values write ``KEY=`` (clears multi-select pools). Keys not in + ENV_ALLOWLIST are ignored. Returns changed env keys + optional backup path. + """ + clean: dict[str, str] = {} + for k, v in (updates or {}).items(): + key = str(k).strip() + if key not in ENV_ALLOWLIST or not _SAFE_ENV_KEY.match(key): + continue + clean[key] = str(v) + + if not clean: + return {"changed_env_keys": [], "backup": None, "path": str(env_path)} + + existing_text = "" + if env_path.is_file(): + existing_text = env_path.read_text(encoding="utf-8") + + lines = existing_text.splitlines(keepends=True) if existing_text else [] + # Normalize to list of lines with newline for rewrite. + if lines and not lines[-1].endswith("\n"): + lines[-1] = lines[-1] + "\n" + + seen: set[str] = set() + changed: list[str] = [] + new_lines: list[str] = [] + for line in lines: + raw = line.rstrip("\n") + stripped = raw.strip() + if not stripped or stripped.startswith("#") or "=" not in stripped: + new_lines.append(line if line.endswith("\n") else line + "\n") + continue + key, _, old_val = stripped.partition("=") + key = key.strip() + if key not in clean: + new_lines.append(line if line.endswith("\n") else line + "\n") + continue + seen.add(key) + new_val = clean[key] + if old_val != new_val: + changed.append(key) + new_lines.append(f"{key}={new_val}\n") + + for key, new_val in clean.items(): + if key in seen: + continue + changed.append(key) + new_lines.append(f"{key}={new_val}\n") + + bak_path: str | None = None + if changed: + env_path.parent.mkdir(parents=True, exist_ok=True) + if backup and env_path.is_file(): + ts = time.strftime("%Y%m%d_%H%M%S") + bak = env_path.with_name(f".env.bak-web-{ts}") + shutil.copy2(env_path, bak) + bak_path = str(bak) + tmp = env_path.with_name(".env.tmp-web") + tmp.write_text("".join(new_lines), encoding="utf-8") + tmp.replace(env_path) + + return { + "changed_env_keys": changed, + "backup": bak_path, + "path": str(env_path), + } + + +def sync_config_to_env( + root: Path, + cfg: dict[str, Any] | None = None, + *, + only_keys: set[str] | list[str] | None = None, + skip_empty: bool = False, +) -> dict[str, Any]: + """Mirror operational config fields into project ``.env`` (console control plane).""" + data = cfg if isinstance(cfg, dict) else load_config(root) + return update_env_file( + root / ".env", + config_to_env_map(data, only_keys=only_keys, skip_empty=skip_empty), + ) + + +def save_config(root: Path, data: dict[str, Any]) -> dict[str, Any]: + """Write config.json and mirror **changed** operational keys into ``.env``. + + Empty or masked secret fields keep previous values. Only keys present in + the put payload that are operational (CONFIG_TO_ENV) are written to .env, + so saving email_provider does not blank PROXY/DEFAULT_DOMAINS. + + Sticky empty: for operational keys outside CLEARABLE_EMPTY_CONFIG_KEYS, + a blank payload value is ignored for both config.json merge and .env sync + (keeps prior non-empty). Multi-select fields like email_providers may still + clear with "". + """ + path = root / "config.json" + existing = load_config(root) if path.is_file() else {} + merged: dict[str, Any] = dict(existing) + + changed: list[str] = [] + payload_keys: list[str] = [] + for key, value in data.items(): + if _is_comment_key(str(key)): + continue + if _is_secret_key(str(key)): + if value in ("", None) or _looks_masked(value): + continue + key_s = str(key) + # Sticky operational fields: blank payload must not wipe prior value. + if ( + key_s in CONFIG_TO_ENV + and key_s not in CLEARABLE_EMPTY_CONFIG_KEYS + and _is_blank_config_value(value) + ): + continue + payload_keys.append(key_s) + old = existing.get(key) + if old != value: + changed.append(key_s) + merged[key] = value + + backup: str | None = None + if path.is_file(): + ts = time.strftime("%Y%m%d_%H%M%S") + bak = path.with_name(f"config.json.bak-web-{ts}") + shutil.copy2(path, bak) + backup = str(bak) + + tmp = path.with_suffix(".json.tmp-web") + tmp.write_text(json.dumps(merged, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + tmp.replace(path) + + # Sync only operational keys that were part of this save payload. + # config_to_env_map also refuses sticky empty → double protection if caller + # ever passes merged-with-blank. + env_keys = [k for k in payload_keys if k in CONFIG_TO_ENV] + env_sync: dict[str, Any] = {"changed_env_keys": [], "backup": None} + if env_keys: + env_sync = sync_config_to_env(root, merged, only_keys=env_keys) + return { + "backup": backup, + "changed_keys": changed, + "changed_env_keys": list(env_sync.get("changed_env_keys") or []), + "env_backup": env_sync.get("backup"), + "config": redact_config(merged), + } diff --git a/apps/control_api/imports_ops.py b/apps/control_api/imports_ops.py new file mode 100644 index 0000000..f2f51db --- /dev/null +++ b/apps/control_api/imports_ops.py @@ -0,0 +1,428 @@ +"""Import helpers: nodes, mail, auths, config packs.""" + +from __future__ import annotations + +import json +import shutil +import stat +import subprocess +import sys +import time +import zipfile +from pathlib import Path +from typing import Any, Literal + +from apps.control_api.config_io import load_config + + +# Cap on the *uncompressed* bytes an upload zip may emit. save_upload caps the +# compressed upload at max_upload_bytes, but a zip bomb (quadratic/quine) can +# explode to many GB from a tiny payload — so the extraction path needs its own +# ceiling independent of the upload size. +DEFAULT_MAX_ZIP_EXTRACT_BYTES = 256 * 1024 * 1024 + + +def staging_dir(root: Path) -> Path: + d = root / "output" / "web_uploads" + d.mkdir(parents=True, exist_ok=True) + return d + + +def ensure_under(root: Path, path: Path) -> Path: + resolved = path.resolve() + root_r = root.resolve() + staging = staging_dir(root).resolve() + if resolved == root_r or root_r in resolved.parents: + return resolved + if resolved == staging or staging in resolved.parents: + return resolved + raise ValueError(f"path escapes project root: {path}") + + +def save_upload(root: Path, filename: str, data: bytes, max_bytes: int) -> Path: + if len(data) > max_bytes: + raise ValueError(f"upload exceeds max_upload_bytes={max_bytes}") + safe = Path(filename).name + if not safe or safe in {".", ".."}: + raise ValueError("invalid filename") + dest = staging_dir(root) / f"{int(time.time())}_{safe}" + dest.write_bytes(data) + return ensure_under(root, dest) + + +def safe_extract_zip( + zf: zipfile.ZipFile, + dest: Path, + *, + max_bytes: int = DEFAULT_MAX_ZIP_EXTRACT_BYTES, +) -> int: + """Extract ``zf`` into ``dest`` with three upload-zip defenses: + + 1. path traversal — reject absolute / drive-prefixed names and any ".." + segment (zip-slip), and re-verify each resolved path stays under dest. + 2. symlink/hardlink entries — skip. A link inside an uploaded zip can + point anywhere on disk; a later import walking the tree would follow it + out of the staging dir. Only regular files and dirs are written. + 3. decompression bomb — cap total uncompressed bytes at ``max_bytes``, + counting real bytes read from the stream (not the declared header size, + which a crafted archive can underreport). + + Returns the number of entries written (files + dirs). Raises ValueError on + the first unsafe entry or overflow. + """ + dest = dest.resolve() + dest.mkdir(parents=True, exist_ok=True) + total = 0 + written = 0 + for info in zf.infolist(): + name = info.filename + # Zip-slip: absolute, drive-prefixed ("C:\\x"), or parent-escaping. + if ( + name.startswith("/") + or name.startswith("\\") + or (len(name) > 1 and name[1] == ":") + or ".." in Path(name).parts + ): + raise ValueError(f"unsafe zip entry: {name!r}") + + # Symlink/hardlink: unix mode lives in the high 16 bits of + # external_attr. S_IFLNK = 0xA000 — drop, never materialize. + mode = (info.external_attr >> 16) & 0xFFFF + if (mode & 0xF000) == stat.S_IFLNK: + continue + + target = (dest / name).resolve() + if target != dest and dest not in target.parents: + raise ValueError(f"zip entry escapes dest: {name!r}") + + if info.is_dir(): + target.mkdir(parents=True, exist_ok=True) + written += 1 + continue + + # Regular file: stream through ourselves so the cumulative cap counts + # REAL decompressed bytes, defeating a header that lies about its size. + target.parent.mkdir(parents=True, exist_ok=True) + with zf.open(info, "r") as src, open(target, "wb") as out: + while True: + chunk = src.read(1024 * 1024) + if not chunk: + break + total += len(chunk) + if total > max_bytes: + out.close() + target.unlink(missing_ok=True) + raise ValueError( + f"zip exceeds max uncompressed bytes ({max_bytes}): {name!r}" + ) + out.write(chunk) + written += 1 + return written + + +def import_nodes( + root: Path, + file_path: Path, + *, + dry_run: bool = False, + replace: bool = False, +) -> dict[str, Any]: + path = ensure_under(root, file_path) + script = root / "scripts" / "import_nodes.py" + if not script.is_file(): + raise FileNotFoundError(str(script)) + argv = [sys.executable, str(script), str(path)] + if dry_run: + argv.append("--dry-run") + if replace: + argv.append("--replace") + proc = subprocess.run( + argv, + cwd=str(root), + capture_output=True, + text=True, + timeout=600, + ) + return { + "exit": proc.returncode, + "stdout": (proc.stdout or "")[-4000:], + "stderr": (proc.stderr or "")[-2000:], + "path": str(path), + "dry_run": dry_run, + "replace": replace, + "ok": proc.returncode == 0, + } + + +def _mail_pool_email_set(path: Path) -> set[str]: + """Lowercased emails currently in the pool file (deduped). No secrets returned.""" + from mail_pool_probe import parse_credential_line + + out: set[str] = set() + if not path.is_file(): + return out + try: + text = path.read_text(encoding="utf-8-sig", errors="replace") + except OSError: + return out + for raw in text.splitlines(): + item = parse_credential_line(raw) + if not item: + continue + out.add(item.email.strip().lower()) + return out + + +def _summarize_mail_import( + *, + mode: str, + parsed: int, + new: int, + duplicate: int, + skipped: int, + pool_before: int, + pool_after: int, + sample_new: list[str], + formats: dict[str, int], +) -> str: + """Human-readable Chinese summary for UI toast/banner (no secrets).""" + bits: list[str] = [] + if mode == "replace": + bits.append(f"替换写入 {new} 条") + else: + bits.append(f"新增 {new}") + if duplicate: + bits.append(f"重复跳过 {duplicate}") + if skipped: + bits.append(f"格式无效 {skipped}") + fmt_bits = [] + if formats.get("json_objects"): + fmt_bits.append(f"JSON {formats['json_objects']}") + if formats.get("csv_rows"): + fmt_bits.append(f"CSV {formats['csv_rows']}") + if fmt_bits: + bits.append("来源 " + "+".join(fmt_bits)) + bits.append(f"池 {pool_before}→{pool_after}") + if sample_new: + show = "、".join(sample_new[:3]) + if len(sample_new) > 3: + show += f" 等{len(sample_new)}个" + bits.append(f"新号 {show}") + if new == 0 and duplicate > 0 and skipped == 0: + return "未新增(全部已在池中)· " + " · ".join(bits) + if new == 0 and skipped > 0 and duplicate == 0: + return "未导入(格式无效)· " + " · ".join(bits) + if new == 0 and parsed == 0: + return "未导入(无有效凭证)· " + " · ".join(bits) + if new > 0 and (duplicate or skipped): + return "部分成功 · " + " · ".join(bits) + if new > 0: + return "导入成功 · " + " · ".join(bits) + return "导入完成 · " + " · ".join(bits) + + +def import_mail( + root: Path, + content: str, + *, + mode: Literal["append", "replace"] = "append", +) -> dict[str, Any]: + """Import mail credentials; normalize vendor formats → dash form before write. + + Accepts classic ``email----password----clientId----refreshToken`` lines, + vendor JSON (objects/arrays/wrappers), CSV headers, and ``|``/``;``/tab/``:`` + 4-field lines. Invalid lines are skipped (not written raw). + + Append mode skips emails already present in the pool (dedupe) and reports + new vs duplicate counts so the UI can show honest feedback. + """ + from mail_pool_probe import normalize_credential_text, parse_credential_line + + cfg = load_config(root) + rel = str(cfg.get("hotmail_accounts_file") or "mail_credentials.txt") + target = ensure_under(root, (root / rel).resolve() if not Path(rel).is_absolute() else Path(rel)) + # Force under root even if absolute path outside + if root.resolve() not in target.parents and target != root.resolve(): + target = root / "mail_credentials.txt" + + text, norm_stats = normalize_credential_text(content) + parsed_lines = [ln for ln in text.splitlines() if ln.strip() and not ln.strip().startswith(("#", "//"))] + + existing = _mail_pool_email_set(target) if target.is_file() else set() + pool_before = len(existing) + + to_write: list[str] = [] + new_emails: list[str] = [] + dup_emails: list[str] = [] + seen_batch: set[str] = set() + for ln in parsed_lines: + item = parse_credential_line(ln) + if not item: + continue + key = item.email.strip().lower() + if key in seen_batch: + dup_emails.append(item.email) + continue + seen_batch.add(key) + if mode == "append" and key in existing: + dup_emails.append(item.email) + continue + to_write.append(ln) + new_emails.append(item.email) + + write_body = "" + if to_write: + write_body = "\n".join(to_write) + if not write_body.endswith("\n"): + write_body += "\n" + + # replace + zero valid credentials would truncate the pool to empty. A .bak is + # taken below, but the UI only reports "未导入(格式无效)" — the user would not + # know the pool was wiped. Refuse instead; append never truncates so it is exempt. + if mode == "replace" and not write_body and target.is_file(): + raise ValueError( + f"replace 模式解析出 0 条有效凭证,将清空邮箱池(当前 {pool_before} 个)——已拒绝。" + f"请检查格式(四段 ---- / JSON / CSV / 管道分隔),或改用 append。" + ) + + backup = None + if target.is_file() and (mode == "replace" or write_body): + bak = target.with_name(target.name + f".bak-web-{time.strftime('%Y%m%d_%H%M%S')}") + shutil.copy2(target, bak) + backup = str(bak) + + if mode == "replace" or not target.is_file(): + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(write_body, encoding="utf-8") + elif write_body: + with target.open("a", encoding="utf-8") as f: + f.write(write_body) + + pool_after = len(_mail_pool_email_set(target)) if target.is_file() else 0 + lines_written = len(to_write) + skipped = int(norm_stats.get("skipped") or 0) + # batch-internal dups counted in duplicate + duplicate = len(dup_emails) + formats = { + "json_objects": int(norm_stats.get("json_objects") or 0), + "csv_rows": int(norm_stats.get("csv_rows") or 0), + } + summary = _summarize_mail_import( + mode=mode, + parsed=len(parsed_lines), + new=lines_written, + duplicate=duplicate, + skipped=skipped, + pool_before=pool_before, + pool_after=pool_after, + sample_new=new_emails, + formats=formats, + ) + # status for UI: success | partial | empty + if lines_written > 0 and (duplicate or skipped): + status = "partial" + elif lines_written > 0: + status = "success" + else: + status = "empty" + + return { + "ok": True, + "status": status, + "summary": summary, + "path": str(target), + "backup": backup, + "mode": mode, + "lines_written": lines_written, + "parsed": len(parsed_lines), + "new": lines_written, + "duplicate": duplicate, + "skipped": skipped, + "pool_before": pool_before, + "pool_after": pool_after, + "new_emails": new_emails[:20], + "duplicate_emails": dup_emails[:20], + "normalized": norm_stats, + "formats": formats, + } + + +def import_auths( + root: Path, + src_dir: Path, + *, + no_remote: bool = True, +) -> dict[str, Any]: + src = ensure_under(root, src_dir) + if not src.is_dir(): + raise ValueError(f"auth src is not a directory: {src}") + script = root / "scripts" / "import_cpa_auth_dir.py" + if not script.is_file(): + raise FileNotFoundError(str(script)) + argv = [sys.executable, str(script), "--src", str(src)] + if no_remote: + argv.append("--no-remote") + proc = subprocess.run( + argv, + cwd=str(root), + capture_output=True, + text=True, + timeout=3600, + ) + return { + "exit": proc.returncode, + "stdout": (proc.stdout or "")[-4000:], + "stderr": (proc.stderr or "")[-2000:], + "src": str(src), + "no_remote": no_remote, + "ok": proc.returncode == 0, + } + + +def import_pack(root: Path, zip_path: Path, *, apply: bool = False) -> dict[str, Any]: + zpath = ensure_under(root, zip_path) + extract_to = staging_dir(root) / f"pack_{int(time.time())}" + extract_to.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(zpath, "r") as zf: + safe_extract_zip(zf, extract_to) + + found = { + "config": next(extract_to.rglob("config.json"), None), + "nodes": next(extract_to.rglob("nodes.json"), None), + "mail": next( + ( + p + for p in extract_to.rglob("*") + if p.is_file() and p.name in {"mail_credentials.txt", "mail_credentials.example.txt"} + ), + None, + ), + } + plan = {k: str(v) if v else None for k, v in found.items()} + applied: dict[str, str] = {} + if apply: + if found["config"]: + dest = root / "config.json" + if dest.is_file(): + shutil.copy2(dest, dest.with_name(f"config.json.bak-web-pack-{time.strftime('%Y%m%d_%H%M%S')}")) + shutil.copy2(found["config"], dest) + applied["config"] = str(dest) + if found["nodes"]: + dest = root / "nodes.json" + if dest.is_file(): + shutil.copy2(dest, dest.with_name(f"nodes.json.bak-web-pack-{time.strftime('%Y%m%d_%H%M%S')}")) + shutil.copy2(found["nodes"], dest) + applied["nodes"] = str(dest) + if found["mail"]: + dest = root / "mail_credentials.txt" + if dest.is_file(): + shutil.copy2(dest, dest.with_name(f"mail_credentials.txt.bak-web-pack-{time.strftime('%Y%m%d_%H%M%S')}")) + shutil.copy2(found["mail"], dest) + applied["mail"] = str(dest) + return { + "ok": True, + "extract_to": str(extract_to), + "plan": plan, + "applied": applied, + "apply": apply, + } diff --git a/apps/control_api/mail_ops.py b/apps/control_api/mail_ops.py new file mode 100644 index 0000000..6d253cb --- /dev/null +++ b/apps/control_api/mail_ops.py @@ -0,0 +1,339 @@ +"""Mail pool probe/quarantine ops for the control plane UI.""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +from typing import Any +from urllib.error import HTTPError, URLError +from urllib.parse import urlencode +from urllib.request import Request, urlopen + +from apps.control_api.config_io import enrich_config_from_env, load_config +from mail_pool_probe import ( + QUARANTINABLE_STATUSES, + compact_pool, + dead_archive_path, + is_quarantinable, + pool_stats, + probe_sample, + quarantine, + resolve_pool_path, +) + + +def _live_path(root: Path) -> Path: + """Resolve pool path; confine writes under project root (match import_mail). + + Env ``HOTMAIL_ACCOUNTS_FILE`` absolute path outside root is allowed only if + the file already exists (ops override). Relative paths that escape root are + forced back to ``root/mail_credentials.txt``. + """ + root_r = root.resolve() + cfg = load_config(root) + cfg_path = str(cfg.get("hotmail_accounts_file") or "").strip() or None + path = resolve_pool_path(root, config_path=cfg_path) + try: + path.resolve().relative_to(root_r) + return path.resolve() + except ValueError: + # Outside root + if path.is_absolute() and path.is_file(): + # Explicit existing absolute (env) — allow read/probe/quarantine there + return path.resolve() + return root_r / "mail_credentials.txt" + + +def get_pool_stats(root: Path) -> dict[str, Any]: + live = _live_path(root) + dead = dead_archive_path(live) + return pool_stats(live, dead_path=dead) + + +def probe_mail( + root: Path, + *, + domains: list[str] | None = None, + limit: int = 30, + seed: int | None = None, + offset: int | None = None, + concurrency: int = 4, + wall_seconds: float = 90.0, +) -> dict[str, Any]: + live = _live_path(root) + if not live.is_file(): + raise FileNotFoundError(f"mail credentials file not found: {live}") + return probe_sample( + live, + domains=domains, + limit=limit, + seed=seed, + offset=offset, + concurrency=concurrency, + writeback_rotated=True, + wall_seconds=wall_seconds, + ) + + +def compact_mail( + root: Path, + *, + dry_run: bool = False, + drop_invalid: bool = True, + drop_comments: bool = False, +) -> dict[str, Any]: + """Dedupe + optional junk strip for the live mail pool (backup first).""" + live = _live_path(root) + if not live.is_file(): + raise FileNotFoundError(f"mail credentials file not found: {live}") + return compact_pool( + live, + dry_run=dry_run, + drop_invalid=drop_invalid, + drop_comments=drop_comments, + ) + + +def quarantine_mail( + root: Path, + emails: list[str], + *, + reason: str = "quarantine", + require_quarantinable_from: list[dict[str, Any]] | None = None, +) -> dict[str, Any]: + """Quarantine explicit emails. + + If ``require_quarantinable_from`` is provided (last probe rows), only emails + whose status is in QUARANTINABLE_STATUSES are accepted; others are reported + in ``skipped_not_quarantinable``. Default (API path) still accepts the + explicit list — UI only sends quarantinable rows. + """ + if not emails: + raise ValueError("emails must be a non-empty list") + live = _live_path(root) + if not live.is_file(): + raise FileNotFoundError(f"mail credentials file not found: {live}") + + clean = [e.strip() for e in emails if e and str(e).strip()] + if not clean: + raise ValueError("emails must be a non-empty list") + + skipped: list[str] = [] + if require_quarantinable_from is not None: + allowed = { + str(r.get("email") or "").strip().lower() + for r in require_quarantinable_from + if is_quarantinable(str(r.get("status") or "")) + } + kept = [] + for e in clean: + if e.lower() in allowed: + kept.append(e) + else: + skipped.append(e) + clean = kept + if not clean: + raise ValueError( + "no quarantinable emails in selection " + f"(allowed statuses: {sorted(QUARANTINABLE_STATUSES)})" + ) + + out = quarantine(live, clean, reason=reason or "quarantine") + if skipped: + out["skipped_not_quarantinable"] = skipped + return out + + +# Browser-like UA: bare urllib / Python-urllib/* is blocked by Cloudflare Error 1010 +# on temp-mail Workers (edge bot signature). Keep a stable Chrome desktop string. +_CF_DOMAINS_USER_AGENT = ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/149.0.0.0 Safari/537.36" +) +# cloudflare_temp_email public settings (no address JWT). ``/api/domains`` is +# address-authed and returns 401 "Invalid address credential" without a JWT. +_CF_OPEN_SETTINGS_PATH = "/open_api/settings" + + +def _pick_list_payload(data: Any) -> list[Any]: + if isinstance(data, list): + return data + if isinstance(data, dict): + for key in ( + "results", + "hydra:member", + "data", + "domains", + "defaultDomains", + "messages", + ): + val = data.get(key) + if isinstance(val, list): + return val + nested = data.get("data") + if isinstance(nested, dict): + for key in ("results", "domains", "defaultDomains", "messages"): + val = nested.get(key) + if isinstance(val, list): + return val + return [] + + +def _one_domain_name(item: Any) -> str: + if isinstance(item, str): + name = item.strip() + elif isinstance(item, dict): + name = "" + for key in ("domain", "name", "address"): + raw = item.get(key) + if not raw: + continue + name = str(raw).strip() + break + else: + name = "" + if not name: + return "" + if "@" in name: + name = name.rsplit("@", 1)[-1].strip() + return name + + +def _normalize_domain_names(items: list[Any]) -> list[str]: + out: list[str] = [] + seen: set[str] = set() + for item in items: + name = _one_domain_name(item) + if not name: + continue + low = name.lower() + if low in seen: + continue + seen.add(low) + out.append(name) + return out + + +def _cf_get_json(url: str, headers: dict[str, str], *, timeout: float = 15) -> tuple[int, Any]: + """GET JSON; raise RuntimeError with short body on HTTP/URL failure.""" + req = Request(url, headers=headers, method="GET") + try: + with urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8", errors="replace") + status = int(getattr(resp, "status", 200) or 200) + except HTTPError as exc: + body = "" + try: + body = exc.read().decode("utf-8", errors="replace")[:200] + except Exception: + body = str(exc.reason or exc) + raise RuntimeError(f"Cloudflare domains HTTP {exc.code}: {body}") from exc + except URLError as exc: + raise RuntimeError(f"Cloudflare domains 请求失败: {exc.reason}") from exc + + try: + data = json.loads(raw) if raw else [] + except json.JSONDecodeError as exc: + raise RuntimeError("Cloudflare domains 返回非 JSON") from exc + return status, data + + +def list_cloudflare_domains(root: Path) -> dict[str, Any]: + """Fetch domain list from the configured Cloudflare temp-mail Worker. + + Uses saved ``cloudflare_api_base`` / ``cloudflare_api_key`` / + ``cloudflare_auth_mode`` / ``cloudflare_path_domains`` from config (+ .env + enrich for non-secret base). Never returns the API key. + + Always sends a browser User-Agent (CF Error 1010 otherwise). When the + configured domains path returns 401/403 (typical for cloudflare_temp_email + ``/api/domains`` without an address JWT), falls back to public + ``/open_api/settings`` which exposes ``domains`` / ``defaultDomains``. + """ + cfg = enrich_config_from_env(root, load_config(root)) + api_base = str(cfg.get("cloudflare_api_base") or os.environ.get("CLOUDFLARE_API_BASE") or "").strip().rstrip("/") + if not api_base: + raise ValueError("cloudflare_api_base 未配置(资源页 Cloudflare 面板填写后保存)") + + api_key = str(cfg.get("cloudflare_api_key") or os.environ.get("CLOUDFLARE_API_KEY") or "").strip() + mode = str( + cfg.get("cloudflare_auth_mode") + or os.environ.get("CLOUDFLARE_AUTH_MODE") + or "bearer" + ).strip().lower() or "bearer" + path = str(cfg.get("cloudflare_path_domains") or "/domains").strip() or "/domains" + if not path.startswith("/"): + path = "/" + path + + headers: dict[str, str] = { + "Accept": "application/json", + "User-Agent": _CF_DOMAINS_USER_AGENT, + } + params: dict[str, str] = {} + if api_key: + if mode == "x-api-key": + headers["X-API-Key"] = api_key + elif mode == "query-key": + params["key"] = api_key + elif mode != "none": + headers["Authorization"] = f"Bearer {api_key}" + + url = f"{api_base}{path}" + if params: + url = f"{url}?{urlencode(params)}" + + primary_err: Exception | None = None + status = 0 + data: Any = [] + used_path = path + try: + status, data = _cf_get_json(url, headers) + except RuntimeError as exc: + primary_err = exc + msg = str(exc) + # 401 address-auth / 403 edge or app deny → public open settings + if "HTTP 401" not in msg and "HTTP 403" not in msg: + raise + + domains = _normalize_domain_names(_pick_list_payload(data)) if not primary_err else [] + # Fallback: cloudflare_temp_email public settings (no JWT). + need_fallback = primary_err is not None or not domains + if need_fallback and path.rstrip("/") != _CF_OPEN_SETTINGS_PATH.rstrip("/"): + open_url = f"{api_base}{_CF_OPEN_SETTINGS_PATH}" + # Public endpoint: drop address/admin auth headers; keep UA + Accept. + open_headers = { + "Accept": "application/json", + "User-Agent": _CF_DOMAINS_USER_AGENT, + } + try: + status, data = _cf_get_json(open_url, open_headers) + domains = _normalize_domain_names(_pick_list_payload(data)) + used_path = _CF_OPEN_SETTINGS_PATH + primary_err = None + except RuntimeError as fallback_exc: + if primary_err is not None: + raise primary_err from fallback_exc + raise + + if primary_err is not None: + raise primary_err + if not domains: + raise RuntimeError( + f"Cloudflare domains 为空(path={used_path})。" + "检查 Worker 是否暴露 /open_api/settings 或配置正确的 domains 路径/凭证" + ) + + selected_raw = str(cfg.get("defaultDomains") or "") + selected = [x.strip() for x in selected_raw.replace(",", ",").split(",") if x.strip()] + return { + "ok": True, + "api_base": api_base, + "path": used_path, + "status": status, + "count": len(domains), + "domains": domains, + "selected": selected, + "has_api_key": bool(api_key), + } diff --git a/apps/control_api/nodes_ops.py b/apps/control_api/nodes_ops.py new file mode 100644 index 0000000..3e95cec --- /dev/null +++ b/apps/control_api/nodes_ops.py @@ -0,0 +1,2021 @@ +"""Node catalog + Clash leaf ops for the control plane UI.""" + +from __future__ import annotations + +import json +import os +import re +import time +from concurrent.futures import ThreadPoolExecutor, as_completed +from pathlib import Path +from typing import Any + +from register_core.nodes.catalog import load_nodes, save_nodes +from register_core.nodes.health import probe_node +from register_core.nodes.models import Node, node_from_dict + + +def catalog_path(root: Path) -> Path: + env = ( + os.environ.get("REGISTER_NODES_FILE") + or os.environ.get("NODES_FILE") + or "" + ).strip() + if env: + p = Path(os.path.expanduser(env)) + if not p.is_absolute(): + p = root / p + return p + for name in ("nodes.json", "nodes.txt", "nodes.list", "proxy_list.txt"): + p = root / name + if p.is_file(): + return p + return root / "nodes.json" + + +def _load_scores(root: Path) -> dict[str, Any]: + path = Path( + os.environ.get("NODE_SCORE_PATH") + or str(root / "output" / "node_scores.json") + ) + if not path.is_absolute(): + path = root / path + if not path.is_file(): + return {} + try: + data = json.loads(path.read_text(encoding="utf-8")) + except Exception: + return {} + nodes = data.get("nodes") if isinstance(data, dict) else None + return nodes if isinstance(nodes, dict) else {} + + +def _public_node(n: Node, scores: dict[str, Any] | None = None) -> dict[str, Any]: + d = n.to_public_dict() + d["tier"] = int(getattr(n, "tier", 0) or 0) + d["attempt_count"] = int(getattr(n, "attempt_count", 0) or 0) + d["success_count"] = int(getattr(n, "success_count", 0) or 0) + d["disallow_count"] = int(getattr(n, "disallow_count", 0) or 0) + try: + d["quality_score"] = round(float(n.quality_score()), 3) + except Exception: + d["quality_score"] = None + # score store may key by clash leaf name / label + sc = scores or {} + for key in (n.label, n.id, getattr(n, "url", "")): + if key and key in sc and isinstance(sc[key], dict): + ent = sc[key] + d["priority_score"] = ent.get("score") + d["cool_until"] = ent.get("cool_until") or ent.get("cooldown_until") + d["score_meta"] = { + k: ent.get(k) + for k in ("score", "success", "fail", "cool_until", "last_reason") + if k in ent + } + break + else: + d["priority_score"] = d.get("quality_score") + # health badge + if n.last_ok is True: + d["health"] = "ok" + elif n.last_ok is False: + d["health"] = "fail" + else: + d["health"] = "unknown" + return d + + +def list_catalog( + root: Path, + *, + q: str = "", + health: str = "", + tier: str | int | None = None, + enabled: str | bool | None = None, + page: int = 1, + page_size: int = 50, + sort: str = "priority", +) -> dict[str, Any]: + """List catalog nodes with optional filter/pagination. + + Without filters page defaults still return a page slice so UIs don't + render 5k rows at once. Pass page_size<=0 to get the full list (tests). + """ + path = catalog_path(root) + nodes = load_nodes(path) + scores = _load_scores(root) + public = [_public_node(n, scores) for n in nodes] + ok_n = sum(1 for n in nodes if n.last_ok is True and n.enabled) + en_n = sum(1 for n in nodes if n.enabled) + fail_n = sum(1 for n in nodes if n.last_ok is False) + unknown_n = sum(1 for n in nodes if n.last_ok is None) + + filtered = public + q_norm = (q or "").strip().lower() + if q_norm: + filtered = [ + n + for n in filtered + if q_norm in (n.get("label") or "").lower() + or q_norm in (n.get("id") or "").lower() + or q_norm in " ".join(n.get("tags") or []).lower() + or q_norm in (n.get("last_ip") or "").lower() + ] + h = (health or "").strip().lower() + if h in {"ok", "fail", "unknown"}: + filtered = [n for n in filtered if (n.get("health") or "unknown") == h] + if tier is not None and str(tier).strip() != "": + try: + t = int(tier) + filtered = [n for n in filtered if int(n.get("tier") or 0) == t] + except (TypeError, ValueError): + pass + if enabled is not None and str(enabled).strip() != "": + want = str(enabled).strip().lower() in {"1", "true", "yes", "on"} + filtered = [n for n in filtered if bool(n.get("enabled")) is want] + + sort_key = (sort or "priority").strip().lower() + if sort_key == "ms": + filtered = sorted( + filtered, + key=lambda n: ( + n.get("last_ms") is None, + n.get("last_ms") if n.get("last_ms") is not None else 10**9, + ), + ) + elif sort_key == "label": + filtered = sorted(filtered, key=lambda n: (n.get("label") or n.get("id") or "").lower()) + else: + # priority: healthy first, then higher score, then lower latency + def _prio(n: dict[str, Any]) -> tuple: + health_rank = {"ok": 0, "unknown": 1, "fail": 2}.get(n.get("health") or "unknown", 1) + score = n.get("priority_score") + try: + score_v = -float(score) if score is not None else 0.0 + except (TypeError, ValueError): + score_v = 0.0 + ms = n.get("last_ms") + ms_v = int(ms) if isinstance(ms, (int, float)) else 10**9 + return (health_rank, score_v, ms_v, (n.get("label") or "")) + + filtered = sorted(filtered, key=_prio) + + total_filtered = len(filtered) + try: + page_i = max(1, int(page or 1)) + except (TypeError, ValueError): + page_i = 1 + try: + size_i = int(page_size if page_size is not None else 50) + except (TypeError, ValueError): + size_i = 50 + if size_i <= 0: + page_nodes = filtered + pages = 1 if total_filtered else 0 + page_i = 1 + size_i = total_filtered or 0 + else: + size_i = min(max(size_i, 1), 500) + pages = max(1, (total_filtered + size_i - 1) // size_i) if total_filtered else 0 + if pages and page_i > pages: + page_i = pages + start = (page_i - 1) * size_i + page_nodes = filtered[start : start + size_i] + + return { + "path": str(path), + "exists": path.is_file(), + "total": len(nodes), + "enabled": en_n, + "healthy": ok_n, + "fail": fail_n, + "unknown": unknown_n, + "filtered": total_filtered, + "page": page_i, + "page_size": size_i, + "pages": pages, + "nodes": page_nodes, + } + + +def add_catalog_node( + root: Path, + *, + url: str, + label: str = "", + tags: list[str] | None = None, + tier: int = 0, + enabled: bool = True, +) -> dict[str, Any]: + url = (url or "").strip() + if not url: + raise ValueError("url required") + path = catalog_path(root) + nodes = load_nodes(path) + if any(n.url == url for n in nodes): + return {"ok": False, "error": "duplicate", "path": str(path)} + node = Node( + url=url, + label=label or "", + tags=list(tags or []), + tier=int(tier or 0), + enabled=bool(enabled), + ) + nodes.append(node) + save_nodes(nodes, path) + return {"ok": True, "path": str(path), "node": _public_node(node)} + + +def delete_catalog_node(root: Path, node_id: str) -> dict[str, Any]: + node_id = (node_id or "").strip() + if not node_id: + raise ValueError("id required") + path = catalog_path(root) + nodes = load_nodes(path) + before = len(nodes) + kept = [n for n in nodes if n.id != node_id and n.label != node_id] + # also allow delete by exact url match id confusion + if len(kept) == before: + kept = [n for n in nodes if n.url != node_id] + if len(kept) == before: + return {"ok": False, "error": "not_found", "id": node_id, "path": str(path)} + save_nodes(kept, path) + return {"ok": True, "removed": before - len(kept), "path": str(path), "total": len(kept)} + + +def set_catalog_enabled(root: Path, node_id: str, enabled: bool) -> dict[str, Any]: + path = catalog_path(root) + nodes = load_nodes(path) + hit = None + for n in nodes: + if n.id == node_id or n.label == node_id: + n.enabled = bool(enabled) + hit = n + break + if hit is None: + return {"ok": False, "error": "not_found", "id": node_id} + save_nodes(nodes, path) + return {"ok": True, "node": _public_node(hit)} + + +def test_catalog_nodes( + root: Path, + *, + ids: list[str] | None = None, + timeout: float = 12.0, + limit: int = 50, +) -> dict[str, Any]: + path = catalog_path(root) + nodes = load_nodes(path) + if ids: + idset = set(ids) + targets = [n for n in nodes if n.id in idset or n.label in idset] + else: + targets = [n for n in nodes if n.enabled][: max(1, int(limit))] + results: list[dict[str, Any]] = [] + for n in targets: + results.append(probe_node(n, timeout=float(timeout))) + # persist health stamps + try: + save_nodes(nodes, path) + except Exception: + pass + ok_n = sum(1 for r in results if r.get("ok")) + return { + "ok": ok_n > 0 or not results, + "tested": len(results), + "healthy": ok_n, + "results": results, + "path": str(path), + } + + +# ── Clash / mihomo controller leaves ────────────────────────────────────── + +_GROUP_TYPES = { + "Selector", + "URLTest", + "Fallback", + "LoadBalance", + "Relay", + "Direct", + "Reject", + "Compatible", + "Pass", + "PassRule", + "RejectDrop", +} + +REGISTER_GROUPS = ("🎯Grok注册", "♻️Grok优选", "PROXY", "🔰ChatGPT", "GROK-REG") + + +def _clash_api() -> str: + return (os.environ.get("CLASH_API") or "http://127.0.0.1:9090").rstrip("/") + + +def _clash_secret(root: Path) -> str: + env = (os.environ.get("CLASH_SECRET") or "").strip() + if env: + return env + clash_dir = Path(os.environ.get("CLASH_DIR") or "/personal/clash") + for cand in ( + clash_dir / ".controller-secret", + root / ".clash_secret", + Path("/personal/clash/.controller-secret"), + ): + if cand.is_file(): + s = cand.read_text(encoding="utf-8").strip() + if s: + return s + cfg = Path(os.environ.get("CLASH_CONFIG") or (clash_dir / "config.yaml")) + if cfg.is_file(): + text = cfg.read_text(encoding="utf-8", errors="replace") + m = re.search(r'^secret:\s*["\']?([^"\'\n]+)', text, re.M) + if m and m.group(1).strip(): + return m.group(1).strip() + return "" + + +def _clash_request( + path: str, + *, + secret: str, + method: str = "GET", + body: dict | None = None, + timeout: float = 8.0, +) -> Any: + import urllib.error + import urllib.request + + url = f"{_clash_api()}{path}" + data = None + headers = {"Content-Type": "application/json"} + if secret: + headers["Authorization"] = f"Bearer {secret}" + if body is not None: + data = json.dumps(body).encode() + req = urllib.request.Request(url, data=data, headers=headers, method=method) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8", errors="replace") + if not raw: + return {} + return json.loads(raw) + except urllib.error.HTTPError as e: + try: + detail = e.read().decode("utf-8", errors="replace")[:300] + except Exception: + detail = str(e) + raise RuntimeError(f"clash HTTP {e.code}: {detail}") from e + except Exception as e: + raise RuntimeError(f"clash unreachable: {type(e).__name__}: {e}") from e + + +def list_clash_nodes(root: Path) -> dict[str, Any]: + secret = _clash_secret(root) + try: + data = _clash_request("/proxies", secret=secret) + except Exception as e: + return { + "ok": False, + "error": str(e), + "api": _clash_api(), + "leaves": [], + "groups": [], + } + proxies = data.get("proxies") if isinstance(data, dict) else {} + if not isinstance(proxies, dict): + return {"ok": False, "error": "bad proxies map", "leaves": [], "groups": []} + + scores = _load_scores(root) + leaves: list[dict[str, Any]] = [] + groups: list[dict[str, Any]] = [] + for name, info in proxies.items(): + if not isinstance(info, dict): + continue + t = str(info.get("type") or "") + if t in _GROUP_TYPES: + all_names = list(info.get("all") or []) + groups.append( + { + "name": name, + "type": t, + "now": info.get("now") or "", + "count": len(all_names), + "register_relevant": name in REGISTER_GROUPS + or "Grok" in name + or "GROK" in name + or name in {"PROXY"}, + } + ) + continue + if name in ("DIRECT", "REJECT", "PASS", "COMPATIBLE"): + continue + hist = info.get("history") or [] + last_delay = None + last_ok = None + if isinstance(hist, list) and hist: + last = hist[-1] if isinstance(hist[-1], dict) else {} + d = last.get("delay") + if isinstance(d, int): + last_delay = d + last_ok = d > 0 + sc = scores.get(name) if isinstance(scores.get(name), dict) else {} + leaves.append( + { + "name": name, + "type": t, + "udp": bool(info.get("udp")), + "last_delay_ms": last_delay, + "last_ok": last_ok, + "health": "ok" if last_ok is True else ("fail" if last_ok is False else "unknown"), + "priority_score": sc.get("score"), + "cool_until": sc.get("cool_until") or sc.get("cooldown_until"), + "score_meta": sc or None, + } + ) + + # mark membership in register groups + group_members: dict[str, set[str]] = {} + for g in groups: + info = proxies.get(g["name"]) or {} + group_members[g["name"]] = set(info.get("all") or []) + for leaf in leaves: + mem = [g for g, members in group_members.items() if leaf["name"] in members] + leaf["groups"] = mem + leaf["in_register_pool"] = any( + g in REGISTER_GROUPS or "Grok" in g or "GROK" in g for g in mem + ) + + leaves.sort(key=lambda x: (0 if x.get("in_register_pool") else 1, x["name"])) + groups.sort(key=lambda x: (0 if x.get("register_relevant") else 1, x["name"])) + return { + "ok": True, + "api": _clash_api(), + "secret_configured": bool(secret), + "leaf_count": len(leaves), + "group_count": len(groups), + "leaves": leaves, + "groups": groups, + "register_groups": list(REGISTER_GROUPS), + } + + +def test_clash_nodes( + root: Path, + *, + names: list[str] | None = None, + timeout_ms: int = 5000, + limit: int = 40, + url: str = "http://www.gstatic.com/generate_204", + workers: int = 24, +) -> dict[str, Any]: + """Delay-test Clash leaves. + + Probes run in a small thread pool — serial tests of 100+ nodes easily exceed + Cloudflare's ~100s origin timeout (HTTP 524) when the console is proxied. + """ + import urllib.parse + + secret = _clash_secret(root) + listing = list_clash_nodes(root) + if not listing.get("ok"): + return listing + if names: + targets = list(names) + else: + # Prefer register-pool leaves, then others + leaves = listing.get("leaves") or [] + pool = [x["name"] for x in leaves if x.get("in_register_pool")] + rest = [x["name"] for x in leaves if not x.get("in_register_pool")] + targets = (pool + rest)[: max(1, int(limit))] + + req_timeout = max(3.0, float(timeout_ms) / 1000.0 + 2.0) + t_all = time.time() + + def _one(name: str) -> dict[str, Any]: + q = urllib.parse.urlencode({"timeout": int(timeout_ms), "url": url}) + path = f"/proxies/{urllib.parse.quote(name, safe='')}/delay?{q}" + t0 = time.time() + try: + data = _clash_request(path, secret=secret, timeout=req_timeout) + delay = data.get("delay") if isinstance(data, dict) else None + ok = isinstance(delay, int) and delay > 0 + return { + "name": name, + "ok": ok, + "delay_ms": delay if ok else None, + "error": "" if ok else f"no_delay:{data!r}"[:160], + "ms": int((time.time() - t0) * 1000), + } + except Exception as e: + return { + "name": name, + "ok": False, + "delay_ms": None, + "error": str(e)[:160], + "ms": int((time.time() - t0) * 1000), + } + + results: list[dict[str, Any]] = [] + if not targets: + results = [] + elif len(targets) == 1: + results = [_one(targets[0])] + else: + n_workers = max(1, min(int(workers) if workers else 24, len(targets), 32)) + by_name: dict[str, dict[str, Any]] = {} + with ThreadPoolExecutor(max_workers=n_workers) as ex: + futs = {ex.submit(_one, n): n for n in targets} + for fut in as_completed(futs): + r = fut.result() + by_name[str(r.get("name") or "")] = r + # preserve request order for stable UI / tests + results = [by_name[n] for n in targets if n in by_name] + + ok_n = sum(1 for r in results if r.get("ok")) + return { + "ok": True, + "tested": len(results), + "healthy": ok_n, + "results": results, + "api": _clash_api(), + "workers": min(int(workers) if workers else 24, max(1, len(targets)), 32) if targets else 0, + "ms": int((time.time() - t_all) * 1000), + } + + +# ── Clash subscription URL → selected pool ─────────────────────────────────── + +# Groups the UI may target for subscription import (register-relevant first). +IMPORTABLE_GROUPS = ( + "🎯Grok注册", + "♻️Grok优选", + "PROXY", + "🔰ChatGPT", + "GROK-REG", +) + +_META_NAME_MARKERS = ( + "剩余流量", + "距离下次", + "套餐到期", + "官网", + "到期", + "流量", + "重置", + "订阅", + "expire", + "traffic", + "reset", + "website", + "官网地址", + # Airport "error as fake node" banners (良心云 / 常见机场超限文案) + "设备数量", + "在线设备", + "超过套餐", + "允许值", + "重新导入", + "新订阅", + "获取新订阅", + "复制新订阅", + "请更新", + "请重新", + "套餐不允许", + "无可用节点", + "节点已用尽", + "连接数", + "device limit", + "too many", + "renew", + "outdated", +) + +# Dummy endpoints airports inject when the token is invalid / over device quota. +_PLACEHOLDER_SERVERS = frozenset( + { + "127.0.0.1", + "localhost", + "::1", + "0.0.0.0", + "10.0.0.0", + "10.0.0.1", + "192.168.0.1", + "example.com", + "www.example.com", + "invalid", + "null", + "none", + } +) +_PLACEHOLDER_PORTS = frozenset({0, 65535}) + + +class SubscriptionFilterError(RuntimeError): + """Raised when a subscription parses but yields zero importable proxies. + + ``code`` is a stable machine token for the UI; ``message`` is human-readable + (Chinese) and is safe to show in the console toast. + """ + + def __init__(self, code: str, message: str, info: dict[str, Any] | None = None): + super().__init__(message) + self.code = (code or "no_importable_proxies").strip() or "no_importable_proxies" + self.message = (message or "").strip() or str(self) + self.info: dict[str, Any] = dict(info or {}) + + +def _clash_dir() -> Path: + return Path(os.environ.get("CLASH_DIR") or "/personal/clash") + + +def clash_config_paths() -> list[Path]: + """Configs that should receive imported proxies. + + Default write set is live config + mac-merged source only (fast path). + Set CLASH_IMPORT_ALL_CONFIGS=1 to also touch mac-sync / grok-register mirrors. + """ + clash_dir = _clash_dir() + env_cfg = (os.environ.get("CLASH_CONFIG") or "").strip() + env_merged = (os.environ.get("CLASH_MERGED") or "").strip() + all_cfgs = (os.environ.get("CLASH_IMPORT_ALL_CONFIGS") or "").strip().lower() in { + "1", + "true", + "yes", + "on", + } + cands: list[Path] = [] + if env_cfg: + cands.append(Path(env_cfg)) + if env_merged: + cands.append(Path(env_merged)) + names = ["config.yaml", "config.mac-merged.yaml"] + if all_cfgs: + names.extend(["config.mac-sync.yaml", "config.grok-register.yaml"]) + for name in names: + cands.append(clash_dir / name) + out: list[Path] = [] + seen: set[str] = set() + for p in cands: + try: + key = str(p.resolve()) if p.exists() else str(p) + except Exception: + key = str(p) + if key in seen: + continue + seen.add(key) + if p.is_file(): + out.append(p) + return out + + +def _require_yaml(): + try: + import yaml # type: ignore + except ImportError as exc: # pragma: no cover + raise RuntimeError("PyYAML required for Clash subscription import") from exc + return yaml + + +def _is_meta_proxy_name(name: str) -> bool: + n = (name or "").strip().lower() + if not n: + return True + for m in _META_NAME_MARKERS: + if m.lower() in n: + return True + return False + + +def _proxy_port(proxy: dict[str, Any]) -> int | None: + raw = proxy.get("port") + if raw is None or raw is False: + return None + try: + return int(raw) + except Exception: + return None + + +def _is_placeholder_server(server: str) -> bool: + s = (server or "").strip().lower().rstrip(".") + if not s: + return True + if s in _PLACEHOLDER_SERVERS: + return True + # bracketed IPv6 loopback + if s in {"[::1]", "[0:0:0:0:0:0:0:1]"}: + return True + return False + + +def _is_placeholder_proxy(proxy: dict[str, Any]) -> tuple[bool, str]: + """Return (is_placeholder, reason). + + Airports (e.g. 良心云) often ship a Clash YAML whose only ``proxies`` are + fake SS rows pointing at 127.0.0.1:65535 with names like + 「在线设备数量超过套餐允许值!」. Those must never enter the register pool. + """ + if not isinstance(proxy, dict): + return True, "not_dict" + name = str(proxy.get("name") or "").strip() + if _is_meta_proxy_name(name): + return True, "meta_name" + server = str(proxy.get("server") or "").strip() + port = _proxy_port(proxy) + loopback = _is_placeholder_server(server) + if loopback and (port is None or port in _PLACEHOLDER_PORTS or port <= 0): + return True, "loopback_dummy" + if loopback: + # Any loopback server is unusable as an egress leaf for registration. + return True, "loopback_server" + if port is not None and port in _PLACEHOLDER_PORTS: + # 0 / 65535 on a public host is almost always an airport banner node. + return True, "dummy_port" + # No type / no server already rejected by normalizer; keep reason explicit. + ptype = str(proxy.get("type") or "").strip().lower() + if not ptype or not server: + return True, "missing_type_or_server" + return False, "" + + +def _classify_fetch_error(exc: BaseException) -> tuple[str, str]: + """Map raw fetch exceptions → (error_code, human message).""" + text = str(exc) if exc is not None else "" + low = text.lower() + raw_body = "" + # fetch HTTP 400: b'No nodes were found!' + if "no nodes were found" in low: + return ( + "subscription_empty", + "订阅源返回空节点(No nodes were found)。常见原因:链接失效、" + "在线设备超限、套餐到期,或需要在机场后台生成新订阅链接。", + ) + if "http 403" in low or "http 401" in low: + return ( + "subscription_forbidden", + f"订阅源拒绝访问(鉴权失败/被墙):{text[:180]}", + ) + if "http 404" in low: + return ( + "subscription_not_found", + f"订阅链接不存在(HTTP 404):请核对 URL 是否完整。", + ) + if "http 4" in low or "http 5" in low: + # Keep status in message; body snippet often carries the airport reason. + m = re.search(r"fetch HTTP (\d+):\s*(.*)$", text) + if m: + code, body = m.group(1), m.group(2).strip() + raw_body = body[:120] + return ( + "subscription_http_error", + f"订阅源 HTTP {code}" + (f":{raw_body}" if raw_body else ""), + ) + return ("fetch_failed", text[:300]) + return ("fetch_failed", text[:300] or "fetch failed") + + +def _sanitize_proxy_name(name: str, *, prefix: str, used: set[str], idx: int) -> str: + base = re.sub(r"\s+", " ", (name or "").strip()) + base = base.replace("\n", " ").replace("\r", "") + if not base: + base = f"node-{idx}" + if prefix: + # avoid double-prefix + if not base.startswith(f"{prefix}-") and not base.startswith(prefix): + base = f"{prefix}-{base}" + # clash name practical limit + if len(base) > 64: + base = base[:64].rstrip() + candidate = base + n = 2 + while candidate in used: + suffix = f"#{n}" + candidate = (base[: max(1, 64 - len(suffix))] + suffix) + n += 1 + used.add(candidate) + return candidate + + +def _normalize_imported_proxy( + proxy: dict[str, Any], + *, + prefix: str, + used_names: set[str], + idx: int, +) -> dict[str, Any] | None: + if not isinstance(proxy, dict): + return None + name = str(proxy.get("name") or "").strip() + ptype = str(proxy.get("type") or "").strip().lower() + server = str(proxy.get("server") or "").strip() + if not ptype or not server: + return None + is_ph, _reason = _is_placeholder_proxy(proxy) + if is_ph: + return None + out = dict(proxy) + out["name"] = _sanitize_proxy_name(name or f"{ptype}-{server}", prefix=prefix, used=used_names, idx=idx) + out["type"] = ptype + return out + + +def _clash_mixed_proxy_url() -> str | None: + """HTTP proxy URL for mihomo mixed-port (default 127.0.0.1:7897).""" + raw = (os.environ.get("CLASH_MIXED_PROXY") or "").strip() + if raw: + return raw + host = (os.environ.get("CLASH_MIXED_HOST") or "127.0.0.1").strip() or "127.0.0.1" + port = (os.environ.get("CLASH_MIXED_PORT") or os.environ.get("MIXED_PORT") or "7897").strip() + try: + p = int(port) + except Exception: + p = 7897 + if p <= 0: + return None + return f"http://{host}:{p}" + + +def fetch_subscription_body(url: str, *, timeout: float = 25.0) -> tuple[str, dict[str, Any]]: + """Fetch subscription URL; return (text, meta). Raises RuntimeError on hard fail. + + Attempts (proxy-first — pxed airport hosts usually need Clash egress): + 1) Clash mixed-port proxy + 2) proxy + unverified SSL (incomplete airport chains) + 3) short direct HTTPS (fallback only; avoids 20s hang when direct is dead) + 4) short direct + unverified SSL + + Each attempt records ms in meta.attempts for ops timing. + """ + import ssl + import urllib.error + import urllib.request + + u = (url or "").strip() + if not u.startswith(("http://", "https://")): + raise RuntimeError("url must start with http:// or https://") + headers = { + "User-Agent": "ClashMeta/1.18 (grok-register control plane)", + "Accept": "*/*", + } + req = urllib.request.Request(u, headers=headers, method="GET") + proxy_url = _clash_mixed_proxy_url() + # Prefer proxy path; keep direct short so a dead WAN doesn't burn ~20s twice. + total_timeout = max(5.0, float(timeout)) + proxy_timeout = min(total_timeout, 15.0) + direct_timeout = min(3.0, total_timeout) + attempts: list[tuple[str, Any, Any, float]] = [] + if proxy_url: + attempts.append(("proxy", proxy_url, None, proxy_timeout)) + attempts.append( + ("proxy_insecure", proxy_url, ssl._create_unverified_context(), proxy_timeout) + ) + attempts.append(("direct", None, None, direct_timeout)) + attempts.append( + ("direct_insecure", None, ssl._create_unverified_context(), direct_timeout) + ) + + last_err: Exception | None = None + used_via = "direct" + ssl_insecure = False + raw = b"" + ctype = "" + status = 0 + userinfo = "" + attempt_log: list[dict[str, Any]] = [] + t_fetch0 = time.time() + + for via, proxy, ctx, to in attempts: + t_a = time.time() + try: + handlers: list[Any] = [] + if proxy: + handlers.append( + urllib.request.ProxyHandler({"http": proxy, "https": proxy}) + ) + if ctx is not None: + handlers.append(urllib.request.HTTPSHandler(context=ctx)) + if handlers: + opener = urllib.request.build_opener(*handlers) + resp_cm = opener.open(req, timeout=float(to)) + else: + resp_cm = urllib.request.urlopen(req, timeout=float(to)) + with resp_cm as resp: + raw = resp.read() + ctype = (resp.headers.get("Content-Type") or "").split(";")[0].strip() + status = getattr(resp, "status", 200) or 200 + userinfo = resp.headers.get("subscription-userinfo") or "" + used_via = via + ssl_insecure = "insecure" in via + last_err = None + attempt_log.append( + { + "via": via, + "ok": True, + "ms": int((time.time() - t_a) * 1000), + "timeout": to, + "bytes": len(raw), + } + ) + break + except urllib.error.HTTPError as e: + # HTTP error still means we reached the host; surface immediately + try: + detail = e.read()[:200] + except Exception: + detail = b"" + attempt_log.append( + { + "via": via, + "ok": False, + "ms": int((time.time() - t_a) * 1000), + "timeout": to, + "error": f"HTTP {e.code}", + } + ) + raise RuntimeError(f"fetch HTTP {e.code}: {detail!r}") from e + except Exception as e: + last_err = e + attempt_log.append( + { + "via": via, + "ok": False, + "ms": int((time.time() - t_a) * 1000), + "timeout": to, + "error": f"{type(e).__name__}: {e}"[:160], + } + ) + continue + + if last_err is not None: + raise RuntimeError(f"fetch failed: {type(last_err).__name__}: {last_err}") from last_err + + # try utf-8 then latin-1 fallback for opaque base64 bodies + try: + text = raw.decode("utf-8") + except UnicodeDecodeError: + text = raw.decode("latin-1", errors="replace") + meta = { + "http_status": int(status), + "content_type": ctype, + "bytes": len(raw), + "subscription_userinfo": userinfo, + "ssl_insecure": ssl_insecure, + "via": used_via, + "proxy": proxy_url if used_via.startswith("proxy") else None, + "ms": int((time.time() - t_fetch0) * 1000), + "attempts": attempt_log, + } + return text, meta + + +def parse_subscription_proxies( + body: str, + *, + source: str = "", + prefix: str = "SUB", +) -> tuple[list[dict[str, Any]], dict[str, Any]]: + """Parse subscription body → clash proxy dicts (meta/placeholder rows dropped). + + Raises: + RuntimeError: underlying format parse failure. + SubscriptionFilterError: body parsed but every row was meta/placeholder/bad. + ``code`` is ``subscription_placeholder_only`` when at least one row looked + like an airport banner node; otherwise ``no_importable_proxies``. + """ + from register_core.nodes.convert.parsers import ParseError, decode_subscription_text, parse_text + + decoded, was_b64 = decode_subscription_text(body) + try: + fmt, raw_proxies = parse_text(decoded if decoded else body, source=source or "subscription") + except ParseError as e: + raise RuntimeError(f"parse failed ({e.format}): {e}") from e + + used: set[str] = set() + cleaned: list[dict[str, Any]] = [] + skipped_meta = 0 + skipped_placeholder = 0 + skipped_bad = 0 + dropped_names: list[str] = [] + drop_reasons: dict[str, int] = {} + for i, p in enumerate(raw_proxies): + if not isinstance(p, dict): + skipped_bad += 1 + drop_reasons["not_dict"] = drop_reasons.get("not_dict", 0) + 1 + continue + raw_name = str(p.get("name") or "").strip() or f"#{i + 1}" + is_ph, reason = _is_placeholder_proxy(p) + if is_ph: + if reason == "meta_name": + skipped_meta += 1 + else: + skipped_placeholder += 1 + drop_reasons[reason or "placeholder"] = drop_reasons.get(reason or "placeholder", 0) + 1 + if len(dropped_names) < 12: + dropped_names.append(raw_name[:64]) + continue + norm = _normalize_imported_proxy(p, prefix=prefix, used_names=used, idx=i + 1) + if norm is None: + skipped_bad += 1 + drop_reasons["normalize_reject"] = drop_reasons.get("normalize_reject", 0) + 1 + if len(dropped_names) < 12: + dropped_names.append(raw_name[:64]) + continue + cleaned.append(norm) + info = { + "format": fmt, + "base64": was_b64, + "parsed_raw": len(raw_proxies), + "imported": len(cleaned), + "skipped_meta": skipped_meta, + "skipped_placeholder": skipped_placeholder, + "skipped_bad": skipped_bad, + "drop_reasons": drop_reasons, + "dropped_names": dropped_names, + "sample_names": [p["name"] for p in cleaned[:8]], + } + if not cleaned: + names_txt = "、".join(dropped_names[:6]) if dropped_names else "(无名称)" + placeholderish = skipped_meta + skipped_placeholder + if placeholderish > 0 and placeholderish >= max(1, len(raw_proxies) - skipped_bad): + raise SubscriptionFilterError( + "subscription_placeholder_only", + "订阅无真实节点,全是机场占位/提示节点(常见:在线设备超限、" + f"订阅过期、需换新链接)。原始节点:{names_txt}", + info, + ) + raise SubscriptionFilterError( + "no_importable_proxies", + "订阅解析后无可用代理" + f"(raw={len(raw_proxies)} meta={skipped_meta} " + f"placeholder={skipped_placeholder} bad={skipped_bad} format={fmt})。" + f"原始节点:{names_txt}", + info, + ) + return cleaned, info + + +def _backup_and_dump_yaml(cfg_path: Path, text: str, data: dict, header_note: str) -> Path: + yaml = _require_yaml() + ts = time.strftime("%Y%m%d-%H%M%S", time.gmtime()) + bak = cfg_path.with_suffix(cfg_path.suffix + f".pre-subimport-{ts}") + bak.write_text(text, encoding="utf-8") + + class NoAliasDumper(yaml.SafeDumper): + def ignore_aliases(self, data): # type: ignore[no-untyped-def] + return True + + header = "" + if text.lstrip().startswith("#"): + lines = text.splitlines(keepends=True) + buf: list[str] = [] + for ln in lines: + if ln.startswith("#") or ln.strip() == "": + buf.append(ln) + if len(buf) > 24: + break + else: + break + header = "".join(buf) + if header and not header.endswith("\n"): + header += "\n" + header += f"# {header_note}\n" + + body = yaml.dump( + data, + Dumper=NoAliasDumper, + allow_unicode=True, + sort_keys=False, + width=120, + default_flow_style=False, + ) + cfg_path.write_text(header + body, encoding="utf-8") + return bak + + +def merge_proxies_into_clash_config( + cfg_path: Path, + proxies: list[dict[str, Any]], + *, + groups: list[str], + mode: str = "merge", + prefix: str = "SUB", +) -> dict[str, Any]: + """Merge proxies into one clash yaml; update selected group leaf lists. + + mode: + - merge: add/replace by name; append missing names into selected groups + - replace_prefix: drop existing proxies whose name starts with ``prefix-`` + then merge (useful for re-import of same airport) + """ + yaml = _require_yaml() + if not cfg_path.is_file(): + return {"ok": False, "path": str(cfg_path), "error": "config_not_found"} + text = cfg_path.read_text(encoding="utf-8", errors="replace") + try: + data = yaml.safe_load(text) + except Exception as e: + return {"ok": False, "path": str(cfg_path), "error": f"yaml_load: {e}"} + if not isinstance(data, dict): + return {"ok": False, "path": str(cfg_path), "error": "yaml_root_not_mapping"} + + existing = data.get("proxies") + if existing is None: + existing = [] + data["proxies"] = existing + if not isinstance(existing, list): + return {"ok": False, "path": str(cfg_path), "error": "proxies_not_list"} + + mode_n = (mode or "merge").strip().lower() + pref = (prefix or "").strip() + removed_prefix = 0 + if mode_n == "replace_prefix" and pref: + kept = [] + for p in existing: + if isinstance(p, dict) and str(p.get("name") or "").startswith(f"{pref}-"): + removed_prefix += 1 + continue + kept.append(p) + existing = kept + data["proxies"] = existing + + by_name: dict[str, int] = {} + for i, p in enumerate(existing): + if isinstance(p, dict) and p.get("name"): + by_name[str(p["name"])] = i + + added = 0 + replaced = 0 + new_names: list[str] = [] + for p in proxies: + name = str(p.get("name") or "") + if not name: + continue + new_names.append(name) + if name in by_name: + existing[by_name[name]] = p + replaced += 1 + else: + by_name[name] = len(existing) + existing.append(p) + added += 1 + + # update groups + want_groups = [g for g in (groups or []) if str(g).strip()] + group_updates: list[dict[str, Any]] = [] + pgroups = data.get("proxy-groups") or [] + if not isinstance(pgroups, list): + pgroups = [] + data["proxy-groups"] = pgroups + existing_group_names = { + str(g.get("name")) for g in pgroups if isinstance(g, dict) and g.get("name") + } + for gname in want_groups: + g = next((x for x in pgroups if isinstance(x, dict) and x.get("name") == gname), None) + if g is None: + # create selector group if missing + g = {"name": gname, "type": "select", "proxies": list(new_names) or ["DIRECT"]} + pgroups.append(g) + group_updates.append( + {"name": gname, "created": True, "before": 0, "after": len(g["proxies"])} + ) + continue + old = list(g.get("proxies") or []) + # keep order: existing first, then append new names not present + seen = set(old) + merged = list(old) + for n in new_names: + if n not in seen: + merged.append(n) + seen.add(n) + # for replace_prefix also strip old prefix members not re-imported + if mode_n == "replace_prefix" and pref: + keep_new = set(new_names) + merged = [ + n + for n in merged + if not (isinstance(n, str) and n.startswith(f"{pref}-") and n not in keep_new) + ] + # ensure all new names present + for n in new_names: + if n not in merged: + merged.append(n) + if not merged: + merged = ["DIRECT"] + g["proxies"] = merged + group_updates.append( + { + "name": gname, + "created": False, + "before": len(old), + "after": len(merged), + } + ) + + ts = time.strftime("%Y%m%d-%H%M%S", time.gmtime()) + note = ( + f"sub-import {ts} added={added} replaced={replaced} " + f"removed_prefix={removed_prefix} groups={','.join(want_groups) or '-'}" + ) + bak = _backup_and_dump_yaml(cfg_path, text, data, note) + return { + "ok": True, + "path": str(cfg_path), + "backup": str(bak), + "proxies_before": len(by_name) - added, # approximate + "proxies_after": len(existing), + "added": added, + "replaced": replaced, + "removed_prefix": removed_prefix, + "group_updates": group_updates, + "existing_groups": sorted(existing_group_names), + } + + +def _reload_clash_config(root: Path, cfg_path: Path) -> dict[str, Any]: + """Ask mihomo to reload config file (PUT /configs?force=true).""" + import urllib.parse + + secret = _clash_secret(root) + # mihomo expects {"path": "..."}; force re-read + path_q = urllib.parse.urlencode({"force": "true"}) + try: + _clash_request( + f"/configs?{path_q}", + secret=secret, + method="PUT", + body={"path": str(cfg_path)}, + timeout=20.0, + ) + return {"ok": True, "reloaded": True, "path": str(cfg_path)} + except Exception as e: + return {"ok": False, "reloaded": False, "path": str(cfg_path), "error": str(e)[:240]} + + +def import_clash_subscription( + root: Path, + *, + url: str, + group: str = "🎯Grok注册", + groups: list[str] | None = None, + prefix: str = "SUB", + mode: str = "merge", + dry_run: bool = False, + reload: bool = True, + timeout: float = 25.0, + max_proxies: int = 400, + include_listing: bool = False, +) -> dict[str, Any]: + """Fetch subscription URL, parse nodes, merge into clash config + selected pool. + + Returns structured ok/fail feedback for the console UI. Stage timings land in + ``timings`` and ops logs so hung imports are diagnosable. + """ + t0 = time.time() + timings: dict[str, int] = {} + group_n = (group or "").strip() or "🎯Grok注册" + target_groups = list(groups) if groups else [group_n] + target_groups = [g.strip() for g in target_groups if str(g).strip()] + if not target_groups: + target_groups = ["🎯Grok注册"] + pref = (prefix or "SUB").strip() or "SUB" + mode_n = (mode or "merge").strip().lower() + if mode_n not in {"merge", "replace_prefix"}: + return { + "ok": False, + "error": "invalid_mode", + "detail": "mode must be merge|replace_prefix", + "timings": timings, + "ms": int((time.time() - t0) * 1000), + } + + # 1) fetch + t_stage = time.time() + try: + body, fetch_meta = fetch_subscription_body(url, timeout=timeout) + except Exception as e: + timings["fetch_ms"] = int((time.time() - t_stage) * 1000) + timings["total_ms"] = int((time.time() - t0) * 1000) + print( + f"[control_api] clash-import FAIL stage=fetch ms={timings['fetch_ms']} " + f"err={type(e).__name__}: {str(e)[:160]}", + flush=True, + ) + return { + "ok": False, + "stage": "fetch", + "error": "fetch_failed", + "detail": str(e)[:300], + "url": (url or "")[:200], + "timings": timings, + "ms": timings["total_ms"], + } + timings["fetch_ms"] = int((time.time() - t_stage) * 1000) + print( + f"[control_api] clash-import fetch via={fetch_meta.get('via')} " + f"bytes={fetch_meta.get('bytes')} ms={timings['fetch_ms']}", + flush=True, + ) + + # 2) parse + t_stage = time.time() + try: + proxies, parse_info = parse_subscription_proxies(body, source=url, prefix=pref) + except Exception as e: + timings["parse_ms"] = int((time.time() - t_stage) * 1000) + timings["total_ms"] = int((time.time() - t0) * 1000) + print( + f"[control_api] clash-import FAIL stage=parse ms={timings['parse_ms']} " + f"err={type(e).__name__}: {str(e)[:160]}", + flush=True, + ) + # A SubscriptionFilterError carries a stable machine code + a + # human-readable Chinese message; surface the code so the UI can branch + # its toast (e.g. subscription_placeholder_only → "需换订阅链接") + # instead of the generic parse_failed. + if isinstance(e, SubscriptionFilterError): + return { + "ok": False, + "stage": "parse", + "error": e.code, + "detail": e.message, + "parse": e.info, + "fetch": fetch_meta, + "url": (url or "")[:200], + "timings": timings, + "ms": timings["total_ms"], + } + return { + "ok": False, + "stage": "parse", + "error": "parse_failed", + "detail": str(e)[:300], + "fetch": fetch_meta, + "url": (url or "")[:200], + "timings": timings, + "ms": timings["total_ms"], + } + timings["parse_ms"] = int((time.time() - t_stage) * 1000) + print( + f"[control_api] clash-import parse imported={parse_info.get('imported')} " + f"format={parse_info.get('format')} ms={timings['parse_ms']}", + flush=True, + ) + + if len(proxies) > int(max_proxies): + proxies = proxies[: int(max_proxies)] + parse_info = dict(parse_info) + parse_info["truncated"] = True + parse_info["imported"] = len(proxies) + + cfg_paths = clash_config_paths() + if not cfg_paths and not dry_run: + timings["total_ms"] = int((time.time() - t0) * 1000) + return { + "ok": False, + "stage": "config", + "error": "clash_config_not_found", + "detail": f"no config under { _clash_dir() } (set CLASH_DIR / CLASH_CONFIG)", + "fetch": fetch_meta, + "parse": parse_info, + "timings": timings, + "ms": timings["total_ms"], + } + + if dry_run: + # list which groups exist in first config if any + group_preview: list[str] = [] + if cfg_paths: + try: + yaml = _require_yaml() + data = yaml.safe_load(cfg_paths[0].read_text(encoding="utf-8", errors="replace")) or {} + group_preview = [ + str(g.get("name")) + for g in (data.get("proxy-groups") or []) + if isinstance(g, dict) and g.get("name") + ] + except Exception: + group_preview = [] + timings["total_ms"] = int((time.time() - t0) * 1000) + print( + f"[control_api] clash-import dry_run ok imported={parse_info.get('imported')} " + f"would_write={len(cfg_paths)} total_ms={timings['total_ms']}", + flush=True, + ) + return { + "ok": True, + "dry_run": True, + "stage": "dry_run", + "url": (url or "")[:200], + "groups": target_groups, + "prefix": pref, + "mode": mode_n, + "fetch": fetch_meta, + "parse": parse_info, + "would_write": [str(p) for p in cfg_paths], + "available_groups": group_preview, + "importable_groups": list(IMPORTABLE_GROUPS), + "message": ( + f"预检成功:解析 {parse_info.get('imported')} 个节点" + f"(format={parse_info.get('format')}" + f"{', base64' if parse_info.get('base64') else ''})," + f"将写入池子 {', '.join(target_groups)};未改配置" + f" · {timings['total_ms']}ms" + ), + "timings": timings, + "ms": timings["total_ms"], + } + + # 3) write — only live + mac-merged by default (see clash_config_paths) + t_stage = time.time() + writes: list[dict[str, Any]] = [] + for p in cfg_paths: + # always write live config.yaml; also mirror into mac-merged if present + # so next start-clash-for-grok.sh keeps the import + writes.append( + merge_proxies_into_clash_config( + p, + proxies, + groups=target_groups, + mode=mode_n, + prefix=pref, + ) + ) + timings["write_ms"] = int((time.time() - t_stage) * 1000) + print( + f"[control_api] clash-import write files={len(writes)} " + f"ok={sum(1 for w in writes if w.get('ok'))} ms={timings['write_ms']}", + flush=True, + ) + + ok_writes = [w for w in writes if w.get("ok")] + if not ok_writes: + timings["total_ms"] = int((time.time() - t0) * 1000) + return { + "ok": False, + "stage": "write", + "error": "write_failed", + "detail": "all config writes failed", + "writes": writes, + "fetch": fetch_meta, + "parse": parse_info, + "timings": timings, + "ms": timings["total_ms"], + } + + reload_info: dict[str, Any] | None = None + if reload: + t_stage = time.time() + # reload the live config.yaml if present, else first successful write + live = next((Path(w["path"]) for w in ok_writes if Path(w["path"]).name == "config.yaml"), None) + if live is None: + live = Path(ok_writes[0]["path"]) + reload_info = _reload_clash_config(root, live) + timings["reload_ms"] = int((time.time() - t_stage) * 1000) + print( + f"[control_api] clash-import reload ok={reload_info.get('ok')} " + f"ms={timings['reload_ms']}", + flush=True, + ) + + # post-import listing is optional — Clash group walk can be slow and the UI + # already refreshes nodes separately after success. + listing = None + if include_listing: + t_stage = time.time() + try: + listing = list_clash_nodes(root) + except Exception: + listing = None + timings["listing_ms"] = int((time.time() - t_stage) * 1000) + + # still ok if write succeeded but reload failed — report clearly + write_ok = bool(ok_writes) + reload_ok = True if not reload else bool((reload_info or {}).get("ok")) + timings["total_ms"] = int((time.time() - t0) * 1000) + msg_parts = [ + f"成功导入 {parse_info.get('imported')} 个节点" if write_ok else "导入失败", + f"池子={','.join(target_groups)}", + f"mode={mode_n}", + f"prefix={pref}", + ] + if write_ok: + w0 = ok_writes[0] + msg_parts.append(f"added={w0.get('added')} replaced={w0.get('replaced')}") + if reload: + msg_parts.append("reload=ok" if reload_ok else f"reload=fail:{(reload_info or {}).get('error', '')[:80]}") + msg_parts.append(f"{timings['total_ms']}ms") + + print( + f"[control_api] clash-import done ok={write_ok} imported={parse_info.get('imported')} " + f"fetch={timings.get('fetch_ms')} parse={timings.get('parse_ms')} " + f"write={timings.get('write_ms')} reload={timings.get('reload_ms')} " + f"total={timings['total_ms']}", + flush=True, + ) + + return { + "ok": write_ok, # file write is the durable success criterion + "stage": "done" if write_ok else "write", + "message": " · ".join(msg_parts), + "url": (url or "")[:200], + "groups": target_groups, + "prefix": pref, + "mode": mode_n, + "fetch": fetch_meta, + "parse": parse_info, + "writes": writes, + "reload": reload_info, + "reload_ok": reload_ok, + "leaf_count_after": (listing or {}).get("leaf_count") if isinstance(listing, dict) else None, + "importable_groups": list(IMPORTABLE_GROUPS), + "timings": timings, + "ms": timings["total_ms"], + "warning": None + if reload_ok + else "配置已写入磁盘,但 mihomo 热重载失败;可手动 bash start-clash-for-grok.sh(注意会短暂中断出口)", + } + + +# ── Clash prune / delete by prefix ─────────────────────────────────────────── + +# Prefixes that require force=true to delete (infra / rarely accidental). +PROTECTED_CLASH_PREFIXES = frozenset({"GVPS", "DIRECT", "REJECT"}) + + +def _normalize_prefix(prefix: str) -> str: + return re.sub(r"\s+", "", (prefix or "").strip()) + + +def _name_matches_prefix(name: str, prefix: str) -> bool: + """True if leaf name is exactly prefix or starts with ``prefix-``.""" + n = str(name or "") + p = _normalize_prefix(prefix) + if not p or not n: + return False + return n == p or n.startswith(f"{p}-") + + +def remove_proxies_by_prefix_from_config( + cfg_path: Path, + *, + prefix: str, +) -> dict[str, Any]: + """Drop all proxies (and group refs) whose name matches prefix / prefix-*. + + Does not reload mihomo — caller should reload once after all writes. + """ + yaml = _require_yaml() + pref = _normalize_prefix(prefix) + if not pref: + return {"ok": False, "path": str(cfg_path), "error": "empty_prefix"} + if not cfg_path.is_file(): + return {"ok": False, "path": str(cfg_path), "error": "config_not_found"} + text = cfg_path.read_text(encoding="utf-8", errors="replace") + try: + data = yaml.safe_load(text) + except Exception as e: + return {"ok": False, "path": str(cfg_path), "error": f"yaml_load: {e}"} + if not isinstance(data, dict): + return {"ok": False, "path": str(cfg_path), "error": "yaml_root_not_mapping"} + + existing = data.get("proxies") + if existing is None: + existing = [] + data["proxies"] = existing + if not isinstance(existing, list): + return {"ok": False, "path": str(cfg_path), "error": "proxies_not_list"} + + kept: list[Any] = [] + removed_names: list[str] = [] + for p in existing: + if isinstance(p, dict): + n = str(p.get("name") or "") + if _name_matches_prefix(n, pref): + removed_names.append(n) + continue + kept.append(p) + data["proxies"] = kept + removed_set = set(removed_names) + + group_updates: list[dict[str, Any]] = [] + pgroups = data.get("proxy-groups") or [] + if isinstance(pgroups, list): + for g in pgroups: + if not isinstance(g, dict): + continue + old = list(g.get("proxies") or []) + if not old: + continue + new = [n for n in old if n not in removed_set] + if len(new) != len(old): + if not new: + new = ["DIRECT"] + g["proxies"] = new + group_updates.append( + { + "name": str(g.get("name") or ""), + "before": len(old), + "after": len(new), + "stripped": len(old) - len(new), + } + ) + + note = ( + f"clash-delete-prefix {pref} removed={len(removed_names)} " + f"groups_touched={len(group_updates)}" + ) + bak = _backup_and_dump_yaml(cfg_path, text, data, note) + return { + "ok": True, + "path": str(cfg_path), + "backup": str(bak), + "prefix": pref, + "removed": len(removed_names), + "removed_names": removed_names[:80], + "proxies_after": len(kept), + "group_updates": group_updates, + } + + +def remove_named_proxies_from_config( + cfg_path: Path, + *, + names: list[str], +) -> dict[str, Any]: + """Drop exact proxy names from proxies list + all group memberships.""" + yaml = _require_yaml() + want = {str(n).strip() for n in (names or []) if str(n).strip()} + if not want: + return {"ok": False, "path": str(cfg_path), "error": "empty_names"} + if not cfg_path.is_file(): + return {"ok": False, "path": str(cfg_path), "error": "config_not_found"} + text = cfg_path.read_text(encoding="utf-8", errors="replace") + try: + data = yaml.safe_load(text) + except Exception as e: + return {"ok": False, "path": str(cfg_path), "error": f"yaml_load: {e}"} + if not isinstance(data, dict): + return {"ok": False, "path": str(cfg_path), "error": "yaml_root_not_mapping"} + + existing = data.get("proxies") + if not isinstance(existing, list): + existing = [] + data["proxies"] = existing + kept: list[Any] = [] + removed_names: list[str] = [] + for p in existing: + if isinstance(p, dict): + n = str(p.get("name") or "") + if n in want: + removed_names.append(n) + continue + kept.append(p) + data["proxies"] = kept + removed_set = set(removed_names) + + group_updates: list[dict[str, Any]] = [] + pgroups = data.get("proxy-groups") or [] + if isinstance(pgroups, list): + for g in pgroups: + if not isinstance(g, dict): + continue + old = list(g.get("proxies") or []) + if not old: + continue + new = [n for n in old if n not in removed_set] + if len(new) != len(old): + if not new: + new = ["DIRECT"] + g["proxies"] = new + group_updates.append( + { + "name": str(g.get("name") or ""), + "before": len(old), + "after": len(new), + "stripped": len(old) - len(new), + } + ) + + note = f"clash-delete-names removed={len(removed_names)}" + bak = _backup_and_dump_yaml(cfg_path, text, data, note) + return { + "ok": True, + "path": str(cfg_path), + "backup": str(bak), + "removed": len(removed_names), + "removed_names": removed_names[:80], + "proxies_after": len(kept), + "group_updates": group_updates, + } + + +def delete_clash_prefix( + root: Path, + *, + prefix: str, + dry_run: bool = False, + reload: bool = True, + force: bool = False, +) -> dict[str, Any]: + """Delete all Clash proxies matching prefix / prefix-* from write configs.""" + t0 = time.time() + pref = _normalize_prefix(prefix) + if not pref: + return { + "ok": False, + "error": "empty_prefix", + "detail": "prefix required (e.g. YF, BP, SUB)", + "ms": int((time.time() - t0) * 1000), + } + if len(pref) > 32: + return { + "ok": False, + "error": "prefix_too_long", + "detail": "prefix max 32 chars", + "ms": int((time.time() - t0) * 1000), + } + if pref.upper() in PROTECTED_CLASH_PREFIXES and not force: + return { + "ok": False, + "error": "protected_prefix", + "detail": f"prefix {pref} is protected; pass force=true to delete", + "prefix": pref, + "ms": int((time.time() - t0) * 1000), + } + + cfg_paths = clash_config_paths() + if not cfg_paths: + return { + "ok": False, + "error": "clash_config_not_found", + "detail": f"no config under {_clash_dir()}", + "prefix": pref, + "ms": int((time.time() - t0) * 1000), + } + + # preview counts from first config + yaml = _require_yaml() + preview_names: list[str] = [] + try: + data0 = yaml.safe_load(cfg_paths[0].read_text(encoding="utf-8", errors="replace")) or {} + for p in data0.get("proxies") or []: + if isinstance(p, dict): + n = str(p.get("name") or "") + if _name_matches_prefix(n, pref): + preview_names.append(n) + except Exception: + preview_names = [] + + if dry_run: + return { + "ok": True, + "dry_run": True, + "prefix": pref, + "would_remove": len(preview_names), + "sample": preview_names[:40], + "would_write": [str(p) for p in cfg_paths], + "message": f"预检:将删除 prefix={pref} 共 {len(preview_names)} 个节点(未改配置)", + "ms": int((time.time() - t0) * 1000), + } + + if not preview_names: + return { + "ok": True, + "prefix": pref, + "removed": 0, + "writes": [], + "reload": None, + "message": f"无匹配节点 prefix={pref}", + "ms": int((time.time() - t0) * 1000), + } + + writes = [remove_proxies_by_prefix_from_config(p, prefix=pref) for p in cfg_paths] + ok_writes = [w for w in writes if w.get("ok")] + reload_info: dict[str, Any] | None = None + if reload and ok_writes: + live = next( + (Path(w["path"]) for w in ok_writes if Path(w["path"]).name == "config.yaml"), + Path(ok_writes[0]["path"]), + ) + reload_info = _reload_clash_config(root, live) + removed = max((int(w.get("removed") or 0) for w in ok_writes), default=0) + print( + f"[control_api] clash-delete-prefix prefix={pref} removed={removed} " + f"files={len(ok_writes)} reload={bool((reload_info or {}).get('ok'))}", + flush=True, + ) + return { + "ok": bool(ok_writes), + "prefix": pref, + "removed": removed, + "sample": preview_names[:40], + "writes": writes, + "reload": reload_info, + "reload_ok": True if not reload else bool((reload_info or {}).get("ok")), + "message": f"已删除 prefix={pref} · {removed} 节点" + + ("" if not reload else (" · reload=ok" if (reload_info or {}).get("ok") else " · reload=fail")), + "ms": int((time.time() - t0) * 1000), + } + + +def prune_clash_unhealthy( + root: Path, + *, + prefix: str = "", + group: str = "🎯Grok注册", + timeout_ms: int = 4500, + limit: int = 200, + dry_run: bool = False, + reload: bool = True, + delete_defs: bool = True, +) -> dict[str, Any]: + """Delay-test candidates and remove failing ones from configs. + + - If ``prefix`` set: only that prefix / prefix-*. + - Else: leaf members of ``group`` that look like imported nodes + (contain ``-`` and not DIRECT/REJECT). + - ``delete_defs``: also drop proxy definitions (not only group membership). + """ + t0 = time.time() + pref = _normalize_prefix(prefix) + group_n = (group or "").strip() or "🎯Grok注册" + cfg_paths = clash_config_paths() + if not cfg_paths: + return { + "ok": False, + "error": "clash_config_not_found", + "ms": int((time.time() - t0) * 1000), + } + + yaml = _require_yaml() + primary = cfg_paths[0] + try: + data0 = yaml.safe_load(primary.read_text(encoding="utf-8", errors="replace")) or {} + except Exception as e: + return { + "ok": False, + "error": f"yaml_load: {e}", + "ms": int((time.time() - t0) * 1000), + } + + candidates: list[str] = [] + if pref: + for p in data0.get("proxies") or []: + if isinstance(p, dict): + n = str(p.get("name") or "") + if _name_matches_prefix(n, pref): + candidates.append(n) + else: + g = next( + ( + x + for x in (data0.get("proxy-groups") or []) + if isinstance(x, dict) and str(x.get("name") or "") == group_n + ), + None, + ) + members = list((g or {}).get("proxies") or []) + skip = {"DIRECT", "REJECT", "REJECT-DROP", "PASS"} + for n in members: + if not isinstance(n, str) or n in skip: + continue + # skip nested group refs without '-' that are pure emoji groups occasionally + if n.startswith("♻️") or n.startswith("🚀") or n.startswith("🎯"): + continue + candidates.append(n) + + # de-dupe preserve order + seen: set[str] = set() + uniq: list[str] = [] + for n in candidates: + if n not in seen: + seen.add(n) + uniq.append(n) + candidates = uniq[: max(1, int(limit))] + + if not candidates: + return { + "ok": True, + "dry_run": dry_run, + "tested": 0, + "unhealthy": 0, + "healthy": 0, + "removed": 0, + "message": "无可测节点", + "ms": int((time.time() - t0) * 1000), + } + + # probe + tr = test_clash_nodes( + root, + names=candidates, + timeout_ms=int(timeout_ms), + limit=len(candidates), + ) + results = tr.get("results") or [] + unhealthy = [r["name"] for r in results if not r.get("ok")] + healthy = [r["name"] for r in results if r.get("ok")] + + if dry_run: + return { + "ok": True, + "dry_run": True, + "prefix": pref or None, + "group": group_n, + "tested": len(results), + "healthy": len(healthy), + "unhealthy": len(unhealthy), + "unhealthy_sample": unhealthy[:40], + "healthy_sample": healthy[:20], + "would_remove": len(unhealthy), + "delete_defs": delete_defs, + "message": ( + f"预检测活 {len(results)} · 通 {len(healthy)} · 不通 {len(unhealthy)}" + f"(将{'删除定义' if delete_defs else '仅踢出组'};未改配置)" + ), + "ms": int((time.time() - t0) * 1000), + } + + if not unhealthy: + return { + "ok": True, + "prefix": pref or None, + "group": group_n, + "tested": len(results), + "healthy": len(healthy), + "unhealthy": 0, + "removed": 0, + "message": f"测活 {len(results)} 全通,无需清理", + "ms": int((time.time() - t0) * 1000), + } + + writes: list[dict[str, Any]] = [] + if delete_defs: + writes = [remove_named_proxies_from_config(p, names=unhealthy) for p in cfg_paths] + else: + # membership-only: strip from all groups but keep proxy defs + for cfg in cfg_paths: + text = cfg.read_text(encoding="utf-8", errors="replace") + try: + data = yaml.safe_load(text) or {} + except Exception as e: + writes.append({"ok": False, "path": str(cfg), "error": str(e)}) + continue + dead = set(unhealthy) + touched = 0 + for g in data.get("proxy-groups") or []: + if not isinstance(g, dict): + continue + old = list(g.get("proxies") or []) + new = [n for n in old if n not in dead] + if len(new) != len(old): + g["proxies"] = new or ["DIRECT"] + touched += 1 + bak = _backup_and_dump_yaml( + cfg, text, data, f"clash-prune-unhealthy membership-only n={len(unhealthy)}" + ) + writes.append( + { + "ok": True, + "path": str(cfg), + "backup": str(bak), + "groups_touched": touched, + "removed": len(unhealthy), + } + ) + + ok_writes = [w for w in writes if w.get("ok")] + reload_info: dict[str, Any] | None = None + if reload and ok_writes: + live = next( + (Path(w["path"]) for w in ok_writes if Path(w["path"]).name == "config.yaml"), + Path(ok_writes[0]["path"]), + ) + reload_info = _reload_clash_config(root, live) + + print( + f"[control_api] clash-prune-unhealthy tested={len(results)} " + f"dead={len(unhealthy)} delete_defs={delete_defs} " + f"reload={bool((reload_info or {}).get('ok'))}", + flush=True, + ) + return { + "ok": bool(ok_writes), + "prefix": pref or None, + "group": group_n, + "tested": len(results), + "healthy": len(healthy), + "unhealthy": len(unhealthy), + "unhealthy_sample": unhealthy[:40], + "removed": len(unhealthy) if ok_writes else 0, + "delete_defs": delete_defs, + "writes": writes, + "reload": reload_info, + "reload_ok": True if not reload else bool((reload_info or {}).get("ok")), + "message": ( + f"测活 {len(results)} · 删不通 {len(unhealthy)}" + + ("" if not reload else (" · reload=ok" if (reload_info or {}).get("ok") else " · reload=fail")) + ), + "ms": int((time.time() - t0) * 1000), + } diff --git a/apps/control_api/overview.py b/apps/control_api/overview.py new file mode 100644 index 0000000..592eb9d --- /dev/null +++ b/apps/control_api/overview.py @@ -0,0 +1,57 @@ +"""Overview aggregates for the control plane.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + + +def count_product_ok(root: Path) -> int: + """Count xai-*.json under cpa_auths with both access_token and refresh_token.""" + d = root / "cpa_auths" + if not d.is_dir(): + return 0 + n = 0 + for f in d.glob("xai-*.json"): + try: + data = json.loads(f.read_text(encoding="utf-8")) + except Exception: + continue + if not isinstance(data, dict): + continue + at = data.get("access_token") + rt = data.get("refresh_token") + if isinstance(at, str) and at and isinstance(rt, str) and rt: + n += 1 + return n + + +def build_overview(root: Path, run_summary: dict[str, Any] | None = None) -> dict[str, Any]: + run = run_summary + if run is None: + try: + from apps.control_api.runs import run_status + + run = run_status(root) + except Exception: + run = None + nodes_summary: dict[str, Any] | None = None + try: + from apps.control_api.nodes_ops import list_catalog + + cat = list_catalog(root) + nodes_summary = { + "total": cat.get("total"), + "enabled": cat.get("enabled"), + "healthy": cat.get("healthy"), + "path": cat.get("path"), + } + except Exception: + nodes_summary = None + return { + "project_root": str(root), + "product_ok": count_product_ok(root), + "run": run, + "nodes": nodes_summary, + } diff --git a/apps/control_api/passwords.py b/apps/control_api/passwords.py new file mode 100644 index 0000000..1a92834 --- /dev/null +++ b/apps/control_api/passwords.py @@ -0,0 +1,67 @@ +"""Password hashing (stdlib scrypt) for control-plane operators.""" + +from __future__ import annotations + +import base64 +import hashlib +import hmac +import secrets + + +_SCRYPT_N = 2**14 +_SCRYPT_R = 8 +_SCRYPT_P = 1 +_DKLEN = 32 + + +def hash_password(password: str) -> str: + if not password: + raise ValueError("password must be non-empty") + salt = secrets.token_bytes(16) + digest = hashlib.scrypt( + password.encode("utf-8"), + salt=salt, + n=_SCRYPT_N, + r=_SCRYPT_R, + p=_SCRYPT_P, + dklen=_DKLEN, + ) + return "scrypt${}${}${}".format( + base64.urlsafe_b64encode(salt).decode("ascii").rstrip("="), + f"n={_SCRYPT_N},r={_SCRYPT_R},p={_SCRYPT_P}", + base64.urlsafe_b64encode(digest).decode("ascii").rstrip("="), + ) + + +def _b64decode(data: str) -> bytes: + pad = "=" * (-len(data) % 4) + return base64.urlsafe_b64decode(data + pad) + + +def verify_password(password: str, encoded: str) -> bool: + if not password or not encoded: + return False + try: + scheme, salt_b64, params, dig_b64 = encoded.split("$", 3) + except ValueError: + return False + if scheme != "scrypt": + return False + try: + parts = dict(p.split("=", 1) for p in params.split(",")) + n = int(parts.get("n", _SCRYPT_N)) + r = int(parts.get("r", _SCRYPT_R)) + p = int(parts.get("p", _SCRYPT_P)) + salt = _b64decode(salt_b64) + expected = _b64decode(dig_b64) + digest = hashlib.scrypt( + password.encode("utf-8"), + salt=salt, + n=n, + r=r, + p=p, + dklen=len(expected) or _DKLEN, + ) + except Exception: + return False + return hmac.compare_digest(digest, expected) diff --git a/apps/control_api/process_registry.py b/apps/control_api/process_registry.py new file mode 100644 index 0000000..e33dfbf --- /dev/null +++ b/apps/control_api/process_registry.py @@ -0,0 +1,235 @@ +"""In-memory + on-disk registry of control-plane started runs.""" + +from __future__ import annotations + +import fcntl +import json +import os +import signal +import time +from pathlib import Path +from typing import Any + +_LOCK = Path("/tmp/grok_batch_supervisor.lock") +_LOCK_PID = Path("/tmp/grok_batch_supervisor.lock.pid") + + +class ProcessRegistry: + def __init__(self, root: Path) -> None: + self.root = root + self.path = root / "logs" / "control_api_runs.json" + self._current: dict[str, Any] | None = None + self._load() + + def _load(self) -> None: + if not self.path.is_file(): + return + try: + data = json.loads(self.path.read_text(encoding="utf-8")) + except Exception: + return + if isinstance(data, dict) and data.get("current"): + self._current = data["current"] + + def _save(self) -> None: + self.path.parent.mkdir(parents=True, exist_ok=True) + payload = {"current": self._current, "updated_at": time.time()} + tmp = self.path.with_suffix(".json.tmp") + tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + tmp.replace(self.path) + + def register(self, run_id: str, pid: int, kind: str, meta: dict[str, Any]) -> None: + self._current = { + "run_id": run_id, + "pid": int(pid), + "kind": kind, + "meta": meta, + "started_at": time.time(), + } + self._save() + + def current(self) -> dict[str, Any] | None: + self.clear_if_dead() + return self._current + + def clear(self) -> None: + self._current = None + self._save() + + @staticmethod + def _reap_children() -> None: + """Non-blocking reap of any exited children (zombies from Popen). + + control_api starts supervisors with Popen and never waits; when the + child exits immediately (e.g. lock held), it becomes a zombie still + owned by control_api. kill(pid, 0) returns True for zombies, so the + registry would stay stuck forever unless we reap + treat Z as dead. + """ + try: + while True: + wpid, _st = os.waitpid(-1, os.WNOHANG) + if wpid <= 0: + break + except ChildProcessError: + # No children — normal when registry pid is not ours. + pass + except OSError: + pass + + @staticmethod + def _pid_is_zombie(pid: int) -> bool: + """Linux /proc: state 'Z' means zombie (still in table, not runnable).""" + try: + raw = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8") + except (FileNotFoundError, PermissionError, OSError): + return False + # comm may contain spaces/parens; state is the first token after last ')' + rparen = raw.rfind(")") + if rparen < 0: + return False + fields = raw[rparen + 2 :].split() + return bool(fields) and fields[0] == "Z" + + @staticmethod + def pid_alive(pid: int) -> bool: + if pid <= 0: + return False + # Best-effort: if this is our zombie child, reap it so the pid vanishes. + ProcessRegistry._reap_children() + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + # Exists but not signalable — treat as alive (not our zombie). + return True + # Zombies still pass kill(0); they are not a live supervisor. + if ProcessRegistry._pid_is_zombie(pid): + return False + return True + + def clear_if_dead(self) -> None: + if not self._current: + return + pid = int(self._current.get("pid") or 0) + if not self.pid_alive(pid): + self._current = None + self._save() + + +def supervisor_lock_pid() -> int | None: + if not _LOCK_PID.is_file(): + return None + try: + raw = _LOCK_PID.read_text(encoding="utf-8").strip() + pid = int(raw) + except Exception: + return None + if ProcessRegistry.pid_alive(pid): + return pid + return None + + +def supervisor_flock_busy() -> bool: + """True if another process currently holds the exclusive flock on the lock file. + + Complements ``supervisor_lock_pid``: after a batch exits, ``.lock.pid`` is often + stale while a *leaked* holder (e.g. mihomo inheriting fd 9 from preflight restart) + still keeps the flock. Probing the flock itself catches that case. + """ + try: + fd = os.open(str(_LOCK), os.O_RDWR | os.O_CREAT, 0o644) + except OSError: + return False + try: + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + return True + except OSError: + return False + try: + fcntl.flock(fd, fcntl.LOCK_UN) + except OSError: + pass + return False + finally: + try: + os.close(fd) + except OSError: + pass + + +def supervisor_lock_held() -> bool: + """True if a live supervisor is indicated by lock.pid **or** the flock is busy.""" + if supervisor_lock_pid() is not None: + return True + return supervisor_flock_busy() + + +def _signal_tree(pid: int, sig: int, *, process_group: bool) -> str: + """Deliver *sig* to the process group when possible, else the single pid. + + Control-started runs use ``start_new_session=True``, so the registered pid is + the session/group leader and ``killpg`` reaps chrome/xvfb/register children. + + External flock supervisors (``batch_dc1k_ns``) are often **not** the group + leader: their pid != pgid. On Linux ``killpg(non_leader_pid, …)`` raises + ``ProcessLookupError`` (ESRCH) even while that pid is still alive. Treating + that as "already dead" makes ``/api/runs/stop`` report success while the + batch keeps running. Resolve the real pgid via ``getpgid`` first; if group + delivery still fails and the pid is alive, fall back to single-pid signal. + """ + if process_group and pid > 0: + pgid = pid + try: + pgid = int(os.getpgid(pid)) + except (ProcessLookupError, PermissionError, OSError): + pgid = pid + try: + os.killpg(pgid, sig) + return "pg" + except ProcessLookupError: + # ESRCH on killpg is ambiguous: real missing group OR bad pgid. + # Only re-raise (→ already dead) when the target pid itself is gone. + if not ProcessRegistry.pid_alive(pid): + raise + # fall through to single-pid + except (PermissionError, OSError): + pass + os.kill(pid, sig) + return "pid" + + +def stop_pid( + pid: int, + grace_sec: float = 10.0, + *, + process_group: bool = True, +) -> dict[str, Any]: + """SIGTERM then optional SIGKILL. + + Prefer process-group delivery (``killpg``) so supervisor children started under + a new session are not left orphaned. Falls back to the single pid when the + target is not a group leader (common for external lock-only runs). + """ + if pid <= 0: + return {"ok": False, "detail": "invalid pid"} + if not ProcessRegistry.pid_alive(pid): + return {"ok": True, "detail": "already dead", "pid": pid, "mode": "none"} + try: + mode = _signal_tree(pid, signal.SIGTERM, process_group=process_group) + except ProcessLookupError: + return {"ok": True, "detail": "already dead", "pid": pid, "mode": "none"} + deadline = time.time() + grace_sec + while time.time() < deadline: + if not ProcessRegistry.pid_alive(pid): + return {"ok": True, "detail": "terminated", "pid": pid, "mode": mode} + time.sleep(0.2) + if ProcessRegistry.pid_alive(pid): + try: + mode = _signal_tree(pid, signal.SIGKILL, process_group=process_group) + except ProcessLookupError: + pass + return {"ok": True, "detail": "killed", "pid": pid, "mode": mode} + return {"ok": True, "detail": "terminated", "pid": pid, "mode": mode} diff --git a/apps/control_api/progress.py b/apps/control_api/progress.py new file mode 100644 index 0000000..79f11e5 --- /dev/null +++ b/apps/control_api/progress.py @@ -0,0 +1,654 @@ +"""Parse supervisor / register_cli logs into human-readable run progress.""" + +from __future__ import annotations + +import json +import re +from pathlib import Path +from typing import Any + +# Avoid matching gained_complete=N (must not start mid-token). +_COMPLETE_RE = re.compile(r"(? str: + if path is None or not path.is_file(): + return "" + try: + size = path.stat().st_size + with path.open("rb") as f: + if size > max_bytes: + f.seek(-max_bytes, 2) + data = f.read() + return data.decode("utf-8", errors="replace") + except Exception: + return "" + + +def _head_text(path: Path | None, max_bytes: int = 16_384) -> str: + """Read start of supervisor log (baseline/goal_complete live only in header).""" + if path is None or not path.is_file(): + return "" + try: + with path.open("rb") as f: + data = f.read(max_bytes) + return data.decode("utf-8", errors="replace") + except Exception: + return "" + + +def _run_tag_from_sup(sup_log: Path | None, sup_text: str) -> str | None: + """Derive batch run tag so we only consider this run's sub logs. + + Supervisor files are `{tag}.supervisor.log`; sub logs are `{tag}.subN_TS.log`. + """ + if sup_log is not None: + name = sup_log.name + if name.endswith(".supervisor.log"): + return name[: -len(".supervisor.log")] + for line in reversed(sup_text.splitlines()): + m = _SUB_LOG_RE.search(line) + if not m: + continue + leaf = Path(m.group(1)).name + m2 = re.match(r"(.+)\.sub\d+", leaf) + if m2: + return m2.group(1) + return None + + +def _mtime(path: Path) -> float: + try: + return path.stat().st_mtime + except OSError: + return 0.0 + + +def _latest_sub_log( + root: Path, sup_text: str, *, sup_log: Path | None = None +) -> Path | None: + """Pick the worker log for the *currently running* sub-batch. + + Supervisor only emits `log=` **after** a sub exits. Preferring that path + during the next sub pins the UI on the finished SUMMARY_JSON (子批汇总) + while the live sub keeps writing a newer `*.subN_*.log`. Always prefer the + newest mtime sub log for this run tag; fall back to explicit log= only when + no newer candidate exists. + """ + logs = root / "logs" + if not logs.is_dir(): + return None + + tag = _run_tag_from_sup(sup_log, sup_text) + cands: list[Path] = [] + if tag: + cands = list(logs.glob(f"{tag}.sub*.log")) + if not cands: + # Cross-run fallback (smoke / ad-hoc): any sub log by mtime. + cands = list(logs.glob("*.sub*_*.log")) or list(logs.glob("*.sub*.log")) + # De-dupe by resolved path. + uniq: dict[str, Path] = {} + for p in cands: + try: + uniq[str(p.resolve())] = p + except OSError: + uniq[str(p)] = p + cands = list(uniq.values()) + if not cands: + for line in reversed(sup_text.splitlines()): + m = _SUB_LOG_RE.search(line) + if m: + p = root / m.group(1) + if p.is_file(): + return p + return None + + newest = max(cands, key=_mtime) + + # If supervisor names an explicit log= that is still the newest (or only) + # finished artifact, keep it — otherwise the in-flight newer file wins. + for line in reversed(sup_text.splitlines()): + m = _SUB_LOG_RE.search(line) + if not m: + continue + p = root / m.group(1) + if p.is_file() and _mtime(p) >= _mtime(newest) - 0.001: + return p + break + return newest + + +def detect_phase(text: str) -> dict[str, str]: + """Infer current phase from the most recent matching log lines.""" + if not text: + return { + "phase": "idle", + "title": "空闲", + "detail": "无活动日志", + } + lines = [ln for ln in text.splitlines() if ln.strip()] + # Prefer structured fatal_reason inside recent SUMMARY_JSON (more precise than + # matching the whole JSON blob as sub_summary only). + for line in reversed(lines[-80:]): + if "SUMMARY_JSON" not in line or "fatal" not in line: + continue + if re.search(r'"fatal"\s*:\s*true', line) and re.search( + r"Turnstile|token_len=0|pre-submit", line, re.I + ): + detail = line.strip() + if len(detail) > 220: + detail = detail[:217] + "…" + return { + "phase": "turnstile", + "title": "Cloudflare Turnstile 人机验证", + "detail": detail, + } + for line in reversed(lines[-400:]): + for pattern, phase, title in _PHASE_RULES: + if re.search(pattern, line, re.I): + detail = line.strip() + if len(detail) > 220: + detail = detail[:217] + "…" + return {"phase": phase, "title": title, "detail": detail} + last = lines[-1].strip() if lines else "" + return { + "phase": "running", + "title": "运行中", + "detail": last[:220] if last else "有日志但未识别步骤", + } + + +def _parse_summary_json(text: str) -> dict[str, Any] | None: + for line in reversed(text.splitlines()): + if "SUMMARY_JSON" not in line: + continue + m = _SUMMARY_RE.search(line.strip()) + if not m: + # tolerate "SUMMARY_JSON {...}" mid-line + idx = line.find("{") + if idx < 0: + continue + try: + return json.loads(line[idx:]) + except Exception: + continue + try: + return json.loads(m.group(1)) + except Exception: + continue + return None + + +def _iter_summary_json(text: str) -> list[dict[str, Any]]: + """Every SUMMARY_JSON object in `text`, in file order. + + The supervisor log accumulates one SUMMARY_JSON line per finished sub + (register_cli copies its summary on exit). Aggregating them gives real + batch-level failure stats rather than a single sub snapshot. + """ + out: list[dict[str, Any]] = [] + for line in text.splitlines(): + if "SUMMARY_JSON" not in line: + continue + s = line.strip() + m = _SUMMARY_RE.search(s) + blob = None + if m: + blob = m.group(1) + else: + idx = s.find("{") + if idx >= 0: + blob = s[idx:] + if not blob: + continue + try: + obj = json.loads(blob) + except Exception: + continue + if isinstance(obj, dict) and obj.get("event") == "register_cli_summary": + out.append(obj) + return out + + +def _int(v: Any) -> int: + try: + return int(v or 0) + except Exception: + return 0 + + +def build_batch_failures(sup_text: str, sub_text: str) -> dict[str, Any] | None: + """Aggregate per-sub SUMMARY_JSON into batch-level failure stats. + + Returns None when no summaries are present yet (batch just started), so + the UI can hide the card instead of showing an all-zero panel. + """ + subs = _iter_summary_json(sup_text) + # The live worker's own summary is only in the worker tail until it exits + # and the supervisor copies it. Include it so the freshest sub counts too. + worker = _iter_summary_json(sub_text) + if worker: + subs = subs + worker[-1:] + if not subs: + return None + + agg = { + "subs": len(subs), + "reg_success": 0, + "reg_fail": 0, + "mint_fail": 0, + "mint_skip": 0, + "chat_denied": 0, + "chat_fail": 0, + "remote_inject_fail": 0, + "remote_live_fail": 0, + "fatal_subs": 0, + } + # Failure taxonomy buckets for the breakdown chart. + mint_reasons: dict[str, int] = {} + fatal_reasons: dict[str, int] = {} + for s in subs: + agg["reg_success"] += _int(s.get("reg_success")) + agg["reg_fail"] += _int(s.get("reg_fail")) + agg["mint_fail"] += _int(s.get("mint_fail")) + agg["mint_skip"] += _int(s.get("mint_skip")) + agg["chat_denied"] += _int(s.get("chat_denied")) + agg["chat_fail"] += _int(s.get("chat_fail")) + agg["remote_inject_fail"] += _int(s.get("remote_inject_fail")) + agg["remote_live_fail"] += _int(s.get("remote_live_fail")) + if s.get("fatal"): + agg["fatal_subs"] += 1 + fr = str(s.get("fatal_reason") or "fatal").strip()[:80] + if fr: + fatal_reasons[fr] = fatal_reasons.get(fr, 0) + 1 + mr = str(s.get("mint_fail_reason") or "").strip()[:80] + if mr and _int(s.get("mint_fail")): + mint_reasons[mr] = mint_reasons.get(mr, 0) + _int(s.get("mint_fail")) + + attempts = agg["reg_success"] + agg["reg_fail"] + total_fail = ( + agg["reg_fail"] + + agg["mint_fail"] + + agg["chat_fail"] + + agg["remote_inject_fail"] + + agg["remote_live_fail"] + ) + agg["attempts"] = attempts + agg["total_fail"] = total_fail + agg["fail_rate"] = round(agg["reg_fail"] / attempts, 4) if attempts else 0.0 + + # Top-N breakdowns as sorted [label, count] lists for the UI. + def _top(d: dict[str, int], n: int = 5) -> list[list[Any]]: + return [[k, v] for k, v in sorted(d.items(), key=lambda kv: -kv[1])[:n]] + + agg["mint_fail_reasons"] = _top(mint_reasons) + agg["fatal_reasons"] = _top(fatal_reasons) + # Per-sub reg_fail series for a trend sparkline. + agg["reg_fail_series"] = [_int(s.get("reg_fail")) for s in subs][-30:] + agg["reg_success_series"] = [_int(s.get("reg_success")) for s in subs][-30:] + return agg + + +def _parse_counters(text: str) -> dict[str, Any]: + complete = None + zero = None + sub = None + chunk = None + attempt = None + gained = None + target = None + gained_total = None + accounts = None + mode = None + exit_code = None + goal_complete = None + baseline_complete = None + target_new = None + for line in reversed(text.splitlines()): + if complete is None: + m = _COMPLETE_RE.search(line) + if m and "[supervisor]" in line: + complete = int(m.group(1)) + if zero is None and "[supervisor]" in line: + m2 = _ZERO_RE.search(line) + if m2: + zero = int(m2.group(1)) + else: + m3 = _ZERO_SHORT_RE.search(line) + if m3: + zero = int(m3.group(1)) + if sub is None: + m = _SUB_RE.search(line) + if m and "[supervisor]" in line: + sub = int(m.group(1)) + if chunk is None: + m = _CHUNK_RE.search(line) + if m: + chunk = int(m.group(1)) + if attempt is None: + m = _ATTEMPT_RE.search(line) + if m and "[supervisor]" in line: + attempt = int(m.group(1)) + if gained is None: + m = _GAINED_RE.search(line) + if m: + gained = int(m.group(1)) + if target is None or gained_total is None: + m = _PLUS_RE.search(line) + if m: + gained_total = int(m.group(1)) + target = int(m.group(2)) + if accounts is None: + m = _ACCOUNTS_RE.search(line) + if m and "[supervisor]" in line: + accounts = int(m.group(1)) + if mode is None: + m = _MODE_RE.search(line) + if m: + mode = m.group(1) + if exit_code is None and "sub=" in line and "exit=" in line: + m = _EXIT_RE.search(line) + if m: + exit_code = int(m.group(1)) + if goal_complete is None: + m = _GOAL_RE.search(line) + if m: + goal_complete = int(m.group(1)) + if target_new is None: + m = _TARGET_NEW_RE.search(line) + if m: + target_new = int(m.group(1)) + if baseline_complete is None: + m = _BASELINE_RE.search(line) + if m: + baseline_complete = int(m.group(2)) + if goal_complete is None and m.group(4): + goal_complete = int(m.group(4)) + if all( + x is not None + for x in (complete, zero, sub, chunk, accounts, goal_complete, target) + ): + break + # Prefer explicit target_new when +N/M not yet seen; keep +N/M as batch target. + if target is None and target_new is not None: + target = target_new + remain = None + if isinstance(complete, int) and isinstance(goal_complete, int): + remain = max(0, goal_complete - complete) + batch_remain = None + if isinstance(gained_total, int) and isinstance(target, int): + batch_remain = max(0, target - gained_total) + elif isinstance(target, int) and gained_total is None: + batch_remain = target + return { + "complete": complete, + "consecutive_zero": zero, + "sub": sub, + "chunk": chunk, + "attempt": attempt if attempt is not None else sub, + "gained_last_sub": gained, + "batch_gained": gained_total, + "target": target, + "target_new": target_new if target_new is not None else target, + "goal_complete": goal_complete, + "baseline_complete": baseline_complete, + "remain": remain, + "batch_remain": batch_remain, + "accounts": accounts, + "mode": mode, + "last_sub_exit": exit_code, + } + + +def build_timeline(sup_text: str, sub_text: str, *, limit: int = 24) -> list[dict[str, str]]: + """Build a short human timeline from recent supervisor + sub lines.""" + interesting = re.compile( + r"\[supervisor\]|SUMMARY_JSON|=== 完成|Fatal|FAIL-FAST|Turnstile|" + r"注册成功|token_ok|wrote |OTP|mint|preflight|clash|batch-end|" + r"gained_complete|browser_boot|FATAL", + re.I, + ) + items: list[dict[str, str]] = [] + for src, text in (("supervisor", sup_text), ("worker", sub_text)): + for line in text.splitlines(): + if not interesting.search(line): + continue + phase = detect_phase(line) + items.append( + { + "source": src, + "phase": phase["phase"], + "title": phase["title"], + "line": line.strip()[:300], + } + ) + return items[-limit:] + + +def build_progress(root: Path, *, sup_log: Path | None) -> dict[str, Any]: + """Full progress payload for UI.""" + sup_text = _tail_text(sup_log) + # Header has goal_complete / baseline / target_new; tail has live counters. + # Merge so reversed-line parse still prefers latest complete= while + # still seeing one-shot baseline fields from the start of the run. + head_text = _head_text(sup_log) + counters = _parse_counters((head_text + "\n" + sup_text).strip() if head_text else sup_text) + sub_path = _latest_sub_log(root, sup_text, sup_log=sup_log) + sub_text = _tail_text(sub_path) + # Phase must reflect the live worker. Supervisor tail often ends with the + # previous sub's SUMMARY_JSON (copied on exit) plus `sub=N chunk=` start — + # those late rules (sub_summary) would otherwise pin the UI on 子批汇总 for + # the entire next sub. Prefer worker-only when it has content; fall back to + # combined only when worker is empty / missing. + if sub_text.strip(): + phase = detect_phase(sub_text) + # If worker is mid-flight but only has boot noise, allow supervisor + # batch-level phases (sub_start / batch_start / done / inject) when + # worker has no stronger in-account phase. + if phase["phase"] in ("idle", "running"): + sup_phase = detect_phase(sup_text) + if sup_phase["phase"] not in ("sub_summary", "idle"): + phase = sup_phase + else: + combined = (sup_text + "\n" + sub_text).strip() + phase = detect_phase(combined if combined else sup_text) + # SUMMARY_JSON is per finished sub. Prefer the active worker's own summary; + # supervisor copy is previous-sub history while a newer worker is mid-flight. + worker_summary = _parse_summary_json(sub_text) + sup_summary = _parse_summary_json(sup_text) + summary = worker_summary or sup_summary + + # Stuck heuristics + stuck = False + stuck_reason = "" + zero = counters.get("consecutive_zero") + if isinstance(zero, int) and zero >= 4: + stuck = True + stuck_reason = f"连续 {zero} 个子批零产出" + if phase["phase"] == "turnstile": + stuck = True + stuck_reason = stuck_reason or "Turnstile 卡住 / 无 token" + # Only treat fatal from the current worker (or when we are still on + # sub_summary of that finished worker). A previous sub's fatal in the + # supervisor tail must not freeze the next live sub as stuck. + fatal_src = worker_summary + if fatal_src is None and phase["phase"] in ("sub_summary", "done", "batch_end_inject"): + fatal_src = sup_summary + if fatal_src and fatal_src.get("fatal"): + stuck = True + stuck_reason = str(fatal_src.get("fatal_reason") or "fatal")[:200] + + recent_writes: list[str] = [] + for line in (sub_text + "\n" + sup_text).splitlines(): + m = _WROTE_RE.search(line) + if m: + recent_writes.append(m.group(1)) + recent_writes = recent_writes[-5:] + + steps = [ + { + "id": "batch_start", + "title": "批次启动", + "desc": "基线 complete / goal / flock", + }, + { + "id": "node_rotate", + "title": "节点测活/换路", + "desc": "Clash preflight 或 force next node", + }, + { + "id": "sub_start", + "title": "子批启动", + "desc": "xvfb + register_cli chunk", + }, + { + "id": "browser_boot", + "title": "浏览器启动", + "desc": "Chromium + 代理", + }, + { + "id": "register_form", + "title": "注册表单", + "desc": "邮箱/密码/资料提交", + }, + { + "id": "turnstile", + "title": "Turnstile", + "desc": "人机验证 token", + }, + { + "id": "otp", + "title": "邮箱 OTP", + "desc": "收信解码验证码", + }, + { + "id": "mint", + "title": "Mint 落盘", + "desc": "access+refresh → cpa_auths", + }, + { + "id": "sub_summary", + "title": "子批汇总", + "desc": "SUMMARY_JSON / gained", + }, + { + "id": "batch_end_inject", + "title": "批末注入", + "desc": "goal 达成后 CPA import", + }, + ] + phase_order = [s["id"] for s in steps] + cur = phase["phase"] + if cur in ("done", "idle", "running"): + active_idx = -1 if cur in ("done", "idle") else 2 + else: + active_idx = phase_order.index(cur) if cur in phase_order else 2 + for i, s in enumerate(steps): + if cur in ("done",): + s["state"] = "done" + elif active_idx < 0: + s["state"] = "pending" + elif i < active_idx: + s["state"] = "done" + elif i == active_idx: + s["state"] = "active" + else: + s["state"] = "pending" + + return { + **counters, + "phase": phase["phase"], + "phase_title": phase["title"], + "phase_detail": phase["detail"], + "stuck": stuck, + "stuck_reason": stuck_reason, + "summary": summary, + "batch_failures": build_batch_failures(sup_text, sub_text), + "steps": steps, + "timeline": build_timeline(sup_text, sub_text), + "supervisor_log": str(sup_log) if sup_log else None, + "worker_log": str(sub_path) if sub_path else None, + "recent_writes": recent_writes, + "last_lines": (sup_text.splitlines()[-8:] if sup_text else []), + "worker_last_lines": (sub_text.splitlines()[-12:] if sub_text else []), + } diff --git a/apps/control_api/rate_limit.py b/apps/control_api/rate_limit.py new file mode 100644 index 0000000..cb102e6 --- /dev/null +++ b/apps/control_api/rate_limit.py @@ -0,0 +1,47 @@ +"""Simple in-process rate limiter for login attempts.""" + +from __future__ import annotations + +import threading +import time +from collections import defaultdict + + +class LoginRateLimiter: + def __init__(self, *, max_failures: int = 8, window_seconds: int = 300) -> None: + self.max_failures = max_failures + self.window_seconds = window_seconds + self._lock = threading.Lock() + self._failures: dict[str, list[float]] = defaultdict(list) + + def _prune(self, key: str, now: float) -> None: + cutoff = now - self.window_seconds + self._failures[key] = [t for t in self._failures[key] if t >= cutoff] + + def is_blocked(self, key: str) -> bool: + now = time.time() + with self._lock: + self._prune(key, now) + return len(self._failures[key]) >= self.max_failures + + def record_failure(self, key: str) -> None: + now = time.time() + with self._lock: + self._prune(key, now) + self._failures[key].append(now) + + def clear(self, key: str) -> None: + with self._lock: + self._failures.pop(key, None) + + def remaining_seconds(self, key: str) -> int: + now = time.time() + with self._lock: + self._prune(key, now) + if len(self._failures[key]) < self.max_failures: + return 0 + oldest = min(self._failures[key]) + return max(0, int(self.window_seconds - (now - oldest)) + 1) + + +login_limiter = LoginRateLimiter() diff --git a/apps/control_api/routes_accounts.py b/apps/control_api/routes_accounts.py new file mode 100644 index 0000000..5faabcb --- /dev/null +++ b/apps/control_api/routes_accounts.py @@ -0,0 +1,32 @@ +"""Account pool (cpa_auths product files) routes.""" + +from __future__ import annotations + +from fastapi import APIRouter, HTTPException, Query, status + +from apps.control_api.accounts_ops import delete_account, list_accounts +from apps.control_api.settings import get_settings + +router = APIRouter(tags=["accounts"]) + + +@router.get("/api/accounts") +def get_accounts( + q: str = Query(default=""), + complete: str = Query(default=""), + page: int = Query(default=1, ge=1), + page_size: int = Query(default=50, ge=0, le=500), +) -> dict: + root = get_settings().project_root + return list_accounts(root, q=q, complete=complete, page=page, page_size=page_size) + + +@router.delete("/api/accounts/{name}") +def remove_account(name: str) -> dict: + root = get_settings().project_root + try: + return delete_account(root, name) + except FileNotFoundError: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="not found") from None + except ValueError as exc: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc diff --git a/apps/control_api/routes_auth.py b/apps/control_api/routes_auth.py new file mode 100644 index 0000000..efc4c3c --- /dev/null +++ b/apps/control_api/routes_auth.py @@ -0,0 +1,106 @@ +"""Login / logout / session me endpoints.""" + +from __future__ import annotations + +from fastapi import APIRouter, Depends, HTTPException, Request, Response, status + +from apps.control_api.auth import auth_is_required, require_auth, session_username +from apps.control_api.rate_limit import login_limiter +from apps.control_api.schemas import LoginIn, LoginOut, MeOut +from apps.control_api.sessions import ( + COOKIE_NAME, + mint_session_token, + session_cookie_kwargs, +) +from apps.control_api.settings import get_settings +from apps.control_api.users import authenticate, has_any_user, list_usernames + +router = APIRouter(prefix="/api/auth", tags=["auth"]) + + +def _client_key(request: Request, username: str) -> str: + host = request.client.host if request.client else "unknown" + return f"{host}|{(username or '').strip().lower()}" + + +@router.get("/me", response_model=MeOut) +def me(request: Request) -> MeOut: + s = get_settings() + user = session_username(request) + return MeOut( + authenticated=bool(user), + username=user, + auth_required=auth_is_required(s.project_root), + password_login_enabled=s.password_login_enabled, + token_auth_enabled=bool(s.token), + users_configured=has_any_user(s.project_root), + ) + + +@router.post("/login", response_model=LoginOut) +def login(body: LoginIn, request: Request, response: Response) -> LoginOut: + s = get_settings() + if not s.password_login_enabled: + raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="password login disabled") + if not s.session_secret: + # Ops-facing: tell operator how to fix without leaking secrets. + print( + "[control_api] login blocked: session secret missing " + f"(source={s.session_secret_source}); " + "set CONTROL_API_SESSION_SECRET or .control_api_session_secret", + flush=True, + ) + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail=( + "session secret not configured — set CONTROL_API_SESSION_SECRET " + "or create .control_api_session_secret under project root " + "(or restart via scripts/run_control_api.sh)" + ), + ) + if not has_any_user(s.project_root): + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="no operators configured; set CONTROL_API_BOOTSTRAP_USER/PASSWORD once", + ) + + key = _client_key(request, body.username) + if login_limiter.is_blocked(key): + wait = login_limiter.remaining_seconds(key) + raise HTTPException( + status_code=status.HTTP_429_TOO_MANY_REQUESTS, + detail=f"too many failed logins; retry in {wait}s", + headers={"Retry-After": str(max(1, wait))}, + ) + + ok = authenticate(s.project_root, body.username, body.password) + if not ok: + login_limiter.record_failure(key) + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid username or password") + + login_limiter.clear(key) + username = body.username.strip() + token = mint_session_token( + secret=s.session_secret, + username=username, + ttl_seconds=s.session_ttl_seconds, + ) + kw = session_cookie_kwargs(secure=s.cookie_secure, max_age=s.session_ttl_seconds) + response.set_cookie(value=token, **kw) + return LoginOut(ok=True, username=username) + + +@router.post("/logout", response_model=LoginOut) +def logout(response: Response) -> LoginOut: + s = get_settings() + response.delete_cookie(COOKIE_NAME, path="/") + # also clear with secure flag variants + response.delete_cookie(COOKIE_NAME, path="/", secure=s.cookie_secure) + return LoginOut(ok=True, username=None) + + +@router.get("/users", response_model=dict, dependencies=[Depends(require_auth)]) +def users_list() -> dict: + """List operator usernames (no hashes). Auth required.""" + s = get_settings() + return {"users": list_usernames(s.project_root)} diff --git a/apps/control_api/routes_config.py b/apps/control_api/routes_config.py new file mode 100644 index 0000000..e1f55c2 --- /dev/null +++ b/apps/control_api/routes_config.py @@ -0,0 +1,56 @@ +"""Config GET/PUT routes.""" + +from __future__ import annotations + +from fastapi import APIRouter + +from apps.control_api.config_io import ( + enrich_config_from_env, + load_config, + redact_config, + save_config, +) +from apps.control_api.schemas import ConfigOut, ConfigPutIn, ConfigPutOut +from apps.control_api.settings import get_settings + +router = APIRouter(tags=["config"]) + + +@router.get("/api/config", response_model=ConfigOut) +def get_config() -> ConfigOut: + """Return config with blank operational fields filled from ``.env``. + + Disk ``config.json`` stays as-is; response enrichment makes the console + show proxy/domains the batch actually uses when only ``.env`` has them. + """ + root = get_settings().project_root + data = enrich_config_from_env(root, load_config(root)) + return ConfigOut(config=redact_config(data), path=str(root / "config.json")) + + +@router.put("/api/config", response_model=ConfigPutOut) +def put_config(body: ConfigPutIn) -> ConfigPutOut: + """Persist config.json and mirror operational keys into ``.env``. + + Batch supervisors load ``.env``; without this sync the console UI could + show hotmail while live register_cli still used a stale EMAIL_PROVIDER. + + Sticky-empty (omit / keep prior): blank ``proxy`` and most other ops keys. + Clearable empty (intentional wipe): ``email_providers``, ``proxy_list``, + ``defaultDomains`` — empty string or empty list writes through to config + and ``.env`` (e.g. ``DEFAULT_DOMAINS=``). Callers that must not clear + (Register page) simply omit those keys from the put payload. + """ + root = get_settings().project_root + result = save_config(root, body.config) + # Re-read disk after save, then enrich once and redact once (same as GET). + # Do not enrich from save_config's already-redacted payload. + enriched = enrich_config_from_env(root, load_config(root)) + return ConfigPutOut( + ok=True, + backup=result.get("backup"), + changed_keys=list(result.get("changed_keys") or []), + changed_env_keys=list(result.get("changed_env_keys") or []), + env_backup=result.get("env_backup"), + config=redact_config(enriched), + ) diff --git a/apps/control_api/routes_import.py b/apps/control_api/routes_import.py new file mode 100644 index 0000000..87bedc2 --- /dev/null +++ b/apps/control_api/routes_import.py @@ -0,0 +1,90 @@ +"""Import multipart routes.""" + +from __future__ import annotations + +import shutil +import zipfile +from pathlib import Path + +from fastapi import APIRouter, File, Form, UploadFile + +from apps.control_api.imports_ops import ( + import_auths, + import_mail, + import_nodes, + import_pack, + safe_extract_zip, + save_upload, + staging_dir, +) +from apps.control_api.schemas import ImportResultOut +from apps.control_api.settings import get_settings + +router = APIRouter(tags=["import"]) + + +@router.post("/api/import/nodes", response_model=ImportResultOut) +async def post_import_nodes( + file: UploadFile = File(...), + dry_run: bool = Form(default=False), + replace: bool = Form(default=False), +) -> ImportResultOut: + s = get_settings() + data = await file.read() + path = save_upload(s.project_root, file.filename or "nodes.yaml", data, s.max_upload_bytes) + result = import_nodes(s.project_root, path, dry_run=dry_run, replace=replace) + return ImportResultOut(ok=bool(result.get("ok")), detail="nodes import", result=result) + + +@router.post("/api/import/mail", response_model=ImportResultOut) +async def post_import_mail( + content: str = Form(...), + mode: str = Form(default="append"), +) -> ImportResultOut: + if mode not in {"append", "replace"}: + raise ValueError("mode must be append or replace") + s = get_settings() + result = import_mail(s.project_root, content, mode=mode) # type: ignore[arg-type] + summary = str(result.get("summary") or "").strip() or "mail import" + # ok stays True for HTTP 200 so UI can render structured result; status field + # (success|partial|empty) drives toast kind. + return ImportResultOut(ok=True, detail=summary, result=result) + + +@router.post("/api/import/auths", response_model=ImportResultOut) +async def post_import_auths( + file: UploadFile = File(...), + no_remote: bool = Form(default=True), +) -> ImportResultOut: + """Accept a zip of xai-*.json or a single json; extract to staging dir.""" + s = get_settings() + data = await file.read() + path = save_upload(s.project_root, file.filename or "auths.zip", data, s.max_upload_bytes) + src_dir: Path + if path.suffix.lower() == ".zip" or zipfile.is_zipfile(path): + extract = staging_dir(s.project_root) / f"auths_{path.stem}" + if extract.exists(): + shutil.rmtree(extract) + extract.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(path, "r") as zf: + safe_extract_zip(zf, extract) + src_dir = extract + else: + # single file → put in a dir + src_dir = staging_dir(s.project_root) / f"auths_one_{path.stem}" + src_dir.mkdir(parents=True, exist_ok=True) + shutil.copy2(path, src_dir / path.name) + result = import_auths(s.project_root, src_dir, no_remote=no_remote) + return ImportResultOut(ok=bool(result.get("ok")), detail="auths import", result=result) + + +@router.post("/api/import/pack", response_model=ImportResultOut) +async def post_import_pack( + file: UploadFile = File(...), + apply: bool = Form(default=False), +) -> ImportResultOut: + s = get_settings() + data = await file.read() + path = save_upload(s.project_root, file.filename or "pack.zip", data, s.max_upload_bytes) + result = import_pack(s.project_root, path, apply=apply) + return ImportResultOut(ok=True, detail="pack import", result=result) diff --git a/apps/control_api/routes_mail.py b/apps/control_api/routes_mail.py new file mode 100644 index 0000000..98dc797 --- /dev/null +++ b/apps/control_api/routes_mail.py @@ -0,0 +1,116 @@ +"""Mail pool stats / probe / quarantine routes.""" + +from __future__ import annotations + +from typing import Any + +from fastapi import APIRouter, HTTPException +from pydantic import BaseModel, Field + +from apps.control_api import mail_ops +from apps.control_api.settings import get_settings + +router = APIRouter(tags=["mail"]) + + +class MailProbeIn(BaseModel): + domains: list[str] = Field(default_factory=list) + # Per-wave cap (full pool = multi-wave via offset). 500 keeps one request + # under control_api request time without a job queue. + limit: int = Field(default=30, ge=1, le=500) + seed: int | None = None + # Sequential full-pool paging. When set, order is stable (no shuffle) and + # response carries next_offset/done for the UI/CLI to loop. + offset: int | None = Field(default=None, ge=0) + concurrency: int = Field(default=4, ge=1, le=8) + wall_seconds: float = Field(default=90.0, ge=5.0, le=600.0) + + +class MailQuarantineIn(BaseModel): + emails: list[str] = Field(min_length=1) + reason: str = Field(default="quarantine", max_length=128) + + +class MailCompactIn(BaseModel): + dry_run: bool = False + drop_invalid: bool = True + drop_comments: bool = False + + +def _http_from_exc(exc: Exception) -> HTTPException: + if isinstance(exc, FileNotFoundError): + return HTTPException(status_code=404, detail=str(exc)) + if isinstance(exc, ValueError): + return HTTPException(status_code=400, detail=str(exc)) + if isinstance(exc, RuntimeError): + return HTTPException(status_code=409, detail=str(exc)) + return HTTPException(status_code=500, detail=str(exc)) + + +@router.get("/api/mail/pool") +def api_mail_pool() -> dict[str, Any]: + root = get_settings().project_root + try: + return mail_ops.get_pool_stats(root) + except FileNotFoundError as exc: + raise _http_from_exc(exc) from exc + + +@router.post("/api/mail/probe") +def api_mail_probe(body: MailProbeIn) -> dict[str, Any]: + root = get_settings().project_root + domains = [d for d in (body.domains or []) if str(d).strip()] or None + try: + return mail_ops.probe_mail( + root, + domains=domains, + limit=body.limit, + seed=body.seed, + offset=body.offset, + concurrency=body.concurrency, + wall_seconds=body.wall_seconds, + ) + except (FileNotFoundError, ValueError, RuntimeError) as exc: + raise _http_from_exc(exc) from exc + + +@router.post("/api/mail/quarantine") +def api_mail_quarantine(body: MailQuarantineIn) -> dict[str, Any]: + root = get_settings().project_root + emails = [e.strip() for e in body.emails if e and str(e).strip()] + if not emails: + raise HTTPException(status_code=400, detail="emails must be a non-empty list") + try: + return mail_ops.quarantine_mail( + root, + emails, + reason=(body.reason or "quarantine").strip() or "quarantine", + ) + except (FileNotFoundError, ValueError) as exc: + raise _http_from_exc(exc) from exc + + +@router.post("/api/mail/compact") +def api_mail_compact(body: MailCompactIn | None = None) -> dict[str, Any]: + """Dedupe live pool by email (first wins); optional drop invalid/comments.""" + root = get_settings().project_root + body = body or MailCompactIn() + try: + return mail_ops.compact_mail( + root, + dry_run=bool(body.dry_run), + drop_invalid=bool(body.drop_invalid), + drop_comments=bool(body.drop_comments), + ) + except (FileNotFoundError, ValueError) as exc: + raise _http_from_exc(exc) from exc + + +@router.get("/api/mail/cloudflare/domains") +def api_mail_cloudflare_domains() -> dict[str, Any]: + """List domains from the configured Cloudflare temp-mail Worker.""" + root = get_settings().project_root + try: + return mail_ops.list_cloudflare_domains(root) + except (ValueError, RuntimeError) as exc: + raise _http_from_exc(exc) from exc diff --git a/apps/control_api/routes_nodes.py b/apps/control_api/routes_nodes.py new file mode 100644 index 0000000..8e05216 --- /dev/null +++ b/apps/control_api/routes_nodes.py @@ -0,0 +1,192 @@ +"""Node catalog + Clash routes.""" + +from __future__ import annotations + +from typing import Any + +from fastapi import APIRouter, Body, Query +from pydantic import BaseModel, Field + +from apps.control_api import nodes_ops +from apps.control_api.settings import get_settings + +router = APIRouter(tags=["nodes"]) + + +class NodeAddIn(BaseModel): + url: str = Field(min_length=3, max_length=2000) + label: str = Field(default="", max_length=128) + tags: list[str] = Field(default_factory=list) + tier: int = Field(default=0, ge=0, le=1) + enabled: bool = True + + +class NodeTestIn(BaseModel): + ids: list[str] = Field(default_factory=list) + timeout: float = Field(default=12.0, ge=1.0, le=60.0) + limit: int = Field(default=50, ge=1, le=500) + + +class ClashTestIn(BaseModel): + names: list[str] = Field(default_factory=list) + timeout_ms: int = Field(default=5000, ge=500, le=30000) + limit: int = Field(default=40, ge=1, le=500) + + +class ClashSubImportIn(BaseModel): + url: str = Field(min_length=8, max_length=2000) + group: str = Field(default="🎯Grok注册", max_length=128) + groups: list[str] = Field(default_factory=list) + prefix: str = Field(default="SUB", max_length=32) + mode: str = Field(default="merge", max_length=32) # merge | replace_prefix + dry_run: bool = False + reload: bool = True + timeout: float = Field(default=25.0, ge=3.0, le=120.0) + max_proxies: int = Field(default=400, ge=1, le=2000) + + +class ClashDeletePrefixIn(BaseModel): + prefix: str = Field(min_length=1, max_length=32) + dry_run: bool = False + reload: bool = True + force: bool = False # required for protected prefixes (e.g. GVPS) + + +class ClashPruneUnhealthyIn(BaseModel): + prefix: str = Field(default="", max_length=32) + group: str = Field(default="🎯Grok注册", max_length=128) + timeout_ms: int = Field(default=4000, ge=500, le=30000) + # keep wall-clock under Cloudflare ~100s when console is proxied + limit: int = Field(default=120, ge=1, le=300) + dry_run: bool = False + reload: bool = True + delete_defs: bool = True # False = only strip from groups + + +class EnabledIn(BaseModel): + enabled: bool = True + + +@router.get("/api/nodes") +def get_nodes( + q: str = Query(default=""), + health: str = Query(default=""), + tier: str = Query(default=""), + enabled: str = Query(default=""), + page: int = Query(default=1, ge=1), + page_size: int = Query(default=50, ge=0, le=500), + sort: str = Query(default="priority"), +) -> dict[str, Any]: + root = get_settings().project_root + return nodes_ops.list_catalog( + root, + q=q, + health=health, + tier=tier if tier != "" else None, + enabled=enabled if enabled != "" else None, + page=page, + page_size=page_size, + sort=sort, + ) + + +@router.post("/api/nodes") +def post_node(body: NodeAddIn) -> dict[str, Any]: + root = get_settings().project_root + return nodes_ops.add_catalog_node( + root, + url=body.url, + label=body.label, + tags=body.tags, + tier=body.tier, + enabled=body.enabled, + ) + + +@router.delete("/api/nodes/{node_id}") +def delete_node(node_id: str) -> dict[str, Any]: + root = get_settings().project_root + return nodes_ops.delete_catalog_node(root, node_id) + + +@router.patch("/api/nodes/{node_id}") +def patch_node(node_id: str, body: EnabledIn) -> dict[str, Any]: + root = get_settings().project_root + return nodes_ops.set_catalog_enabled(root, node_id, body.enabled) + + +@router.post("/api/nodes/test") +def post_test_nodes(body: NodeTestIn | None = Body(default=None)) -> dict[str, Any]: + root = get_settings().project_root + body = body or NodeTestIn() + return nodes_ops.test_catalog_nodes( + root, + ids=body.ids or None, + timeout=body.timeout, + limit=body.limit, + ) + + +@router.get("/api/nodes/clash") +def get_clash_nodes() -> dict[str, Any]: + root = get_settings().project_root + return nodes_ops.list_clash_nodes(root) + + +@router.post("/api/nodes/clash/test") +def post_clash_test(body: ClashTestIn | None = Body(default=None)) -> dict[str, Any]: + root = get_settings().project_root + body = body or ClashTestIn() + return nodes_ops.test_clash_nodes( + root, + names=body.names or None, + timeout_ms=body.timeout_ms, + limit=body.limit, + ) + + +@router.post("/api/nodes/clash/import-url") +def post_clash_import_url(body: ClashSubImportIn) -> dict[str, Any]: + """Fetch a Clash/airport subscription URL and merge into selected pool.""" + root = get_settings().project_root + return nodes_ops.import_clash_subscription( + root, + url=body.url, + group=body.group, + groups=body.groups or None, + prefix=body.prefix, + mode=body.mode, + dry_run=body.dry_run, + reload=body.reload, + timeout=body.timeout, + max_proxies=body.max_proxies, + ) + + +@router.post("/api/nodes/clash/delete-prefix") +def post_clash_delete_prefix(body: ClashDeletePrefixIn) -> dict[str, Any]: + """Delete Clash proxies whose name is ``prefix`` or starts with ``prefix-``.""" + root = get_settings().project_root + return nodes_ops.delete_clash_prefix( + root, + prefix=body.prefix, + dry_run=body.dry_run, + reload=body.reload, + force=body.force, + ) + + +@router.post("/api/nodes/clash/prune-unhealthy") +def post_clash_prune_unhealthy(body: ClashPruneUnhealthyIn) -> dict[str, Any]: + """Delay-test candidates and remove failing proxies from Clash configs.""" + root = get_settings().project_root + return nodes_ops.prune_clash_unhealthy( + root, + prefix=body.prefix, + group=body.group, + timeout_ms=body.timeout_ms, + limit=body.limit, + dry_run=body.dry_run, + reload=body.reload, + delete_defs=body.delete_defs, + ) diff --git a/apps/control_api/routes_ops.py b/apps/control_api/routes_ops.py new file mode 100644 index 0000000..a613e96 --- /dev/null +++ b/apps/control_api/routes_ops.py @@ -0,0 +1,105 @@ +"""Self-check and maintenance ops.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from fastapi import APIRouter, Query + +from apps.control_api.settings import get_settings +from apps.control_api.system_ops import cleanup_orphans, selfcheck + +router = APIRouter(tags=["ops"]) + + +@router.get("/api/ops/selfcheck") +def api_selfcheck() -> dict: + root = get_settings().project_root + return selfcheck(root) + + +@router.post("/api/ops/cleanup-orphans") +def api_cleanup_orphans(dry_run: bool = Query(default=False)) -> dict: + return cleanup_orphans(dry_run=dry_run) + + +# --------------------------------------------------------------------------- +# Outlook auth import/export helpers +# +# Outlook accounts persist as private 0600 per-account JSON files under a +# dedicated ``outlook_auths/`` directory (see OutlookProvider._write_outlook_artifact). +# These helpers expose a strict glob and a redacted public record shape so the +# control API can list/import/export Outlook accounts without ever returning a +# password or refresh_token in a response. They are deliberately separate from +# the ``xai-*.json`` glob in ``accounts_ops``: the two products must not share +# a glob or a directory. +# --------------------------------------------------------------------------- + +# A path is a valid Outlook auth file only when its full name starts with +# ``outlook-`` and ends with ``.json``; the collision suffix +# ``outlook---.json`` keeps matching. +def _is_outlook_auth_file(path: Path) -> bool: + name = path.name + return name.startswith("outlook-") and name.endswith(".json") + + +def _outlook_auth_files(root: Path) -> list[Path]: + """Sorted list of Outlook auth JSON files under ``root`` (no xai overlap).""" + if not root.exists(): + return [] + return sorted(p for p in root.iterdir() if p.is_file() and _is_outlook_auth_file(p)) + + +_OUTLOOK_REQUIRED_FIELDS = ("email", "password", "client_id", "refresh_token") + + +def _public_outlook_record(payload: dict[str, Any]) -> dict[str, Any]: + """Redacted view of one Outlook auth record (never secret values).""" + missing = [k for k in _OUTLOOK_REQUIRED_FIELDS if not payload.get(k)] + if missing: + raise ValueError(f"missing outlook fields: {','.join(sorted(missing))}") + return { + "email": str(payload["email"]), + "client_id": str(payload["client_id"]), + "bound": bool(payload.get("bound", False)), + "recovery_email": str(payload.get("recovery_email", "")), + "has_password": bool(payload.get("password")), + "has_refresh_token": bool(payload.get("refresh_token")), + } + + +@router.get("/api/outlook-accounts") +def api_list_outlook_accounts() -> dict: + """List Outlook auth records as a redacted public view. + + Strict ``outlook-*.json`` glob over the ``outlook_auths/`` directory; the + xai ``cpa_auths`` pool is never touched. Response records never carry the + password or refresh_token value — only ``has_password``/``has_refresh_token`` + flags. Records that fail the required-fields contract are skipped with a + ``skipped`` count rather than 500ing the whole list (an operator can then + repair the partial file). + """ + import json + import os + + root = get_settings().project_root + # Honor the same OUTLOOK_AUTHS_DIR env the supervisor count block and the + # adapter config use, so listing/counting stays aligned with where the + # adapter writes artifacts. Defaults to "outlook_auths" everywhere. + auth_dir_name = os.environ.get("OUTLOOK_AUTHS_DIR") or "outlook_auths" + auth_dir = root / auth_dir_name + records: list[dict[str, Any]] = [] + skipped = 0 + for path in _outlook_auth_files(auth_dir): + try: + payload = json.loads(path.read_text(encoding="utf-8")) + records.append(_public_outlook_record(payload)) + except (ValueError, OSError, json.JSONDecodeError): + skipped += 1 + return { + "accounts": records, + "count": len(records), + "skipped": skipped, + "dir": auth_dir_name, + } diff --git a/apps/control_api/routes_runs.py b/apps/control_api/routes_runs.py new file mode 100644 index 0000000..c838936 --- /dev/null +++ b/apps/control_api/routes_runs.py @@ -0,0 +1,58 @@ +"""Run control routes.""" + +from __future__ import annotations + +from fastapi import APIRouter, Query + +from apps.control_api.runs import list_runs, run_status, start_run, stop_run, tail_log +from apps.control_api.schemas import LogsOut, RunActionOut, StartRunRequest +from apps.control_api.settings import get_settings + +router = APIRouter(tags=["runs"]) + + +@router.get("/api/runs") +def get_runs() -> dict: + root = get_settings().project_root + return {"runs": list_runs(root), "current": run_status(root)} + + +@router.get("/api/runs/current") +def get_current() -> dict: + root = get_settings().project_root + return {"run": run_status(root)} + + +@router.get("/api/runs/current/logs", response_model=LogsOut) +def get_current_logs( + tail: int = Query(default=200, ge=1, le=5000), + which: str = Query(default="auto", pattern="^(auto|supervisor|worker|both)$"), +) -> LogsOut: + root = get_settings().project_root + data = tail_log(root, n=tail, which=which) + return LogsOut(path=data.get("path"), text=data.get("text") or "") + + +@router.post("/api/runs/start", response_model=RunActionOut) +def post_start(body: StartRunRequest) -> RunActionOut: + root = get_settings().project_root + result = start_run(root, body) + return RunActionOut(ok=True, run=result.get("run"), detail=result.get("detail", "")) + + +@router.post("/api/runs/stop", response_model=RunActionOut) +def post_stop() -> RunActionOut: + root = get_settings().project_root + result = stop_run(root) + # Surface pid/source/mode in detail so UI never looks like a silent no-op. + detail = str(result.get("detail") or "") + extra = [] + if result.get("pid") is not None: + extra.append(f"pid={result.get('pid')}") + if result.get("source"): + extra.append(f"source={result.get('source')}") + if result.get("mode"): + extra.append(f"mode={result.get('mode')}") + if extra: + detail = f"{detail} ({', '.join(extra)})" if detail else ", ".join(extra) + return RunActionOut(ok=bool(result.get("ok")), run=result.get("run"), detail=detail) diff --git a/apps/control_api/runs.py b/apps/control_api/runs.py new file mode 100644 index 0000000..b2eb7bd --- /dev/null +++ b/apps/control_api/runs.py @@ -0,0 +1,387 @@ +"""Start/stop/status/logs for supervised and one-shot register runs.""" + +from __future__ import annotations + +import os +import subprocess +import time +import uuid +from pathlib import Path +from typing import Any + +from fastapi import HTTPException, status + +from apps.control_api.config_io import ENV_ALLOWLIST, config_to_env_map, load_config +from apps.control_api.process_registry import ( + ProcessRegistry, + stop_pid, + supervisor_lock_held, + supervisor_lock_pid, +) +from apps.control_api.progress import build_progress +from apps.control_api.schemas import StartRunRequest + +# Request extra_env may only set allowlisted operational keys (same set as .env sync). +EXTRA_ENV_ALLOWLIST = frozenset(ENV_ALLOWLIST) + +# Max length and accepted charset for an extra_env VALUE. Values flow into the +# supervisor subprocess env (and from there can be re-serialized into .env lines +# or glued into log/config strings), so reject control characters — especially +# LF/CR, which would let a single value inject or corrupt a following line — and +# cap total length to bound log/stack growth. Keys are already allowlisted. +EXTRA_ENV_VALUE_MAX_LEN = 4096 + + +def _sanitize_extra_env_value(key: str, value: str) -> str: + """Validate a single extra_env value; raise ValueError on anything unsafe. + + Keeps printable ASCII + common printable Unicode (letters/digits/punct and + whitespace OTHER than the line terminators NUL/CR/LF). NUL/CR/LF/vtab/FF and + the DEL byte are refused outright — these are the characters that break + line-oriented .env parsing and shell sourcing, the actual injection vector. + """ + v = str(value) + if len(v) > EXTRA_ENV_VALUE_MAX_LEN: + raise ValueError( + f"extra_env value too long for {key!r} " + f"({len(v)} > {EXTRA_ENV_VALUE_MAX_LEN})" + ) + for ch in v: + o = ord(ch) + if o == 0 or o in (0x0A, 0x0D, 0x0B, 0x0C) or o == 0x7F: + raise ValueError(f"extra_env value for {key!r} contains control char") + return v + + +def filter_extra_env(extra: dict[str, str] | None) -> dict[str, str]: + out: dict[str, str] = {} + for k, v in (extra or {}).items(): + key = str(k) + if key not in EXTRA_ENV_ALLOWLIST: + raise ValueError(f"extra_env key not allowed: {key}") + out[key] = _sanitize_extra_env_value(key, v) + return out + + +def env_from_config(root: Path) -> dict[str, str]: + """Build process env overlays from config.json (console source of truth). + + Empty strings are skipped so a blank config ``proxy`` does not wipe a + working process/PROXY inherited by the supervisor. + """ + return config_to_env_map(load_config(root), skip_empty=True) + + +def _latest_supervisor_log(root: Path) -> Path | None: + logs = root / "logs" + if not logs.is_dir(): + return None + cands = sorted(logs.glob("*supervisor.log"), key=lambda p: p.stat().st_mtime, reverse=True) + return cands[0] if cands else None + + +def run_status(root: Path) -> dict[str, Any] | None: + reg = ProcessRegistry(root) + cur = reg.current() + lock_pid = supervisor_lock_pid() + sup_log = _latest_supervisor_log(root) + progress = build_progress(root, sup_log=sup_log) + + base: dict[str, Any] = { + "lock_pid": lock_pid, + "progress": progress, + # flatten common counters for backward-compatible UI/overview + "complete": progress.get("complete"), + "consecutive_zero": progress.get("consecutive_zero"), + "phase": progress.get("phase"), + "phase_title": progress.get("phase_title"), + "phase_detail": progress.get("phase_detail"), + "stuck": progress.get("stuck"), + "stuck_reason": progress.get("stuck_reason"), + "supervisor_log": progress.get("supervisor_log"), + "worker_log": progress.get("worker_log"), + "last_lines": progress.get("last_lines") or [], + "steps": progress.get("steps") or [], + "timeline": progress.get("timeline") or [], + "summary": progress.get("summary"), + "batch_failures": progress.get("batch_failures"), + "sub": progress.get("sub"), + "chunk": progress.get("chunk"), + "target": progress.get("target"), + "target_new": progress.get("target_new"), + "batch_gained": progress.get("batch_gained"), + "batch_remain": progress.get("batch_remain"), + "goal_complete": progress.get("goal_complete"), + "baseline_complete": progress.get("baseline_complete"), + "remain": progress.get("remain"), + "accounts": progress.get("accounts"), + "mode": progress.get("mode"), + # UI: surface recent xai-*.json writes at top level so front-end + # doesn't need to reach into `progress.recent_writes`. + "recent_writes": progress.get("recent_writes") or [], + } + + if cur: + return { + "source": "registry", + "alive": True, + "run_id": cur.get("run_id"), + "pid": cur.get("pid"), + "kind": cur.get("kind"), + "meta": cur.get("meta") or {}, + **base, + } + + if lock_pid is not None: + return { + "source": "lock", + "alive": True, + "run_id": None, + "pid": lock_pid, + "kind": "grok_supervisor", + "meta": {}, + **base, + } + + if progress.get("complete") is not None or base["last_lines"]: + return { + "source": "log", + "alive": False, + "run_id": None, + "pid": None, + "kind": None, + "meta": {}, + **base, + } + return None + + +def tail_log( + root: Path, + n: int = 200, + *, + which: str = "auto", +) -> dict[str, str | None]: + """Tail supervisor and/or worker logs. + + which: auto|supervisor|worker|both + """ + reg = ProcessRegistry(root) + cur = reg.current() + sup = _latest_supervisor_log(root) + progress = build_progress(root, sup_log=sup) + worker = Path(progress["worker_log"]) if progress.get("worker_log") else None + + # Prefer registry meta log for control-api-started runs + meta_log: Path | None = None + if cur and cur.get("meta", {}).get("log_path"): + meta_log = Path(cur["meta"]["log_path"]) + + def _read(path: Path | None) -> tuple[str | None, str]: + if path is None or not path.is_file(): + return None, "" + lines = path.read_text(encoding="utf-8", errors="replace").splitlines() + return str(path), "\n".join(lines[-n:]) + + if which == "worker": + p, t = _read(worker) + return {"path": p, "text": t, "which": "worker"} + if which == "supervisor": + p, t = _read(sup or meta_log) + return {"path": p, "text": t, "which": "supervisor"} + if which == "both": + sp, st = _read(sup or meta_log) + wp, wt = _read(worker) + parts = [] + if sp: + parts.append(f"===== supervisor: {sp} =====\n{st}") + if wp: + parts.append(f"===== worker: {wp} =====\n{wt}") + return { + "path": sp or wp, + "text": "\n\n".join(parts), + "which": "both", + "supervisor_path": sp, + "worker_path": wp, + } + # auto: worker if alive-ish else supervisor + if worker and worker.is_file(): + p, t = _read(worker) + # append a bit of supervisor footer for context + sp, st = _read(sup) + if st: + t = t + "\n\n----- supervisor tail -----\n" + "\n".join(st.splitlines()[-30:]) + return {"path": p, "text": t, "which": "auto", "supervisor_path": sp} + p, t = _read(meta_log or sup) + return {"path": p, "text": t, "which": "auto"} + + +def start_run(root: Path, req: StartRunRequest) -> dict[str, Any]: + extra = filter_extra_env(req.extra_env) + reg = ProcessRegistry(root) + existing = reg.current() + if existing: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=f"run already active pid={existing.get('pid')} kind={existing.get('kind')}", + ) + if req.kind == "grok_supervisor" and supervisor_lock_held(): + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=f"supervisor lock held pid={supervisor_lock_pid()}", + ) + + run_id = uuid.uuid4().hex[:12] + logs_dir = root / "logs" + logs_dir.mkdir(parents=True, exist_ok=True) + log_path = logs_dir / f"control_api_{run_id}.log" + + if req.kind == "grok_supervisor": + argv = [ + "bash", + str(root / "scripts" / "launch_batch_supervisor.sh"), + req.mode, + str(req.target), + str(req.threads), + req.tag, + ] + script = root / "scripts" / "launch_batch_supervisor.sh" + if not script.is_file(): + raise HTTPException(status_code=500, detail=f"missing {script}") + else: + _ORIG_PRODUCTS = {"grok", "mimo", "chatgpt", "outlook", "typesafe"} + universal = root / "register_universal.py" + if req.product not in _ORIG_PRODUCTS and universal.is_file(): + # universal registrar: route to combat autoreg scripts + _PY311 = r"C:/Users/User/AppData/Local/Programs/Python/Python311/python.exe" + argv = [_PY311, str(universal), req.product, str(req.target), str(req.threads)] + else: + register_sh = root / "register.sh" + if not register_sh.is_file(): + raise HTTPException(status_code=500, detail=f"missing {register_sh}") + argv = ["bash", str(register_sh), req.product, str(req.target), str(req.threads)] + + # Precedence for operational controls: + # 1) process env inherited from control_api (weakest for UI intent) + # 2) config.json mirrored via config_to_env_map (console source of truth) + # 3) request extra_env (explicit one-shot override) + # launch_batch_supervisor loads .env without clobbering already-set keys, + # so injecting config here makes the batch follow the console even when + # a stale .env still has EMAIL_PROVIDER=cloudflare. + env = os.environ.copy() + env.update(env_from_config(root)) + env.update(extra) + env["REGISTER_PROJECT_ROOT"] = str(root) + + log_f = open(log_path, "a", encoding="utf-8") + try: + proc = subprocess.Popen( + argv, + cwd=str(root), + env=env, + stdout=log_f, + stderr=subprocess.STDOUT, + # New session ⇒ pid is process-group leader; stop_run uses killpg. + start_new_session=True, + ) + except Exception: + log_f.close() + raise + else: + # Child inherited the fd; close the parent handle so we don't leak. + log_f.close() + + meta = { + "argv": argv, + "log_path": str(log_path), + "product": req.product, + "mode": req.mode, + "target": req.target, + "threads": req.threads, + "tag": req.tag, + # start_new_session=True ⇒ session/group leader == pid + "process_group": True, + "pgid": int(proc.pid), + } + reg.register(run_id, proc.pid, req.kind, meta) + + # Fail-fast: launch_batch_supervisor exits immediately when flock is held + # (or script missing). Without this poll the registry sticks on a zombie + # bash and the UI shows ALIVE + stale progress forever. + for _ in range(10): + ret = proc.poll() + if ret is not None: + reg.clear() + try: + proc.wait(timeout=0.2) + except Exception: + pass + tail = "" + try: + lines = Path(log_path).read_text(encoding="utf-8", errors="replace").splitlines() + tail = "\n".join(lines[-20:]).strip() + except Exception: + pass + detail = f"process exited immediately code={ret}" + if tail: + detail = f"{detail}: {tail[:500]}" + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail=detail, + ) + time.sleep(0.1) + + return {"ok": True, "run": reg.current(), "detail": "started"} + + +def stop_run(root: Path) -> dict[str, Any]: + """Stop control-started run (process group) or fall back to lock pid. + + Control-plane starts always use a new session, so we kill the whole group. + Lock-only (externally launched) supervisors still try process-group delivery + first and fall back to single-pid inside ``stop_pid``. + """ + reg = ProcessRegistry(root) + cur = reg.current() + pid: int | None = None + process_group = True + source = "none" + if cur: + pid = int(cur.get("pid") or 0) + meta = cur.get("meta") if isinstance(cur.get("meta"), dict) else {} + # Default True for control-started; honor explicit false if ever stored. + process_group = bool(meta.get("process_group", True)) + source = "registry" + if not pid: + pid = supervisor_lock_pid() + process_group = True # best-effort; stop_pid falls back if not leader + source = "lock" + if not pid: + return {"ok": False, "run": None, "detail": "no active run"} + result = stop_pid(pid, grace_sec=10.0, process_group=process_group) + reg.clear() + return { + "ok": bool(result.get("ok")), + "run": None, + "detail": result.get("detail", ""), + "pid": pid, + "source": source, + "mode": result.get("mode"), + } + + +def list_runs(root: Path) -> list[dict[str, Any]]: + """Recent supervisor logs index (lightweight).""" + logs = root / "logs" + if not logs.is_dir(): + return [] + out: list[dict[str, Any]] = [] + for p in sorted(logs.glob("*supervisor.log"), key=lambda x: x.stat().st_mtime, reverse=True)[:20]: + out.append( + { + "path": str(p), + "name": p.name, + "mtime": p.stat().st_mtime, + } + ) + return out diff --git a/apps/control_api/schemas.py b/apps/control_api/schemas.py new file mode 100644 index 0000000..6fde983 --- /dev/null +++ b/apps/control_api/schemas.py @@ -0,0 +1,87 @@ +"""Pydantic models for control API.""" + +from __future__ import annotations + +from typing import Any, Literal + +from pydantic import BaseModel, Field + + +class HealthOut(BaseModel): + ok: bool = True + project_root: str + token_required: bool + password_login_enabled: bool = False + users_configured: bool = False + auth_required: bool = False + + +class OverviewOut(BaseModel): + project_root: str + product_ok: int + run: dict[str, Any] | None = None + nodes: dict[str, Any] | None = None + + +class ConfigOut(BaseModel): + config: dict[str, Any] + path: str + + +class ConfigPutIn(BaseModel): + config: dict[str, Any] + + +class ConfigPutOut(BaseModel): + ok: bool + backup: str | None = None + changed_keys: list[str] = Field(default_factory=list) + changed_env_keys: list[str] = Field(default_factory=list) + env_backup: str | None = None + config: dict[str, Any] + + +class StartRunRequest(BaseModel): + kind: Literal["grok_supervisor", "register_sh"] = "grok_supervisor" + product: str = "grok" + mode: Literal["ordinary", "residential"] = "ordinary" + target: int = Field(default=100, ge=1, le=100_000) + threads: int = Field(default=1, ge=1, le=32) + tag: str = Field(default="batch_web", min_length=1, max_length=64) + extra_env: dict[str, str] = Field(default_factory=dict) + + +class RunActionOut(BaseModel): + ok: bool + run: dict[str, Any] | None = None + detail: str = "" + + +class LogsOut(BaseModel): + path: str | None = None + text: str = "" + + +class ImportResultOut(BaseModel): + ok: bool + detail: str = "" + result: dict[str, Any] = Field(default_factory=dict) + + +class LoginIn(BaseModel): + username: str = Field(min_length=1, max_length=64) + password: str = Field(min_length=1, max_length=256) + + +class LoginOut(BaseModel): + ok: bool + username: str | None = None + + +class MeOut(BaseModel): + authenticated: bool + username: str | None = None + auth_required: bool = True + password_login_enabled: bool = True + token_auth_enabled: bool = False + users_configured: bool = False diff --git a/apps/control_api/sessions.py b/apps/control_api/sessions.py new file mode 100644 index 0000000..0908027 --- /dev/null +++ b/apps/control_api/sessions.py @@ -0,0 +1,84 @@ +"""Signed HttpOnly session cookies for browser login.""" + +from __future__ import annotations + +import time +from typing import Any + +from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer + +from apps.control_api.settings import MAX_SESSION_TTL_SECONDS + +COOKIE_NAME = "control_session" + + +def _serializer(secret: str) -> URLSafeTimedSerializer: + return URLSafeTimedSerializer(secret, salt="control-api-session-v1") + + +def mint_session_token(*, secret: str, username: str, ttl_seconds: int) -> str: + if not secret: + raise ValueError("session secret required") + # Bake the ttl into the payload, clamped to the hard ceiling so a token + # whose ttl was somehow raised past the cap (older build, or a caller that + # bypassed get_settings) still verifies within the bound at read time. + ttl = max(0, min(int(ttl_seconds), MAX_SESSION_TTL_SECONDS)) + payload = { + "u": username, + "iat": int(time.time()), + "ttl": ttl, + } + return _serializer(secret).dumps(payload) + + +def read_session_token( + token: str, + *, + secret: str, + max_age: int, + max_ttl: int = MAX_SESSION_TTL_SECONDS, +) -> dict[str, Any] | None: + """Return the decoded session payload, or None for any invalid/expired token. + + Two independent guards bound a token's lifetime: + + - ``max_age``: itsdangerous rejects any token whose ``iat`` is older than + ``max_age`` seconds (the server-side ceiling, normally + settings.session_ttl_seconds). + - ``max_ttl``: the payload's baked-in ``ttl`` field is re-checked against + this hard ceiling (MAX_SESSION_TTL_SECONDS). A token minted by an older + build that did NOT clamp the ttl, or whose ttl was raised past the cap, + is refused even if it is still within ``max_age`` — so the lifetime can + only ever shrink, never grow past the constant. + """ + if not token or not secret: + return None + try: + payload = _serializer(secret).loads(token, max_age=max_age) + except (BadSignature, SignatureExpired): + return None + if not isinstance(payload, dict): + return None + user = payload.get("u") + if not isinstance(user, str) or not user: + return None + # Re-validate the baked-in ttl against the hard ceiling. A token carrying a + # ttl above max_ttl is untrustworthy (older build / tampered) — refuse it. + ttl = payload.get("ttl") + if not isinstance(ttl, int) or ttl > max_ttl or ttl < 0: + return None + return payload + + +def session_cookie_kwargs(*, secure: bool, max_age: int) -> dict[str, Any]: + # Cookie max_age is also clamped to the hard ceiling so a runaway TTL env + # can't ask the browser to keep an effectively-immortal cookie either. + capped = max(0, min(int(max_age), MAX_SESSION_TTL_SECONDS)) + return { + "key": COOKIE_NAME, + "httponly": True, + "samesite": "strict", + "secure": secure, + "path": "/", + "max_age": capped, + } diff --git a/apps/control_api/settings.py b/apps/control_api/settings.py new file mode 100644 index 0000000..c66a1a5 --- /dev/null +++ b/apps/control_api/settings.py @@ -0,0 +1,195 @@ +"""Environment settings for the control API.""" + +from __future__ import annotations + +from dataclasses import dataclass +from functools import lru_cache +from pathlib import Path +import os +import secrets + + +# Durable secret files under project root (mode 0600 recommended). +SESSION_SECRET_FILENAME = ".control_api_session_secret" +TOKEN_FILENAME = ".control_api_token" + +# Hard ceiling on session cookie / token lifetime, independent of the +# operator-tunable CONTROL_API_SESSION_TTL. Even if an operator raises the TTL +# env (it is clamped to [MIN_SESSION_TTL_SECONDS, MAX_SESSION_TTL_SECONDS] in +# get_settings), a signed token can never outlive this bound: read_session_token +# re-validates the ttl baked into the payload against this constant. +MIN_SESSION_TTL_SECONDS = 300 +MAX_SESSION_TTL_SECONDS = 7 * 24 * 3600 + + +@dataclass(frozen=True) +class Settings: + project_root: Path + host: str + port: int + token: str | None + max_upload_bytes: int = 20 * 1024 * 1024 + # Password / session auth + session_secret: str | None = None + session_ttl_seconds: int = 12 * 3600 + cookie_secure: bool = False + password_login_enabled: bool = True + bootstrap_user: str | None = None + bootstrap_password: str | None = None + # Where session_secret / token came from (for ops logs only; never the value) + session_secret_source: str = "missing" + token_source: str = "missing" + + @property + def auth_required(self) -> bool: + """True when bearer token is set. Password users checked via auth_is_required().""" + return bool(self.token) + + +def _read_secret_file(path: Path) -> str | None: + """Read one-line secret file; return stripped text or None. Never log contents.""" + try: + if not path.is_file(): + return None + text = path.read_text(encoding="utf-8", errors="replace").strip() + # first non-empty line only + for line in text.splitlines(): + line = line.strip() + if line and not line.startswith("#"): + return line + return text or None + except Exception: + return None + + +def _resolve_project_root() -> Path: + root = os.environ.get("REGISTER_PROJECT_ROOT") + return Path(root).resolve() if root else Path.cwd().resolve() + + +@lru_cache(maxsize=1) +def get_settings() -> Settings: + project_root = _resolve_project_root() + host = os.environ.get("CONTROL_API_HOST", "127.0.0.1") + port = int(os.environ.get("CONTROL_API_PORT", "8787")) + max_upload = int(os.environ.get("CONTROL_API_MAX_UPLOAD_BYTES", str(20 * 1024 * 1024))) + + # ── bearer token: env → file ──────────────────────────────────────────── + token = os.environ.get("CONTROL_API_TOKEN") + token_source = "env" + if token is not None and token.strip() == "": + token = None + if not token: + file_token = _read_secret_file(project_root / TOKEN_FILENAME) + if file_token: + token = file_token + token_source = f"file:{TOKEN_FILENAME}" + else: + token_source = "missing" + + # ── session secret: env → file → token → dev env → ephemeral ──────────── + session_secret = os.environ.get("CONTROL_API_SESSION_SECRET") + session_secret_source = "env" + if session_secret is not None and session_secret.strip() == "": + session_secret = None + if not session_secret: + file_secret = _read_secret_file(project_root / SESSION_SECRET_FILENAME) + if file_secret: + session_secret = file_secret + session_secret_source = f"file:{SESSION_SECRET_FILENAME}" + if not session_secret and token: + session_secret = token + session_secret_source = "token" + if not session_secret: + dev = os.environ.get("CONTROL_API_DEV_SESSION_SECRET") + if dev and dev.strip(): + session_secret = dev.strip() + session_secret_source = "env:CONTROL_API_DEV_SESSION_SECRET" + if not session_secret and os.environ.get("CONTROL_API_ALLOW_EPHEMERAL_SESSION") == "1": + session_secret = secrets.token_hex(32) + session_secret_source = "ephemeral" + if not session_secret: + session_secret_source = "missing" + + ttl = int(os.environ.get("CONTROL_API_SESSION_TTL", str(12 * 3600))) + # Clamp to a safe band: never below the min floor (5 min) and never above the + # hard ceiling (7 days). The cookie max_age AND the signed-token ttl both + # derive from this, so a runaway TTL env can't mint effectively-immortal + # sessions. read_session_token additionally re-validates the ttl in the + # payload against MAX_SESSION_TTL_SECONDS, so a token minted before a + # re-clamp can't slip a longer-lived ttl through either. + ttl = max(MIN_SESSION_TTL_SECONDS, min(MAX_SESSION_TTL_SECONDS, ttl)) + cookie_secure = os.environ.get("CONTROL_API_COOKIE_SECURE", "").strip().lower() in { + "1", + "true", + "yes", + "on", + } + # Password login on by default; set CONTROL_API_PASSWORD_LOGIN=0 to disable + pw_flag = os.environ.get("CONTROL_API_PASSWORD_LOGIN", "1").strip().lower() + password_login_enabled = pw_flag not in {"0", "false", "no", "off"} + + # Empty user store only: first-start default operator. Override via env. + # Production hosts that already have .control_api_users.json are untouched + # (ensure_bootstrap_user is a no-op when any user exists). + bootstrap_user = os.environ.get("CONTROL_API_BOOTSTRAP_USER") + bootstrap_password = os.environ.get("CONTROL_API_BOOTSTRAP_PASSWORD") + if bootstrap_user is not None and bootstrap_user.strip() == "": + bootstrap_user = None + if bootstrap_password is not None and bootstrap_password.strip() == "": + bootstrap_password = None + if bootstrap_user is None and "CONTROL_API_BOOTSTRAP_USER" not in os.environ: + bootstrap_user = "admin" + if bootstrap_password is None and "CONTROL_API_BOOTSTRAP_PASSWORD" not in os.environ: + bootstrap_password = "admin123" + + return Settings( + project_root=project_root, + host=host, + port=port, + token=token, + max_upload_bytes=max_upload, + session_secret=session_secret, + session_ttl_seconds=ttl, + cookie_secure=cookie_secure, + password_login_enabled=password_login_enabled, + bootstrap_user=bootstrap_user, + bootstrap_password=bootstrap_password, + session_secret_source=session_secret_source, + token_source=token_source, + ) + + +def clear_settings_cache() -> None: + get_settings.cache_clear() + + +def log_auth_startup(settings: Settings | None = None) -> None: + """Ops-safe startup line: sources + readiness, never secret values.""" + s = settings or get_settings() + secret_ok = bool(s.session_secret) + token_ok = bool(s.token) + users = "yes" if (s.project_root / ".control_api_users.json").is_file() else "no" + print( + "[control_api] auth " + f"session_secret={s.session_secret_source} " + f"token={s.token_source} " + f"password_login={'on' if s.password_login_enabled else 'off'} " + f"users_file={users} " + f"ready={'yes' if (secret_ok and s.password_login_enabled) or token_ok else 'NO'}", + flush=True, + ) + if s.password_login_enabled and not secret_ok: + print( + "[control_api] WARN password login will fail: session secret missing. " + f"Set CONTROL_API_SESSION_SECRET or create {s.project_root / SESSION_SECRET_FILENAME} " + f"(or set CONTROL_API_TOKEN / {TOKEN_FILENAME}). " + "Bare `python -m apps.control_api` without secrets is unsupported on production.", + flush=True, + ) + if s.session_secret_source == "ephemeral": + print( + "[control_api] WARN session secret is ephemeral — logins invalidate on restart. " + f"Persist via {SESSION_SECRET_FILENAME} or CONTROL_API_SESSION_SECRET.", + flush=True, + ) diff --git a/apps/control_api/system_ops.py b/apps/control_api/system_ops.py new file mode 100644 index 0000000..290cba1 --- /dev/null +++ b/apps/control_api/system_ops.py @@ -0,0 +1,177 @@ +"""Self-check + orphan browser/Xvfb cleanup for the control plane.""" + +from __future__ import annotations + +import json +import os +import shutil +import socket +import time +from pathlib import Path +from typing import Any +from urllib.error import URLError +from urllib.request import ProxyHandler, Request, build_opener + + +def _ok(name: str, ok: bool, detail: str = "", **extra: Any) -> dict[str, Any]: + out = {"name": name, "ok": bool(ok), "detail": detail} + out.update(extra) + return out + + +def _tcp_open(host: str, port: int, timeout: float = 1.5) -> bool: + try: + with socket.create_connection((host, port), timeout=timeout): + return True + except OSError: + return False + + +def _http_probe(url: str, proxy: str | None = None, timeout: float = 8.0) -> tuple[bool, str]: + try: + handlers = [] + if proxy: + handlers.append(ProxyHandler({"http": proxy, "https": proxy})) + opener = build_opener(*handlers) + req = Request(url, method="GET", headers={"User-Agent": "control-api-selfcheck/1"}) + with opener.open(req, timeout=timeout) as resp: + code = getattr(resp, "status", None) or resp.getcode() + return True, f"HTTP {code}" + except Exception as exc: + return False, f"{type(exc).__name__}: {exc}"[:200] + + +def selfcheck(root: Path) -> dict[str, Any]: + checks: list[dict[str, Any]] = [] + cfg_path = root / "config.json" + cfg: dict[str, Any] = {} + if cfg_path.is_file(): + try: + raw = json.loads(cfg_path.read_text(encoding="utf-8")) + cfg = {k: v for k, v in raw.items() if not str(k).startswith("//")} + checks.append(_ok("config.json", True, f"keys={len(cfg)}")) + except Exception as exc: + checks.append(_ok("config.json", False, str(exc)[:200])) + else: + checks.append(_ok("config.json", False, "missing")) + + venv_py = root / ".venv" / "bin" / "python" + checks.append(_ok("venv_python", venv_py.is_file(), str(venv_py))) + reg_cli = root / "register_cli.py" + checks.append(_ok("register_cli.py", reg_cli.is_file(), str(reg_cli))) + sup = root / "scripts" / "launch_batch_supervisor.sh" + checks.append(_ok("launch_batch_supervisor.sh", sup.is_file(), str(sup))) + auths = root / "cpa_auths" + if auths.is_dir(): + n = sum(1 for _ in auths.glob("xai-*.json")) + checks.append(_ok("cpa_auths", True, f"files={n}", path=str(auths))) + else: + checks.append(_ok("cpa_auths", False, "missing dir", path=str(auths))) + + # Clash mixed-port default + clash_port = 7897 + clash_up = _tcp_open("127.0.0.1", clash_port) + checks.append( + _ok( + "clash_mixed_7897", + clash_up, + "up" if clash_up else "down (ordinary batch needs mihomo mixed-port)", + ) + ) + clash_api = _tcp_open("127.0.0.1", 9090) or _tcp_open("127.0.0.1", 9097) + checks.append(_ok("clash_api", clash_api, "9090/9097 reachable" if clash_api else "api port closed")) + + # Display / browsers for headed mint + display = os.environ.get("DISPLAY") or "" + checks.append(_ok("DISPLAY", bool(display) or shutil.which("Xvfb") is not None, display or "no DISPLAY; Xvfb available" if shutil.which("Xvfb") else "no DISPLAY/Xvfb")) + checks.append(_ok("xvfb-run", shutil.which("xvfb-run") is not None, shutil.which("xvfb-run") or "missing")) + + proxy = str(cfg.get("proxy") or cfg.get("cpa_proxy") or "http://127.0.0.1:7897") + if clash_up: + ok, detail = _http_probe("https://accounts.x.ai/", proxy=proxy, timeout=10) + checks.append(_ok("egress_accounts_xai", ok, detail, proxy=proxy)) + else: + checks.append(_ok("egress_accounts_xai", False, "skipped: clash down", proxy=proxy)) + + # Mail provider hint (singleton + multi pool) + provider = str(cfg.get("email_provider") or os.environ.get("EMAIL_PROVIDER") or "") + raw_multi = cfg.get("email_providers") + if raw_multi is None or raw_multi == "": + raw_multi = os.environ.get("EMAIL_PROVIDERS") or "" + if isinstance(raw_multi, (list, tuple, set)): + multi = [str(x).strip() for x in raw_multi if str(x).strip()] + else: + multi = [p.strip() for p in str(raw_multi).replace(",", ",").split(",") if p.strip()] + multi_s = ",".join(multi) if multi else "" + domains = str(cfg.get("defaultDomains") or os.environ.get("DEFAULT_DOMAINS") or "") + checks.append( + _ok( + "email_config", + bool(provider or multi), + ( + f"provider={provider or '?'} " + f"providers={multi_s or '(empty)'} " + f"domains={domains or '(empty)'}" + ), + ) + ) + + # Live run lock + lock_pid = None + lock_alive = False + pid_path = Path("/tmp/grok_batch_supervisor.lock.pid") + if pid_path.is_file(): + try: + lock_pid = int(pid_path.read_text().strip()) + os.kill(lock_pid, 0) + lock_alive = True + except Exception: + lock_alive = False + checks.append( + _ok( + "supervisor_lock", + True, + f"pid={lock_pid} alive={lock_alive}" if lock_pid is not None else "no lock", + pid=lock_pid, + alive=lock_alive, + ) + ) + + failed = [c for c in checks if not c.get("ok")] + return { + "ok": len(failed) == 0, + "ts": int(time.time()), + "failed": len(failed), + "checks": checks, + "summary": "all green" if not failed else f"{len(failed)} check(s) failed", + } + + +def cleanup_orphans(*, dry_run: bool = False) -> dict[str, Any]: + """Kill PPID=1 leftover Drission Chromes + empty Xvfb (safe for live register_cli children).""" + try: + from tab_pool import cleanup_orphan_drission_chromes, cleanup_orphan_xvfb + except Exception as exc: + return {"ok": False, "detail": f"import tab_pool failed: {exc}", "dry_run": dry_run} + + chrome = cleanup_orphan_drission_chromes( + dry_run=dry_run, + only_ppid_init=True, + include_self_children=False, + kill_related_helpers=True, + clean_tmp_dirs=True, + tmp_dir_max_age_sec=0 if not dry_run else 0, + ) + xvfb = cleanup_orphan_xvfb(dry_run=dry_run, only_ppid_init=True, require_no_children=True) + return { + "ok": True, + "dry_run": dry_run, + "chrome": chrome, + "xvfb": xvfb, + "detail": ( + f"chrome_killed={chrome.get('killed', 0)} xvfb_killed={xvfb.get('killed', 0)}" + if not dry_run + else f"chrome_would={chrome.get('would_kill', chrome.get('matched', 0))} " + f"xvfb_would={xvfb.get('would_kill', xvfb.get('matched', 0))}" + ), + } diff --git a/apps/control_api/users.py b/apps/control_api/users.py new file mode 100644 index 0000000..29d4a39 --- /dev/null +++ b/apps/control_api/users.py @@ -0,0 +1,122 @@ +"""Operator credentials store for control-plane login. + +File: {project_root}/.control_api_users.json (gitignored) +Schema: + { + "version": 1, + "users": { + "admin": {"password_hash": "scrypt$...", "disabled": false} + } + } +""" + +from __future__ import annotations + +import json +import os +import threading +from pathlib import Path +from typing import Any + +from apps.control_api.passwords import hash_password, verify_password + +USERS_FILENAME = ".control_api_users.json" +_lock = threading.Lock() + + +def users_path(project_root: Path) -> Path: + return project_root / USERS_FILENAME + + +def _default_doc() -> dict[str, Any]: + return {"version": 1, "users": {}} + + +def load_users_doc(path: Path) -> dict[str, Any]: + if not path.is_file(): + return _default_doc() + try: + data = json.loads(path.read_text(encoding="utf-8")) + except Exception: + return _default_doc() + if not isinstance(data, dict): + return _default_doc() + users = data.get("users") + if not isinstance(users, dict): + data = _default_doc() + else: + data.setdefault("version", 1) + data["users"] = users + return data + + +def save_users_doc(path: Path, doc: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix(path.suffix + ".tmp") + text = json.dumps(doc, ensure_ascii=False, indent=2) + "\n" + tmp.write_text(text, encoding="utf-8") + os.chmod(tmp, 0o600) + tmp.replace(path) + try: + os.chmod(path, 0o600) + except OSError: + pass + + +def list_usernames(project_root: Path) -> list[str]: + doc = load_users_doc(users_path(project_root)) + return sorted(str(u) for u in (doc.get("users") or {}) if str(u)) + + +def has_any_user(project_root: Path) -> bool: + return bool(list_usernames(project_root)) + + +def authenticate(project_root: Path, username: str, password: str) -> bool: + username = (username or "").strip() + if not username or not password: + return False + path = users_path(project_root) + with _lock: + doc = load_users_doc(path) + rec = (doc.get("users") or {}).get(username) + if not isinstance(rec, dict): + return False + if rec.get("disabled"): + return False + hashed = rec.get("password_hash") or "" + return verify_password(password, str(hashed)) + + +def upsert_user(project_root: Path, username: str, password: str, *, disabled: bool = False) -> None: + username = (username or "").strip() + if not username: + raise ValueError("username required") + if len(username) > 64 or any(c in username for c in " \t\n\r/\\"): + raise ValueError("invalid username") + if not password or len(password) < 8: + raise ValueError("password must be at least 8 characters") + path = users_path(project_root) + with _lock: + doc = load_users_doc(path) + users = doc.setdefault("users", {}) + users[username] = { + "password_hash": hash_password(password), + "disabled": bool(disabled), + } + save_users_doc(path, doc) + + +def ensure_bootstrap_user( + project_root: Path, + *, + username: str | None, + password: str | None, +) -> str | None: + """Create first user from env if store empty. Returns created username or None.""" + if has_any_user(project_root): + return None + if not username or not password: + return None + upsert_user(project_root, username, password, disabled=False) + return username.strip() diff --git a/apps/gui/README.md b/apps/gui/README.md new file mode 100644 index 0000000..0d14b04 --- /dev/null +++ b/apps/gui/README.md @@ -0,0 +1,13 @@ +# Desktop GUI — removed + +The TTK desktop UI (`GrokRegisterGUI`) was removed. + +Use the **Web control plane** instead: + +```bash +export CONTROL_API_TOKEN=$(openssl rand -hex 32) # recommended +./scripts/run_control_api.sh +# open http://127.0.0.1:8787 +``` + +See `apps/README.md` and `docs/superpowers/specs/2026-07-21-web-control-plane-design.md`. diff --git a/apps/web/index.html b/apps/web/index.html new file mode 100644 index 0000000..dc05e01 --- /dev/null +++ b/apps/web/index.html @@ -0,0 +1,12 @@ + + + + + + AI РеГЕР · Control Plane + + +
+ + + diff --git a/apps/web/package-lock.json b/apps/web/package-lock.json new file mode 100644 index 0000000..420425a --- /dev/null +++ b/apps/web/package-lock.json @@ -0,0 +1,4147 @@ +{ + "name": "ai-register-console", + "version": "10.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "ai-register-console", + "version": "10.0.0", + "dependencies": { + "@preact/signals": "^2.0.4", + "preact": "^10.26.4" + }, + "devDependencies": { + "@preact/preset-vite": "^2.10.1", + "@testing-library/preact": "^3.2.4", + "jsdom": "^26.1.0", + "vite": "^6.2.0", + "vitest": "^4.1.10" + } + }, + "node_modules/@asamuzakjp/css-color": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", + "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.3", + "@csstools/css-color-parser": "^3.0.9", + "@csstools/css-parser-algorithms": "^3.0.4", + "@csstools/css-tokenizer": "^3.0.3", + "lru-cache": "^10.4.3" + } + }, + "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", + "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.7", + "@babel/helper-compilation-targets": "^7.29.7", + "@babel/helper-module-transforms": "^7.29.7", + "@babel/helpers": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.7.tgz", + "integrity": "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-annotate-as-pure": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.29.7.tgz", + "integrity": "sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", + "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", + "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz", + "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.7.tgz", + "integrity": "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.7" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-syntax-jsx": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.29.7.tgz", + "integrity": "sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.29.7.tgz", + "integrity": "sha512-WsZulLVBUHXVj2cUcPVx6UE21TpalB6bHbSFErKT0Ib++ax24jjXe73FqlWvdylFOjiuPHYi6VCcgRad1ItN+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.29.7", + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-plugin-utils": "^7.29.7", + "@babel/plugin-syntax-jsx": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-development": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-development/-/plugin-transform-react-jsx-development-7.29.7.tgz", + "integrity": "sha512-Xfy3UVMF04+ypnFbkhvfqtmvwfe92qwQdbGZVonhE+6v35GzlofmOnA1szaZqzb9xYWr0nl1e5EMmzi0DNON1g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/plugin-transform-react-jsx": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz", + "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.7.tgz", + "integrity": "sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.7", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.7", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.7.tgz", + "integrity": "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@preact/preset-vite": { + "version": "2.10.6", + "resolved": "https://registry.npmjs.org/@preact/preset-vite/-/preset-vite-2.10.6.tgz", + "integrity": "sha512-ZZ5RIT2ZVXg8UxRA8VZpoT8CdpDG7RFIqOT4bELqNBp85+HKvQBbgmh3gsoW1UOQXx26TLe+ZRNKI7q281Kckw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/plugin-transform-react-jsx": "^7.27.1", + "@babel/plugin-transform-react-jsx-development": "^7.27.1", + "@prefresh/vite": "^2.4.11", + "@rollup/pluginutils": "^5.0.0", + "babel-plugin-transform-hook-names": "^1.0.2", + "debug": "^4.4.3", + "magic-string": "^0.30.21", + "picocolors": "^1.1.1", + "vite-prerender-plugin": "^0.5.8", + "zimmerframe": "^1.1.4" + }, + "peerDependencies": { + "@babel/core": "7.x", + "vite": "2.x || 3.x || 4.x || 5.x || 6.x || 7.x || 8.x" + } + }, + "node_modules/@preact/signals": { + "version": "2.9.4", + "resolved": "https://registry.npmjs.org/@preact/signals/-/signals-2.9.4.tgz", + "integrity": "sha512-JzAZXcRkmCNf9wVuxNI7UWseu3++Mm0dZ6UFyjFby44CyKIl7Y06oOsW3KA5Nx0L8tpE87OY5pLe0uQ0xcWKrg==", + "license": "MIT", + "dependencies": { + "@preact/signals-core": "^1.14.4" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + }, + "peerDependencies": { + "preact": ">= 10.25.0 || >=11.0.0-0" + } + }, + "node_modules/@preact/signals-core": { + "version": "1.14.4", + "resolved": "https://registry.npmjs.org/@preact/signals-core/-/signals-core-1.14.4.tgz", + "integrity": "sha512-HNB6HYeYKhQbJ1aKl+YRjrS4+QWHLKX6qKoUsfS/m0vqzsVaEBiZiaKbG/e+NKk2ch5ALQr/ihWaMHxiCuuWHA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + } + }, + "node_modules/@prefresh/babel-plugin": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/@prefresh/babel-plugin/-/babel-plugin-0.5.3.tgz", + "integrity": "sha512-57LX2SHs4BX2s1IwCjNzTE2OJeEepRCNf1VTEpbNcUyHfMO68eeOWGDIt4ob9aYlW6PEWZ1SuwNikuoIXANDtQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@prefresh/core": { + "version": "1.5.10", + "resolved": "https://registry.npmjs.org/@prefresh/core/-/core-1.5.10.tgz", + "integrity": "sha512-7yPTFbG56sutaFu8krp3B4a200KOFUvrtlllKWRuLjsYXo9UUucHOZRcer+gtgMkFTpv6ob8TGcTwA32bSwa1w==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "preact": "^10.0.0 || ^11.0.0-0" + } + }, + "node_modules/@prefresh/utils": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@prefresh/utils/-/utils-1.2.1.tgz", + "integrity": "sha512-vq/sIuN5nYfYzvyayXI4C2QkprfNaHUQ9ZX+3xLD8nL3rWyzpxOm1+K7RtMbhd+66QcaISViK7amjnheQ/4WZw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@prefresh/vite": { + "version": "2.4.12", + "resolved": "https://registry.npmjs.org/@prefresh/vite/-/vite-2.4.12.tgz", + "integrity": "sha512-FY1fzXpUjiuosznMV0YM7XAOPZjB5FIdWS0W24+XnlxYkt9hNAwwsiKYn+cuTEoMtD/ZVazS5QVssBr9YhpCQA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.22.1", + "@prefresh/babel-plugin": "^0.5.2", + "@prefresh/core": "^1.5.0", + "@prefresh/utils": "^1.2.0", + "@rollup/pluginutils": "^4.2.1" + }, + "peerDependencies": { + "preact": "^10.4.0 || ^11.0.0-0", + "vite": ">=2.0.0" + } + }, + "node_modules/@prefresh/vite/node_modules/@rollup/pluginutils": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-4.2.1.tgz", + "integrity": "sha512-iKnFXr7NkdZAIHiIWE+BX5ULi/ucVFYWD6TbAV+rZctiRTY2PL6tsIKhoIOaoskiWAkgu+VsbXgUVDNLHf+InQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "estree-walker": "^2.0.1", + "picomatch": "^2.2.2" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/@prefresh/vite/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/@rollup/pluginutils": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.4.0.tgz", + "integrity": "sha512-MfPp06CjRLfXQ3wY0R8vJDYBy/MvVcc9OulEfR0B8Iv9ko+GCNaRZ+EpJYFl27LhKsZK0o420sYCRHCjfCgeUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "estree-walker": "^2.0.2", + "picomatch": "^4.0.2" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.2.tgz", + "integrity": "sha512-6o7ZLZK+BeenkZCFNDXqpbjw9bD6nuWonvS/lwQJp7NoVVxm6p3qE7qQ5jGuBjiFsgvqjD8mZAU5oWxTmbOeOg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.62.2.tgz", + "integrity": "sha512-BaH7BllCACHoH1LguOU56UItGfUWjujlO65kS9LAodViaN4bwIKd7oeW/ZHJ/4ljr/7MIiENnNy3HJ0zXv8Zkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.62.2.tgz", + "integrity": "sha512-v39RCCvj4He82I9sFmk+M1VZ0PLM9sfsLVikjfx2hYBNALhrrOR2D3JjQA6AhlaSOgcR+RzrKY7e1+bT6SUO/A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.62.2.tgz", + "integrity": "sha512-yl0y2vq3S3lHeuXhEdss6TWfKW8vkujImO12tn4ZkG/4oghr09LvdYm2RElVjokTQiUvDUGXLGsYeLqUMCKpGA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.62.2.tgz", + "integrity": "sha512-tT4pvt4qXD+vEoezupCWi+a1F0vvDiksiHc+PxRlYTOH1I6/X4id9jPxTP+Fg+545euaFT1jJVs4CEdHZAU1vw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.62.2.tgz", + "integrity": "sha512-6nU5F2wCW+qvCBhTn1pdIU3bzsIoF7EUwsCDRxilWGprQR6yd508YnH9+OKFCwpfS8pjZqDUmnCAr7exax0XCg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.62.2.tgz", + "integrity": "sha512-n1GJHPOvpIfhi3TmrCeh6S6URt9BFCt0KQE3qvexyGCTAKpR4Lg+eWvNZEqu7epxwus/8ElT3hacYEucm49SZg==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.62.2.tgz", + "integrity": "sha512-JqgflS8wEB+UXV/vS1RpRbifGBeN4D5lz8D8oOFbFZw4vedvdOgCFAjfBmIMdW3yL10XpQQ0Ambepw6MXrhOnA==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.62.2.tgz", + "integrity": "sha512-wnFJkogWvN4jm/hQRF2UBaeUmk20j5+DmHvoyWii2b8HJDyvz1MF2OU/6ynXt2KR63rbZLWkFpoytpdc/yBuSA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.62.2.tgz", + "integrity": "sha512-HVu2bp0zhvJ8xHEV9+UUs7S90VadmBSY3LcIMvozbPo4AuMGDWlz3ymHLHZPX4hR67TKTt8Qp5PJ5RBg/i+RMQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.62.2.tgz", + "integrity": "sha512-mQqqAV8QaoSgr9I2fKDLY2BAVvmKjWoGiu/cSYQonsLvtqwEn1E4QYfnCOcp5zoEqNhsDYin1s6jx/VJmrxlZg==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.62.2.tgz", + "integrity": "sha512-IxKLoxCQ2IWi6bT2akyDUBGsOImDKB+sPp4EsTmwFQ/fMwpCKm8uLSSgP/Kx/QYUgKis6SEZ5/Nlhup0DIA0PQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.62.2.tgz", + "integrity": "sha512-Mk5ha2RQSgyFfmYYLkBpPnUk8D8FriBxesO1u9O75X0mHgXL1UQcH5Itl2lurWL2tj0RxV9b9tJgipac0hRY9A==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.62.2.tgz", + "integrity": "sha512-CjvEnqJL/0/TQ3TXX3OPIJ/kmBellrWd4heXUmHeJlTnmwjKpSJzoehLaL6Xk0ZnMHBu9dZuFADNOrtjF4v+2w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.62.2.tgz", + "integrity": "sha512-1SiZbzwdkaDURsew/tSOrooKiYy7EQGT6m8ufavAi9NEyQb/6VuIxFXAL1fqa4iZe3g4NbNk4P7J32z2tw5Mgg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.62.2.tgz", + "integrity": "sha512-nQts12zJ3NQRoE6uYljOH89v7szzLDvG2JD/vsX+vGXU8w/At1GowTZ5/7qeFQ8m7L55rpR8Okugnuo5bgjy2Q==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.62.2.tgz", + "integrity": "sha512-E9/ll019jhPIJgpzfZoIkBGhcz+kKNgVWYRY0zr9srBdPPFVpvOKW8VaJKUbeK+eZXyQF9ltME+Kk6affeaPgg==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.62.2.tgz", + "integrity": "sha512-5BqxR/pshjey51iliyzTD5Xi3EN0aLmQ2lZ3lvefVV9c82BvrLo2/6OT55iifpWBufs6kdwWbuOKS841DrmK9A==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.62.2.tgz", + "integrity": "sha512-uNN83XxQrRAh/w0/pmAfibcwyb6YWt4gP+dpnQKPVJshAloQ785ii8CT8ZCIxkGg9opVsvAlGhFitSm6D1Jjpg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.62.2.tgz", + "integrity": "sha512-srjEIxSH3LRnJN6THczDHWQplqEMFiAJrTab0msUryh9kwNpkICf3Ea6q6MN/2cZwRFUNx5w+h6Hpi4QuHS6Zg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.62.2.tgz", + "integrity": "sha512-8hOJnxgbyObnCm5AlRA3A931xX19xq80RjVTKgJOvEKWqJruP/Uf12IbAOaDjjEXYRewwHLfmF0YRIdK3OwKWA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.62.2.tgz", + "integrity": "sha512-mmF4AY1i0hG/bLWUctUq59gtmgaSIRa3cu/A3JFRp/sCNEme2bgDEiDS22P9FbnJB8NJNF4jPJiSP5RHQpUTDg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.62.2.tgz", + "integrity": "sha512-DZgkknc6jhHrk46V25vbAM0zZkyP0nSDkJB8/dRkLTxv470dOmWDqGoEJl/9A0dFfS7yE3REOwNDxpHwSLSt0Q==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.62.2.tgz", + "integrity": "sha512-T6xr6ucWSFto+VGajA8YH26LdpHRuP4YLHEKAtCWvJDOlnmWcDZVCI2Jmjr+IFHDlt2zRaTAKE4tfjTaWLgJBg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.62.2.tgz", + "integrity": "sha512-BfzEnDJOt9T8M989/lA37EcJgat01wLRnoi5dQf3QzOH7jzpqTAzdDbVfRljVr5r+jzKqpbHeyOfAaXxAd0PAA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@testing-library/dom": { + "version": "8.20.1", + "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-8.20.1.tgz", + "integrity": "sha512-/DiOQ5xBxgdYRC8LNk7U+RWat0S3qRLeIw3ZIkMQ9kkVlRmwD/Eg8k8CqIpD6GW7u20JIUOfMKbxtiLutpjQ4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.10.4", + "@babel/runtime": "^7.12.5", + "@types/aria-query": "^5.0.1", + "aria-query": "5.1.3", + "chalk": "^4.1.0", + "dom-accessibility-api": "^0.5.9", + "lz-string": "^1.5.0", + "pretty-format": "^27.0.2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@testing-library/preact": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@testing-library/preact/-/preact-3.2.4.tgz", + "integrity": "sha512-F+kJ243LP6VmEK1M809unzTE/ijg+bsMNuiRN0JEDIJBELKKDNhdgC/WrUSZ7klwJvtlO3wQZ9ix+jhObG07Fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@testing-library/dom": "^8.11.1" + }, + "engines": { + "node": ">= 12" + }, + "peerDependencies": { + "preact": ">=10 || ^10.0.0-alpha.0 || ^10.0.0-beta.0" + } + }, + "node_modules/@types/aria-query": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", + "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@vitest/expect": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.10.tgz", + "integrity": "sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.1.10", + "@vitest/utils": "4.1.10", + "chai": "^6.2.2", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.10.tgz", + "integrity": "sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.1.10", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker/node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.10.tgz", + "integrity": "sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.10.tgz", + "integrity": "sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.1.10", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.10.tgz", + "integrity": "sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.10", + "@vitest/utils": "4.1.10", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.10.tgz", + "integrity": "sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.10.tgz", + "integrity": "sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.10", + "convert-source-map": "^2.0.0", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/aria-query": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.1.3.tgz", + "integrity": "sha512-R5iJ5lkuHybztUfuOAznmboyjWq8O6sqNqtK7CLOqdydi54VNbORp49mb14KbWgG1QD3JFO9hJdZ+y4KutfdOQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "deep-equal": "^2.0.5" + } + }, + "node_modules/array-buffer-byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.2.tgz", + "integrity": "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "is-array-buffer": "^3.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/babel-plugin-transform-hook-names": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-hook-names/-/babel-plugin-transform-hook-names-1.0.2.tgz", + "integrity": "sha512-5gafyjyyBTTdX/tQQ0hRgu4AhNHG/hqWi0ZZmg2xvs2FgRkJXzDNKBZCyoYqgFkovfDrgM8OoKg8karoUvWeCw==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@babel/core": "^7.12.10" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.1.tgz", + "integrity": "sha512-HYXq73DDpCtNzOmrFsm9eSwCvWCql0RzqjpDzXN9EadiLJ4DNat0nsZ/Bzmy+Ud12mb4/zKDY0cQ805ZzN+i0A==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/boolbase": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", + "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==", + "dev": true, + "license": "ISC" + }, + "node_modules/browserslist": { + "version": "4.28.7", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.7.tgz", + "integrity": "sha512-JxV13hNrFxqjOc8alRbq9dK1MM79NEXYpma2B2J4wAtpWS5zIEIKqWPGCl7N4o7Uc7B7itylh7SuDujATRyyTw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.10.44", + "caniuse-lite": "^1.0.30001806", + "electron-to-chromium": "^1.5.393", + "node-releases": "^2.0.51", + "update-browserslist-db": "^1.2.3" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/call-bind": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", + "integrity": "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "get-intrinsic": "^1.3.0", + "set-function-length": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001806", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001806.tgz", + "integrity": "sha512-72Cuvd95zbSYPKq6Fhg8eDJRlzgWDf7/mtoZv6Qe/DYNCEBdNxoA3+rZAU2ZhGCpZlns3EssFavaZomckT5Uuw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chai": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/css-select": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.2.2.tgz", + "integrity": "sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0", + "css-what": "^6.1.0", + "domhandler": "^5.0.2", + "domutils": "^3.0.1", + "nth-check": "^2.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/css-what": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.2.2.tgz", + "integrity": "sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">= 6" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/cssstyle": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz", + "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^3.2.0", + "rrweb-cssom": "^0.8.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/data-urls": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", + "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/deep-equal": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-2.2.3.tgz", + "integrity": "sha512-ZIwpnevOurS8bpT4192sqAowWM76JDKSHYzMLty3BZGSswgq6pBaH3DhCSW5xVAZICZyKdOBPjwww5wfgT/6PA==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.0", + "call-bind": "^1.0.5", + "es-get-iterator": "^1.1.3", + "get-intrinsic": "^1.2.2", + "is-arguments": "^1.1.1", + "is-array-buffer": "^3.0.2", + "is-date-object": "^1.0.5", + "is-regex": "^1.1.4", + "is-shared-array-buffer": "^1.0.2", + "isarray": "^2.0.5", + "object-is": "^1.1.5", + "object-keys": "^1.1.1", + "object.assign": "^4.1.4", + "regexp.prototype.flags": "^1.5.1", + "side-channel": "^1.0.4", + "which-boxed-primitive": "^1.0.2", + "which-collection": "^1.0.1", + "which-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/dom-accessibility-api": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", + "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", + "dev": true, + "license": "MIT" + }, + "node_modules/dom-serializer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", + "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", + "dev": true, + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.2", + "entities": "^4.2.0" + }, + "funding": { + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/domelementtype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "BSD-2-Clause" + }, + "node_modules/domhandler": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", + "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "domelementtype": "^2.3.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/domutils": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", + "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "dom-serializer": "^2.0.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.395", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.395.tgz", + "integrity": "sha512-7zt9Aw+SrmxLWLN0zhaTWZQiCdryLVrYTq5R7iZakLvi2UQPYMMsROYV/2qVCzMeCiSXHwKOU+sZ4zOVVlrtKA==", + "dev": true, + "license": "ISC" + }, + "node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-get-iterator": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/es-get-iterator/-/es-get-iterator-1.1.3.tgz", + "integrity": "sha512-sPZmqHBe6JIiTfN5q2pEi//TwxmAFHwj/XEuYjTuse78i8KxaqMTTzxPoFKuzRpDpTJ+0NAbpfenkmH2rePtuw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.1.3", + "has-symbols": "^1.0.3", + "is-arguments": "^1.1.1", + "is-map": "^2.0.2", + "is-set": "^2.0.2", + "is-string": "^1.0.7", + "isarray": "^2.0.5", + "stop-iteration-iterator": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.1.tgz", + "integrity": "sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/for-each": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz", + "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-bigints": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz", + "integrity": "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "dev": true, + "license": "MIT", + "bin": { + "he": "bin/he" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/internal-slot": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz", + "integrity": "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "hasown": "^2.0.2", + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-arguments": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.2.0.tgz", + "integrity": "sha512-7bVbi0huj/wrIAOzb8U1aszg9kdi3KN/CyU19CTI7tAoZYEZoL9yCDXpbXN+uPsuWnP02cyug1gleqq+TU+YCA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz", + "integrity": "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-bigint": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.1.0.tgz", + "integrity": "sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-bigints": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-boolean-object": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.2.2.tgz", + "integrity": "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-date-object": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.1.0.tgz", + "integrity": "sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-map": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz", + "integrity": "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-number-object": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.1.1.tgz", + "integrity": "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-regex": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz", + "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-set": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.3.tgz", + "integrity": "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.4.tgz", + "integrity": "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-string": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz", + "integrity": "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-symbol": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.1.1.tgz", + "integrity": "sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-symbols": "^1.1.0", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakmap": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.2.tgz", + "integrity": "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakset": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.4.tgz", + "integrity": "sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsdom": { + "version": "26.1.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz", + "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssstyle": "^4.2.1", + "data-urls": "^5.0.0", + "decimal.js": "^10.5.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.16", + "parse5": "^7.2.1", + "rrweb-cssom": "^0.8.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^5.1.1", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.1.1", + "ws": "^8.18.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/kolorist": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/kolorist/-/kolorist-1.8.0.tgz", + "integrity": "sha512-Y+60/zizpJ3HRH8DCss+q95yr6145JXZo46OTpFvDZWLfRCE4qChOyk1b26nMaNpfHHgxagk9dXT5OP0Tfe+dQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/lz-string": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", + "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", + "dev": true, + "license": "MIT", + "bin": { + "lz-string": "bin/bin.js" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.16", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz", + "integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-html-parser": { + "version": "6.1.13", + "resolved": "https://registry.npmjs.org/node-html-parser/-/node-html-parser-6.1.13.tgz", + "integrity": "sha512-qIsTMOY4C/dAa5Q5vsobRpOOvPfC4pB61UVW2uSwZNUp0QU/jCekTal1vMmbO0DgdHeLUJpv/ARmDqErVxA3Sg==", + "dev": true, + "license": "MIT", + "dependencies": { + "css-select": "^5.1.0", + "he": "1.2.0" + } + }, + "node_modules/node-releases": { + "version": "2.0.51", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.51.tgz", + "integrity": "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/nth-check": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", + "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0" + }, + "funding": { + "url": "https://github.com/fb55/nth-check?sponsor=1" + } + }, + "node_modules/nwsapi": { + "version": "2.2.24", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.24.tgz", + "integrity": "sha512-7YRhZ3jS45LwmSCT4b2sVFHt/WuovaktDU07QrtOBY2PXskss5a9jfmR9jptyumwXST+rFjrmppMY1KT/yn35A==", + "dev": true, + "license": "MIT" + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-is": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.6.tgz", + "integrity": "sha512-F8cZ+KfGlSGi09lJT7/Nd6KJZ9ygtvYC0/UYYLI9nmQKLMnydpB9yvbv9K1uSkEu7FU9vYPmVwLg328tX+ot3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.7.tgz", + "integrity": "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0", + "has-symbols": "^1.1.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/obug": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz", + "integrity": "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5/node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", + "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/possible-typed-array-names": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", + "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/postcss": { + "version": "8.5.22", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.22.tgz", + "integrity": "sha512-KBDEIpLrvpv16pp3K0Fw+UCoZfopFjjgeB+0tA/aaThfEE74kKDLrgg603YvOWJyg3+WYtyq3xYsQWsIyZlPqQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.16", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/preact": { + "version": "10.29.7", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.29.7.tgz", + "integrity": "sha512-DCHYrK/B10yUD3ZjLfhZ3WIE/9Vf9VFUODcRE2dRomTYDpJk6z6L9wecSfhfE6M9ZTHUdyQkoC46arIDhEV84Q==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + }, + "peerDependencies": { + "preact-render-to-string": ">=5" + }, + "peerDependenciesMeta": { + "preact-render-to-string": { + "optional": true + } + } + }, + "node_modules/pretty-format": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", + "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "react-is": "^17.0.1" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + } + }, + "node_modules/pretty-format/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/react-is": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", + "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", + "dev": true, + "license": "MIT" + }, + "node_modules/regexp.prototype.flags": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz", + "integrity": "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-errors": "^1.3.0", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "set-function-name": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/rollup": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz", + "integrity": "sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.62.2", + "@rollup/rollup-android-arm64": "4.62.2", + "@rollup/rollup-darwin-arm64": "4.62.2", + "@rollup/rollup-darwin-x64": "4.62.2", + "@rollup/rollup-freebsd-arm64": "4.62.2", + "@rollup/rollup-freebsd-x64": "4.62.2", + "@rollup/rollup-linux-arm-gnueabihf": "4.62.2", + "@rollup/rollup-linux-arm-musleabihf": "4.62.2", + "@rollup/rollup-linux-arm64-gnu": "4.62.2", + "@rollup/rollup-linux-arm64-musl": "4.62.2", + "@rollup/rollup-linux-loong64-gnu": "4.62.2", + "@rollup/rollup-linux-loong64-musl": "4.62.2", + "@rollup/rollup-linux-ppc64-gnu": "4.62.2", + "@rollup/rollup-linux-ppc64-musl": "4.62.2", + "@rollup/rollup-linux-riscv64-gnu": "4.62.2", + "@rollup/rollup-linux-riscv64-musl": "4.62.2", + "@rollup/rollup-linux-s390x-gnu": "4.62.2", + "@rollup/rollup-linux-x64-gnu": "4.62.2", + "@rollup/rollup-linux-x64-musl": "4.62.2", + "@rollup/rollup-openbsd-x64": "4.62.2", + "@rollup/rollup-openharmony-arm64": "4.62.2", + "@rollup/rollup-win32-arm64-msvc": "4.62.2", + "@rollup/rollup-win32-ia32-msvc": "4.62.2", + "@rollup/rollup-win32-x64-gnu": "4.62.2", + "@rollup/rollup-win32-x64-msvc": "4.62.2", + "fsevents": "~2.3.2" + } + }, + "node_modules/rrweb-cssom": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/safe-regex-test": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.1.0.tgz", + "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-regex": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-function-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz", + "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/simple-code-frame": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/simple-code-frame/-/simple-code-frame-1.3.0.tgz", + "integrity": "sha512-MB4pQmETUBlNs62BBeRjIFGeuy/x6gGKh7+eRUemn1rCFhqo7K+4slPqsyizCbcbYLnaYqaoZ2FWsZ/jN06D8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "kolorist": "^1.6.0" + } + }, + "node_modules/source-map": { + "version": "0.7.6", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz", + "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">= 12" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stack-trace": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-1.0.0.tgz", + "integrity": "sha512-H6D7134xi6qONvh7ZHKgviXf+rd3vhGBSvebPZCaUkd8zvQ+7PtDw6CljPTe4cXWNf2IKZGNqw6VJXSb9IgBpA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz", + "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==", + "dev": true, + "license": "MIT" + }, + "node_modules/stop-iteration-iterator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz", + "integrity": "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "internal-slot": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.4.tgz", + "integrity": "sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyrainbow": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz", + "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tldts": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz", + "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.86" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz", + "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz", + "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^6.1.32" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/vite": { + "version": "6.4.3", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz", + "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite-prerender-plugin": { + "version": "0.5.13", + "resolved": "https://registry.npmjs.org/vite-prerender-plugin/-/vite-prerender-plugin-0.5.13.tgz", + "integrity": "sha512-IKSpYkzDBsKAxa05naRbj7GvNVMSdww/Z/E89oO3xndz+gWnOBOKOAbEXv7qDhktY/j3vHgJmoV1pPzqU2tx9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "kolorist": "^1.8.0", + "magic-string": "0.x >= 0.26.0", + "node-html-parser": "^6.1.12", + "simple-code-frame": "^1.3.0", + "source-map": "^0.7.4", + "stack-trace": "^1.0.0-pre2" + }, + "peerDependencies": { + "vite": "5.x || 6.x || 7.x || 8.x" + } + }, + "node_modules/vitest": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.10.tgz", + "integrity": "sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.1.10", + "@vitest/mocker": "4.1.10", + "@vitest/pretty-format": "4.1.10", + "@vitest/runner": "4.1.10", + "@vitest/snapshot": "4.1.10", + "@vitest/spy": "4.1.10", + "@vitest/utils": "4.1.10", + "es-module-lexer": "^2.0.0", + "expect-type": "^1.3.0", + "magic-string": "^0.30.21", + "obug": "^2.1.1", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^4.0.0-rc.1", + "tinybench": "^2.9.0", + "tinyexec": "^1.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.1.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.1.10", + "@vitest/browser-preview": "4.1.10", + "@vitest/browser-webdriverio": "4.1.10", + "@vitest/coverage-istanbul": "4.1.10", + "@vitest/coverage-v8": "4.1.10", + "@vitest/ui": "4.1.10", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/which-boxed-primitive": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz", + "integrity": "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-bigint": "^1.1.0", + "is-boolean-object": "^1.2.1", + "is-number-object": "^1.1.1", + "is-string": "^1.1.1", + "is-symbol": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-collection": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.2.tgz", + "integrity": "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-map": "^2.0.3", + "is-set": "^2.0.3", + "is-weakmap": "^2.0.2", + "is-weakset": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-typed-array": { + "version": "1.1.22", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.22.tgz", + "integrity": "sha512-fvO4ExWMFsqyhG3AiPAObMuY1lxaqgYcxbc49CNdWDDECOJNgQyvsOWVwbZc+qf3rzRtxojBK+CMEv0Ld5CYpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "for-each": "^0.3.5", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ws": { + "version": "8.21.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.1.tgz", + "integrity": "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + }, + "node_modules/zimmerframe": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz", + "integrity": "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/apps/web/package.json b/apps/web/package.json new file mode 100644 index 0000000..7925ff5 --- /dev/null +++ b/apps/web/package.json @@ -0,0 +1,24 @@ +{ + "name": "ai-register-console", + "private": true, + "version": "10.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview", + "test": "vitest run", + "test:watch": "vitest" + }, + "dependencies": { + "@preact/signals": "^2.0.4", + "preact": "^10.26.4" + }, + "devDependencies": { + "@preact/preset-vite": "^2.10.1", + "@testing-library/preact": "^3.2.4", + "jsdom": "^26.1.0", + "vite": "^6.2.0", + "vitest": "^4.1.10" + } +} diff --git a/apps/web/src/App.jsx b/apps/web/src/App.jsx new file mode 100644 index 0000000..e6c0269 --- /dev/null +++ b/apps/web/src/App.jsx @@ -0,0 +1,137 @@ +import { useEffect, useState } from "preact/hooks"; +import { session } from "./store/session.js"; +import * as api from "./api/client.js"; +import { ToastHost } from "./ui/ToastHost.jsx"; +import { OpsFeedbackBar } from "./ui/OpsFeedbackBar.jsx"; +import { LoginGate } from "./pages/LoginGate.jsx"; +import { RegisterPage } from "./pages/Register/RegisterPage.jsx"; +import { LogsPage } from "./pages/RunLogs/LogsPage.jsx"; +import { AccountsPage } from "./pages/Accounts/AccountsPage.jsx"; +import { ResourcesPage } from "./pages/Resources/ResourcesPage.jsx"; +import { SettingsPage } from "./pages/Settings/SettingsPage.jsx"; + +const NAV = [ + { id: "register", label: "Обзор / Регистрация", hash: "#/register" }, + { id: "logs", label: "Журнал запусков", hash: "#/logs" }, + { id: "accounts", label: "Пул аккаунтов", hash: "#/accounts" }, + { id: "resources", label: "Ресурсы", hash: "#/resources" }, + { id: "settings", label: "Настройки", hash: "#/settings" }, +]; + +function pageFromHash() { + const h = (location.hash || "#/register").replace(/^#\/?/, ""); + const id = h.split("?")[0] || "register"; + return NAV.some((n) => n.id === id) ? id : "register"; +} + +export function App() { + const [page, setPage] = useState(pageFromHash); + const [sidebarOpen, setSidebarOpen] = useState(false); + + useEffect(() => { + const onHash = () => setPage(pageFromHash()); + window.addEventListener("hashchange", onHash); + return () => window.removeEventListener("hashchange", onHash); + }, []); + + useEffect(() => { + (async () => { + try { + const m = await api.me(); + session.value = { ...session.value, ...m, checked: true }; + } catch { + session.value = { ...session.value, authenticated: false, checked: true }; + } + })(); + }, []); + + const authed = session.value.authenticated || !session.value.auth_required; + + if (!session.value.checked) return ; + if (!authed) return ; + + const Page = { + register: RegisterPage, + logs: LogsPage, + accounts: AccountsPage, + resources: ResourcesPage, + settings: SettingsPage, + }[page]; + + return ( + <> + +
+ + {sidebarOpen ? ( + +
+ +
+ + +
+ + + ); +} diff --git a/apps/web/src/api/client.js b/apps/web/src/api/client.js new file mode 100644 index 0000000..2ef9fb8 --- /dev/null +++ b/apps/web/src/api/client.js @@ -0,0 +1,217 @@ +const TOKEN_KEY = "controlToken"; + +export function getToken() { + return sessionStorage.getItem(TOKEN_KEY) || ""; +} +export function setToken(t) { + if (t) sessionStorage.setItem(TOKEN_KEY, t); + else sessionStorage.removeItem(TOKEN_KEY); +} +export function clearToken() { + sessionStorage.removeItem(TOKEN_KEY); +} + +export function headers(json = false) { + const h = {}; + if (json) h["Content-Type"] = "application/json"; + const t = getToken(); + if (t) h["Authorization"] = `Bearer ${t}`; + return h; +} + +export async function api(path, opts = {}) { + const callerHeaders = opts.headers || {}; + const hasAuth = Object.keys(callerHeaders).some( + (k) => k.toLowerCase() === "authorization" + ); + const token = getToken(); + const merged = { + ...(token && !hasAuth ? { Authorization: `Bearer ${token}` } : {}), + ...callerHeaders, + }; + const res = await fetch(path, { + credentials: "same-origin", + ...opts, + headers: merged, + }); + const text = await res.text(); + let body; + try { + body = text ? JSON.parse(text) : {}; + } catch { + body = { detail: text }; + } + if (!res.ok) { + const detail = body.detail || body.error || body.message || res.statusText; + let msg = + typeof detail === "string" + ? detail + : detail != null + ? JSON.stringify(detail) + : res.statusText; + // Never keep multi-KB Cloudflare HTML in Error.message — toast/banner explode. + if ( + msg.length > 280 || + /]/i.test(msg) + ) { + const title = (msg.match(/]*>([^<]+)<\/title>/i) || [])[1] || ""; + const codeM = msg.match(/Error code\s+(\d{3})/i); + const code = codeM ? codeM[1] : String(res.status); + if (String(code) === "524" || /timeout occurred/i.test(msg)) { + msg = `Таймаут шлюза (Cloudflare 524): origin не ответил вовремя${title ? ` · ${title}` : ""}`; + } else { + msg = `HTTP ${code}: ${(title || "страница ошибки origin").replace(/\s*\|\s*.*$/, "").trim()}`; + } + } + const err = new Error(msg); + err.status = res.status; + throw err; + } + return body; +} + +export async function postMultipart(url, formData) { + const res = await fetch(url, { + method: "POST", + headers: headers(), + body: formData, + credentials: "same-origin", + }); + const body = await res.json().catch(() => ({})); + if (!res.ok) { + const err = new Error(body.detail || res.statusText); + err.status = res.status; + throw err; + } + return body; +} + +// Auth +export const login = (username, password) => + api("/api/auth/login", { + method: "POST", + headers: headers(true), + body: JSON.stringify({ username, password }), + }); +export const logout = () => api("/api/auth/logout", { method: "POST", headers: headers(true) }); +export const me = () => api("/api/auth/me"); + +// Core +export const overview = () => api("/api/overview"); +export const getConfig = () => api("/api/config"); +export const putConfig = (partial) => + api("/api/config", { + method: "PUT", + headers: headers(true), + body: JSON.stringify(partial), + }); + +// Runs +export const listRuns = () => api("/api/runs"); +export const currentRun = () => api("/api/runs/current"); +export const startRun = (body) => + api("/api/runs/start", { + method: "POST", + headers: headers(true), + body: JSON.stringify(body), + }); +export const stopRun = () => + api("/api/runs/stop", { method: "POST", headers: headers(true) }); +export const runLogs = (tail = 200, which = "auto") => + api(`/api/runs/current/logs?tail=${tail}&which=${which}`); + +// Accounts +export const listAccounts = (qs) => api(`/api/accounts?${qs}`); +export const deleteAccount = (name) => + api(`/api/accounts/${encodeURIComponent(name)}`, { + method: "DELETE", + headers: headers(), + }); + +// Nodes +export const listClash = () => api("/api/nodes/clash"); +export const testClash = (body) => + api("/api/nodes/clash/test", { + method: "POST", + headers: headers(true), + body: JSON.stringify(body || {}), + }); +export const importClashUrl = (body) => + api("/api/nodes/clash/import-url", { + method: "POST", + headers: headers(true), + body: JSON.stringify(body), + }); +export const deleteClashPrefix = (body) => + api("/api/nodes/clash/delete-prefix", { + method: "POST", + headers: headers(true), + body: JSON.stringify(body), + }); +export const pruneClashUnhealthy = (body) => + api("/api/nodes/clash/prune-unhealthy", { + method: "POST", + headers: headers(true), + body: JSON.stringify(body), + }); +export const listCatalog = (qs) => api(`/api/nodes?${qs}`); +export const addCatalogNode = (body) => + api("/api/nodes", { + method: "POST", + headers: headers(true), + body: JSON.stringify(body), + }); +export const testCatalog = (body) => + api("/api/nodes/test", { + method: "POST", + headers: headers(true), + body: JSON.stringify(body || {}), + }); +export const deleteCatalogNode = (id) => + api(`/api/nodes/${encodeURIComponent(id)}`, { + method: "DELETE", + headers: headers(), + }); +export const patchCatalogNode = (id, body) => + api(`/api/nodes/${encodeURIComponent(id)}`, { + method: "PATCH", + headers: headers(true), + body: JSON.stringify(body), + }); + +// Import multipart +export const importNodesFile = (fd) => postMultipart("/api/import/nodes", fd); +export const importMailText = (fd) => postMultipart("/api/import/mail", fd); +export const importAuthsFile = (fd) => postMultipart("/api/import/auths", fd); +export const importPackFile = (fd) => postMultipart("/api/import/pack", fd); + +// Ops +export const selfcheck = () => api("/api/ops/selfcheck", { headers: headers() }); +export const cleanupOrphans = () => + api("/api/ops/cleanup-orphans?dry_run=false", { + method: "POST", + headers: headers(true), + }); + +// Mail pool probe +export const mailPoolStats = () => api("/api/mail/pool"); +export const probeMail = (body) => + api("/api/mail/probe", { + method: "POST", + headers: headers(true), + body: JSON.stringify(body || {}), + }); +export const quarantineMail = (body) => + api("/api/mail/quarantine", { + method: "POST", + headers: headers(true), + body: JSON.stringify(body || {}), + }); +export const compactMail = (body) => + api("/api/mail/compact", { + method: "POST", + headers: headers(true), + body: JSON.stringify(body || {}), + }); +export const cloudflareDomains = () => api("/api/mail/cloudflare/domains"); diff --git a/apps/web/src/lib/format.js b/apps/web/src/lib/format.js new file mode 100644 index 0000000..bf8272d --- /dev/null +++ b/apps/web/src/lib/format.js @@ -0,0 +1,90 @@ +export function escapeHtml(s) { + return String(s ?? "") + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); +} + +export function dash(v) { + return v == null || v === "" ? "—" : String(v); +} + +export function fmtNum(v) { + return v == null || v === "" ? "—" : String(v); +} + +export function pct(a, b) { + if (b == null || a == null || Number(b) <= 0) return null; + return Math.max(0, Math.min(100, (Number(a) / Number(b)) * 100)); +} + +/** Collapse Cloudflare / HTML error pages into a short operator-facing line. */ +export function summarizeErrorText(raw, status) { + const text = String(raw ?? "").trim(); + if (!text) return status ? `HTTP ${status}` : "unknown error"; + + const looksHtml = + /]/i.test(text) || + /<\/html>/i.test(text) || + //i.test(text); + const mCode = + text.match(/Error code\s+(\d{3})/i) || + text.match(/\bError\s+(\d{3})\b/i) || + text.match(/\b(52[0-9]|50[0-9])\s*:\s*A timeout occurred/i); + const title = + (text.match(/<title[^>]*>([^<]+)<\/title>/i) || [])[1] || + (text.match(/A timeout occurred/i) ? "A timeout occurred" : ""); + const code = mCode + ? Number(mCode[1]) + : status && Number(status) >= 400 + ? Number(status) + : null; + + if (looksHtml || (code && code >= 500 && text.length > 180)) { + if (code === 524 || /timeout occurred/i.test(text) || /524/.test(title)) { + return ( + "Таймаут шлюза (Cloudflare 524): origin обрабатывал слишком долго." + + "Сузьте диапазон/префикс проверки или повторите позже (долгие задачи переведены на параллельную проверку)." + ); + } + if (code === 502 || code === 503 || code === 504) { + return `Ошибка шлюза (HTTP ${code}): origin временно недоступен, повторите позже.`; + } + if (code) { + const shortTitle = String(title || "") + .replace(/\s*\|\s*.*$/, "") + .trim() + .slice(0, 80); + return shortTitle + ? `HTTP ${code}: ${shortTitle}` + : `HTTP ${code}: origin вернул страницу ошибки`; + } + return "Origin вернул HTML-страницу ошибки (тело опущено)"; + } + + // strip accidental HTML tags if a short fragment leaked + let one = text.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim(); + if (one.length > 240) one = `${one.slice(0, 220)}…`; + return one; +} + +export function formatApiError(e) { + if (!e) return "unknown error"; + if (typeof e === "string") return summarizeErrorText(e); + const status = e.status; + const msg = e.message != null ? e.message : String(e); + const summary = summarizeErrorText(msg, status); + // summarizeErrorText already prefixes HTTP codes for HTML pages; avoid double "524: 524:" + if (status && !/^HTTP\s+\d+/.test(summary) && !summary.includes(String(status))) { + return `${status}: ${summary}`; + } + return summary; +} + +export function healthBadge(h) { + if (h === "ok" || h === true) return { label: "ok", cls: "ok" }; + if (h === "fail" || h === false) return { label: "fail", cls: "danger" }; + return { label: "?", cls: "muted" }; +} diff --git a/apps/web/src/lib/http.js b/apps/web/src/lib/http.js new file mode 100644 index 0000000..543ac36 --- /dev/null +++ b/apps/web/src/lib/http.js @@ -0,0 +1,22 @@ +// Shared API-call helpers: JSON pretty-printing + 401 session handling. +// Extracted from the four identical copies previously inlined in +// Settings / MailTab / NodesTab / ImportTab. +import { session } from "../store/session.js"; + +/** JSON.stringify with 2-space indent; strings pass through; never throws. */ +export function pretty(v) { + try { + return typeof v === "string" ? v : JSON.stringify(v, null, 2); + } catch { + return String(v); + } +} + +/** On a 401 error, drop the session so LoginGate shows. Returns true if handled. */ +export function auth401(e) { + if (e && e.status === 401) { + session.value = { ...session.value, authenticated: false }; + return true; + } + return false; +} diff --git a/apps/web/src/lib/http.test.js b/apps/web/src/lib/http.test.js new file mode 100644 index 0000000..1d776a5 --- /dev/null +++ b/apps/web/src/lib/http.test.js @@ -0,0 +1,52 @@ +import { describe, it, expect, beforeEach } from "vitest"; +import { pretty, auth401 } from "./http.js"; +import { session } from "../store/session.js"; + +const BASE = { + authenticated: true, + username: "op", + auth_required: true, + password_login_enabled: true, + users_configured: true, + checked: true, +}; + +beforeEach(() => { + session.value = { ...BASE }; +}); + +describe("pretty", () => { + it("passes strings through unchanged", () => { + expect(pretty("hi")).toBe("hi"); + expect(pretty("")).toBe(""); + }); + it("pretty-prints objects with 2-space indent", () => { + expect(pretty({ a: 1 })).toBe('{\n "a": 1\n}'); + }); + it("falls back to String() on circular refs", () => { + const o = {}; + o.self = o; + expect(pretty(o)).toBe("[object Object]"); + }); +}); + +describe("auth401", () => { + it("returns false and leaves session alone for non-401", () => { + expect(auth401({ status: 500 })).toBe(false); + expect(session.value.authenticated).toBe(true); + }); + it("returns false for null/undefined", () => { + expect(auth401(null)).toBe(false); + expect(auth401(undefined)).toBe(false); + expect(session.value.authenticated).toBe(true); + }); + it("returns true and clears authenticated on 401", () => { + expect(auth401({ status: 401 })).toBe(true); + expect(session.value.authenticated).toBe(false); + }); + it("keeps the rest of the session fields intact", () => { + auth401({ status: 401 }); + expect(session.value.username).toBe("op"); + expect(session.value.checked).toBe(true); + }); +}); diff --git a/apps/web/src/lib/providers.js b/apps/web/src/lib/providers.js new file mode 100644 index 0000000..7bab41d --- /dev/null +++ b/apps/web/src/lib/providers.js @@ -0,0 +1,56 @@ +// Shared email-provider pool helpers (Register / Settings / RegForm). +// Keep in sync with runtime _EMAIL_PROVIDER_POOL_KNOWN in grok_register_ttk.py. + +export const EMAIL_PROVIDERS = [ + "cloudflare", + "cloudmail", + "duckmail", + "yyds", + "gmail", + "hotmail", +]; + +export const EMAIL_PROVIDER_STRATEGIES = ["round_robin", "random", "failover"]; + +export function normalizeProviderName(raw) { + let p = String(raw || "") + .trim() + .toLowerCase(); + if (p === "outlook" || p === "outlookmail" || p === "microsoft") p = "hotmail"; + if (p === "google" || p === "googlemail") p = "gmail"; + return p; +} + +/** Parse multi-select from array or comma/space string; dedupe; known only. */ +export function normalizeProvidersList(raw) { + const parts = Array.isArray(raw) + ? raw + : String(raw || "") + .split(/[,,;\s]+/) + .filter(Boolean); + const out = []; + const seen = new Set(); + for (const item of parts) { + const p = normalizeProviderName(item); + if (!p || !EMAIL_PROVIDERS.includes(p) || seen.has(p)) continue; + seen.add(p); + out.push(p); + } + return out; +} + +/** + * Resolve pool from config.email_providers, else single email_provider. + * Console Register/Settings load multi-only (no singleton promote) so a Settings + * clear-pool stays empty across Reload/Save. Use this helper only where + * runtime-style "multi or singleton" display is intentional. + * @param {object} c + * @param {{ fallback?: string[] }} [opts] + */ +export function providersFromConfig(c, { fallback = [] } = {}) { + const multi = normalizeProvidersList(c && c.email_providers); + if (multi.length) return multi; + const single = normalizeProviderName(c && c.email_provider); + if (single && EMAIL_PROVIDERS.includes(single)) return [single]; + return Array.isArray(fallback) ? fallback.slice() : []; +} diff --git a/apps/web/src/lib/providers.test.js b/apps/web/src/lib/providers.test.js new file mode 100644 index 0000000..8eccc69 --- /dev/null +++ b/apps/web/src/lib/providers.test.js @@ -0,0 +1,81 @@ +import { describe, it, expect } from "vitest"; +import { + normalizeProviderName, + normalizeProvidersList, + providersFromConfig, + EMAIL_PROVIDERS, +} from "./providers.js"; + +describe("normalizeProviderName", () => { + it("maps outlook aliases to hotmail", () => { + expect(normalizeProviderName("Outlook")).toBe("hotmail"); + expect(normalizeProviderName("microsoft")).toBe("hotmail"); + expect(normalizeProviderName(" outlookmail ")).toBe("hotmail"); + }); + it("maps google aliases to gmail", () => { + expect(normalizeProviderName("GoogleMail")).toBe("gmail"); + expect(normalizeProviderName("google")).toBe("gmail"); + }); + it("returns empty string for blank input", () => { + expect(normalizeProviderName(null)).toBe(""); + expect(normalizeProviderName(" ")).toBe(""); + }); +}); + +describe("normalizeProvidersList", () => { + it("parses comma / space / full-width separators", () => { + expect(normalizeProvidersList("gmail, hotmail cloudflare")).toEqual([ + "gmail", + "hotmail", + "cloudflare", + ]); + }); + it("dedupes and drops unknown", () => { + expect(normalizeProvidersList(["gmail", "gmail", "bogus"])).toEqual(["gmail"]); + }); + it("accepts arrays and preserves input order", () => { + expect(normalizeProvidersList(EMAIL_PROVIDERS)).toEqual(EMAIL_PROVIDERS); + expect(normalizeProvidersList(["hotmail", "cloudflare"])).toEqual([ + "hotmail", + "cloudflare", + ]); + }); + it("normalizes aliases while deduping", () => { + expect(normalizeProvidersList("outlook,hotmail,google")).toEqual([ + "hotmail", + "gmail", + ]); + }); + it("empty in → empty out", () => { + expect(normalizeProvidersList("")).toEqual([]); + expect(normalizeProvidersList(null)).toEqual([]); + expect(normalizeProvidersList([])).toEqual([]); + }); +}); + +describe("providersFromConfig", () => { + it("prefers multi over singleton", () => { + expect( + providersFromConfig({ email_providers: ["gmail"], email_provider: "hotmail" }), + ).toEqual(["gmail"]); + }); + it("falls back to singleton when multi empty", () => { + expect( + providersFromConfig({ email_providers: [], email_provider: "hotmail" }), + ).toEqual(["hotmail"]); + }); + it("drops an unknown singleton and uses the fallback", () => { + expect( + providersFromConfig({ email_provider: "bogus" }, { fallback: ["yyds"] }), + ).toEqual(["yyds"]); + }); + it("returns a copy of the fallback, not the same array", () => { + const fallback = ["yyds"]; + const out = providersFromConfig({}, { fallback }); + expect(out).toEqual(["yyds"]); + expect(out).not.toBe(fallback); + }); + it("tolerates null config", () => { + expect(providersFromConfig(null)).toEqual([]); + }); +}); diff --git a/apps/web/src/lib/useBusy.js b/apps/web/src/lib/useBusy.js new file mode 100644 index 0000000..6c8f2bb --- /dev/null +++ b/apps/web/src/lib/useBusy.js @@ -0,0 +1,17 @@ +// Single-slot busy-tag state. Replaces the setBusy("tag") / busy === "tag" +// string pairs that were duplicated across every ops page. +import { useCallback, useState } from "preact/hooks"; + +export function useBusy(initial = "") { + const [busy, setBusy] = useState(initial); + const is = useCallback((tag) => busy === tag, [busy]); + const run = useCallback(async (tag, fn) => { + setBusy(tag); + try { + return await fn(); + } finally { + setBusy(""); + } + }, []); + return { busy, setBusy, is, any: busy !== "", run }; +} diff --git a/apps/web/src/lib/useBusy.test.jsx b/apps/web/src/lib/useBusy.test.jsx new file mode 100644 index 0000000..407bcb0 --- /dev/null +++ b/apps/web/src/lib/useBusy.test.jsx @@ -0,0 +1,62 @@ +import { describe, it, expect } from "vitest"; +import { render, screen, waitFor } from "@testing-library/preact"; +import { useBusy } from "./useBusy.js"; + +function Probe({ onReady }) { + const b = useBusy(); + onReady(b); + return <span data-testid="busy">{`${b.busy}|${b.is("save")}|${b.any}`}</span>; +} + +describe("useBusy", () => { + it("starts idle", () => { + render(<Probe onReady={() => {}} />); + expect(screen.getByTestId("busy").textContent).toBe("|false|false"); + }); + + it("sets tag during run and clears after", async () => { + let api; + render( + <Probe + onReady={(b) => { + api = b; + }} + />, + ); + let release; + const p = api.run( + "save", + () => + new Promise((r) => { + release = r; + }), + ); + await waitFor(() => + expect(screen.getByTestId("busy").textContent).toBe("save|true|true"), + ); + release("done"); + await expect(p).resolves.toBe("done"); + await waitFor(() => + expect(screen.getByTestId("busy").textContent).toBe("|false|false"), + ); + }); + + it("clears the tag and rethrows when fn throws", async () => { + let api; + render( + <Probe + onReady={(b) => { + api = b; + }} + />, + ); + await expect( + api.run("save", async () => { + throw new Error("boom"); + }), + ).rejects.toThrow("boom"); + await waitFor(() => + expect(screen.getByTestId("busy").textContent).toBe("|false|false"), + ); + }); +}); diff --git a/apps/web/src/lib/useConfigForm.js b/apps/web/src/lib/useConfigForm.js new file mode 100644 index 0000000..a4522f7 --- /dev/null +++ b/apps/web/src/lib/useConfigForm.js @@ -0,0 +1,130 @@ +// Shared hydrated / dirty / baseline / clearable-confirm skeleton for the +// config-editing pages (Settings, Resources→Почта). Extracted with behavior +// strictly unchanged; every page-specific decision (messages, hydrate +// mapping, PUT payload, post-save rehydrate) stays in the page via callbacks. +// +// Invariants owned here (locked by SettingsPage.test.jsx / MailTab.test.jsx): +// 1. Save is a no-op until a GET succeeded (hydrated) and no load is running. +// 2. GET 401 → session cleared (auth401) and hydrated=false so Save stays blocked. +// 3. load({force:true}) while dirty asks window.confirm first; cancel = no GET. +// 4. Clearing a clearable field asks window.confirm on save; cancel = no PUT. +// 5. Successful save clears dirty and applies the page's rehydrate result. +// +// Option callbacks (all page-provided; see Settings/MailTab for usage): +// loadRequest: async () => config — GET + unwrap +// hydrate: (config) => { form, baseline } — map config into page state +// onLoaded?: async (config, form) — post-load side effects +// onLoadError?: (e) — non-401 load failure feedback +// confirmReload: { message, onCancel? } — dirty-reload confirm copy +// onSaveBlocked?: () — Save clicked before hydrated +// confirmClear?: (form, baseline) => { message } | null +// onSaveCancelled?: () — clearable confirm declined +// saveRequest: async (form) => data — build partial + PUT +// onSaved?: (data, form) => { form?, baseline? } | void +// onSaveError?: (e) — non-401 save failure feedback +import { useCallback, useRef, useState } from "preact/hooks"; +import { auth401 } from "./http.js"; +import { useBusy } from "./useBusy.js"; + +export function useConfigForm(options) { + const { empty, initialBaseline } = options; + const [form, setForm] = useState(empty); + const [hydrated, setHydrated] = useState(false); + const [dirty, setDirty] = useState(false); + const [baseline, setBaseline] = useState(initialBaseline); + const busyApi = useBusy(); + const { setBusy, is: busyIs } = busyApi; + + // Callbacks read page state (e.g. primaryProvider) — keep them fresh via a + // ref so load/save never close over a stale render. + const opts = useRef(options); + opts.current = options; + + const set = useCallback((partial) => { + setDirty(true); + setForm((p) => ({ ...p, ...partial })); + }, []); + + const load = useCallback( + async ({ force = false } = {}) => { + const o = opts.current; + if (force && dirty) { + if (!window.confirm(o.confirmReload.message)) { + o.confirmReload.onCancel?.(); + return; + } + } + setBusy("load"); + try { + const config = await o.loadRequest(); + const next = o.hydrate(config); + setForm(next.form); + setBaseline(next.baseline); + setDirty(false); + setHydrated(true); + await o.onLoaded?.(config, next.form); + } catch (e) { + // Always clear hydrated on failure (incl. 401) so Save stays blocked. + setHydrated(false); + if (auth401(e)) return; + o.onLoadError?.(e); + } finally { + setBusy(""); + } + }, + // eslint-disable-next-line react-hooks/exhaustive-deps + [dirty], + ); + + const save = useCallback(async () => { + const o = opts.current; + if (!hydrated || busyIs("load")) { + o.onSaveBlocked?.(); + return; + } + const clearing = o.confirmClear?.(form, baseline); + if (clearing) { + if (!window.confirm(clearing.message)) { + o.onSaveCancelled?.(); + return; + } + } + setBusy("save"); + try { + const data = await o.saveRequest(form); + const next = o.onSaved?.(data, form); + if (next && next.form !== undefined) { + setForm((p) => + typeof next.form === "function" ? next.form(p) : next.form, + ); + } + if (next && next.baseline !== undefined) setBaseline(next.baseline); + setDirty(false); + } catch (e) { + if (auth401(e)) { + setHydrated(false); + return; + } + o.onSaveError?.(e); + } finally { + setBusy(""); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [hydrated, form, baseline, busyIs]); + + return { + form, + set, + setForm, + hydrated, + setHydrated, + dirty, + setDirty, + baseline, + setBaseline, + load, + save, + ...busyApi, + busyIs, + }; +} diff --git a/apps/web/src/main.jsx b/apps/web/src/main.jsx new file mode 100644 index 0000000..7ce8e57 --- /dev/null +++ b/apps/web/src/main.jsx @@ -0,0 +1,7 @@ +import { render } from "preact"; +import { App } from "./App.jsx"; +import "./styles/tokens.css"; +import "./styles/base.css"; +import "./styles/components.css"; + +render(<App />, document.getElementById("root")); diff --git a/apps/web/src/pages/Accounts/AccountsPage.jsx b/apps/web/src/pages/Accounts/AccountsPage.jsx new file mode 100644 index 0000000..7bae158 --- /dev/null +++ b/apps/web/src/pages/Accounts/AccountsPage.jsx @@ -0,0 +1,278 @@ +// src/pages/Accounts/AccountsPage.jsx +// Account pool: filter + paginate cpa_auths (complete = access+refresh on disk). +// Delete is local-only (DELETE /api/accounts/{name}); does not touch tebi. +import { useCallback, useEffect, useRef, useState } from "preact/hooks"; +import * as api from "../../api/client.js"; +import { showOpsFeedback } from "../../store/feedback.js"; +import { Button, Select, Kpi, PageHeader, LogDetails } from "../../ui/index.js"; +import { formatApiError } from "../../lib/format.js"; +import { auth401 } from "../../lib/http.js"; +import "../../styles/accounts.css"; + +const COMPLETE_OPTS = [ + { value: "", label: "Все" }, + { value: "1", label: "только complete" }, + { value: "0", label: "только incomplete" }, +]; + +const PAGE_SIZE_OPTS = [ + { value: "25", label: "25" }, + { value: "50", label: "50" }, + { value: "100", label: "100" }, +]; + +function buildAccountsQuery({ q, complete, page, pageSize }) { + const params = new URLSearchParams(); + const qq = (q || "").trim(); + if (qq) params.set("q", qq); + if (complete !== "" && complete != null) params.set("complete", complete); + params.set("page", String(page || 1)); + params.set("page_size", String(pageSize || 50)); + return params.toString(); +} + +export function AccountsPage() { + const [q, setQ] = useState(""); + const [complete, setComplete] = useState(""); + const [pageSize, setPageSize] = useState("50"); + const [page, setPage] = useState(1); + const [data, setData] = useState(null); + const [err, setErr] = useState(""); + const [result, setResult] = useState(""); + const [busy, setBusy] = useState(false); + const qTimer = useRef(null); + const qFirst = useRef(true); + // Keep latest filters for debounced load without stale closures. + const filtersRef = useRef({ q: "", complete: "", pageSize: "50", page: 1 }); + filtersRef.current = { q, complete, pageSize, page }; + + const load = useCallback(async (override = {}) => { + const f = { ...filtersRef.current, ...override }; + const pg = f.page != null ? f.page : 1; + setBusy(true); + setErr(""); + try { + const qs = buildAccountsQuery({ + q: f.q, + complete: f.complete, + page: pg, + pageSize: f.pageSize, + }); + const res = await api.listAccounts(qs); + setData(res); + if (override.page != null) setPage(override.page); + else if (res && res.page != null) setPage(res.page); + } catch (e) { + if (auth401(e)) return; + setData(null); + setErr(formatApiError(e)); + } finally { + setBusy(false); + } + }, []); + + // Initial load + useEffect(() => { + load({ page: 1 }); + }, [load]); + + // Debounced search (skip mount — initial load handles first paint) + useEffect(() => { + if (qFirst.current) { + qFirst.current = false; + return undefined; + } + if (qTimer.current) clearTimeout(qTimer.current); + qTimer.current = setTimeout(() => { + setPage(1); + load({ page: 1, q }); + }, 300); + return () => { + if (qTimer.current) clearTimeout(qTimer.current); + }; + }, [q, load]); + + function onCompleteChange(v) { + setComplete(v); + setPage(1); + load({ page: 1, complete: v }); + } + + function onPageSizeChange(v) { + setPageSize(v); + setPage(1); + load({ page: 1, pageSize: v }); + } + + async function onDelete(name) { + if (!name) return; + if (!window.confirm(`Удалить ${name}? Удаляет только локальный cpa_auths, не влияет на tebi.`)) { + return; + } + try { + const r = await api.deleteAccount(name); + setResult(typeof r === "string" ? r : JSON.stringify(r, null, 2)); + showOpsFeedback(`Удалено ${name}`, "ok", { toast: true, sticky: false }); + await load(); + } catch (e) { + if (auth401(e)) return; + setResult(String(e.message || e)); + showOpsFeedback(`Ошибка удаления: ${formatApiError(e)}`, "err"); + } + } + + const items = (data && data.items) || []; + const total = data ? data.total || 0 : 0; + const c = data ? data.complete || 0 : 0; + const inc = Math.max(0, total - c); + const dc = data && data.disk_complete != null ? data.disk_complete : null; + const pages = data ? data.pages || 1 : 1; + const curPage = data ? data.page || page : page; + + return ( + <section class="page page-accounts"> + <PageHeader + title="Пул аккаунтов" + hint={ + <> + cpa_auths пишет на диск complete (access+refresh). Основной путь регистрации заканчивается на диске; импорт в tebi идёт отдельно + Import。 + </> + } + > + <Button variant="ghost" busy={busy} onClick={() => load()}> + Обновить + </Button> + </PageHeader> + + <div class="card filter-bar"> + <label class="inline"> + Поиск{" "} + <input + type="search" + value={q} + placeholder="email / имя файла" + onInput={(e) => setQ(e.currentTarget.value)} + /> + </label> + <label class="inline"> + Полнота{" "} + <Select + value={complete} + options={COMPLETE_OPTS} + onChange={onCompleteChange} + /> + </label> + <label class="inline"> + На стр.{" "} + <Select + value={pageSize} + options={PAGE_SIZE_OPTS} + onChange={onPageSizeChange} + /> + </label> + <Button + variant="ghost" + size="sm" + disabled={curPage <= 1 || busy} + onClick={() => load({ page: Math.max(1, curPage - 1) })} + > + Назад + </Button> + <Button + variant="ghost" + size="sm" + disabled={curPage >= pages || busy} + onClick={() => load({ page: curPage + 1 })} + > + Вперёд + </Button> + <span class="hint"> + page {curPage}/{pages} + </span> + </div> + + {err ? ( + <p class="hint err-text">{err}</p> + ) : ( + <div class="kpi-grid compact acc-summary"> + <Kpi + label="итого (эта стр.)" + value={String(total)} + hint={data?.path ? `path=${data.path}` : ""} + /> + <Kpi + label="complete" + value={String(c)} + hint={`стр. ${curPage}/${pages}`} + class={c > 0 ? "ok" : ""} + /> + <Kpi + label="incomplete" + value={String(inc)} + class={inc > 0 ? "warn" : ""} + /> + {dc != null ? ( + <Kpi label="disk complete" value={String(dc)} hint="Полный" class="ok" /> + ) : null} + </div> + )} + + <div class="card table-wrap"> + <table class="data"> + <thead> + <tr> + <th>Статус</th> + <th>email</th> + <th>mtime</th> + <th>priority</th> + <th>kind</th> + <th>Действия</th> + </tr> + </thead> + <tbody> + {!items.length ? ( + <tr> + <td colspan="6" class="hint"> + Нет аккаунтов + </td> + </tr> + ) : ( + items.map((it) => ( + <tr key={it.name || it.email}> + <td> + <span class={`badge ${it.complete ? "ok" : "fail"}`}> + {it.complete ? "complete" : "incomplete"} + </span>{" "} + {it.disabled ? ( + <span class="badge fail">disabled</span> + ) : null}{" "} + {it.expired ? <span class="badge fail">expired</span> : null} + </td> + <td> + <div>{it.email || ""}</div> + <div class="hint">{it.name || ""}</div> + </td> + <td>{it.mtime_iso || ""}</td> + <td>{it.priority != null ? String(it.priority) : "—"}</td> + <td>{it.auth_kind || "—"}</td> + <td class="ops"> + <Button + variant="danger" + size="sm" + onClick={() => onDelete(it.name)} + > + Удалить + </Button> + </td> + </tr> + )) + )} + </tbody> + </table> + </div> + + <LogDetails text={result} summary="Детали ответа операции" compact /> + </section> + ); +} diff --git a/apps/web/src/pages/LoginGate.jsx b/apps/web/src/pages/LoginGate.jsx new file mode 100644 index 0000000..dbc5758 --- /dev/null +++ b/apps/web/src/pages/LoginGate.jsx @@ -0,0 +1,83 @@ +import { useState } from "preact/hooks"; +import * as api from "../api/client.js"; +import { session } from "../store/session.js"; +import { Button } from "../ui/Button.jsx"; + +export function LoginGate() { + const [username, setUsername] = useState(""); + const [password, setPassword] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + + async function onSubmit(e) { + e.preventDefault(); + if (busy) return; + setBusy(true); + setError(""); + try { + await api.login(username.trim(), password); + const m = await api.me(); + session.value = { + ...session.value, + ...m, + authenticated: true, + username: (m && m.username) || username.trim(), + checked: true, + }; + } catch (err) { + setError((err && err.message) || "Ошибка входа"); + } finally { + setBusy(false); + } + } + + return ( + <div class="login-gate"> + <form class="login-card" autocomplete="on" onSubmit={onSubmit}> + <h1>Вход в Control Plane</h1> + <p class="hint">Нужны логин/пароль оператора. Скрипты могут использовать Bearer token.</p> + <p class="hint brand-line"> + Open-source проект{" "} + <a + href="https://github.com/dengyie/ai-register-machine" + target="_blank" + rel="noopener noreferrer" + > + ai-register-machine + </a> + </p> + <label> + Логин{" "} + <input + name="username" + autocomplete="username" + placeholder="admin" + required + value={username} + onInput={(e) => setUsername(e.currentTarget.value)} + /> + </label> + <label> + Пароль{" "} + <input + name="password" + type="password" + autocomplete="current-password" + placeholder="Пароль" + required + value={password} + onInput={(e) => setPassword(e.currentTarget.value)} + /> + </label> + <div class="actions"> + <Button variant="primary" type="submit" busy={busy}> + Войти + </Button> + </div> + <p class="error" role="alert"> + {error} + </p> + </form> + </div> + ); +} diff --git a/apps/web/src/pages/Register/RegForm.jsx b/apps/web/src/pages/Register/RegForm.jsx new file mode 100644 index 0000000..430f14a --- /dev/null +++ b/apps/web/src/pages/Register/RegForm.jsx @@ -0,0 +1,333 @@ +// src/pages/Register/RegForm.jsx +// Left panel: start parameters. Email channel is multi-select only — +// per-provider secrets/domains live on Resources → Почта; pipeline pool +// on Settings. State is lifted to RegisterPage so the 4s poll never wipes edits. +import { useEffect } from "preact/hooks"; +import { Field, Select, ProviderPoolStatus } from "../../ui/index.js"; +import { regFormDirty } from "../../store/run.js"; +import { + EMAIL_PROVIDERS, + normalizeProvidersList, +} from "../../lib/providers.js"; + +const DEFAULTS = { + email_providers: [], + target: 100, + threads: 1, + mode: "ordinary", + tag: "batch_web", + chunk: 3, + turnstile: 150, + probeChat: false, + ssoOnly: true, + batchEndInject: false, + importEvery: 100, + importSize: "", + importPause: "", + proxyMode: "clash", + proxy: "", + proxyList: "", + kind: "grok_supervisor", + product: "grok", + skipPreflight: false, + nodeScore: "", + syncMailEnv: true, +}; + +export function RegForm({ + value, + onChange, + advancedOpen, + onToggleAdvanced, + residualPrimary = "", +}) { + useEffect(() => { + // dirty handling is done in field onChange below + }, []); + + const v = { ...DEFAULTS, ...value }; + const isSupervisor = (v.kind || "grok_supervisor") === "grok_supervisor"; + const selected = normalizeProvidersList(v.email_providers); + + function set(partial) { + regFormDirty.value = true; + onChange({ ...v, ...partial }); + } + + function toggleProvider(name) { + const cur = new Set(selected); + if (cur.has(name)) cur.delete(name); + else cur.add(name); + // preserve EMAIL_PROVIDERS order + set({ email_providers: EMAIL_PROVIDERS.filter((p) => cur.has(p)) }); + } + + return ( + <form class="stack-form" onSubmit={(e) => e.preventDefault()}> + <div class="field-grid"> + <Field label="Почтовые сервисы (мультивыбор)" span2> + <div class="provider-multi mail-domain-chips"> + {EMAIL_PROVIDERS.map((p) => ( + <label key={p} class="check chip"> + <input + type="checkbox" + checked={selected.includes(p)} + onChange={() => toggleProvider(p)} + />{" "} + {p} + </label> + ))} + </div> + <ProviderPoolStatus + selected={selected} + primaryProvider={residualPrimary} + canClear={false} + /> + <p class="hint tight"> + Выбор каналов только для этого батча (общий с настройками <code>email_providers</code>). Ключи / домены →{" "} + <a href="#/resources?tab=mail">Ресурсы · Почта</a>; стратегия опроса →{" "} + <a href="#/settings">Настройки</a> + </p> + {!selected.length ? ( + <p class="hint warn tight"> + Отметьте хотя бы один для запуска + {residualPrimary ? `(страница регистрации не отмечает автоматически остаточный одиночный канал)` : ""}。 + </p> + ) : null} + </Field> + <Field label="Количество target"> + <input + type="number" + min="1" + value={v.target} + onInput={(e) => + set({ target: e.currentTarget.value === "" ? "" : Number(e.currentTarget.value) }) + } + /> + </Field> + <Field label="Потоки threads"> + <input + type="number" + min="1" + max="32" + value={v.threads} + onInput={(e) => + set({ threads: e.currentTarget.value === "" ? "" : Number(e.currentTarget.value) }) + } + /> + </Field> + <Field label="Режим"> + <Select + options={[ + { value: "ordinary", label: "ordinary · Clash (дата-центр)" }, + { value: "residential", label: "residential · резидентные" }, + ]} + value={v.mode} + onChange={(val) => set({ mode: val })} + /> + </Field> + <Field label="tag"> + <input value={v.tag} onInput={(e) => set({ tag: e.currentTarget.value })} /> + </Field> + </div> + + <div class="info-box">По умолчанию disk-first: без mid-tebi инъекции. Полные логи на странице «Логи».</div> + + <details class="advanced" open={advancedOpen} onToggle={onToggleAdvanced}> + <summary>Расширенный запуск · параметры батча / прокси / kind / product / SKIP_CLASH / NODE_SCORE</summary> + <div class="field-grid"> + <Field label="SUPERVISOR_CHUNK" class={isSupervisor ? "" : "hidden"}> + <input + type="number" + min="1" + max="20" + value={v.chunk} + disabled={!isSupervisor} + onInput={(e) => + set({ chunk: e.currentTarget.value === "" ? "" : Number(e.currentTarget.value) }) + } + /> + </Field> + <Field label="Таймаут зависания Turnstile (сек)"> + <input + type="number" + min="5" + value={v.turnstile} + onInput={(e) => + set({ + turnstile: e.currentTarget.value === "" ? "" : Number(e.currentTarget.value), + }) + } + /> + </Field> + <label class="check muted" title="Supervisor жёстко задаёт CPA_PROBE_CHAT=false"> + <input type="checkbox" checked={false} disabled /> Chat-проба после регистрации (принудительно выкл) + </label> + <label + class="check" + title="Инфо: mid-mint никогда не инжектится в tebi (контракт disk-first); снятие галочки не включает mid-mint inject" + > + <input + type="checkbox" + checked={v.ssoOnly} + onChange={(e) => set({ ssoOnly: e.currentTarget.checked })} + />{" "} + Только запись auth на диск (по умолчанию · инфо) + </label> + <label class="check" title="только граница батча CPA_BATCH_END_INJECT"> + <input + type="checkbox" + checked={v.batchEndInject} + disabled={!isSupervisor} + onChange={(e) => set({ batchEndInject: e.currentTarget.checked })} + />{" "} + Авто-импорт CPA на границе батча + </label> + <Field label="CPA_BATCH_IMPORT_EVERY" class={isSupervisor ? "" : "hidden"}> + <input + type="number" + min="1" + value={v.importEvery} + disabled={!isSupervisor} + onInput={(e) => + set({ + importEvery: e.currentTarget.value === "" ? "" : Number(e.currentTarget.value), + }) + } + /> + </Field> + + <Field label="Стратегия прокси proxy_rotate_mode"> + <Select + options={[ + { value: "clash", label: "clash · ротация встроенного пула узлов" }, + { value: "list", label: "list · PROXY_LIST / proxy_list" }, + { value: "off", label: "off · фиксированный выход" }, + ]} + value={v.proxyMode} + onChange={(val) => set({ proxyMode: val })} + /> + </Field> + <Field label="Фиксированный proxy URL"> + <input + placeholder="http://127.0.0.1:7897" + value={v.proxy} + onInput={(e) => set({ proxy: e.currentTarget.value })} + /> + </Field> + <Field label="Пул прокси proxy_list / PROXY_LIST" span2> + <textarea + rows="4" + placeholder="По одному прокси на строку; запись только непустых; очистка — на странице настроек" + value={v.proxyList} + onInput={(e) => set({ proxyList: e.currentTarget.value })} + /> + <p class="hint tight"> + Пустое поле здесь <strong>НЕ</strong> очищает серверный <code>PROXY_LIST</code> + (очистка clearable в + <a href="#/settings">Настройки</a>)。 + </p> + </Field> + + <Field label="kind"> + <Select + options={[ + { value: "grok_supervisor", label: "grok_supervisor · пакетный надзор" }, + { value: "register_sh", label: "register_sh · одиночная оболочка" }, + ]} + value={v.kind} + onChange={(val) => + set({ kind: val, product: val === "grok_supervisor" ? "grok" : v.product }) + } + /> + </Field> + <Field label="product"> + <Select + options={[ + { value: "grok", label: "grok (оригинал)" }, + { value: "mimo", label: "mimo (оригинал)" }, + { value: "chatgpt", label: "chatgpt (оригинал)" }, + { value: "typesafe", label: "typesafe (оригинал)" }, + { value: "vip7891", label: "⚡ vip7891 · new-api GH-OAuth" }, + { value: "agentrouter", label: "⚡ agentrouter · GH-OAuth" }, + { value: "conol", label: "⚡ conol.ai · 600cr" }, + { value: "vani", label: "⚡ vani.ai" }, + { value: "notion", label: "⚡ notion · Opus-ферма" }, + { value: "kiro", label: "⚡ kiro · BuilderID" }, + { value: "type", label: "⚡ type.com · voidash+SMS" }, + { value: "llmtr", label: "⚡ llmtr.com" }, + { value: "xkiro", label: "⚡ xkiro · TG-верификация" }, + { value: "omnirush", label: "⚡ omnirush.ai" }, + { value: "gname", label: "⚡ gname.com · слайдер" }, + { value: "abliteration", label: "⚡ abliteration.ai · квесты" }, + { value: "terrapolis", label: "⚡ terrapolis.xyz · 15M" }, + { value: "cleanapis", label: "⚡ cleanapis.com · GH-OAuth" }, + { value: "miarouter", label: "⚡ miarouter.online · TG-miniapp" }, + { value: "treg", label: "⚡ treg.to · voidash $1" }, + ]} + value={isSupervisor ? "grok" : v.product} + disabled={isSupervisor} + onChange={(val) => + set( + ["grok", "mimo", "chatgpt", "typesafe"].includes(val) + ? { product: val } + : { product: val, kind: "register_sh" } + ) + } + /> + </Field> + <label class="check" title="SKIP_CLASH_PREFLIGHT=1 пропускает пред-проверку Clash перед батчем; по умолчанию выкл"> + <input + type="checkbox" + checked={v.skipPreflight} + onChange={(e) => set({ skipPreflight: e.currentTarget.checked })} + />{" "} + Пропустить пред-проверку Clash перед батчем + </label> + <Field label="NODE_SCORE"> + <Select + options={[ + { value: "", label: "(не передаётся, берётся из env)" }, + { value: "1", label: "1 · сортировка по скору" }, + { value: "0", label: "0 · скоринг выкл" }, + ]} + value={v.nodeScore} + onChange={(val) => set({ nodeScore: val })} + /> + </Field> + <Field label="CPA_BATCH_IMPORT_SIZE" class={isSupervisor ? "" : "hidden"}> + <input + type="number" + min="1" + placeholder="100" + value={v.importSize} + disabled={!isSupervisor} + onInput={(e) => set({ importSize: e.currentTarget.value })} + /> + </Field> + <Field label="CPA_BATCH_IMPORT_PAUSE" class={isSupervisor ? "" : "hidden"}> + <input + type="number" + min="0" + placeholder="3" + value={v.importPause} + disabled={!isSupervisor} + onInput={(e) => set({ importPause: e.currentTarget.value })} + /> + </Field> + <label + class="check span2" + title="При старте синхронизировать отмеченные EMAIL_PROVIDERS в extra_env (перекрывает одиночный канал .env)" + > + <input + type="checkbox" + checked={v.syncMailEnv} + onChange={(e) => set({ syncMailEnv: e.currentTarget.checked })} + />{" "} + Синхронизировать EMAIL_PROVIDERS в extra_env + </label> + </div> + </details> + </form> + ); +} diff --git a/apps/web/src/pages/Register/RegisterPage.jsx b/apps/web/src/pages/Register/RegisterPage.jsx new file mode 100644 index 0000000..d8f79ed --- /dev/null +++ b/apps/web/src/pages/Register/RegisterPage.jsx @@ -0,0 +1,562 @@ +// src/pages/Register/RegisterPage.jsx +// Register / control home: left form + right progress. Full parity with legacy +// register UX (apps/web/legacy/assets/app.js register + renderRunStatus pipeline). +// +// Key behaviors: +// - 4s poll of api.currentRun() + api.overview(); never wipes form while +// regFormDirty.value === true; form loaded from config only once. +// - startRun body keys mirror legacy (kind/product/mode/target/threads/ +// tag/extra_env{SUPERVISOR_CHUNK,CPA_BATCH_END_INJECT,CPA_BATCH_IMPORT_*, +// CPA_PROBE_CHAT=false,SKIP_CLASH_PREFLIGHT,NODE_SCORE,EMAIL_PROVIDERS, +// EMAIL_PROVIDER}). Secrets/domains are NOT written from this page. +// - stopRun: window.confirm Chinese warning first. +// - putConfig wrapped as { config: partial } (backend ConfigPutIn schema). +// - 401 → session.authenticated=false (gate shows). +// - интерфейс/эксплуатация: Сохранить / self-check(link #/settings) / Тест прокси. No duplicate cleanup/selfcheck +// buttons here (spec IA — selfcheck lives on settings). +import { useEffect, useState, useCallback } from "preact/hooks"; +import * as api from "../../api/client.js"; +import { auth401 } from "../../lib/http.js"; +import { showOpsFeedback } from "../../store/feedback.js"; +import { + currentRunState, + overviewState, + regFormDirty, + regFormLoaded, + lastProductOk, +} from "../../store/run.js"; +import { PageHeader } from "../../ui/index.js"; +import { RegForm } from "./RegForm.jsx"; +import { RunProgress } from "./RunProgress.jsx"; +import { formatApiError as formatApiErrorShared } from "../../lib/format.js"; +import { normalizeProvidersList } from "../../lib/providers.js"; +import "../../styles/run.css"; + +// Initial form state (also used before config loads). Mirrors legacy defaults. +// Email: multi-select pool only — secrets/domains on Resources, strategy on Settings. +// email_providers starts empty until GET /api/config (no singleton pre-fill). +const initialForm = { + email_providers: [], + target: 100, + threads: 1, + mode: "ordinary", + tag: "batch_web", + chunk: 3, + turnstile: 150, + ssoOnly: true, + batchEndInject: false, + importEvery: 100, + importSize: "", + importPause: "", + proxyMode: "clash", + proxy: "", + proxyList: "", + kind: "grok_supervisor", + product: "grok", + skipPreflight: false, + nodeScore: "", + syncMailEnv: true, +}; + +function formatApiError(e) { + if (!e) return "Неизвестная ошибка"; + if (e.status === 409) { + const msg = String(e.message || e); + return `Задача уже выполняется (${msg}). Главная покажет текущий progress; для остановки нажмите «Стоп» (убьёт внешний supervisor).`; + } + if (e.status === 401) return "Не авторизованы или сессия истекла — войдите заново."; + if (e.status === 422) return `Ошибка валидации параметров: ${formatApiErrorShared(e)}`; + return formatApiErrorShared(e); +} + +function snapshotFormFromConfig(c, prev) { + // No prev → first load: apply defaults, then overlay config protocol bits + // (email pool / proxy / turnstile). Run params stay at HTML defaults. + // prev → forced refresh: re-hydrate protocol bits but PRESERVE user edits to + // run params. + // Multi-list only — never promote singleton email_provider into chips + // (Settings clear-pool must survive Register load/save). + const f = { ...initialForm, ...(prev || {}) }; + f.email_providers = normalizeProvidersList(c.email_providers); + if (c.proxy != null) f.proxy = String(c.proxy); + if (c.proxy_rotate_mode) f.proxyMode = c.proxy_rotate_mode; + if (c.proxy_list != null) { + const pl = c.proxy_list; + f.proxyList = Array.isArray(pl) ? pl.join("\n") : String(pl); + } + if (c.turnstile_stuck_timeout != null) { + f.turnstile = Number(c.turnstile_stuck_timeout); + } + f.probeChat = false; // supervisor hard-forced off + return f; +} + +export function RegisterPage() { + const [form, setForm] = useState(initialForm); + // Residual singleton when multi is empty (Settings single-channel mode). + const [primaryProvider, setPrimaryProvider] = useState(""); + const [advancedOpen, setAdvancedOpen] = useState(false); + const [busyKey, setBusyKey] = useState(null); // 'start' | 'stop' | 'save' | 'proxy' | 'refresh' + const [actionResult, setActionResult] = useState(""); + + // Load form from /api/config exactly once (and on explicit refresh). + const loadForm = useCallback(async ({ force = false } = {}) => { + if (regFormLoaded.value && !force) return; + if (!force && regFormDirty.value && regFormLoaded.value) return; + try { + const data = await api.getConfig(); + const c = data.config || {}; + setPrimaryProvider(String(c.email_provider || "").trim().toLowerCase()); + setForm((prev) => + snapshotFormFromConfig(c, force ? prev : undefined), + ); + regFormLoaded.value = true; + if (force) regFormDirty.value = false; + } catch (e) { + if (auth401(e)) { + return; + } + if (force) showOpsFeedback(`Ошибка загрузки конфига: ${formatApiError(e)}`, "err"); + } + }, []); + + // 4s poll: run + overview only. Never destroys form edits. + useEffect(() => { + let cancelled = false; + async function tick() { + try { + const [cur, ov] = await Promise.all([api.currentRun(), api.overview()]); + if (cancelled) return; + const run = cur.run ?? cur ?? null; + currentRunState.value = run; + if (ov) { + overviewState.value = ov; + if (ov.product_ok != null) lastProductOk.value = ov.product_ok; + } + } catch (e) { + auth401(e); + // poll failures stay silent (no toast spam) + } + } + loadForm({ force: false }); + tick(); + const id = setInterval(tick, 4000); + return () => { + cancelled = true; + clearInterval(id); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + function gotoLogs() { + location.hash = "#/logs"; + } + + // Build the start body exactly mirroring legacy startRun(). + function buildStartBody() { + const v = form; + const kind = v.kind || "grok_supervisor"; + const product = + kind === "grok_supervisor" ? "grok" : v.product || "grok"; + const extra_env = {}; + + if (kind === "grok_supervisor") { + const chunk = String(v.chunk ?? "").trim(); + if (chunk) extra_env.SUPERVISOR_CHUNK = chunk; + extra_env.CPA_BATCH_END_INJECT = v.batchEndInject ? "true" : "false"; + const every = String(v.importEvery ?? "").trim(); + if (every) extra_env.CPA_BATCH_IMPORT_EVERY = every; + const size = String(v.importSize ?? "").trim(); + if (size) extra_env.CPA_BATCH_IMPORT_SIZE = size; + const pause = String(v.importPause ?? "").trim(); + if (pause !== "") extra_env.CPA_BATCH_IMPORT_PAUSE = pause; + } + + // Universal: probe-off + extra_env.CPA_PROBE_CHAT = "false"; + + if (v.skipPreflight) extra_env.SKIP_CLASH_PREFLIGHT = "1"; + const nodeScore = String(v.nodeScore ?? "").trim(); + if (nodeScore !== "") extra_env.NODE_SCORE = nodeScore; + + if (v.syncMailEnv) { + const pool = normalizeProvidersList(v.email_providers); + if (pool.length) { + extra_env.EMAIL_PROVIDERS = pool.join(","); + // Keep single EMAIL_PROVIDER aligned with first pool member for + // code paths that still read the singleton. + extra_env.EMAIL_PROVIDER = pool[0]; + } + // Empty multi: do NOT inject EMAIL_PROVIDERS (would not clear disk pool + // via empty env anyway). Start is blocked unless chips are checked. + } + + return { + kind, + product, + mode: v.mode || "ordinary", + target: Number(v.target == null || v.target === "" ? 100 : v.target), + threads: Number(v.threads == null || v.threads === "" ? 1 : v.threads), + tag: String(v.tag || "batch_web").trim() || "batch_web", + extra_env, + }; + } + + // Build the config partial from the form (save path). + // Register only writes email_providers + proxy/turnstile knobs — + // never secrets or defaultDomains (those live on Resources). + // Empty provider multi-select is OMITTED (not clearable from this page) so a + // mis-click cannot wipe the saved EMAIL_PROVIDERS pool. + // Empty proxy_list is also OMITTED — intentional clear lives on Settings. + function buildConfigPartial() { + const v = form; + const providers = normalizeProvidersList(v.email_providers); + const proxy = (v.proxy || "").trim(); + const proxyList = String(v.proxyList ?? "").trim(); + const partial = { + proxy_rotate_mode: v.proxyMode, + turnstile_stuck_timeout: Number(v.turnstile || 150), + // disk-first mid-mint inject always off; batch-end inject is CPA_BATCH_END_INJECT (extra_env). + cpa_remote_inject: false, + cpa_probe_chat: false, + }; + if (providers.length) { + partial.email_providers = providers; + // Primary for UIs / code paths that still read the singleton. + partial.email_provider = providers[0]; + } + if (proxy) partial.proxy = proxy; + // Non-empty only: blank must not clear PROXY_LIST via clearable write-through. + if (proxyList) partial.proxy_list = v.proxyList; + return { partial, providers }; + } + + async function saveConfig({ silent = false } = {}) { + // Never persist the pre-load default form (would risk proxy_list/provider drift). + if (!regFormLoaded.value) { + if (!silent) { + showOpsFeedback("Сначала загрузите конфиг, потом сохраняйте", "err", { toast: true, sticky: true }); + } + throw new Error("config not loaded"); + } + if (!silent) setBusyKey("save"); + try { + const { partial, providers } = buildConfigPartial(); + // Wrap in { config: partial } — backend ConfigPutIn schema. + const data = await api.putConfig({ config: partial }); + regFormDirty.value = false; + regFormLoaded.value = true; + // Re-hydrate from server multi only (never singleton → chips). + const saved = data.config || {}; + if (saved.email_provider != null) { + setPrimaryProvider(String(saved.email_provider || "").trim().toLowerCase()); + } + const serverMulti = normalizeProvidersList(saved.email_providers); + setForm((p) => { + const next = { + ...p, + // Prefer server multi. Empty form omit leaves disk multi intact → + // show server list so UI matches disk (Register cannot clear pool). + email_providers: serverMulti.length + ? serverMulti + : providers.length + ? providers + : [], + }; + if (saved.proxy != null && String(saved.proxy).trim()) { + next.proxy = String(saved.proxy); + } + return next; + }); + if (!silent) { + const envN = (data.changed_env_keys || []).length; + const envHint = envN ? ` · env×${envN}` : ""; + if (!providers.length) { + const kept = serverMulti.join(",") || "∅"; + showOpsFeedback( + `Конфиг сохранён · пустой выбор не изменил пул · серверные providers=${kept}${envHint}`, + "ok", + ); + } else { + showOpsFeedback( + `Конфиг сохранён · providers=${providers.join(",")}${envHint}`, + "ok", + ); + } + } + return data; + } catch (e) { + if (auth401(e)) { + throw e; + } + if (!silent) showOpsFeedback(`Ошибка сохранения: ${formatApiError(e)}`, "err"); + throw e; + } finally { + if (!silent) setBusyKey(null); + } + } + + async function refresh() { + setBusyKey("refresh"); + try { + await loadForm({ force: true }); + // One immediate run refresh too. + const cur = await api.currentRun(); + const run = cur.run ?? cur ?? null; + currentRunState.value = run; + try { + const ov = await api.overview(); + overviewState.value = ov; + if (ov && ov.product_ok != null) lastProductOk.value = ov.product_ok; + } catch { + /* render with last known */ + } + const phase = (run && (run.phase_title || run.phase)) || "—"; + const alive = !!(run && run.alive); + const sub = run && run.sub != null ? ` sub=${run.sub}` : ""; + const complete = run && run.complete != null ? ` complete=${run.complete}` : ""; + const worker = + run && run.worker_log + ? ` · worker=${String(run.worker_log).split(/[\\/]/).pop()}` + : ""; + showOpsFeedback( + `Обновлено · ${alive ? "выполняется" : "ожидание"} · ${phase}${sub}${complete}${worker}`, + "ok", + { toast: true, sticky: true }, + ); + } catch (e) { + if (auth401(e)) { + return; + } + showOpsFeedback(formatApiError(e), "err"); + } finally { + setBusyKey(null); + } + } + + async function start() { + if (!regFormLoaded.value) { + showOpsFeedback("Дождитесь загрузки конфига перед стартом", "err", { + toast: true, + sticky: true, + }); + return; + } + const providers = normalizeProvidersList(form.email_providers); + if (!providers.length) { + showOpsFeedback( + primaryProvider + ? `Отметьте хотя бы один Provider перед стартом (одиночный канал ${primaryProvider} используется runtime только после очистки multi в настройках; страница регистрации не пишет singleton обратно в пул)` + : "Отметьте хотя бы один почтовый Provider перед стартом (пустой выбор не очищает сохранённый пул и не инжектит EMAIL_PROVIDERS в этот батч)", + "err", + { toast: true, sticky: true }, + ); + return; + } + setBusyKey("start"); + showOpsFeedback("Сохранение конфига и запуск…", "info", { toast: false, sticky: true }); + try { + await saveConfig({ silent: true }); + } catch (e) { + showOpsFeedback( + `Ошибка сохранения конфига (старт всё равно пробует): ${formatApiError(e)}`, + "warn", + { toast: true, sticky: true }, + ); + } + const body = buildStartBody(); + try { + const data = await api.startRun(body); + const pid = data && data.run && data.run.pid; + const detail = (data && data.detail) || "started"; + showOpsFeedback( + `Запущено · ${detail}${pid != null ? ` pid=${pid}` : ""} · tag=${body.tag}`, + "ok", + ); + // immediate progress refresh + try { + const cur = await api.currentRun(); + currentRunState.value = cur.run ?? cur ?? null; + const ov = await api.overview(); + overviewState.value = ov; + if (ov && ov.product_ok != null) lastProductOk.value = ov.product_ok; + } catch { + /* fine */ + } + } catch (e) { + if (auth401(e)) { + return; + } + showOpsFeedback(formatApiError(e), "err"); + if (e.status === 409) { + try { + const cur = await api.currentRun(); + currentRunState.value = cur.run ?? cur ?? null; + } catch { + /* ignore */ + } + } + } finally { + setBusyKey(null); + } + } + + async function stop() { + const ok = window.confirm( + "Остановить текущую задачу?\n\nЗавершит группу процессов control и попытается остановить внешний supervisor (flock pid).\nРабочий batch будет убит.", + ); + if (!ok) { + showOpsFeedback("Остановка отменена", "info", { toast: true, sticky: false }); + return; + } + setBusyKey("stop"); + showOpsFeedback("Остановка…", "warn", { toast: false, sticky: true }); + try { + const data = await api.stopRun(); + const detail = + (data && data.detail) || (data && data.ok ? "stopped" : "no active run"); + const pid = data && data.pid; + showOpsFeedback( + `${data && data.ok ? "Остановлено" : "Остановка не сработала"} · ${detail}${pid != null ? ` pid=${pid}` : ""}`, + data && data.ok ? "ok" : "warn", + ); + const cur = await api.currentRun(); + currentRunState.value = cur.run ?? cur ?? null; + } catch (e) { + if (auth401(e)) { + return; + } + showOpsFeedback(formatApiError(e), "err"); + } finally { + setBusyKey(null); + } + } + + async function testProxy() { + setBusyKey("proxy"); + showOpsFeedback("Тестирование прокси…", "info", { toast: false, sticky: true }); + try { + let data; + let via = "clash"; + try { + data = await api.testClash({ limit: 8 }); + } catch { + via = "catalog"; + data = await api.testCatalog({ limit: 8 }); + } + const healthy = + data && (data.healthy != null + ? data.healthy + : data.ok_count != null + ? data.ok_count + : null); + const total = + data && (data.total != null + ? data.total + : data.tested != null + ? data.tested + : null); + const summary = + healthy != null && total != null + ? `healthy=${healthy}/${total}` + : (data && data.detail) || "done"; + showOpsFeedback(`Тест прокси завершён (${via}) · ${summary}`, "ok"); + setActionResult(typeof data === "string" ? data : JSON.stringify(data, null, 2)); + } catch (e) { + if (auth401(e)) { + return; + } + showOpsFeedback(`Ошибка теста прокси: ${formatApiError(e)}`, "err"); + } finally { + setBusyKey(null); + } + } + + return ( + <section class="page"> + <PageHeader + title="Протокольная регистрация" + hint="Слева параметры запуска · справа live-прогресс. Полные логи worker/supervisor → страница логов." + > + <button + type="button" + class="btn btn-primary btn-md" + disabled={busyKey === "start" || !regFormLoaded.value} + title={!regFormLoaded.value ? "Сначала загрузите конфиг" : undefined} + onClick={start} + > + {busyKey === "start" ? "Запуск…" : "Старт"} + </button> + <button + type="button" + class="btn btn-danger btn-md" + disabled={busyKey === "stop"} + onClick={stop} + > + {busyKey === "stop" ? "Остановка…" : "Стоп"} + </button> + <button + type="button" + class="btn btn-ghost btn-md" + disabled={busyKey === "refresh"} + onClick={refresh} + > + {busyKey === "refresh" ? "Обновление…" : "Обновить"} + </button> + <button + type="button" + class="btn btn-ghost btn-md" + onClick={gotoLogs} + > + Логи → + </button> + </PageHeader> + + {/* Sticky banner + ops log live in App shell OpsFeedbackBar (all pages). */} + + <div class="split"> + <div class="panel form-panel"> + <RegForm + value={form} + residualPrimary={primaryProvider} + onChange={(next) => setForm(next)} + advancedOpen={advancedOpen} + onToggleAdvanced={(e) => setAdvancedOpen(e.currentTarget.open)} + /> + {/* Footer toolbar: Сохранить / self-check(link #/settings) / Тест прокси. + No duplicate cleanup/selfcheck buttons (settings only). */} + <div class="form-foot-toolbar"> + <button + type="button" + class="btn btn-ghost btn-sm" + disabled={busyKey === "save" || !regFormLoaded.value} + title={!regFormLoaded.value ? "Сначала загрузите конфиг" : undefined} + onClick={() => saveConfig().catch(() => {})} + > + {busyKey === "save" ? "Сохранение…" : "Сохранить"} + </button> + <button + type="button" + class="btn btn-ghost btn-sm" + disabled={busyKey === "proxy"} + onClick={testProxy} + > + {busyKey === "proxy" ? "Тест прокси…" : "Тест прокси"} + </button> + {/* Not a button: эта страница не выполняет self-check/чистку, только переход на страницу настроек. */} + <a class="link-hint" href="#/settings"> + Self-check / чистка → страница настроек + </a> + </div> + {actionResult ? ( + <pre class={`log compact ${actionResult ? "ok" : ""}`}>{actionResult}</pre> + ) : null} + </div> + + <div class="panel progress-panel"> + <RunProgress onGotoLogs={gotoLogs} /> + </div> + </div> + </section> + ); +} diff --git a/apps/web/src/pages/Register/RunProgress.jsx b/apps/web/src/pages/Register/RunProgress.jsx new file mode 100644 index 0000000..43fbbdd --- /dev/null +++ b/apps/web/src/pages/Register/RunProgress.jsx @@ -0,0 +1,292 @@ +// src/pages/Register/RunProgress.jsx +// Right panel: live run progress. Renders from run store signals. +// Pure render pieces come from progressRender.jsx. +import { useState } from "preact/hooks"; +import { StatusDot, Chip, Kpi } from "../../ui/index.js"; +import { + currentRunState, + overviewState, + lastProductOk, +} from "../../store/run.js"; +import { + runHeader, + kpiGrid, + bars, + stepRail, + statusCard, + recentWrites, + timeline, + failureStats, +} from "./progressRender.jsx"; +import "../../styles/run-progress.css"; + +function barKind(cls) { + if (cls === "danger") return "err"; + if (cls === "warn") return "warn"; + return "ok"; +} + +export function RunProgress({ onGotoLogs }) { + const [timelineOpen, setTimelineOpen] = useState(true); + const [writesOpen, setWritesOpen] = useState(true); + const run = currentRunState.value; + const ov = overviewState.value; + + const head = runHeader(run); + const kpis = kpiGrid(run, ov, lastProductOk.value); + const brs = bars(run); + const steps = stepRail(run && run.steps); + const sc = statusCard(run); + const writes = recentWrites(run && run.recent_writes); + const tl = timeline(run && run.timeline); + const fstats = failureStats(run); + + return ( + <div class="run-progress"> + <div + class={`run-header run-header-${head.state}`} + data-state={head.state} + > + <StatusDot kind={head.dotKind} /> + <span class="status-word">{head.word}</span> + <span class="meta-chips"> + {head.chips.map((c, i) => ( + <Chip + key={i} + kind={c.danger ? "err" : "default"} + class="mini" + title={c.title} + > + {c.label} + </Chip> + ))} + </span> + </div> + + <div class="kpi-grid"> + {kpis.map((k, i) => ( + <Kpi + key={i} + label={k.label} + value={k.value} + hint={k.hint} + class={k.cls} + /> + ))} + </div> + + <div class="bars"> + {brs.map((b, i) => { + const p = b.value == null ? 0 : b.value; + const cap = b.value == null + ? "—" + : `${fmtN(b.a)} / ${fmtN(b.b)} (${Math.round(b.value)}%)`; + return ( + <div key={i} class="bar-row"> + <span class="bar-label">{b.label}</span> + <div + class="bar-track" + role="progressbar" + aria-valuenow={Math.round(p)} + aria-valuemin={0} + aria-valuemax={100} + > + <div + class={`bar-fill bar-${barKind(b.cls)}`} + style={{ width: `${p.toFixed(1)}%` }} + /> + </div> + <span class={`bar-caption ${b.cls || ""}`}>{cap}</span> + </div> + ); + })} + </div> + + {steps.length > 0 ? ( + <div class="step-rail"> + {steps.map((s, i) => ( + <span + key={i} + class={`step ${s.state}`} + title={s.desc} + > + {s.title} + </span> + ))} + </div> + ) : null} + + <div class="status-card"> + <div class="status-title">{sc.title}</div> + <pre class="status-body">{sc.body}</pre> + </div> + + {fstats ? <FailureStats stats={fstats} /> : null} + + {writes.length > 0 ? ( + <details + class="writes-wrap" + open={writesOpen} + onToggle={(e) => setWritesOpen(e.currentTarget.open)} + > + <summary>Последние записи на диск ({writes.length})</summary> + <div class="run-writes"> + {writes.map((w, i) => ( + <span key={i} class="write-chip" title={w.raw}> + {w.name} + </span> + ))} + </div> + </details> + ) : null} + + <details + class="timeline-wrap" + open={timelineOpen} + onToggle={(e) => setTimelineOpen(e.currentTarget.open)} + > + <summary>Таймлайн</summary> + <ol class="timeline"> + {tl.length ? ( + tl.map((it, i) => ( + <li key={i} class="timeline-item"> + <span class="src">{it.src}</span> + <span> + {it.title} + {it.line ? ` · ${it.line}` : ""} + </span> + </li> + )) + ) : ( + <li class="timeline-item hint">событий пока нет</li> + )} + </ol> + </details> + + <p class="hint progress-log-hint"> + Полный tail и история worker / supervisor → + <button + type="button" + class="linkish" + onClick={onGotoLogs} + > + Логи + </button> + </p> + </div> + ); +} + +function fmtN(v) { + return v == null || v === "" ? "—" : String(v); +} + +// Batch failure statistics card. Renders only when run.batch_failures has data. +function FailureStats({ stats }) { + const { kpis, breakdown, reasons, series } = stats; + return ( + <div class="failure-stats"> + <div class="failure-stats-head"> + <span class="failure-stats-title">Статистика ошибок батча</span> + <span class="hint">агрегат {stats.subs} под-батчей</span> + </div> + + <div class="failure-kpis"> + {kpis.map((k, i) => ( + <div key={i} class={`failure-kpi ${k.cls || ""}`}> + <div class="failure-kpi-value">{k.value}</div> + <div class="failure-kpi-label">{k.label}</div> + {k.hint ? <div class="failure-kpi-hint hint">{k.hint}</div> : null} + </div> + ))} + </div> + + {breakdown.length > 0 ? ( + <div class="failure-breakdown"> + <div class="failure-breakdown-bar"> + {breakdown.map((s, i) => ( + <div + key={i} + class={`fseg fseg-${s.cls}`} + style={{ width: `${s.pct.toFixed(1)}%` }} + title={`${s.label}: ${s.value}`} + /> + ))} + </div> + <div class="failure-legend"> + {breakdown.map((s, i) => ( + <span key={i} class="failure-legend-item"> + <span class={`fdot fseg-${s.cls}`} /> + {s.label} <b>{s.value}</b> + </span> + ))} + </div> + </div> + ) : ( + <p class="hint failure-empty">В этом батче ошибок нет ✓</p> + )} + + {series.fail.length > 1 ? ( + <FailureSparkline fail={series.fail} success={series.success} /> + ) : null} + + {reasons.map((r, i) => ( + <div key={i} class="failure-reasons"> + <div class="failure-reasons-title">{r.title}</div> + {r.rows.map((row, j) => ( + <div key={j} class="failure-reason-row"> + <span class="failure-reason-label" title={row.label}> + {row.label} + </span> + <span class="failure-reason-count">{row.count}</span> + </div> + ))} + </div> + ))} + </div> + ); +} + +// Compact per-sub reg fail/success trend. Pure SVG, no chart lib. +function FailureSparkline({ fail, success }) { + const n = fail.length; + const totals = fail.map((f, i) => f + (success[i] || 0)); + const max = Math.max(1, ...totals); + const W = 100; + const H = 28; + const bw = W / n; + return ( + <div class="failure-spark"> + <div class="failure-spark-title hint">Тренд ошибок/успехов по под-батчам</div> + <svg viewBox={`0 0 ${W} ${H}`} class="failure-spark-svg" preserveAspectRatio="none"> + {fail.map((f, i) => { + const ok = success[i] || 0; + const total = f + ok; + const x = i * bw; + const failH = (f / max) * H; + const okH = (ok / max) * H; + return ( + <g key={i}> + <rect + x={x + bw * 0.15} + y={H - okH} + width={bw * 0.7} + height={okH} + class="spark-ok" + /> + <rect + x={x + bw * 0.15} + y={H - okH - failH} + width={bw * 0.7} + height={failH} + class="spark-fail" + > + <title>{`sub#${i + 1}: fail=${f} ok=${ok}`} + + + ); + })} + + + ); +} diff --git a/apps/web/src/pages/Register/progressRender.jsx b/apps/web/src/pages/Register/progressRender.jsx new file mode 100644 index 0000000..4f19ad0 --- /dev/null +++ b/apps/web/src/pages/Register/progressRender.jsx @@ -0,0 +1,252 @@ +// src/pages/Register/progressRender.jsx +// Pure render (no DOM mutation) ported from legacy app.js: +// renderRunHeader / renderKpiGrid / renderBars / renderStepRail / +// renderStatusCard / renderRecentWrites / renderTimeline. +// All pure helpers: given (run, overview) → { ... } plain data for JSX. +import { fmtNum, pct } from "../../lib/format.js"; + +// ── Run header (hero) ──────────────────────────────────────────────────────── +// returns { state, word, dotKind, chips: [{ label, danger, title }] } +export function runHeader(run) { + const alive = !!(run && run.alive); + const stuck = !!(run && run.stuck); + const state = stuck ? "stuck" : alive ? "alive" : "idle"; + const word = alive ? "ALIVE" : run ? "idle" : "нет задачи"; + const dotKind = stuck ? "err" : alive ? "busy" : "idle"; + const meta = (run && run.meta) || {}; + const tag = (run && run.tag) || meta.tag; + const chips = []; + if (tag) chips.push({ label: `tag=${tag}` }); + if (run && run.pid != null) chips.push({ label: `pid=${run.pid}` }); + if (run && run.mode) chips.push({ label: String(run.mode) }); + if (run && run.kind) chips.push({ label: String(run.kind) }); + if (run && run.complete != null) { + const goal = run.goal_complete != null ? ` / ${run.goal_complete}` : ""; + chips.push({ label: `complete=${run.complete}${goal}` }); + } + if (stuck) { + const reason = + (run && (run.stuck_reason || (run.summary && run.summary.fatal_reason))) || + ""; + chips.push({ label: "stuck", danger: true, title: reason }); + } + return { state, word, dotKind, chips }; +} + +// ── KPI grid ──────────────────────────────────────────────────────────────── +// returns [{ label, value, hint, cls }] +export function kpiGrid(run, overview, lastProductOk) { + const alive = !!(run && run.alive); + const complete = run && run.complete != null ? run.complete : null; + const goal = run && run.goal_complete != null ? run.goal_complete : null; + const remain = run && run.remain != null ? run.remain : null; + const gained = run && run.batch_gained != null ? run.batch_gained : null; + const target = run && (run.target != null ? run.target : run.target_new); + const batchRemain = run && run.batch_remain != null ? run.batch_remain : null; + const sub = run && run.sub != null ? run.sub : null; + const zero = run && run.consecutive_zero != null ? run.consecutive_zero : null; + const disk = + overview && overview.product_ok != null ? overview.product_ok : lastProductOk; + const nodes = overview && overview.nodes ? overview.nodes : null; + + const zeroClass = + run && run.stuck ? "danger" : zero != null && Number(zero) >= 4 ? "warn" : ""; + const completeClass = alive && remain === 0 ? "ok" : ""; + const diskClass = + disk != null && Number(disk) > 0 ? "ok" : disk == null ? "" : "warn"; + + return [ + { + label: "complete / goal", + value: `${fmtNum(complete)}${goal != null ? " / " + goal : ""}`, + hint: remain != null ? `осталось ${remain}` : "", + cls: completeClass, + }, + { + label: "gained этого батча", + value: `${fmtNum(gained)}${target != null ? " / " + target : ""}`, + hint: batchRemain != null ? `осталось ${batchRemain}` : "", + cls: "", + }, + { + label: "disk product_ok", + value: fmtNum(disk), + hint: "", + cls: diskClass, + }, + { + label: "sub · zero", + value: `${fmtNum(sub)} · ${fmtNum(zero)}`, + hint: run && run.chunk != null ? `chunk ${run.chunk}` : "", + cls: zeroClass, + }, + { + label: "mode", + value: fmtNum(run && run.mode), + hint: run && run.kind ? String(run.kind) : "", + cls: "", + }, + { + label: "nodes healthy", + value: nodes ? `${fmtNum(nodes.healthy)} / ${fmtNum(nodes.total)}` : "—", + hint: nodes && nodes.enabled != null ? `enabled ${nodes.enabled}` : "", + cls: "", + }, + ]; +} + +// ── Bars ──────────────────────────────────────────────────────────────────── +// returns [{ label, a, b, value: pctVal|null, cls }] +export function bars(run) { + const complete = run && run.complete != null ? run.complete : null; + const goal = run && run.goal_complete != null ? run.goal_complete : null; + const gained = run && run.batch_gained != null ? run.batch_gained : null; + const target = run && (run.target != null ? run.target : run.target_new); + const stuck = !!(run && run.stuck); + const gp = pct(complete, goal); + const bp = pct(gained, target); + return [ + { label: "Глобально", a: complete, b: goal, value: gp, cls: stuck ? "danger" : "ok" }, + { label: "Этот батч", a: gained, b: target, value: bp, cls: stuck ? "warn" : "ok" }, + ]; +} + +// ── Step rail ─────────────────────────────────────────────────────────────── +// returns [{ state, title, desc }] (state: done|active|pending) +export function stepRail(steps) { + if (!Array.isArray(steps) || !steps.length) return []; + return steps.map((s) => { + const state = s && s.state ? String(s.state) : "pending"; + const title = s && (s.title || s.id) ? String(s.title || s.id) : ""; + const desc = s && s.desc ? String(s.desc) : ""; + return { state, title, desc }; + }); +} + +// ── Status card ───────────────────────────────────────────────────────────── +// returns { title, body } +export function statusCard(run) { + const alive = !!(run && run.alive); + const phase = (run && (run.phase_title || run.phase)) || "—"; + const title = `Статус задачи: ${alive ? "выполняется" : run ? "ожидание" : "—"} · ${phase}`; + const lines = []; + if (run) { + if (run.phase_detail) lines.push(run.phase_detail); + const fatal = run.summary && run.summary.fatal_reason; + if (fatal) lines.push(`fatal: ${fatal}`); + if (run.worker_log) lines.push(`worker: ${run.worker_log}`); + if (run.supervisor_log) lines.push(`supervisor: ${run.supervisor_log}`); + if (run.stuck_reason && !fatal) lines.push(`stuck: ${run.stuck_reason}`); + if (!lines.length) lines.push("Текущая задача загружена."); + } else { + lines.push("Активного supervisor нет. Заполните параметры слева и нажмите «Старт»."); + } + return { title, body: lines.join("\n") }; +} + +// ── Recent writes ──────────────────────────────────────────────────────────── +// returns [{ name, raw }] (last ≤5) +export function recentWrites(writes) { + if (!Array.isArray(writes) || !writes.length) return []; + return writes.slice(-5).map((p) => { + const raw = String(p); + const name = raw.split(/[\\/]/).pop() || raw; + return { name, raw }; + }); +} + +// ── Failure stats ───────────────────────────────────────────────────────────── +// Aggregated batch-level failures from run.batch_failures (control_api parses +// every per-sub SUMMARY_JSON in the supervisor log). Returns null when there is +// nothing to show yet so the card can hide entirely. +// returns { subs, kpis:[{label,value,cls,hint}], breakdown:[{label,value,cls}], +// reasons:[{title, rows:[{label,count}]}], series:{fail,success} } | null +export function failureStats(run) { + const bf = run && run.batch_failures; + if (!bf || !bf.subs) return null; + + const regFail = Number(bf.reg_fail || 0); + const attempts = Number(bf.attempts || 0); + const rate = attempts ? (regFail / attempts) * 100 : 0; + const rateCls = rate >= 50 ? "danger" : rate >= 20 ? "warn" : rate > 0 ? "" : "ok"; + const totalFail = Number(bf.total_fail || 0); + + const kpis = [ + { + label: "Доля ошибок регистрации", + value: attempts ? `${rate.toFixed(0)}%` : "—", + hint: attempts ? `${regFail} / ${attempts} попыток` : "нет записей попыток", + cls: rateCls, + }, + { + label: "Всего ошибок", + value: String(totalFail), + hint: `агрегат ${bf.subs} под-батчей`, + cls: totalFail > 0 ? "warn" : "ok", + }, + { + label: "fatal под-батч", + value: String(bf.fatal_subs || 0), + hint: bf.fatal_subs ? "см. причину fatal ниже" : "нет", + cls: bf.fatal_subs > 0 ? "danger" : "ok", + }, + ]; + + // Failure-type distribution (stacked/segmented bar). + const segRaw = [ + { label: "Регистрация", value: regFail, cls: "err" }, + { label: "Mint", value: Number(bf.mint_fail || 0), cls: "warn" }, + { label: "Chat отказ", value: Number(bf.chat_denied || 0), cls: "warn" }, + { label: "Chat ошибка", value: Number(bf.chat_fail || 0), cls: "err" }, + { label: "Инъекция", value: Number(bf.remote_inject_fail || 0), cls: "err" }, + { label: "Live", value: Number(bf.remote_live_fail || 0), cls: "warn" }, + ]; + const segTotal = segRaw.reduce((a, s) => a + s.value, 0) || 1; + const breakdown = segRaw + .filter((s) => s.value > 0) + .map((s) => ({ + label: s.label, + value: s.value, + pct: (s.value / segTotal) * 100, + cls: s.cls, + })); + + const reasons = []; + const mintReasons = Array.isArray(bf.mint_fail_reasons) ? bf.mint_fail_reasons : []; + if (mintReasons.length) { + reasons.push({ + title: "Причина ошибки Mint", + rows: mintReasons.map(([label, count]) => ({ label: String(label), count })), + }); + } + const fatalReasons = Array.isArray(bf.fatal_reasons) ? bf.fatal_reasons : []; + if (fatalReasons.length) { + reasons.push({ + title: "Причина fatal", + rows: fatalReasons.map(([label, count]) => ({ label: String(label), count })), + }); + } + + const failSeries = Array.isArray(bf.reg_fail_series) ? bf.reg_fail_series : []; + const okSeries = Array.isArray(bf.reg_success_series) ? bf.reg_success_series : []; + + return { + subs: bf.subs, + kpis, + breakdown, + reasons, + series: { fail: failSeries, success: okSeries }, + }; +} + +// ── Timeline ────────────────────────────────────────────────────────────────── +// returns [{ src, title, line }] (last ≤6) +export function timeline(items) { + const cap = 6; + const rows = Array.isArray(items) ? items.slice(-cap) : []; + return rows.map((it) => ({ + src: String((it && (it.source || it.phase)) || "log"), + title: String((it && it.title) || ""), + line: String((it && it.line) || "").slice(0, 300), + })); +} diff --git a/apps/web/src/pages/Resources/ImportTab.jsx b/apps/web/src/pages/Resources/ImportTab.jsx new file mode 100644 index 0000000..bb383e1 --- /dev/null +++ b/apps/web/src/pages/Resources/ImportTab.jsx @@ -0,0 +1,187 @@ +// ImportTab — 2×2 cards: nodes file, mail text, auths file, pack zip +import { useRef, useState } from "preact/hooks"; +import * as api from "../../api/client.js"; +import { showOpsFeedback } from "../../store/feedback.js"; +import { Button, LogDetails } from "../../ui/index.js"; +import { formatApiError } from "../../lib/format.js"; +import { pretty, auth401 } from "../../lib/http.js"; +import { useBusy } from "../../lib/useBusy.js"; + +export function ImportTab() { + const [result, setResult] = useState(""); + const { is: busyIs, run: withBusy } = useBusy(); + const nodesFile = useRef(null); + const authsFile = useRef(null); + const packFile = useRef(null); + const [nodesDry, setNodesDry] = useState(true); + const [nodesReplace, setNodesReplace] = useState(false); + const [mailText, setMailText] = useState(""); + const [mailMode, setMailMode] = useState("append"); + const [authsRemote, setAuthsRemote] = useState(false); + const [packApply, setPackApply] = useState(false); + + async function run(key, fn) { + await withBusy(key, async () => { + try { + const body = await fn(); + setResult(pretty(body)); + if (key === "mail") { + const r = (body && body.result) || body || {}; + const summary = + (body && body.detail) || + r.summary || + `Импорт почты · новых ${r.new ?? r.lines_written ?? 0} · дублей ${r.duplicate ?? 0} · невалидных ${r.skipped ?? 0}`; + const status = r.status || (r.new > 0 || r.lines_written > 0 ? "success" : "empty"); + const kind = status === "success" ? "ok" : "info"; + showOpsFeedback(summary, kind, { toast: true, sticky: true }); + } else { + showOpsFeedback(`Импорт завершён · ${key}`, "ok", { toast: true, sticky: false }); + } + } catch (e) { + if (auth401(e)) return; + setResult(pretty({ error: formatApiError(e) })); + showOpsFeedback(`Ошибка импорта: ${formatApiError(e)}`, "err"); + } + }); + } + + return ( +
+
+
+

Файл Nodes / proxies

+ + + + +
+ +
+

Mail credentials

+

+ Общий источник с «Ресурсы → Почта». Поддержка JSON/CSV/pipe; append с дедупом, фидбек: новых/дублей/невалидных. +

+