synabun 2.2.1 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +53 -0
- package/README.md +1 -1
- package/docs/whatsapp.md +52 -20
- package/hooks/claude-code/pre-websearch.mjs +4 -1
- package/hooks/claude-code/prompt-submit.mjs +7 -0
- package/lib/mcp-build.js +519 -0
- package/lib/mcp-dist.js +10 -4
- package/lib/release-scan.mjs +23 -10
- package/lib/server-supervisor.js +7 -1
- package/lib/virustotal.mjs +146 -40
- package/mcp-server/dist/http.d.ts +57 -0
- package/mcp-server/dist/http.d.ts.map +1 -1
- package/mcp-server/dist/http.js +128 -18
- package/mcp-server/dist/http.js.map +1 -1
- package/mcp-server/dist/index.d.ts.map +1 -1
- package/mcp-server/dist/index.js +14 -9
- package/mcp-server/dist/index.js.map +1 -1
- package/mcp-server/dist/services/browser-route-flow.d.ts +119 -0
- package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -0
- package/mcp-server/dist/services/browser-route-flow.js +340 -0
- package/mcp-server/dist/services/browser-route-flow.js.map +1 -0
- package/mcp-server/dist/services/desktop-client.js +2 -2
- package/mcp-server/dist/services/desktop-client.js.map +1 -1
- package/mcp-server/dist/services/embedding-service.d.ts.map +1 -1
- package/mcp-server/dist/services/embedding-service.js +2 -1
- package/mcp-server/dist/services/embedding-service.js.map +1 -1
- package/mcp-server/dist/services/identity.d.ts +66 -3
- package/mcp-server/dist/services/identity.d.ts.map +1 -1
- package/mcp-server/dist/services/identity.js +61 -4
- package/mcp-server/dist/services/identity.js.map +1 -1
- package/mcp-server/dist/services/neural-interface.d.ts +133 -1
- package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
- package/mcp-server/dist/services/neural-interface.js +630 -64
- package/mcp-server/dist/services/neural-interface.js.map +1 -1
- package/mcp-server/dist/services/tool-catalog.js +2 -2
- package/mcp-server/dist/services/tool-catalog.js.map +1 -1
- package/mcp-server/dist/tools/agents.d.ts +3 -2
- package/mcp-server/dist/tools/agents.d.ts.map +1 -1
- package/mcp-server/dist/tools/agents.js +6 -4
- package/mcp-server/dist/tools/agents.js.map +1 -1
- package/mcp-server/dist/tools/bluesky.d.ts +20 -7
- package/mcp-server/dist/tools/bluesky.d.ts.map +1 -1
- package/mcp-server/dist/tools/bluesky.js +147 -45
- package/mcp-server/dist/tools/bluesky.js.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts +13 -2
- package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.js +153 -18
- package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
- package/mcp-server/dist/tools/browser-cheatsheet.d.ts +2 -0
- package/mcp-server/dist/tools/browser-cheatsheet.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-cheatsheet.js +3 -0
- package/mcp-server/dist/tools/browser-cheatsheet.js.map +1 -1
- package/mcp-server/dist/tools/browser-navigate.d.ts +3 -3
- package/mcp-server/dist/tools/browser-navigate.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-navigate.js +19 -16
- package/mcp-server/dist/tools/browser-navigate.js.map +1 -1
- package/mcp-server/dist/tools/browser-observe.d.ts +2 -1
- package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-observe.js +61 -20
- package/mcp-server/dist/tools/browser-observe.js.map +1 -1
- package/mcp-server/dist/tools/morelogin.d.ts +13 -3
- package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
- package/mcp-server/dist/tools/morelogin.js +82 -19
- package/mcp-server/dist/tools/morelogin.js.map +1 -1
- package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
- package/mcp-server/dist/tools/youtube/helpers.d.ts +1 -0
- package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
- package/mcp-server/dist/tools/youtube/helpers.js +1 -1
- package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
- package/mcp-server/dist/tools/youtube/upload.d.ts.map +1 -1
- package/mcp-server/dist/tools/youtube/upload.js +225 -88
- package/mcp-server/dist/tools/youtube/upload.js.map +1 -1
- package/mcp-server/package-lock.json +2 -2
- package/mcp-server/package.json +1 -1
- package/mcp-server/src/http.ts +135 -17
- package/mcp-server/src/index.ts +15 -9
- package/mcp-server/src/services/browser-route-flow.ts +403 -0
- package/mcp-server/src/services/desktop-client.ts +2 -2
- package/mcp-server/src/services/embedding-service.ts +2 -1
- package/mcp-server/src/services/identity.ts +80 -4
- package/mcp-server/src/services/neural-interface.ts +648 -73
- package/mcp-server/src/services/tool-catalog.ts +2 -2
- package/mcp-server/src/tools/agents.ts +8 -4
- package/mcp-server/src/tools/bluesky.ts +164 -51
- package/mcp-server/src/tools/browser-advanced.ts +142 -17
- package/mcp-server/src/tools/browser-cheatsheet.ts +3 -0
- package/mcp-server/src/tools/browser-navigate.ts +19 -16
- package/mcp-server/src/tools/browser-observe.ts +62 -20
- package/mcp-server/src/tools/morelogin.ts +82 -19
- package/mcp-server/src/tools/youtube/helpers.ts +2 -2
- package/mcp-server/src/tools/youtube/upload.ts +218 -99
- package/neural-interface/i18n/en.json +655 -123
- package/neural-interface/i18n/pt-BR.json +542 -10
- package/neural-interface/lib/assistant-api.js +90 -23
- package/neural-interface/lib/assistant-brains/claude.js +5 -0
- package/neural-interface/lib/assistant-catalog.js +134 -3
- package/neural-interface/lib/assistant-dispatch.js +97 -1
- package/neural-interface/lib/assistant-persona.js +15 -7
- package/neural-interface/lib/assistant-router.js +6 -4
- package/neural-interface/lib/assistant-runtime.js +18 -1
- package/neural-interface/lib/assistant-task-prompt.js +5 -0
- package/neural-interface/lib/assistant-tools.js +10 -1
- package/neural-interface/lib/automation-approval.js +249 -0
- package/neural-interface/lib/automation-browser-owner-access.js +82 -0
- package/neural-interface/lib/backup-service.js +16 -1
- package/neural-interface/lib/browser-automation-routes.js +84 -0
- package/neural-interface/lib/browser-background-tab.js +72 -3
- package/neural-interface/lib/browser-execution.js +16 -3
- package/neural-interface/lib/browser-extraction.js +106 -45
- package/neural-interface/lib/browser-owner.js +48 -0
- package/neural-interface/lib/browser-profile-choices.js +143 -0
- package/neural-interface/lib/browser-profiles.js +142 -0
- package/neural-interface/lib/browser-session-close.js +84 -0
- package/neural-interface/lib/browser-start-handoff.js +202 -0
- package/neural-interface/lib/browser-tab-recovery.js +153 -0
- package/neural-interface/lib/browser-tool-policy.js +23 -4
- package/neural-interface/lib/browser-wedge-retire.js +64 -0
- package/neural-interface/lib/chromium-on-device-model.js +67 -0
- package/neural-interface/lib/claude-agent-bridge.js +43 -5
- package/neural-interface/lib/claude-background-hold.js +239 -0
- package/neural-interface/lib/claude-model-catalog.js +12 -0
- package/neural-interface/lib/effort-levels.js +28 -2
- package/neural-interface/lib/exec-loop-command.js +8 -0
- package/neural-interface/lib/http-guards.js +11 -6
- package/neural-interface/lib/local-profile-proxy.js +362 -0
- package/neural-interface/lib/local-profiles.js +929 -0
- package/neural-interface/lib/loop-logger.js +31 -5
- package/neural-interface/lib/maritaca/api.js +179 -0
- package/neural-interface/lib/maritaca/attachments.js +44 -0
- package/neural-interface/lib/maritaca/client.js +362 -0
- package/neural-interface/lib/maritaca/key-store.js +122 -0
- package/neural-interface/lib/maritaca/models.js +181 -0
- package/neural-interface/lib/maritaca/modes.js +39 -0
- package/neural-interface/lib/maritaca/opencode-proxy.js +236 -0
- package/neural-interface/lib/maritaca/opencode-stream.js +345 -0
- package/neural-interface/lib/maritaca/opencode.js +218 -0
- package/neural-interface/lib/maritaca/panel-bridge.js +273 -0
- package/neural-interface/lib/maritaca/sessions.js +198 -0
- package/neural-interface/lib/mcp-external-servers.js +37 -10
- package/neural-interface/lib/morelogin-agent-profiles.js +149 -0
- package/neural-interface/lib/morelogin.js +278 -14
- package/neural-interface/lib/native-loop-providers.js +124 -11
- package/neural-interface/lib/native-loop-runtime.js +112 -11
- package/neural-interface/lib/owner-authority.js +137 -43
- package/neural-interface/lib/page-session.js +111 -27
- package/neural-interface/lib/peer-identity.js +263 -43
- package/neural-interface/lib/provider-panel-api-key-auth.js +7 -2
- package/neural-interface/lib/pty-host/core.js +36 -0
- package/neural-interface/lib/pty-host/protocol.js +2 -0
- package/neural-interface/lib/request-gate.js +2 -0
- package/neural-interface/lib/skills/api-v2.js +13 -2
- package/neural-interface/lib/skills/creation-api.js +3 -1
- package/neural-interface/lib/skills/evals-api.js +5 -1
- package/neural-interface/lib/social-write-pacing.js +151 -0
- package/neural-interface/lib/system-activity.js +1 -1
- package/neural-interface/lib/terminal-token-redaction.js +293 -0
- package/neural-interface/lib/terminal-tokens.js +436 -0
- package/neural-interface/lib/worker-mcp-channel.js +45 -10
- package/neural-interface/package-lock.json +3 -2
- package/neural-interface/package.json +2 -1
- package/neural-interface/public/assets/mascot/README.md +11 -0
- package/neural-interface/public/assets/mascot/ask.gif +0 -0
- package/neural-interface/public/assets/mascot/ask.png +0 -0
- package/neural-interface/public/assets/mascot/blocked.gif +0 -0
- package/neural-interface/public/assets/mascot/blocked.png +0 -0
- package/neural-interface/public/assets/mascot/budget.gif +0 -0
- package/neural-interface/public/assets/mascot/budget.png +0 -0
- package/neural-interface/public/assets/mascot/computer.gif +0 -0
- package/neural-interface/public/assets/mascot/computer.png +0 -0
- package/neural-interface/public/assets/mascot/edit.gif +0 -0
- package/neural-interface/public/assets/mascot/edit.png +0 -0
- package/neural-interface/public/assets/mascot/error.gif +0 -0
- package/neural-interface/public/assets/mascot/error.png +0 -0
- package/neural-interface/public/assets/mascot/hover-attention.gif +0 -0
- package/neural-interface/public/assets/mascot/hover-attention.png +0 -0
- package/neural-interface/public/assets/mascot/idle-hero.gif +0 -0
- package/neural-interface/public/assets/mascot/idle-hero.png +0 -0
- package/neural-interface/public/assets/mascot/idle.gif +0 -0
- package/neural-interface/public/assets/mascot/idle.png +0 -0
- package/neural-interface/public/assets/mascot/manifest.json +254 -0
- package/neural-interface/public/assets/mascot/mcp.gif +0 -0
- package/neural-interface/public/assets/mascot/mcp.png +0 -0
- package/neural-interface/public/assets/mascot/memory.gif +0 -0
- package/neural-interface/public/assets/mascot/memory.png +0 -0
- package/neural-interface/public/assets/mascot/offline.gif +0 -0
- package/neural-interface/public/assets/mascot/offline.png +0 -0
- package/neural-interface/public/assets/mascot/pick.gif +0 -0
- package/neural-interface/public/assets/mascot/pick.png +0 -0
- package/neural-interface/public/assets/mascot/plan.gif +0 -0
- package/neural-interface/public/assets/mascot/plan.png +0 -0
- package/neural-interface/public/assets/mascot/present.gif +0 -0
- package/neural-interface/public/assets/mascot/present.png +0 -0
- package/neural-interface/public/assets/mascot/project.gif +0 -0
- package/neural-interface/public/assets/mascot/project.png +0 -0
- package/neural-interface/public/assets/mascot/read.gif +0 -0
- package/neural-interface/public/assets/mascot/read.png +0 -0
- package/neural-interface/public/assets/mascot/runs.gif +0 -0
- package/neural-interface/public/assets/mascot/runs.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/automation.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/automation.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/browser.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/browser.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/code.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/code.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/complex.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/complex.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/computer.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/computer.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/design.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/design.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/edit.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/edit.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/generic.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/generic.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/image_gen.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/image_gen.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/manifest.json +173 -0
- package/neural-interface/public/assets/mascot/scenes/memory.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/memory.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/quick.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/quick.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/read.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/read.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/research.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/research.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/review.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/review.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/search.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/search.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/shell.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/shell.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/thinking.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/thinking.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/video_gen.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/video_gen.png +0 -0
- package/neural-interface/public/assets/mascot/scenes/web.gif +0 -0
- package/neural-interface/public/assets/mascot/scenes/web.png +0 -0
- package/neural-interface/public/assets/mascot/search.gif +0 -0
- package/neural-interface/public/assets/mascot/search.png +0 -0
- package/neural-interface/public/assets/mascot/shell.gif +0 -0
- package/neural-interface/public/assets/mascot/shell.png +0 -0
- package/neural-interface/public/assets/mascot/skill.gif +0 -0
- package/neural-interface/public/assets/mascot/skill.png +0 -0
- package/neural-interface/public/assets/mascot/sleep.gif +0 -0
- package/neural-interface/public/assets/mascot/sleep.png +0 -0
- package/neural-interface/public/assets/mascot/subagent.gif +0 -0
- package/neural-interface/public/assets/mascot/subagent.png +0 -0
- package/neural-interface/public/assets/mascot/success.gif +0 -0
- package/neural-interface/public/assets/mascot/success.png +0 -0
- package/neural-interface/public/assets/mascot/think.gif +0 -0
- package/neural-interface/public/assets/mascot/think.png +0 -0
- package/neural-interface/public/assets/mascot/wait.gif +0 -0
- package/neural-interface/public/assets/mascot/wait.png +0 -0
- package/neural-interface/public/assets/mascot/watch.gif +0 -0
- package/neural-interface/public/assets/mascot/watch.png +0 -0
- package/neural-interface/public/assets/mascot/web.gif +0 -0
- package/neural-interface/public/assets/mascot/web.png +0 -0
- package/neural-interface/public/onboarding.html +14 -1
- package/neural-interface/public/shared/agent-runtime-options.js +49 -8
- package/neural-interface/public/shared/agy/agy-panel.js +2 -2
- package/neural-interface/public/shared/agy/agy-render.js +41 -1
- package/neural-interface/public/shared/agy/agy-styles.js +5 -0
- package/neural-interface/public/shared/api.js +5 -4
- package/neural-interface/public/shared/assistant/asst-ask-styles.js +8 -8
- package/neural-interface/public/shared/assistant/asst-ask.js +1 -1
- package/neural-interface/public/shared/assistant/asst-brain-picker.js +99 -9
- package/neural-interface/public/shared/assistant/asst-computer.js +47 -2
- package/neural-interface/public/shared/assistant/asst-control.js +1 -1
- package/neural-interface/public/shared/assistant/asst-limit-wait.js +7 -5
- package/neural-interface/public/shared/assistant/asst-panel.js +13 -5
- package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -4
- package/neural-interface/public/shared/assistant/asst-render.js +16 -10
- package/neural-interface/public/shared/assistant/asst-route-models.js +64 -4
- package/neural-interface/public/shared/assistant/asst-route.js +24 -7
- package/neural-interface/public/shared/assistant/asst-routes-editor.js +154 -39
- package/neural-interface/public/shared/assistant/asst-run-stage.js +3 -3
- package/neural-interface/public/shared/assistant/asst-scene-styles.js +8 -111
- package/neural-interface/public/shared/assistant/asst-scenes.js +46 -318
- package/neural-interface/public/shared/assistant/asst-sidepanel.js +2 -2
- package/neural-interface/public/shared/assistant/asst-state.js +72 -2
- package/neural-interface/public/shared/assistant/asst-styles.js +60 -15
- package/neural-interface/public/shared/automation-approval-view.js +75 -0
- package/neural-interface/public/shared/cdx/cdx-panel.js +2 -2
- package/neural-interface/public/shared/cdx/cdx-render.js +73 -7
- package/neural-interface/public/shared/cdx/cdx-tabs.js +3 -3
- package/neural-interface/public/shared/context-menu-model.js +2 -0
- package/neural-interface/public/shared/cp/cp-agents.js +8 -0
- package/neural-interface/public/shared/cp/cp-permissions.js +6 -2
- package/neural-interface/public/shared/cp/cp-rehydrate.js +25 -1
- package/neural-interface/public/shared/cp/cp-tasks-model.js +33 -0
- package/neural-interface/public/shared/editor/editor-panel-logic.js +10 -0
- package/neural-interface/public/shared/editor/editor-panel.js +10 -2
- package/neural-interface/public/shared/html-shell.js +30 -22
- package/neural-interface/public/shared/judgments-log-origins.js +29 -0
- package/neural-interface/public/shared/morelogin-profile-choices.js +107 -0
- package/neural-interface/public/shared/morelogin-profile-field.js +186 -0
- package/neural-interface/public/shared/mtc/mtc-client.js +181 -0
- package/neural-interface/public/shared/mtc/mtc-compose.js +40 -0
- package/neural-interface/public/shared/mtc/mtc-copy.js +253 -0
- package/neural-interface/public/shared/mtc/mtc-logic.js +478 -0
- package/neural-interface/public/shared/mtc/mtc-panel.js +1354 -0
- package/neural-interface/public/shared/mtc/mtc-render.js +172 -0
- package/neural-interface/public/shared/mtc/mtc-styles.js +437 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-automation-ownership.js +23 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +13 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-icons.js +3 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +10 -4
- package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +6 -86
- package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +5 -2
- package/neural-interface/public/shared/owner-access.js +134 -0
- package/neural-interface/public/shared/owner-authority-view.js +92 -0
- package/neural-interface/public/shared/page-session.js +143 -14
- package/neural-interface/public/shared/poll-backoff.js +59 -0
- package/neural-interface/public/shared/provider-icons.js +3 -0
- package/neural-interface/public/shared/schedules-view.js +7 -0
- package/neural-interface/public/shared/server-back.js +50 -0
- package/neural-interface/public/shared/settings/settings-browser-owner-access.js +72 -0
- package/neural-interface/public/shared/settings/settings-data.js +7 -1
- package/neural-interface/public/shared/settings/settings-ia.js +3 -1
- package/neural-interface/public/shared/settings/settings-kit.js +11 -3
- package/neural-interface/public/shared/settings/settings-local-profiles.js +153 -0
- package/neural-interface/public/shared/settings/settings-maritaca-opencode.js +105 -0
- package/neural-interface/public/shared/settings/settings-shell.js +7 -0
- package/neural-interface/public/shared/shown-children.js +72 -0
- package/neural-interface/public/shared/sidepanel-session-status.js +16 -2
- package/neural-interface/public/shared/state.js +1 -1
- package/neural-interface/public/shared/static-bg-state.js +22 -0
- package/neural-interface/public/shared/styles.css +457 -164
- package/neural-interface/public/shared/synabun-mascot-assets.js +67 -0
- package/neural-interface/public/shared/synabun-mascot.js +136 -12
- package/neural-interface/public/shared/synabun-ticker.js +3 -0
- package/neural-interface/public/shared/synabun-tools.js +173 -0
- package/neural-interface/public/shared/tool-heartbeat.js +43 -0
- package/neural-interface/public/shared/tool-list-picker.js +3 -1
- package/neural-interface/public/shared/tool-list-view.js +23 -4
- package/neural-interface/public/shared/topright-overflow-logic.js +1 -0
- package/neural-interface/public/shared/ui-automation-approval.js +188 -0
- package/neural-interface/public/shared/ui-automation-studio.js +138 -91
- package/neural-interface/public/shared/ui-claude-panel.js +209 -31
- package/neural-interface/public/shared/ui-judgments.js +37 -10
- package/neural-interface/public/shared/ui-maritaca-panel.js +15 -0
- package/neural-interface/public/shared/ui-navbar.js +23 -0
- package/neural-interface/public/shared/ui-owner-access.js +191 -0
- package/neural-interface/public/shared/ui-owner-authority.js +162 -0
- package/neural-interface/public/shared/ui-panels.js +3 -1
- package/neural-interface/public/shared/ui-schedules-studio.js +118 -17
- package/neural-interface/public/shared/ui-scroll-follow.js +3 -0
- package/neural-interface/public/shared/ui-sessions.js +45 -16
- package/neural-interface/public/shared/ui-settings.js +676 -42
- package/neural-interface/public/shared/ui-sidepanel-session-entry.js +8 -2
- package/neural-interface/public/shared/ui-sidepanel-sessions.js +3 -3
- package/neural-interface/public/shared/ui-sidepanel-tray.js +24 -0
- package/neural-interface/public/shared/ui-sidepanel-windows.js +1 -1
- package/neural-interface/public/shared/ui-terminal.js +15 -7
- package/neural-interface/public/shared/ui-tutorial-preview.js +4 -0
- package/neural-interface/public/shared/ui-update.js +3 -0
- package/neural-interface/public/shared/ui-whiteboard.js +4 -0
- package/neural-interface/public/shared/window-keys.js +38 -0
- package/neural-interface/scripts/build-mascot-assets.mjs +30 -0
- package/neural-interface/server.js +2903 -359
- package/npm-shrinkwrap.json +5 -17
- package/package.json +5 -6
- package/postinstall.js +38 -39
- package/setup.js +33 -31
- package/skills/synabun/modules/changelog.md +14 -0
|
@@ -0,0 +1,929 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local browser profiles: profiles SynaBun creates and runs itself on this computer.
|
|
3
|
+
*
|
|
4
|
+
* A local profile is a Chrome that SynaBun starts with a data folder of its own (`--user-data-dir`). It stands next to
|
|
5
|
+
* the MoreLogin profiles and is used through the same rails (lib/browser-profiles.js routes by id): the default AI
|
|
6
|
+
* browser, the owner's list of profiles agents may choose, a run's or a session's own profile, the pickers, the
|
|
7
|
+
* `morelogin` tool's list / use / start / stop. Starting one answers a DevTools port, as MoreLogin's start does.
|
|
8
|
+
*
|
|
9
|
+
* What it is NOT: it is not a MoreLogin profile. Nothing here reads or writes MoreLogin's app data, its browser, its
|
|
10
|
+
* account or its API, and the MoreLogin app does not list these profiles. It does no fingerprint spoofing either (no
|
|
11
|
+
* canvas, WebGL or user-agent faking): the browser is the Chrome installed on this computer, unmodified. What a
|
|
12
|
+
* profile keeps to itself is its storage (cookies, logins, cache, extensions), its proxy, its language, its timezone,
|
|
13
|
+
* its window size, and WebRTC kept on the proxy.
|
|
14
|
+
*
|
|
15
|
+
* Store: `<root>/profiles.json` (mode 0600; a proxy password is kept there as typed) and one folder per profile,
|
|
16
|
+
* `<root>/<id>/`, which is its `--user-data-dir`. `root` is DATA_HOME/data/local-profiles in the server.
|
|
17
|
+
*
|
|
18
|
+
* Everything that starts or stops a process works on `<root>/<id>` only (assertLocalProfileRoot): a process is stopped
|
|
19
|
+
* only when its command line holds that exact `--user-data-dir`.
|
|
20
|
+
*
|
|
21
|
+
* Built-ins only. ESM, Node >= 22.
|
|
22
|
+
*/
|
|
23
|
+
import { randomBytes } from 'node:crypto';
|
|
24
|
+
import { execFileSync } from 'node:child_process';
|
|
25
|
+
import {
|
|
26
|
+
chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, unlinkSync, writeFileSync,
|
|
27
|
+
} from 'node:fs';
|
|
28
|
+
import { createServer } from 'node:net';
|
|
29
|
+
import { join, resolve, sep } from 'node:path';
|
|
30
|
+
import { withOnDeviceModelBlocked } from './chromium-on-device-model.js';
|
|
31
|
+
import { PROXY_TYPES, checkProxy, createProxyRelay, directProxyServer, proxyNeedsRelay } from './local-profile-proxy.js';
|
|
32
|
+
|
|
33
|
+
export const LOCAL_PROFILE_ID_RE = /^lp-[0-9a-f]{12}$/;
|
|
34
|
+
export const LOCAL_PROFILES_MAX = 200;
|
|
35
|
+
export const DEFAULT_WINDOW = Object.freeze({ width: 1280, height: 800 });
|
|
36
|
+
const RELAY_FILE = 'synabun-relay.json';
|
|
37
|
+
const LAUNCH_FILE = 'synabun-launch.json';
|
|
38
|
+
const STOP_GRACE_MS = 5000;
|
|
39
|
+
/**
|
|
40
|
+
* The loopback ports SynaBun keeps for its local profiles: every proxy relay and every DevTools port of a profile it
|
|
41
|
+
* starts is inside this range and nowhere else, so a guarded worker's sandbox denies the range as a whole (server.js
|
|
42
|
+
* workerBrowserControlPorts) and a port opened after the worker started is covered too. 400 ports: a relay and a
|
|
43
|
+
* DevTools port for each of the 200 profiles. Below every system's range of ports handed out by themselves (Linux
|
|
44
|
+
* from 32768, macOS and Windows from 49152), and clear of what SynaBun uses elsewhere (3344 / 3345, 13344, 4096-4400,
|
|
45
|
+
* 9222, MoreLogin's 40000 and 15523).
|
|
46
|
+
*/
|
|
47
|
+
export const LOCAL_PROFILE_PORT_RANGE = Object.freeze({ from: 26200, to: 26599 });
|
|
48
|
+
/** Whether a port is one of the ports kept for local profiles. */
|
|
49
|
+
export function isLocalProfilePort(port, range = LOCAL_PROFILE_PORT_RANGE) {
|
|
50
|
+
const p = Number(port);
|
|
51
|
+
return Number.isInteger(p) && p >= range.from && p <= range.to;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Whether an id is a local profile's (by its shape alone: `lp-` and 12 hex characters). */
|
|
55
|
+
export function isLocalProfileId(id) {
|
|
56
|
+
return typeof id === 'string' && LOCAL_PROFILE_ID_RE.test(id);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function refusal(status, code, message, extra = {}) {
|
|
60
|
+
return Object.assign(new Error(message), { status, code, ...extra });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const clean = (value, max) => (typeof value === 'string' ? value.replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, max) : '');
|
|
64
|
+
|
|
65
|
+
/** An IANA timezone name as Intl spells it, or null when Intl does not know it. */
|
|
66
|
+
export function canonicalTimezone(value) {
|
|
67
|
+
const name = clean(value, 80);
|
|
68
|
+
if (!name) return null;
|
|
69
|
+
try { return new Intl.DateTimeFormat('en-US', { timeZone: name }).resolvedOptions().timeZone || null; } catch { return null; }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** A language tag as Intl spells it (pt-br → pt-BR), or null when it is not one. */
|
|
73
|
+
export function canonicalLanguage(value) {
|
|
74
|
+
const tag = clean(value, 35);
|
|
75
|
+
if (!tag || !/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/.test(tag)) return null;
|
|
76
|
+
try { return Intl.getCanonicalLocales(tag)[0] || null; } catch { return null; }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** What Chrome sends as Accept-Language for a profile language: the tag, its base language, then English. */
|
|
80
|
+
export function acceptLanguagesFor(language) {
|
|
81
|
+
if (!language) return '';
|
|
82
|
+
const out = [language];
|
|
83
|
+
const base = language.split('-')[0];
|
|
84
|
+
if (base && base !== language) out.push(base);
|
|
85
|
+
for (const extra of ['en-US', 'en']) if (!out.includes(extra)) out.push(extra);
|
|
86
|
+
return out.join(',');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function normalizeProxy(input, saved = null) {
|
|
90
|
+
const before = saved || { type: 'none', host: '', port: null, username: '', password: '' };
|
|
91
|
+
if (input === undefined) return { ...before };
|
|
92
|
+
if (input === null) return { type: 'none', host: '', port: null, username: '', password: '' };
|
|
93
|
+
if (typeof input !== 'object') throw refusal(400, 'LOCAL_PROFILE_PROXY', 'proxy must be an object: { type, host, port, username, password }.', { field: 'proxy' });
|
|
94
|
+
const type = input.type === undefined ? before.type : String(input.type || 'none').toLowerCase();
|
|
95
|
+
if (!PROXY_TYPES.includes(type)) throw refusal(400, 'LOCAL_PROFILE_PROXY', `The proxy type is one of: ${PROXY_TYPES.join(', ')}.`, { field: 'proxy.type' });
|
|
96
|
+
if (type === 'none') return { type: 'none', host: '', port: null, username: '', password: '' };
|
|
97
|
+
const host = input.host === undefined ? before.host : clean(input.host, 253);
|
|
98
|
+
if (!host || /[\s/@?#]/.test(host)) throw refusal(400, 'LOCAL_PROFILE_PROXY', 'The proxy host is a host name or an IP address, without a scheme, a path or a login.', { field: 'proxy.host' });
|
|
99
|
+
const port = input.port === undefined ? before.port : Number(input.port);
|
|
100
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw refusal(400, 'LOCAL_PROFILE_PROXY', 'The proxy port is a number from 1 to 65535.', { field: 'proxy.port' });
|
|
101
|
+
const username = input.username === undefined ? before.username : clean(input.username, 255);
|
|
102
|
+
// The password is kept as typed. Not sent: the saved one stays (it is never returned, so a form cannot send it
|
|
103
|
+
// back), but only for the very proxy and login it was typed for. With another type, host, port or username the
|
|
104
|
+
// saved password is dropped (it would be sent to another server, or as another account) and has to be typed again.
|
|
105
|
+
// A proxy without a username has no password.
|
|
106
|
+
const sameLogin = type === before.type && host === before.host && port === before.port && username === before.username;
|
|
107
|
+
let password = input.password === undefined || input.password === null ? (sameLogin ? before.password : '') : String(input.password).slice(0, 255);
|
|
108
|
+
if (!username) password = '';
|
|
109
|
+
if (/[\u0000-\u001f]/.test(password)) throw refusal(400, 'LOCAL_PROFILE_PROXY', 'The proxy password holds a control character.', { field: 'proxy.password' });
|
|
110
|
+
return { type, host, port, username, password };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function normalizeWindow(input, saved = null) {
|
|
114
|
+
const before = saved || { ...DEFAULT_WINDOW };
|
|
115
|
+
if (input === undefined || input === null) return { ...before };
|
|
116
|
+
const width = input.width === undefined ? before.width : Number(input.width);
|
|
117
|
+
const height = input.height === undefined ? before.height : Number(input.height);
|
|
118
|
+
if (!Number.isInteger(width) || width < 400 || width > 7680 || !Number.isInteger(height) || height < 300 || height > 4320) {
|
|
119
|
+
throw refusal(400, 'LOCAL_PROFILE_WINDOW', 'The window size is a width from 400 to 7680 and a height from 300 to 4320, in pixels.', { field: 'window' });
|
|
120
|
+
}
|
|
121
|
+
return { width, height };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** A stored profile from a request body, over the saved one for an update. Throws 400 with `field`. */
|
|
125
|
+
export function normalizeLocalProfile(input, saved = null) {
|
|
126
|
+
const body = input && typeof input === 'object' ? input : {};
|
|
127
|
+
const name = body.name === undefined ? (saved?.name || '') : clean(body.name, 80);
|
|
128
|
+
if (!name) throw refusal(400, 'LOCAL_PROFILE_NAME', 'A local profile needs a name (at most 80 characters).', { field: 'name' });
|
|
129
|
+
let language = saved?.language || '';
|
|
130
|
+
if (body.language !== undefined) {
|
|
131
|
+
language = clean(body.language, 35) ? canonicalLanguage(body.language) : '';
|
|
132
|
+
if (language === null) throw refusal(400, 'LOCAL_PROFILE_LANGUAGE', 'The language is a tag such as pt-BR or en-US (or empty for Chrome\'s own).', { field: 'language' });
|
|
133
|
+
}
|
|
134
|
+
let timezone = saved?.timezone || '';
|
|
135
|
+
if (body.timezone !== undefined) {
|
|
136
|
+
timezone = clean(body.timezone, 80) ? canonicalTimezone(body.timezone) : '';
|
|
137
|
+
if (timezone === null) throw refusal(400, 'LOCAL_PROFILE_TIMEZONE', 'The timezone is an IANA name such as America/Sao_Paulo (or empty for this computer\'s).', { field: 'timezone' });
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
name,
|
|
141
|
+
proxy: normalizeProxy(body.proxy, saved?.proxy || null),
|
|
142
|
+
language,
|
|
143
|
+
timezone,
|
|
144
|
+
window: normalizeWindow(body.window, saved?.window || null),
|
|
145
|
+
notes: body.notes === undefined ? (saved?.notes || '') : String(body.notes ?? '').replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, '').slice(0, 2000),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** How many leading fields of a launch signature are the proxy's. */
|
|
150
|
+
const SIGNATURE_PROXY_FIELDS = 6;
|
|
151
|
+
/** The proxy part of a launch signature (as launchSignature wrote it), or null when it cannot be read. */
|
|
152
|
+
function proxyPartOf(signature) {
|
|
153
|
+
try {
|
|
154
|
+
const fields = JSON.parse(signature);
|
|
155
|
+
return Array.isArray(fields) && fields.length >= SIGNATURE_PROXY_FIELDS ? JSON.stringify(fields.slice(0, SIGNATURE_PROXY_FIELDS)) : null;
|
|
156
|
+
} catch { return null; }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Chrome's `--host-resolver-rules` for a profile with a proxy: no name is resolved on this computer (a name Chrome
|
|
161
|
+
* would look up by itself, as its prefetcher or a component does, gets "not found"), except the proxy's own host,
|
|
162
|
+
* which Chrome has to find, and this computer's loopback names (the relay, a local dev server). Names of pages are
|
|
163
|
+
* resolved by the proxy.
|
|
164
|
+
*/
|
|
165
|
+
export function hostResolverRules(proxyHost) {
|
|
166
|
+
const excluded = [];
|
|
167
|
+
const add = (host) => { const h = String(host || '').replace(/^\[|\]$/g, '').toLowerCase(); if (h && !/[\s,"']/.test(h) && !excluded.includes(h)) excluded.push(h); };
|
|
168
|
+
add(proxyHost);
|
|
169
|
+
add('127.0.0.1');
|
|
170
|
+
add('localhost');
|
|
171
|
+
add('*.localhost');
|
|
172
|
+
return ['MAP * ~NOTFOUND', ...excluded.map((host) => `EXCLUDE ${host}`)].join(' , ');
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** What a start depends on, as one string: a running profile whose launch record differs needs a restart. */
|
|
176
|
+
function launchSignature(profile) {
|
|
177
|
+
const { proxy, language, timezone, window } = profile;
|
|
178
|
+
return JSON.stringify([proxy.type, proxy.host, proxy.port, proxy.username, proxy.password ? 1 : 0, proxy.password ? simpleHash(proxy.password) : 0, language, timezone, window.width, window.height]);
|
|
179
|
+
}
|
|
180
|
+
function simpleHash(text) {
|
|
181
|
+
let h = 2166136261;
|
|
182
|
+
for (let i = 0; i < text.length; i++) { h ^= text.charCodeAt(i); h = Math.imul(h, 16777619); }
|
|
183
|
+
return h >>> 0;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* The Chrome arguments and environment of one start. `relayPort`: the profile's relay, when its proxy has a login.
|
|
188
|
+
* `debugPort`: the DevTools port Chrome is told to listen on. A start names a free one (startLocalProfile): with
|
|
189
|
+
* `--remote-debugging-port=0` Chrome marks every page as automated (`navigator.webdriver`), which a Chrome started
|
|
190
|
+
* with a port of its own, as attach mode's is, does not. 0 (Chrome picks) is the default for callers that name none.
|
|
191
|
+
*/
|
|
192
|
+
export function localProfileLaunch(profile, userDataDir, { relayPort = null, debugPort = 0, env = process.env } = {}) {
|
|
193
|
+
const proxyServer = proxyNeedsRelay(profile.proxy)
|
|
194
|
+
? (relayPort ? `http://127.0.0.1:${relayPort}` : null)
|
|
195
|
+
: directProxyServer(profile.proxy);
|
|
196
|
+
if (proxyNeedsRelay(profile.proxy) && !proxyServer) throw refusal(500, 'LOCAL_PROFILE_RELAY', 'The profile\'s proxy has a login and its relay is not running: nothing was started (never without the proxy).');
|
|
197
|
+
const args = withOnDeviceModelBlocked([
|
|
198
|
+
'--no-first-run',
|
|
199
|
+
'--no-default-browser-check',
|
|
200
|
+
`--window-size=${profile.window.width},${profile.window.height}`,
|
|
201
|
+
'--disable-backgrounding-occluded-windows',
|
|
202
|
+
'--disable-renderer-backgrounding',
|
|
203
|
+
'--disable-background-timer-throttling',
|
|
204
|
+
]);
|
|
205
|
+
args.push(`--user-data-dir=${userDataDir}`, `--remote-debugging-port=${Number.isInteger(debugPort) && debugPort > 0 && debugPort < 65536 ? debugPort : 0}`);
|
|
206
|
+
if (profile.language) args.push(`--lang=${profile.language}`, `--accept-lang=${acceptLanguagesFor(profile.language)}`);
|
|
207
|
+
if (proxyServer) {
|
|
208
|
+
// Chrome keeps localhost off the proxy by itself, so a local dev server still opens. WebRTC is kept on the proxy:
|
|
209
|
+
// without this its UDP goes out directly and shows the computer's own address.
|
|
210
|
+
args.push(`--proxy-server=${proxyServer}`, '--force-webrtc-ip-handling-policy=disable_non_proxied_udp');
|
|
211
|
+
// Names are resolved by the proxy, never here: without this rule a part of Chrome that looks a name up by itself
|
|
212
|
+
// (the prefetcher, a component) asks this computer's DNS, which shows where the profile really is. A Chrome
|
|
213
|
+
// argument is passed as it is (no shell), so the rule's spaces need no quotes.
|
|
214
|
+
args.push(`--host-resolver-rules=${hostResolverRules(proxyNeedsRelay(profile.proxy) ? '127.0.0.1' : profile.proxy.host)}`);
|
|
215
|
+
}
|
|
216
|
+
const launchEnv = { ...env };
|
|
217
|
+
if (profile.timezone) launchEnv.TZ = profile.timezone; else delete launchEnv.TZ;
|
|
218
|
+
return { args, env: launchEnv, proxyServer };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function readJson(file) {
|
|
222
|
+
try { return JSON.parse(readFileSync(file, 'utf8')); } catch { return null; }
|
|
223
|
+
}
|
|
224
|
+
function writeJsonAtomic(file, data, mode = 0o600) {
|
|
225
|
+
const temp = `${file}.${process.pid}.${randomBytes(3).toString('hex')}.tmp`;
|
|
226
|
+
writeFileSync(temp, JSON.stringify(data, null, 2), { encoding: 'utf8', mode });
|
|
227
|
+
renameSync(temp, file);
|
|
228
|
+
try { chmodSync(file, mode); } catch { /* a file system without modes */ }
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Chrome's own files in the profile folder, set before a start (never while it runs). */
|
|
232
|
+
export function seedLocalProfileFiles(profile, userDataDir) {
|
|
233
|
+
mkdirSync(join(userDataDir, 'Default'), { recursive: true });
|
|
234
|
+
const prefsFile = join(userDataDir, 'Default', 'Preferences');
|
|
235
|
+
const prefs = (existsSync(prefsFile) && readJson(prefsFile)) || {};
|
|
236
|
+
prefs.profile = { ...(prefs.profile || {}), exit_type: 'Normal', exited_cleanly: true, name: profile.name };
|
|
237
|
+
if (profile.language) prefs.intl = { ...(prefs.intl || {}), accept_languages: acceptLanguagesFor(profile.language), selected_languages: acceptLanguagesFor(profile.language) };
|
|
238
|
+
if (profile.proxy.type !== 'none') prefs.webrtc = { ...(prefs.webrtc || {}), ip_handling_policy: 'disable_non_proxied_udp' };
|
|
239
|
+
else if (prefs.webrtc) delete prefs.webrtc.ip_handling_policy;
|
|
240
|
+
writeFileSync(prefsFile, JSON.stringify(prefs));
|
|
241
|
+
const stateFile = join(userDataDir, 'Local State');
|
|
242
|
+
const state = (existsSync(stateFile) && readJson(stateFile)) || {};
|
|
243
|
+
state.profile = { ...(state.profile || {}) };
|
|
244
|
+
state.profile.info_cache = { ...(state.profile.info_cache || {}) };
|
|
245
|
+
state.profile.info_cache.Default = { ...(state.profile.info_cache.Default || {}), name: profile.name, is_using_default_name: false };
|
|
246
|
+
writeFileSync(stateFile, JSON.stringify(state));
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* The pids of the processes whose command line holds `--user-data-dir=<dir>` exactly. `mainOnly`: the browser
|
|
251
|
+
* process alone (the one that is not a helper: no `--type=`), which is the one to ask for a clean end.
|
|
252
|
+
*/
|
|
253
|
+
function defaultFindProcesses(userDataDir, { mainOnly = false } = {}) {
|
|
254
|
+
const needle = `--user-data-dir=${userDataDir}`;
|
|
255
|
+
if (process.platform === 'win32') {
|
|
256
|
+
const script = '$root = $env:SYNABUN_LOCAL_PROFILE_ROOT; Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -and $_.CommandLine.Contains("--user-data-dir=$root") } | ForEach-Object { "$($_.ProcessId) $($_.CommandLine)" }';
|
|
257
|
+
const out = execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', '-'], {
|
|
258
|
+
input: script, encoding: 'utf8', timeout: 10000, windowsHide: true, env: { ...process.env, SYNABUN_LOCAL_PROFILE_ROOT: userDataDir },
|
|
259
|
+
});
|
|
260
|
+
return parseProcessList(out, needle, { mainOnly });
|
|
261
|
+
}
|
|
262
|
+
const ps = ['/bin/ps', '/usr/bin/ps'].find((p) => existsSync(p)) || 'ps';
|
|
263
|
+
const out = execFileSync(ps, ['-Aww', '-o', 'pid=,args='], { encoding: 'utf8', timeout: 5000, maxBuffer: 64 * 1024 * 1024, env: { PATH: '/usr/bin:/bin', LANG: 'C', LC_ALL: 'C' } });
|
|
264
|
+
return parseProcessList(out, needle, { mainOnly });
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* `pid args` lines → the pids whose arguments hold `needle` as a whole argument (never a longer folder name).
|
|
269
|
+
* `mainOnly`: without Chrome's helpers (renderer, GPU, network service: their command line names a `--type=`).
|
|
270
|
+
*/
|
|
271
|
+
export function parseProcessList(text, needle, { mainOnly = false } = {}) {
|
|
272
|
+
const pids = [];
|
|
273
|
+
for (const line of String(text || '').split('\n')) {
|
|
274
|
+
const m = /^\s*(\d+)\s+(.*)$/.exec(line);
|
|
275
|
+
if (!m) continue;
|
|
276
|
+
const args = m[2];
|
|
277
|
+
let at = args.indexOf(needle);
|
|
278
|
+
let hit = false;
|
|
279
|
+
while (at !== -1 && !hit) {
|
|
280
|
+
const next = args[at + needle.length];
|
|
281
|
+
hit = next === undefined || /[\s"']/.test(next);
|
|
282
|
+
at = args.indexOf(needle, at + 1);
|
|
283
|
+
}
|
|
284
|
+
const pid = Number(m[1]);
|
|
285
|
+
if (hit && mainOnly && /(?:^|\s)--type=/.test(args)) continue;
|
|
286
|
+
if (hit && pid > 0 && pid !== process.pid) pids.push(pid);
|
|
287
|
+
}
|
|
288
|
+
return pids;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Asks a process to end by itself; the kill comes after the grace period. Sent to Chrome's browser process alone,
|
|
293
|
+
* which then ends its helpers itself. This is the last resort before the kill, for a Chrome that takes no
|
|
294
|
+
* Browser.close: Chrome treats the signal as the end of the session (settings and session saved), and does not
|
|
295
|
+
* wait for the cookie store's next write (checked live: a cookie set seconds before is lost; Browser.close keeps it).
|
|
296
|
+
*/
|
|
297
|
+
function defaultTerminateProcess(pid) {
|
|
298
|
+
if (process.platform === 'win32') {
|
|
299
|
+
try { execFileSync('taskkill', ['/PID', String(pid)], { stdio: 'ignore', timeout: 5000, windowsHide: true }); } catch { /* gone, or it takes no such request */ }
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
try { process.kill(pid, 'SIGTERM'); } catch { /* gone */ }
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function defaultKillProcess(pid) {
|
|
306
|
+
if (process.platform === 'win32') {
|
|
307
|
+
try { execFileSync('taskkill', ['/F', '/PID', String(pid)], { stdio: 'ignore', timeout: 5000, windowsHide: true }); } catch { /* gone */ }
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
try { process.kill(pid, 'SIGKILL'); } catch { /* gone */ }
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async function defaultProbe(port, timeoutMs = 1500) {
|
|
314
|
+
try {
|
|
315
|
+
const res = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(timeoutMs) });
|
|
316
|
+
if (!res.ok) { try { await res.body?.cancel(); } catch { /* ignore */ } return null; }
|
|
317
|
+
const body = await res.json();
|
|
318
|
+
return body && typeof body === 'object' && (body.webSocketDebuggerUrl || body.Browser) ? body : null;
|
|
319
|
+
} catch { return null; }
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Ask a browser to close itself over its DevTools socket (`Browser.close`), so it writes its cookies first. */
|
|
323
|
+
async function defaultCloseBrowser(wsUrl, timeoutMs = 3000) {
|
|
324
|
+
if (!wsUrl || typeof WebSocket !== 'function') return false;
|
|
325
|
+
return new Promise((done) => {
|
|
326
|
+
let settled = false;
|
|
327
|
+
const finish = (value) => { if (settled) return; settled = true; clearTimeout(timer); try { socket.close(); } catch { /* gone */ } done(value); };
|
|
328
|
+
const timer = setTimeout(() => finish(false), timeoutMs);
|
|
329
|
+
timer.unref?.();
|
|
330
|
+
let socket;
|
|
331
|
+
try { socket = new WebSocket(wsUrl); } catch { clearTimeout(timer); return done(false); }
|
|
332
|
+
socket.addEventListener('open', () => { try { socket.send(JSON.stringify({ id: 1, method: 'Browser.close' })); } catch { finish(false); } });
|
|
333
|
+
socket.addEventListener('message', () => finish(true));
|
|
334
|
+
socket.addEventListener('close', () => finish(true));
|
|
335
|
+
socket.addEventListener('error', () => finish(false));
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
const sleep = (ms) => new Promise((r) => { const t = setTimeout(r, ms); t.unref?.(); });
|
|
340
|
+
|
|
341
|
+
/** Whether nothing listens on a loopback port right now (it is taken and released). */
|
|
342
|
+
function defaultPortFree(port) {
|
|
343
|
+
return new Promise((done) => {
|
|
344
|
+
const server = createServer();
|
|
345
|
+
server.unref();
|
|
346
|
+
server.once('error', () => done(false));
|
|
347
|
+
server.listen({ port, host: '127.0.0.1', exclusive: true }, () => server.close(() => done(true)));
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** The ports of a range, each once, from a random one on (so two starts seldom try the same port first). */
|
|
352
|
+
export function portsOfRange(range = LOCAL_PROFILE_PORT_RANGE, random = Math.random) {
|
|
353
|
+
const size = range.to - range.from + 1;
|
|
354
|
+
const first = Math.floor(random() * size) % size;
|
|
355
|
+
return Array.from({ length: size }, (_, i) => range.from + ((first + i) % size));
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* The local profiles of one data home.
|
|
360
|
+
* @param {object} o
|
|
361
|
+
* @param {string} o.root the folder that holds profiles.json and one folder per profile
|
|
362
|
+
* @param {(o: { chromeBin, chromeArgs, userDataDir, timeoutMs, allowPreferredPortProbe, env }) => Promise<{ httpEndpoint }>} o.launchChrome
|
|
363
|
+
* starts Chrome detached and waits for its DevTools endpoint (server.js _launchChromeAndWaitForCdp)
|
|
364
|
+
* @param {() => string|null} o.resolveChromeBin the Chrome to start (attach mode's resolution)
|
|
365
|
+
* Everything else is for tests: findProcesses, killProcess, probe, closeBrowser, relayFactory, checkProxy, log, now.
|
|
366
|
+
*/
|
|
367
|
+
export function createLocalProfiles({
|
|
368
|
+
root,
|
|
369
|
+
launchChrome = null,
|
|
370
|
+
resolveChromeBin = () => null,
|
|
371
|
+
findProcesses = defaultFindProcesses,
|
|
372
|
+
killProcess = defaultKillProcess,
|
|
373
|
+
probe = defaultProbe,
|
|
374
|
+
closeBrowser = defaultCloseBrowser,
|
|
375
|
+
terminateProcess = undefined,
|
|
376
|
+
findBrowserProcesses = undefined,
|
|
377
|
+
portFree = defaultPortFree,
|
|
378
|
+
portRange = LOCAL_PROFILE_PORT_RANGE,
|
|
379
|
+
random = Math.random,
|
|
380
|
+
probeRetries = 4,
|
|
381
|
+
probeRetryMs = 750,
|
|
382
|
+
exitWaitMs = 3000,
|
|
383
|
+
relayFactory = createProxyRelay,
|
|
384
|
+
checkProxyImpl = checkProxy,
|
|
385
|
+
log = () => {},
|
|
386
|
+
now = Date.now,
|
|
387
|
+
launchTimeoutMs = 30000,
|
|
388
|
+
stopGraceMs = STOP_GRACE_MS,
|
|
389
|
+
} = {}) {
|
|
390
|
+
if (!root || typeof root !== 'string') throw new Error('createLocalProfiles needs its root folder');
|
|
391
|
+
if (!portRange || !Number.isInteger(portRange.from) || !Number.isInteger(portRange.to) || portRange.from < 1 || portRange.to > 65535 || portRange.to < portRange.from) {
|
|
392
|
+
throw new Error('createLocalProfiles needs a port range { from, to }');
|
|
393
|
+
}
|
|
394
|
+
// A graceful end is asked of real processes only: a caller that brings its own kill (a test) and no terminate of
|
|
395
|
+
// its own never has a signal sent to a pid by this module.
|
|
396
|
+
const terminate = terminateProcess !== undefined ? terminateProcess : (killProcess === defaultKillProcess ? defaultTerminateProcess : null);
|
|
397
|
+
// Whom to ask: the browser process alone where the list can tell it from its helpers (the real one can).
|
|
398
|
+
const findMain = findBrowserProcesses !== undefined ? findBrowserProcesses
|
|
399
|
+
: (findProcesses === defaultFindProcesses ? (dir) => defaultFindProcesses(dir, { mainOnly: true }) : findProcesses);
|
|
400
|
+
const inRange = (port) => isLocalProfilePort(port, portRange);
|
|
401
|
+
/** DevTools ports this instance handed to a start that is still coming up (id → port). */
|
|
402
|
+
const pendingPorts = new Map();
|
|
403
|
+
const rootDir = resolve(root);
|
|
404
|
+
const storeFile = join(rootDir, 'profiles.json');
|
|
405
|
+
/** id → the relay that listens for it. */
|
|
406
|
+
const relays = new Map();
|
|
407
|
+
/** id → the start or stop under way (one at a time per profile). */
|
|
408
|
+
const busy = new Map();
|
|
409
|
+
|
|
410
|
+
// ── Store ──
|
|
411
|
+
function readAll() {
|
|
412
|
+
if (!existsSync(storeFile)) return [];
|
|
413
|
+
const data = readJson(storeFile);
|
|
414
|
+
if (data === null) throw refusal(500, 'LOCAL_PROFILES_UNREADABLE', `${storeFile} cannot be read as JSON; nothing was changed. Fix or remove the file.`);
|
|
415
|
+
const rows = Array.isArray(data) ? data : (Array.isArray(data?.profiles) ? data.profiles : []);
|
|
416
|
+
const out = [];
|
|
417
|
+
const seen = new Set();
|
|
418
|
+
for (const row of rows) {
|
|
419
|
+
if (!row || !isLocalProfileId(row.id) || seen.has(row.id)) continue;
|
|
420
|
+
seen.add(row.id);
|
|
421
|
+
try {
|
|
422
|
+
out.push({ id: row.id, createdAt: Number(row.createdAt) || 0, ...normalizeLocalProfile(row) });
|
|
423
|
+
} catch { /* a row that no longer passes the checks is left out, never rewritten by a read */ }
|
|
424
|
+
}
|
|
425
|
+
return out;
|
|
426
|
+
}
|
|
427
|
+
function writeAll(rows) {
|
|
428
|
+
mkdirSync(rootDir, { recursive: true, mode: 0o700 });
|
|
429
|
+
try { chmodSync(rootDir, 0o700); } catch { /* a file system without modes */ }
|
|
430
|
+
writeJsonAtomic(storeFile, rows.map((p) => ({ id: p.id, name: p.name, createdAt: p.createdAt, proxy: p.proxy, language: p.language, timezone: p.timezone, window: p.window, notes: p.notes })));
|
|
431
|
+
}
|
|
432
|
+
/** The stored profile, or a 404. */
|
|
433
|
+
function stored(id) {
|
|
434
|
+
const found = isLocalProfileId(id) ? readAll().find((p) => p.id === id) : null;
|
|
435
|
+
if (!found) throw refusal(404, 'LOCAL_PROFILE_NOT_FOUND', `There is no local profile with id ${String(id).slice(0, 64)}.`);
|
|
436
|
+
return found;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// ── Folder guard ──
|
|
440
|
+
/**
|
|
441
|
+
* The folder of a local profile, or a throw: `dir` must be exactly `<root>/<id>` for a local profile id, and not a
|
|
442
|
+
* link. Called before anything is started in, stopped on or removed from a folder.
|
|
443
|
+
*/
|
|
444
|
+
function assertLocalProfileRoot(dir) {
|
|
445
|
+
const abs = resolve(String(dir || ''));
|
|
446
|
+
const id = abs.slice(rootDir.length + 1);
|
|
447
|
+
if (!abs.startsWith(rootDir + sep) || !isLocalProfileId(id) || abs !== join(rootDir, id)) {
|
|
448
|
+
throw refusal(500, 'LOCAL_PROFILE_ROOT', `Refusing to work on a folder that is not a local profile's: ${dir}`);
|
|
449
|
+
}
|
|
450
|
+
let info = null;
|
|
451
|
+
try { info = lstatSync(abs); } catch { /* not there yet */ }
|
|
452
|
+
if (info && (info.isSymbolicLink() || !info.isDirectory())) throw refusal(500, 'LOCAL_PROFILE_ROOT', `Refusing to work on ${dir}: it is not a plain folder`);
|
|
453
|
+
if (info) {
|
|
454
|
+
let real = abs;
|
|
455
|
+
let realRoot = rootDir;
|
|
456
|
+
try { real = realpathSync(abs); realRoot = realpathSync(rootDir); } catch { /* compared as written */ }
|
|
457
|
+
if (real !== join(realRoot, id)) throw refusal(500, 'LOCAL_PROFILE_ROOT', `Refusing to work on ${dir}: it resolves outside the local profiles folder`);
|
|
458
|
+
}
|
|
459
|
+
return abs;
|
|
460
|
+
}
|
|
461
|
+
const folderOf = (id) => assertLocalProfileRoot(join(rootDir, id));
|
|
462
|
+
|
|
463
|
+
// ── What runs ──
|
|
464
|
+
/**
|
|
465
|
+
* The live DevTools endpoint of a profile folder: { port, wsUrl } or null. Where it is read from: the record of
|
|
466
|
+
* SynaBun's own start (LAUNCH_FILE: the port, and the browser's id as /json/version said it then), else Chrome's
|
|
467
|
+
* DevToolsActivePort (which Chrome writes only when it picked the port itself). The port must answer as that very
|
|
468
|
+
* browser (its id), so a port another program took since is never adopted as this profile.
|
|
469
|
+
*/
|
|
470
|
+
async function liveEndpoint(dir) {
|
|
471
|
+
const candidates = [];
|
|
472
|
+
const launched = readJson(join(dir, LAUNCH_FILE));
|
|
473
|
+
// Our own record counts only with the browser's id: a port alone proves nothing after a restart.
|
|
474
|
+
if (launched && typeof launched.browser === 'string' && launched.browser) candidates.push({ port: Number(launched.debugPort), browser: launched.browser });
|
|
475
|
+
try {
|
|
476
|
+
const lines = readFileSync(join(dir, 'DevToolsActivePort'), 'utf8').split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
|
|
477
|
+
candidates.push({ port: Number.parseInt(lines[0], 10), browser: lines[1] || null });
|
|
478
|
+
} catch { /* no such file */ }
|
|
479
|
+
for (const { port, browser } of candidates) {
|
|
480
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) continue;
|
|
481
|
+
const version = await probe(port);
|
|
482
|
+
if (!version) continue;
|
|
483
|
+
const wsUrl = typeof version.webSocketDebuggerUrl === 'string' ? version.webSocketDebuggerUrl : null;
|
|
484
|
+
if (browser && (!wsUrl || !wsUrl.endsWith(browser))) continue;
|
|
485
|
+
return { port, wsUrl };
|
|
486
|
+
}
|
|
487
|
+
return null;
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* The pids that run on a profile folder. Throws LOCAL_PROFILE_BUSY when the processes could not be listed (ps timed
|
|
491
|
+
* out, PowerShell failed): "could not look" is never "none", so nothing is cleared, started or removed on a folder
|
|
492
|
+
* a Chrome may still be using.
|
|
493
|
+
*/
|
|
494
|
+
function processesOf(dir) {
|
|
495
|
+
const folder = assertLocalProfileRoot(dir);
|
|
496
|
+
let pids;
|
|
497
|
+
try { pids = findProcesses(folder); } catch (err) { pids = err instanceof Error ? err : new Error(String(err)); }
|
|
498
|
+
if (!Array.isArray(pids)) {
|
|
499
|
+
const why = pids instanceof Error ? pids.message : 'the process list gave no answer';
|
|
500
|
+
log(`processes of ${dir} could not be listed: ${why}`);
|
|
501
|
+
throw refusal(500, 'LOCAL_PROFILE_BUSY', `SynaBun could not check whether a browser is still running on this local profile's folder (${String(why).slice(0, 200)}). Nothing was started, stopped or deleted: try again.`);
|
|
502
|
+
}
|
|
503
|
+
return pids;
|
|
504
|
+
}
|
|
505
|
+
/** Kills what runs on the folder and waits for it to be gone. → true when nothing runs there any more. */
|
|
506
|
+
async function killAndWait(dir) {
|
|
507
|
+
let pids = processesOf(dir);
|
|
508
|
+
if (!pids.length) return true;
|
|
509
|
+
for (const pid of pids) killProcess(pid);
|
|
510
|
+
const deadline = now() + exitWaitMs;
|
|
511
|
+
for (;;) {
|
|
512
|
+
pids = processesOf(dir);
|
|
513
|
+
if (!pids.length) return true;
|
|
514
|
+
if (now() >= deadline) return false;
|
|
515
|
+
await sleep(Math.min(100, Math.max(1, exitWaitMs)));
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
function clearRunFiles(dir) {
|
|
519
|
+
let names = [];
|
|
520
|
+
try { names = readdirSync(dir); } catch { return; }
|
|
521
|
+
for (const name of names) {
|
|
522
|
+
if (name === 'DevToolsActivePort' || name === LAUNCH_FILE || name.startsWith('Singleton')) {
|
|
523
|
+
try { unlinkSync(join(dir, name)); } catch { /* gone */ }
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// ── Relay ──
|
|
529
|
+
const relayFile = (dir) => join(dir, RELAY_FILE);
|
|
530
|
+
async function stopRelay(id, { forget = false } = {}) {
|
|
531
|
+
const relay = relays.get(id);
|
|
532
|
+
relays.delete(id);
|
|
533
|
+
if (relay) { try { await relay.close(); } catch { /* closed */ } }
|
|
534
|
+
if (forget) { try { unlinkSync(relayFile(join(rootDir, id))); } catch { /* none */ } }
|
|
535
|
+
}
|
|
536
|
+
/** The ports of the range other profiles of this instance hold or are being started on. */
|
|
537
|
+
function portsInUse() {
|
|
538
|
+
const used = new Set([...pendingPorts.values()]);
|
|
539
|
+
for (const relay of relays.values()) if (relay.port) used.add(relay.port);
|
|
540
|
+
return used;
|
|
541
|
+
}
|
|
542
|
+
/** A free DevTools port inside the range for a start of `id`. Throws when the whole range is taken. */
|
|
543
|
+
async function pickDebugPort(id, skip = new Set()) {
|
|
544
|
+
const used = portsInUse();
|
|
545
|
+
for (const port of portsOfRange(portRange, random)) {
|
|
546
|
+
if (used.has(port) || skip.has(port)) continue;
|
|
547
|
+
if (await portFree(port)) { pendingPorts.set(id, port); return port; }
|
|
548
|
+
}
|
|
549
|
+
throw refusal(500, 'LOCAL_PROFILE_PORTS', `No free port is left in the ports SynaBun keeps for local profiles (${portRange.from}-${portRange.to}): stop a local profile, or close what else listens there.`);
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* The relay of a profile, listening: on `port` (its saved one, which must be inside the range) or, for 0, on a free
|
|
553
|
+
* port of the range (the next one is tried when a port is taken). → the port. Throws when it cannot.
|
|
554
|
+
*/
|
|
555
|
+
async function openRelay(profile, dir, port = 0) {
|
|
556
|
+
await stopRelay(profile.id);
|
|
557
|
+
if (port && !inRange(port)) throw Object.assign(new Error(`port ${port} is outside the ports kept for local profiles (${portRange.from}-${portRange.to})`), { code: 'LOCAL_PROFILE_PORT_RANGE' });
|
|
558
|
+
const relay = relayFactory({ upstream: { ...profile.proxy }, log: (line) => log(`${profile.id} ${line}`) });
|
|
559
|
+
let listening = null;
|
|
560
|
+
if (port) listening = await relay.listen(port);
|
|
561
|
+
else {
|
|
562
|
+
const used = portsInUse();
|
|
563
|
+
let failure = null;
|
|
564
|
+
for (const candidate of portsOfRange(portRange, random)) {
|
|
565
|
+
if (used.has(candidate)) continue;
|
|
566
|
+
try { listening = await relay.listen(candidate); break; } catch (err) {
|
|
567
|
+
failure = err;
|
|
568
|
+
if (err?.code !== 'EADDRINUSE' && err?.code !== 'EACCES') throw err;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
if (!listening) throw refusal(500, 'LOCAL_PROFILE_PORTS', `No free port is left in the ports SynaBun keeps for local profiles (${portRange.from}-${portRange.to}) for the proxy relay${failure?.code ? ` (${failure.code})` : ''}.`);
|
|
572
|
+
}
|
|
573
|
+
if (!inRange(listening)) {
|
|
574
|
+
try { await relay.close(); } catch { /* closed */ }
|
|
575
|
+
throw refusal(500, 'LOCAL_PROFILE_PORTS', `The proxy relay opened on port ${listening}, outside the ports kept for local profiles (${portRange.from}-${portRange.to}); it was closed.`);
|
|
576
|
+
}
|
|
577
|
+
relays.set(profile.id, relay);
|
|
578
|
+
writeJsonAtomic(relayFile(dir), { port: listening, at: now() });
|
|
579
|
+
return listening;
|
|
580
|
+
}
|
|
581
|
+
const savedRelayPort = (dir) => {
|
|
582
|
+
const port = Number(readJson(relayFile(dir))?.port);
|
|
583
|
+
return Number.isInteger(port) && port > 0 && port < 65536 ? port : null;
|
|
584
|
+
};
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* Why a running profile has to be started again before it is used, or null:
|
|
588
|
+
* 'proxy' — it runs with another proxy than the saved one (or what it was started with is not known), so its
|
|
589
|
+
* traffic would not leave where the owner now says;
|
|
590
|
+
* 'relay' — its proxy has a login and the relay is not listening;
|
|
591
|
+
* 'ports' — its DevTools port is outside the ports kept for local profiles (a guarded worker could reach it);
|
|
592
|
+
* 'settings' — language, timezone or window size changed (harmless to a run; shown as "restart to apply").
|
|
593
|
+
*/
|
|
594
|
+
function restartReason(profile, dir, live = null) {
|
|
595
|
+
const launched = readJson(join(dir, LAUNCH_FILE));
|
|
596
|
+
const signature = typeof launched?.signature === 'string' ? launched.signature : null;
|
|
597
|
+
const wanted = launchSignature(profile);
|
|
598
|
+
if (!signature || proxyPartOf(signature) !== proxyPartOf(wanted)) return 'proxy';
|
|
599
|
+
if (proxyNeedsRelay(profile.proxy) && !relays.get(profile.id)?.port) return 'relay';
|
|
600
|
+
const port = live ? live.port : Number(launched?.debugPort);
|
|
601
|
+
if (Number.isInteger(port) && port > 0 && !inRange(port)) return 'ports';
|
|
602
|
+
if (signature !== wanted) return 'settings';
|
|
603
|
+
return null;
|
|
604
|
+
}
|
|
605
|
+
/** Whether a running profile runs with other settings than the saved ones, or without the relay it needs. */
|
|
606
|
+
function restartNeededFor(profile, dir) {
|
|
607
|
+
return restartReason(profile, dir) !== null;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/** One start or stop at a time per profile; the second caller of the same kind gets the first one's answer. */
|
|
611
|
+
function serialized(id, kind, work) {
|
|
612
|
+
const current = busy.get(id);
|
|
613
|
+
if (current && current.kind === kind) return current.promise;
|
|
614
|
+
const run = async () => {
|
|
615
|
+
if (current) { try { await current.promise; } catch { /* its own caller was told */ } }
|
|
616
|
+
return work();
|
|
617
|
+
};
|
|
618
|
+
const promise = run().finally(() => { if (busy.get(id)?.promise === promise) busy.delete(id); });
|
|
619
|
+
busy.set(id, { kind, promise });
|
|
620
|
+
return promise;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
const RESTART_WHY = {
|
|
624
|
+
proxy: 'its proxy settings changed since it was started (or what it was started with is not known), so it would not go out through the proxy that is saved now',
|
|
625
|
+
relay: 'the relay of its proxy is not running',
|
|
626
|
+
ports: 'it listens on a port outside the ports SynaBun keeps for local profiles',
|
|
627
|
+
};
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* @param {string} id
|
|
631
|
+
* @param {{ owner?: boolean }} [o] owner: the owner's own Start (Settings). Only the owner's start may end a
|
|
632
|
+
* running Chrome (to start it again with the saved settings, or because it no longer answers); every other caller
|
|
633
|
+
* (an automation's start, a browser session opening in the profile) is refused by name and gets no browser.
|
|
634
|
+
*/
|
|
635
|
+
async function startNow(id, { owner = false } = {}) {
|
|
636
|
+
const profile = stored(id);
|
|
637
|
+
const dir = folderOf(id);
|
|
638
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
639
|
+
let live = await liveEndpoint(dir);
|
|
640
|
+
if (!live) {
|
|
641
|
+
// No answer on its DevTools port. That is "not running" only when no process runs on the folder: a busy Chrome
|
|
642
|
+
// can miss one probe, so it is asked again a few times before anything else is decided.
|
|
643
|
+
let pids = processesOf(dir);
|
|
644
|
+
for (let attempt = 0; attempt < probeRetries && pids.length && !live; attempt += 1) {
|
|
645
|
+
await sleep(probeRetryMs);
|
|
646
|
+
live = await liveEndpoint(dir);
|
|
647
|
+
if (!live) pids = processesOf(dir);
|
|
648
|
+
}
|
|
649
|
+
if (!live && pids.length) {
|
|
650
|
+
if (!owner) {
|
|
651
|
+
throw refusal(409, 'LOCAL_PROFILE_BUSY', `Local profile "${profile.name}" (${id}) has a browser running that does not answer on its DevTools port. Nothing was started or stopped, and no other profile or browser was used in its place. The owner can stop and start it in SynaBun → Settings → Connected tools → MoreLogin.`);
|
|
652
|
+
}
|
|
653
|
+
log(`${id} "${profile.name}": a browser runs on its folder without answering; the owner's start stops it first`);
|
|
654
|
+
await stopNow(id);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
if (live) {
|
|
658
|
+
// Already running (it outlives a SynaBun restart, as a MoreLogin profile does): adopted as it is, unless it has
|
|
659
|
+
// to be started again first (restartReason). A relay that is only missing is put back on its saved port.
|
|
660
|
+
let reason = restartReason(profile, dir, live);
|
|
661
|
+
if (reason === 'relay') {
|
|
662
|
+
const port = savedRelayPort(dir);
|
|
663
|
+
try { if (!port) throw new Error('no saved port'); await openRelay(profile, dir, port); reason = restartReason(profile, dir, live); }
|
|
664
|
+
catch (err) { log(`${id}: its relay could not be reopened (${err?.code || err?.message || err})`); }
|
|
665
|
+
}
|
|
666
|
+
if (!reason || (reason === 'settings' && !owner)) return { debugPort: live.port, kernel: 'chromium', webdriver: null, reused: true };
|
|
667
|
+
if (!owner) {
|
|
668
|
+
throw refusal(409, 'LOCAL_PROFILE_RESTART_NEEDED', `Local profile "${profile.name}" (${id}) is running, but ${RESTART_WHY[reason]}. It was not handed out, and no other profile or browser was used in its place. The owner restarts it in SynaBun → Settings → Connected tools → MoreLogin (Stop, then Start); starting it again closes the tabs open in it.`, { reason });
|
|
669
|
+
}
|
|
670
|
+
log(`${id} "${profile.name}": started again by the owner (${reason})`);
|
|
671
|
+
await stopNow(id);
|
|
672
|
+
}
|
|
673
|
+
if (typeof launchChrome !== 'function') throw refusal(500, 'LOCAL_PROFILE_LAUNCHER', 'Local profiles cannot be started here: no launcher was given.');
|
|
674
|
+
const chromeBin = resolveChromeBin();
|
|
675
|
+
if (!chromeBin || !existsSync(chromeBin)) {
|
|
676
|
+
throw refusal(500, 'LOCAL_PROFILE_NO_CHROME', 'No Chrome, Edge or Chromium was found to start the local profile with. Install Google Chrome, or set the browser path in Settings → Browser.');
|
|
677
|
+
}
|
|
678
|
+
// SynaBun's own profiles run on the Chrome of this computer, never on MoreLogin's browser.
|
|
679
|
+
if (/morelogin/i.test(chromeBin)) throw refusal(500, 'LOCAL_PROFILE_NO_CHROME', `The browser path in Settings → Browser points into MoreLogin (${chromeBin}). A local profile runs on Chrome, Edge or Chromium: choose one of those.`);
|
|
680
|
+
// Nothing runs on the folder by now (it was never running, or stopNow saw it gone). Asked once more, and never
|
|
681
|
+
// assumed: Chrome's lock files are cleared and its preferences written only on a folder no process uses.
|
|
682
|
+
if (processesOf(dir).length) throw refusal(409, 'LOCAL_PROFILE_BUSY', `Local profile "${profile.name}" (${id}) still has a browser running on its folder; nothing was started.`);
|
|
683
|
+
clearRunFiles(dir);
|
|
684
|
+
seedLocalProfileFiles(profile, dir);
|
|
685
|
+
let relayPort = null;
|
|
686
|
+
if (proxyNeedsRelay(profile.proxy)) relayPort = await openRelay(profile, dir, 0);
|
|
687
|
+
else await stopRelay(id, { forget: true });
|
|
688
|
+
// A DevTools port of the profile's own, free right now, inside the ports kept for local profiles. Should another
|
|
689
|
+
// program take it before Chrome does, the start fails and is tried again on another port of the range.
|
|
690
|
+
let ready = null;
|
|
691
|
+
let failure = null;
|
|
692
|
+
const tried = new Set();
|
|
693
|
+
try {
|
|
694
|
+
for (let attempt = 0; attempt < 3 && !ready; attempt += 1) {
|
|
695
|
+
let debugPort;
|
|
696
|
+
try { debugPort = await pickDebugPort(id, tried); } catch (err) { failure = err; break; }
|
|
697
|
+
tried.add(debugPort);
|
|
698
|
+
const { args, env } = localProfileLaunch(profile, dir, { relayPort, debugPort });
|
|
699
|
+
try {
|
|
700
|
+
ready = await launchChrome({ chromeBin, chromeArgs: args, userDataDir: dir, timeoutMs: launchTimeoutMs, allowPreferredPortProbe: false, env });
|
|
701
|
+
} catch (err) {
|
|
702
|
+
failure = err;
|
|
703
|
+
// What the failed start left behind is ended, and its lock files cleared only once it is gone.
|
|
704
|
+
let gone = false;
|
|
705
|
+
try { gone = await killAndWait(dir); } catch { gone = false; }
|
|
706
|
+
if (!gone) break;
|
|
707
|
+
clearRunFiles(dir);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
} finally { pendingPorts.delete(id); }
|
|
711
|
+
if (!ready) {
|
|
712
|
+
await stopRelay(id);
|
|
713
|
+
if (failure?.code === 'LOCAL_PROFILE_PORTS' || failure?.code === 'LOCAL_PROFILE_BUSY') throw failure;
|
|
714
|
+
throw refusal(500, 'LOCAL_PROFILE_START', `Local profile "${profile.name}" did not start: ${failure?.message || failure}`);
|
|
715
|
+
}
|
|
716
|
+
let port = null;
|
|
717
|
+
try { port = Number(new URL(ready.httpEndpoint).port); } catch { port = null; }
|
|
718
|
+
if (!port) throw refusal(500, 'LOCAL_PROFILE_START', `Local profile "${profile.name}" started but named no DevTools port`);
|
|
719
|
+
if (!inRange(port)) {
|
|
720
|
+
// Never handed out: a DevTools port outside the range is one a guarded worker's sandbox does not deny.
|
|
721
|
+
try { if (await killAndWait(dir)) clearRunFiles(dir); } catch { /* reported below */ }
|
|
722
|
+
await stopRelay(id);
|
|
723
|
+
throw refusal(500, 'LOCAL_PROFILE_START', `Local profile "${profile.name}" came up on DevTools port ${port}, outside the ports SynaBun keeps for local profiles (${portRange.from}-${portRange.to}); it was stopped.`);
|
|
724
|
+
}
|
|
725
|
+
// The start's record: what it was started with (a later change means "restart needed"), its DevTools port and
|
|
726
|
+
// the browser's own id there, by which a later start or a new SynaBun knows this Chrome again.
|
|
727
|
+
let browserId = null;
|
|
728
|
+
try { browserId = new URL((await probe(port))?.webSocketDebuggerUrl || ready.wsEndpoint || '').pathname || null; } catch { browserId = null; }
|
|
729
|
+
writeJsonAtomic(join(dir, LAUNCH_FILE), { signature: launchSignature(profile), at: now(), debugPort: port, browser: browserId });
|
|
730
|
+
log(`${id} "${profile.name}" started on DevTools port ${port}${relayPort ? ` (proxy relay on ${relayPort})` : ''}`);
|
|
731
|
+
return { debugPort: port, kernel: 'chromium', webdriver: null, reused: false };
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
async function stopNow(id) {
|
|
735
|
+
const dir = folderOf(id);
|
|
736
|
+
const live = existsSync(dir) ? await liveEndpoint(dir) : null;
|
|
737
|
+
let asked = false;
|
|
738
|
+
if (live?.wsUrl) asked = await closeBrowser(live.wsUrl);
|
|
739
|
+
if (existsSync(dir)) {
|
|
740
|
+
// A Chrome that missed the probe (busy) may still take Browser.close on the socket of its own start record:
|
|
741
|
+
// the address holds the browser's id, so nothing but this very browser answers there. Browser.close is the
|
|
742
|
+
// one way Chrome writes the cookies of the last seconds before it ends.
|
|
743
|
+
if (!asked && processesOf(dir).length) {
|
|
744
|
+
const launched = readJson(join(dir, LAUNCH_FILE));
|
|
745
|
+
const port = Number(launched?.debugPort);
|
|
746
|
+
if (Number.isInteger(port) && port > 0 && port < 65536 && typeof launched?.browser === 'string' && launched.browser.startsWith('/devtools/browser/')) {
|
|
747
|
+
try { asked = await closeBrowser(`ws://127.0.0.1:${port}${launched.browser}`); } catch { asked = false; }
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
// One that cannot be asked over DevTools at all is asked to end as a process (it saves its settings and its
|
|
751
|
+
// session; cookies of the last half minute may be lost, as with any Chrome that is ended from outside); what is
|
|
752
|
+
// left after the grace period is killed.
|
|
753
|
+
if (!asked && terminate && processesOf(dir).length) {
|
|
754
|
+
let mains = [];
|
|
755
|
+
try { mains = findMain(assertLocalProfileRoot(dir)); } catch { mains = []; }
|
|
756
|
+
for (const pid of Array.isArray(mains) ? mains : []) terminate(pid);
|
|
757
|
+
asked = Array.isArray(mains) && mains.length > 0;
|
|
758
|
+
}
|
|
759
|
+
const deadline = now() + (asked ? stopGraceMs : 0);
|
|
760
|
+
while (processesOf(dir).length && now() < deadline) await sleep(Math.min(200, Math.max(1, stopGraceMs)));
|
|
761
|
+
// The lock files and the launch record go only once nothing runs on the folder any more.
|
|
762
|
+
if (!(await killAndWait(dir))) {
|
|
763
|
+
throw refusal(409, 'LOCAL_PROFILE_BUSY', `The browser of this local profile (${id}) is still running and could not be stopped; its folder was left as it is.`);
|
|
764
|
+
}
|
|
765
|
+
clearRunFiles(dir);
|
|
766
|
+
try { unlinkSync(join(dir, LAUNCH_FILE)); } catch { /* none */ }
|
|
767
|
+
}
|
|
768
|
+
await stopRelay(id, { forget: true });
|
|
769
|
+
return { stopped: !!live || asked };
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
const publicRow = (profile, running, dir) => ({
|
|
773
|
+
id: profile.id,
|
|
774
|
+
name: profile.name,
|
|
775
|
+
status: running ? 'running' : 'stopped',
|
|
776
|
+
groupId: null,
|
|
777
|
+
proxyId: null,
|
|
778
|
+
proxy: profile.proxy.type === 'none' ? null : { type: profile.proxy.type, host: profile.proxy.host, port: String(profile.proxy.port), country: null },
|
|
779
|
+
kind: 'local',
|
|
780
|
+
browser: 'chromium',
|
|
781
|
+
hasPassword: !!profile.proxy.password,
|
|
782
|
+
...(running && restartNeededFor(profile, dir) ? { restartNeeded: true } : {}),
|
|
783
|
+
});
|
|
784
|
+
|
|
785
|
+
return {
|
|
786
|
+
root: rootDir,
|
|
787
|
+
isLocalProfileId,
|
|
788
|
+
assertLocalProfileRoot,
|
|
789
|
+
|
|
790
|
+
/** How many local profiles there are (no process is asked). */
|
|
791
|
+
count() { try { return readAll().length; } catch { return 0; } },
|
|
792
|
+
/** A profile's name, or null (no process is asked). */
|
|
793
|
+
nameOf(id) { try { return isLocalProfileId(id) ? (readAll().find((p) => p.id === id)?.name || null) : null; } catch { return null; } },
|
|
794
|
+
/** What a session in the profile is told to emulate: { timezone, language } ('' = not set), or null. */
|
|
795
|
+
settingsOf(id) { try { const p = isLocalProfileId(id) ? readAll().find((row) => row.id === id) : null; return p ? { name: p.name, timezone: p.timezone, language: p.language } : null; } catch { return null; } },
|
|
796
|
+
|
|
797
|
+
/** Rows in the shape of MoreLogin's list, plus kind 'local'. Never the proxy's login. */
|
|
798
|
+
async listLocalProfiles() {
|
|
799
|
+
const rows = readAll();
|
|
800
|
+
return Promise.all(rows.map(async (profile) => {
|
|
801
|
+
const dir = join(rootDir, profile.id);
|
|
802
|
+
const live = existsSync(dir) ? await liveEndpoint(dir) : null;
|
|
803
|
+
return publicRow(profile, !!live, dir);
|
|
804
|
+
}));
|
|
805
|
+
},
|
|
806
|
+
|
|
807
|
+
/** The rows of the owner's editor: the list's, plus what the form shows. The password is never returned. */
|
|
808
|
+
async localProfileDetails() {
|
|
809
|
+
const rows = readAll();
|
|
810
|
+
return Promise.all(rows.map(async (profile) => {
|
|
811
|
+
const dir = join(rootDir, profile.id);
|
|
812
|
+
const live = existsSync(dir) ? await liveEndpoint(dir) : null;
|
|
813
|
+
return {
|
|
814
|
+
...publicRow(profile, !!live, dir),
|
|
815
|
+
createdAt: profile.createdAt,
|
|
816
|
+
proxyUsername: profile.proxy.username || '',
|
|
817
|
+
language: profile.language,
|
|
818
|
+
timezone: profile.timezone,
|
|
819
|
+
window: { ...profile.window },
|
|
820
|
+
notes: profile.notes,
|
|
821
|
+
relay: proxyNeedsRelay(profile.proxy) ? (relays.get(profile.id)?.port ? 'running' : (live ? 'missing' : 'stopped')) : null,
|
|
822
|
+
};
|
|
823
|
+
}));
|
|
824
|
+
},
|
|
825
|
+
|
|
826
|
+
async createLocalProfile(input) {
|
|
827
|
+
const rows = readAll();
|
|
828
|
+
if (rows.length >= LOCAL_PROFILES_MAX) throw refusal(409, 'LOCAL_PROFILES_FULL', `There are ${LOCAL_PROFILES_MAX} local profiles, the most SynaBun keeps: delete one first.`);
|
|
829
|
+
const settings = normalizeLocalProfile(input);
|
|
830
|
+
let id;
|
|
831
|
+
do { id = `lp-${randomBytes(6).toString('hex')}`; } while (rows.some((p) => p.id === id));
|
|
832
|
+
const profile = { id, createdAt: now(), ...settings };
|
|
833
|
+
const dir = folderOf(id);
|
|
834
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
835
|
+
writeAll([...rows, profile]);
|
|
836
|
+
return publicRow(profile, false, dir);
|
|
837
|
+
},
|
|
838
|
+
|
|
839
|
+
/** Saves new settings. They hold from the profile's next start: a running one answers `restartNeeded`. */
|
|
840
|
+
async updateLocalProfile(id, input) {
|
|
841
|
+
const rows = readAll();
|
|
842
|
+
const at = rows.findIndex((p) => p.id === id);
|
|
843
|
+
if (at === -1) throw refusal(404, 'LOCAL_PROFILE_NOT_FOUND', `There is no local profile with id ${String(id).slice(0, 64)}.`);
|
|
844
|
+
const profile = { ...rows[at], ...normalizeLocalProfile(input, rows[at]) };
|
|
845
|
+
rows[at] = profile;
|
|
846
|
+
writeAll(rows);
|
|
847
|
+
const dir = join(rootDir, id);
|
|
848
|
+
const live = existsSync(dir) ? await liveEndpoint(dir) : null;
|
|
849
|
+
return publicRow(profile, !!live, dir);
|
|
850
|
+
},
|
|
851
|
+
|
|
852
|
+
/** Stops the profile, then removes its folder and its entry. */
|
|
853
|
+
async deleteLocalProfile(id) {
|
|
854
|
+
const profile = stored(id);
|
|
855
|
+
const dir = folderOf(id);
|
|
856
|
+
await serialized(id, 'stop', () => stopNow(id));
|
|
857
|
+
if (processesOf(dir).length) throw refusal(409, 'LOCAL_PROFILE_BUSY', `Local profile "${profile.name}" is still running and could not be stopped; nothing was deleted.`);
|
|
858
|
+
rmSync(assertLocalProfileRoot(dir), { recursive: true, force: true, maxRetries: 3, retryDelay: 200 });
|
|
859
|
+
writeAll(readAll().filter((p) => p.id !== id));
|
|
860
|
+
return { id, name: profile.name };
|
|
861
|
+
},
|
|
862
|
+
|
|
863
|
+
/**
|
|
864
|
+
* → { debugPort, kernel: 'chromium', webdriver: null }. A profile that is running is reused, unless it has to be
|
|
865
|
+
* started again first: then the owner's start does that, and every other caller gets LOCAL_PROFILE_RESTART_NEEDED
|
|
866
|
+
* (or LOCAL_PROFILE_BUSY for a Chrome that does not answer) and no browser.
|
|
867
|
+
*/
|
|
868
|
+
async startLocalProfile(id, { owner = false } = {}) {
|
|
869
|
+
stored(id);
|
|
870
|
+
// The owner's start and anybody else's are not the same work (only the owner's may end a running Chrome), so
|
|
871
|
+
// one never rides on the other's answer.
|
|
872
|
+
return serialized(id, owner ? 'start-owner' : 'start', () => startNow(id, { owner: owner === true }));
|
|
873
|
+
},
|
|
874
|
+
|
|
875
|
+
/** Asks the profile's Chrome to close, stops what is left on its folder after the grace period, and its relay. */
|
|
876
|
+
async stopLocalProfile(id) {
|
|
877
|
+
stored(id);
|
|
878
|
+
return serialized(id, 'stop', () => stopNow(id));
|
|
879
|
+
},
|
|
880
|
+
|
|
881
|
+
/** → { status: 'running' | 'stopped', debugPort } */
|
|
882
|
+
async localProfileStatus(id) {
|
|
883
|
+
stored(id);
|
|
884
|
+
const dir = join(rootDir, id);
|
|
885
|
+
const live = existsSync(dir) ? await liveEndpoint(dir) : null;
|
|
886
|
+
return { status: live ? 'running' : 'stopped', debugPort: live ? live.port : null, localStatus: live ? 'running' : 'stopped' };
|
|
887
|
+
},
|
|
888
|
+
|
|
889
|
+
/** The exit address through a profile's proxy (or through `override`, the editor's unsaved values). */
|
|
890
|
+
async checkLocalProfileProxy(id, override = null) {
|
|
891
|
+
const profile = stored(id);
|
|
892
|
+
let proxy = profile.proxy;
|
|
893
|
+
if (override && typeof override === 'object') proxy = normalizeProxy(override, profile.proxy);
|
|
894
|
+
return checkProxyImpl(proxy);
|
|
895
|
+
},
|
|
896
|
+
|
|
897
|
+
/**
|
|
898
|
+
* After a SynaBun start: the relay of every profile whose Chrome is still running is put back on its saved port.
|
|
899
|
+
* → [{ id, name, debugPort, relay: 'reopened' | 'restart-needed' | null }] for the profiles found running.
|
|
900
|
+
*/
|
|
901
|
+
async adoptRunning() {
|
|
902
|
+
const out = [];
|
|
903
|
+
let rows = [];
|
|
904
|
+
try { rows = readAll(); } catch (err) { log(`local profiles not read at start: ${err?.message || err}`); return out; }
|
|
905
|
+
for (const profile of rows) {
|
|
906
|
+
const dir = join(rootDir, profile.id);
|
|
907
|
+
let live = null;
|
|
908
|
+
try { live = existsSync(dir) ? await liveEndpoint(assertLocalProfileRoot(dir)) : null; } catch { live = null; }
|
|
909
|
+
if (!live) continue;
|
|
910
|
+
let relay = null;
|
|
911
|
+
if (proxyNeedsRelay(profile.proxy) && !relays.get(profile.id)?.port) {
|
|
912
|
+
const port = savedRelayPort(dir);
|
|
913
|
+
try { if (!port) throw new Error('no saved port'); await openRelay(profile, dir, port); relay = 'reopened'; }
|
|
914
|
+
catch (err) { relay = 'restart-needed'; log(`${profile.id} "${profile.name}": its proxy relay could not be reopened on port ${port || '?'} (${err?.code || err?.message || err}); pages fail there until the profile is started again`); }
|
|
915
|
+
}
|
|
916
|
+
out.push({ id: profile.id, name: profile.name, debugPort: live.port, relay });
|
|
917
|
+
}
|
|
918
|
+
return out;
|
|
919
|
+
},
|
|
920
|
+
|
|
921
|
+
/** The ports kept for the relays and the DevTools ports: { from, to }. */
|
|
922
|
+
portRange: Object.freeze({ from: portRange.from, to: portRange.to }),
|
|
923
|
+
/** The ports the relays listen on now (all inside portRange, which a guarded worker's sandbox denies whole). */
|
|
924
|
+
relayPorts() { return [...relays.values()].map((relay) => relay.port).filter((port) => port > 0); },
|
|
925
|
+
|
|
926
|
+
/** Stops every relay (the server is going down, or a test is over). The profiles' Chromes are left as they are. */
|
|
927
|
+
async closeRelays() { for (const id of [...relays.keys()]) await stopRelay(id); },
|
|
928
|
+
};
|
|
929
|
+
}
|