@lsamien/yaoyao 0.4.75
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/LICENSE +202 -0
- package/NOTICE +6 -0
- package/README.md +103 -0
- package/THIRD_PARTY_NOTICES.md +16 -0
- package/bin/desktop-service-sync.mjs +43 -0
- package/bin/hermes-yaoyao-updater.mjs +315 -0
- package/bin/hermes-yaoyao.mjs +246 -0
- package/bin/lib/data-home.d.mts +4 -0
- package/bin/lib/data-home.mjs +24 -0
- package/bin/lib/data-migration.d.mts +2 -0
- package/bin/lib/data-migration.mjs +107 -0
- package/bin/lib/desktop-activation.d.mts +4 -0
- package/bin/lib/desktop-activation.mjs +18 -0
- package/bin/lib/managed-data-migration.mjs +45 -0
- package/bin/lib/release-source.d.mts +2 -0
- package/bin/lib/release-source.mjs +23 -0
- package/bin/lib/runtime-release.mjs +78 -0
- package/bin/lib/service-data.mjs +57 -0
- package/bin/lib/service-update.mjs +372 -0
- package/bin/migrate-data-home.mjs +20 -0
- package/build-info.json +657 -0
- package/desktop/main.mjs +679 -0
- package/dist/assets/AboutDialog-BvuJp8Pe.js +2 -0
- package/dist/assets/AboutDialog-BvuJp8Pe.js.map +1 -0
- package/dist/assets/AboutDialog-DC5YWX39.css +1 -0
- package/dist/assets/BotAutomationsView-Ddgs5Hes.js +2 -0
- package/dist/assets/BotAutomationsView-Ddgs5Hes.js.map +1 -0
- package/dist/assets/BotAutomationsView-DeJ-e3y5.css +1 -0
- package/dist/assets/BotPluginsDialog-Db5dTqvg.css +1 -0
- package/dist/assets/BotPluginsDialog-xPqUSyHS.js +2 -0
- package/dist/assets/BotPluginsDialog-xPqUSyHS.js.map +1 -0
- package/dist/assets/BotSettingsDialog-BkjoAZtf.css +1 -0
- package/dist/assets/BotSettingsDialog-wLz_KGzX.js +5 -0
- package/dist/assets/BotSettingsDialog-wLz_KGzX.js.map +1 -0
- package/dist/assets/ChatView-DRPu2nKr.js +2 -0
- package/dist/assets/ChatView-DRPu2nKr.js.map +1 -0
- package/dist/assets/ChatView-Dx8YlcPr.css +1 -0
- package/dist/assets/ChevronForwardOutline-D--GIQK6.js +2 -0
- package/dist/assets/ChevronForwardOutline-D--GIQK6.js.map +1 -0
- package/dist/assets/ComputerPanel-Byr2_yKj.js +2 -0
- package/dist/assets/ComputerPanel-Byr2_yKj.js.map +1 -0
- package/dist/assets/ComputerPanel-CQOv4v8E.css +1 -0
- package/dist/assets/ComputerViewerView-BBAs4bzi.css +1 -0
- package/dist/assets/ComputerViewerView-DJ6hB-5e.js +2 -0
- package/dist/assets/ComputerViewerView-DJ6hB-5e.js.map +1 -0
- package/dist/assets/ConversationsView-C_VZl5g2.css +1 -0
- package/dist/assets/ConversationsView-cu1Yrq68.js +6 -0
- package/dist/assets/ConversationsView-cu1Yrq68.js.map +1 -0
- package/dist/assets/FilesView-DAIzo9Ps.css +1 -0
- package/dist/assets/FilesView-h9oJFmZt.js +2 -0
- package/dist/assets/FilesView-h9oJFmZt.js.map +1 -0
- package/dist/assets/FloatingResourceSearch-BF2XOLd-.css +1 -0
- package/dist/assets/FloatingResourceSearch-TofG1_DV.js +9 -0
- package/dist/assets/FloatingResourceSearch-TofG1_DV.js.map +1 -0
- package/dist/assets/HistoryView-Bh0SU969.js +2 -0
- package/dist/assets/HistoryView-Bh0SU969.js.map +1 -0
- package/dist/assets/HistoryView-DvuCAjlo.css +1 -0
- package/dist/assets/KanbanView-B-2vG4w7.css +1 -0
- package/dist/assets/KanbanView-CcqMOzB7.js +2 -0
- package/dist/assets/KanbanView-CcqMOzB7.js.map +1 -0
- package/dist/assets/LocalVmSettingsPanel-C8PIgMr3.js +2 -0
- package/dist/assets/LocalVmSettingsPanel-C8PIgMr3.js.map +1 -0
- package/dist/assets/LocalVmSettingsPanel-Dedfhqlq.css +1 -0
- package/dist/assets/RunnerSettingsPanel-CfxxQKpV.css +1 -0
- package/dist/assets/RunnerSettingsPanel-CvNnWcdH.js +4 -0
- package/dist/assets/RunnerSettingsPanel-CvNnWcdH.js.map +1 -0
- package/dist/assets/StandaloneDialog-BbNWY6IJ.js +2 -0
- package/dist/assets/StandaloneDialog-BbNWY6IJ.js.map +1 -0
- package/dist/assets/StandaloneDialog-Bg5U9bMJ.css +1 -0
- package/dist/assets/UpdateCheckDialog-C357uDSE.js +2 -0
- package/dist/assets/UpdateCheckDialog-C357uDSE.js.map +1 -0
- package/dist/assets/UpdateCheckDialog-CRlyWnE7.css +1 -0
- package/dist/assets/WorkspaceKnowledgePanel-B6xMyHdp.css +1 -0
- package/dist/assets/WorkspaceKnowledgePanel-CE7qsu2i.js +2 -0
- package/dist/assets/WorkspaceKnowledgePanel-CE7qsu2i.js.map +1 -0
- package/dist/assets/WorkspaceRoutinesPanel-CLsHmBuH.css +1 -0
- package/dist/assets/WorkspaceRoutinesPanel-DybBh6PZ.js +2 -0
- package/dist/assets/WorkspaceRoutinesPanel-DybBh6PZ.js.map +1 -0
- package/dist/assets/WorkspaceShell-7wn8iTne.css +1 -0
- package/dist/assets/WorkspaceShell-kp1ObJTk.js +44 -0
- package/dist/assets/WorkspaceShell-kp1ObJTk.js.map +1 -0
- package/dist/assets/WorkspaceView-CtNI0_AO.js +2 -0
- package/dist/assets/WorkspaceView-CtNI0_AO.js.map +1 -0
- package/dist/assets/_plugin-vue_export-helper-CscYwSBt.js +3 -0
- package/dist/assets/_plugin-vue_export-helper-CscYwSBt.js.map +1 -0
- package/dist/assets/browser-B97PQaMt.js +11 -0
- package/dist/assets/browser-B97PQaMt.js.map +1 -0
- package/dist/assets/docx-preview-YvkiVUyQ.js +22 -0
- package/dist/assets/docx-preview-YvkiVUyQ.js.map +1 -0
- package/dist/assets/index-GQxxBKs2.js +17 -0
- package/dist/assets/index-GQxxBKs2.js.map +1 -0
- package/dist/assets/index-g5POnMkp.css +1 -0
- package/dist/assets/localVm-owThjmhy.js +2 -0
- package/dist/assets/localVm-owThjmhy.js.map +1 -0
- package/dist/assets/pdf-pqGpzpl1.js +55 -0
- package/dist/assets/pdf-pqGpzpl1.js.map +1 -0
- package/dist/assets/pdf.worker.min-iDqQPrd3.mjs +31 -0
- package/dist/assets/sessionOwnership-BTz0Fyp5.css +1 -0
- package/dist/assets/sessionOwnership-bedp16q1.js +6 -0
- package/dist/assets/sessionOwnership-bedp16q1.js.map +1 -0
- package/dist/assets/viewModels-BYFb-v4u.js +38 -0
- package/dist/assets/viewModels-BYFb-v4u.js.map +1 -0
- package/dist/assets/viewModels-CkZuSvKm.css +1 -0
- package/dist/brand/AppIcon-1024.png +0 -0
- package/dist/icons/apple-touch-icon.png +0 -0
- package/dist/icons/favicon-32.png +0 -0
- package/dist/icons/icon-192.png +0 -0
- package/dist/icons/icon-512.png +0 -0
- package/dist/icons/logo-64.png +0 -0
- package/dist/index.html +19 -0
- package/dist/manifest.webmanifest +21 -0
- package/dist/setting-previews/dark.png +0 -0
- package/dist/setting-previews/light.png +0 -0
- package/dist/setting-previews/system.png +0 -0
- package/dist-server/runner/agent.js +563 -0
- package/dist-server/runner/browser/installation.js +180 -0
- package/dist-server/runner/browser/publicProxy.js +157 -0
- package/dist-server/runner/browser/runtime.js +622 -0
- package/dist-server/runner/browser/types.js +8 -0
- package/dist-server/runner/computers/commandProcess.js +127 -0
- package/dist-server/runner/computers/compose.js +139 -0
- package/dist-server/runner/computers/computer-image/Dockerfile +101 -0
- package/dist-server/runner/computers/computer-image/Dockerfile.cursor +27 -0
- package/dist-server/runner/computers/computer-image/Dockerfile.network +9 -0
- package/dist-server/runner/computers/computer-image/compose_bridge.py +329 -0
- package/dist-server/runner/computers/computer-image/cursor-browser.sh +6 -0
- package/dist-server/runner/computers/computer-image/cursor-desktop.py +86 -0
- package/dist-server/runner/computers/computer-image/network_gateway.py +197 -0
- package/dist-server/runner/computers/computer-image/prepare-firefox.sh +11 -0
- package/dist-server/runner/computers/computer-image/skill_bundle.py +111 -0
- package/dist-server/runner/computers/computerFailures.js +30 -0
- package/dist-server/runner/computers/container.js +652 -0
- package/dist-server/runner/computers/dataSnapshot.js +62 -0
- package/dist-server/runner/computers/desktopClose.js +41 -0
- package/dist-server/runner/computers/imageCli.js +42 -0
- package/dist-server/runner/computers/imageManagement.js +321 -0
- package/dist-server/runner/computers/images.js +130 -0
- package/dist-server/runner/computers/localVm.js +270 -0
- package/dist-server/runner/computers/maintenance.js +96 -0
- package/dist-server/runner/computers/maintenanceCli.js +59 -0
- package/dist-server/runner/computers/migrateUserData.js +62 -0
- package/dist-server/runner/computers/pool.js +407 -0
- package/dist-server/runner/computers/third-party/openmausbot/LICENSE +202 -0
- package/dist-server/runner/computers/third-party/openmausbot/NOTICE +4 -0
- package/dist-server/runner/computers/userData.js +128 -0
- package/dist-server/runner/computers/workspaceRecovery.js +120 -0
- package/dist-server/runner/config.js +37 -0
- package/dist-server/runner/hermes-bots-bridge/README.md +102 -0
- package/dist-server/runner/hermes-bots-bridge/__init__.py +59 -0
- package/dist-server/runner/hermes-bots-bridge/bootstrap.py +31 -0
- package/dist-server/runner/hermes-bots-bridge/bridge_runtime.py +1179 -0
- package/dist-server/runner/hermes-bots-bridge/dashboard/bridge.js +2 -0
- package/dist-server/runner/hermes-bots-bridge/dashboard/manifest.json +9 -0
- package/dist-server/runner/hermes-bots-bridge/dashboard/plugin_api.py +132 -0
- package/dist-server/runner/hermes-bots-bridge/file_transfer.py +146 -0
- package/dist-server/runner/hermes-bots-bridge/model_settings.py +136 -0
- package/dist-server/runner/hermes-bots-bridge/plugin.yaml +4 -0
- package/dist-server/runner/hermes-bots-bridge/profile_runtime_repair.py +77 -0
- package/dist-server/runner/index.js +75 -0
- package/dist-server/runner/install-hermes-bridge.py +192 -0
- package/dist-server/runner/managedBrowser.js +266 -0
- package/dist-server/runner/network/computerProxy.js +117 -0
- package/dist-server/runner/network/managedProxy.js +96 -0
- package/dist-server/runner/network/publicDestination.js +47 -0
- package/dist-server/runner/network/socketBroker.js +131 -0
- package/dist-server/runner/network/upstreamProxy.js +118 -0
- package/dist-server/runner/worker/control.js +212 -0
- package/dist-server/runner/worker/fileTransfer.js +9 -0
- package/dist-server/runner/worker/gateway.js +1009 -0
- package/dist-server/runner/worker/guest_proxy.py +116 -0
- package/dist-server/runner/worker/hermes_worker.py +310 -0
- package/dist-server/runner/worker/hostTools.js +115 -0
- package/dist-server/runner/worker/process.js +123 -0
- package/dist-server/runner/worker/profileSession.js +144 -0
- package/dist-server/runner/worker/profile_skills.py +361 -0
- package/dist-server/runner/worker/skill_bundle.py +111 -0
- package/dist-server/runner/worker/skills.js +119 -0
- package/dist-server/runner/worker/taskEnvironment.js +35 -0
- package/dist-server/server/accountPairing.js +72 -0
- package/dist-server/server/allowedHostsConfiguration.js +170 -0
- package/dist-server/server/apns.js +261 -0
- package/dist-server/server/apnsConfiguration.js +298 -0
- package/dist-server/server/app.js +639 -0
- package/dist-server/server/botModelSettings.js +60 -0
- package/dist-server/server/botPlugins/connectedApps.js +213 -0
- package/dist-server/server/botPlugins/httpMcp.js +117 -0
- package/dist-server/server/botPlugins/stdioMcp.js +263 -0
- package/dist-server/server/botPlugins/workspacePlugins.js +353 -0
- package/dist-server/server/browserFiles.js +79 -0
- package/dist-server/server/buildIdentity.js +18 -0
- package/dist-server/server/chatCache.js +1651 -0
- package/dist-server/server/chatEventProjection.js +70 -0
- package/dist-server/server/chatTranscriptApi.js +145 -0
- package/dist-server/server/chatTranscriptStore.js +1021 -0
- package/dist-server/server/chatUnread.js +34 -0
- package/dist-server/server/codexAuthorization.js +149 -0
- package/dist-server/server/composeDesktops.js +69 -0
- package/dist-server/server/computerControls.js +122 -0
- package/dist-server/server/computerNames.js +41 -0
- package/dist-server/server/config.js +176 -0
- package/dist-server/server/dashboardController.js +120 -0
- package/dist-server/server/dashboardSupervisor.js +176 -0
- package/dist-server/server/desktopActivation.js +26 -0
- package/dist-server/server/desktopEnvironments.js +600 -0
- package/dist-server/server/desktopHostProtocol.js +17 -0
- package/dist-server/server/desktopHosts.js +117 -0
- package/dist-server/server/errors.js +12 -0
- package/dist-server/server/executionSettings.js +171 -0
- package/dist-server/server/fcm.js +247 -0
- package/dist-server/server/fcmConfiguration.js +270 -0
- package/dist-server/server/fileAccess.js +103 -0
- package/dist-server/server/fileTransfer.js +98 -0
- package/dist-server/server/githubReleases.js +73 -0
- package/dist-server/server/grokAuth.js +333 -0
- package/dist-server/server/grokCloud.js +458 -0
- package/dist-server/server/hermesBotRelay.js +117 -0
- package/dist-server/server/hermesBridge.js +245 -0
- package/dist-server/server/hostToolSettings.js +60 -0
- package/dist-server/server/imageManagement.js +55 -0
- package/dist-server/server/index.js +132 -0
- package/dist-server/server/leases.js +69 -0
- package/dist-server/server/localAuth.js +737 -0
- package/dist-server/server/localVm.js +358 -0
- package/dist-server/server/loopbackAuthorization.js +58 -0
- package/dist-server/server/managedBrowserTools.js +16 -0
- package/dist-server/server/managedBrowsers.js +735 -0
- package/dist-server/server/notificationText.js +125 -0
- package/dist-server/server/openVikingConfiguration.js +222 -0
- package/dist-server/server/openVikingMemoryProvider.js +279 -0
- package/dist-server/server/openVikingService.js +177 -0
- package/dist-server/server/openVikingSessionSync.js +286 -0
- package/dist-server/server/pairing.js +342 -0
- package/dist-server/server/profileIdentities.js +103 -0
- package/dist-server/server/pushCoordinator.js +1422 -0
- package/dist-server/server/pushEventAdapter.js +31 -0
- package/dist-server/server/pushEvents.js +1218 -0
- package/dist-server/server/realtimeApi.js +330 -0
- package/dist-server/server/realtimeBroker.js +835 -0
- package/dist-server/server/realtimeProtocol.js +353 -0
- package/dist-server/server/realtimeReceipts.js +60 -0
- package/dist-server/server/releases.js +46 -0
- package/dist-server/server/routes.js +2156 -0
- package/dist-server/server/runnerHub.js +687 -0
- package/dist-server/server/security.js +196 -0
- package/dist-server/server/serverIdentity.js +31 -0
- package/dist-server/server/serviceInstance.js +178 -0
- package/dist-server/server/sessionWorkingDirectory.js +39 -0
- package/dist-server/server/sharedComputers.js +221 -0
- package/dist-server/server/subaccountAccess.js +28 -0
- package/dist-server/server/taskCoordinator.js +580 -0
- package/dist-server/server/toolOperationJournal.js +81 -0
- package/dist-server/server/updateManager.js +340 -0
- package/dist-server/server/uploads.js +265 -0
- package/dist-server/server/upstream.js +375 -0
- package/dist-server/server/upstreamReadCache.js +133 -0
- package/dist-server/server/vmComputer.js +96 -0
- package/dist-server/server/websocket.js +753 -0
- package/dist-server/server/workspaceAssets.js +192 -0
- package/dist-server/server/workspaceCollaboration.js +224 -0
- package/dist-server/server/workspaceDiscussion.js +23 -0
- package/dist-server/server/workspaceEnvironment.js +43 -0
- package/dist-server/server/workspaceGateway.js +509 -0
- package/dist-server/server/workspaceInspector.js +47 -0
- package/dist-server/server/workspaceKnowledge.js +557 -0
- package/dist-server/server/workspaceKnowledgeRoutes.js +78 -0
- package/dist-server/server/workspaceKnowledgeTools.js +105 -0
- package/dist-server/server/workspaceMemoryContext.js +34 -0
- package/dist-server/server/workspaceMemorySynthesis.js +201 -0
- package/dist-server/server/workspaceMentions.js +31 -0
- package/dist-server/server/workspacePairedNode.js +166 -0
- package/dist-server/server/workspacePrompt.js +93 -0
- package/dist-server/server/workspaceRelay.js +90 -0
- package/dist-server/server/workspaceRemoteAgents.js +191 -0
- package/dist-server/server/workspaceRoutes.js +703 -0
- package/dist-server/server/workspaceRoutineTools.js +109 -0
- package/dist-server/server/workspaceRoutines.js +163 -0
- package/dist-server/server/workspaceRuntime.js +1363 -0
- package/dist-server/server/workspaceScheduler.js +592 -0
- package/dist-server/server/workspaceStore.js +1220 -0
- package/dist-server/server/workspaceSync.js +129 -0
- package/dist-server/server/workspaceTeamTools.js +312 -0
- package/dist-server/server/workspaceToolLease.js +280 -0
- package/dist-server/shared/agentIdentity.js +90 -0
- package/dist-server/shared/agentTasks.js +1 -0
- package/dist-server/shared/botEnvironment.js +28 -0
- package/dist-server/shared/botModelSettings.js +3 -0
- package/dist-server/shared/chatTools.js +32 -0
- package/dist-server/shared/chatTranscript.js +50 -0
- package/dist-server/shared/composeDesktops.js +1 -0
- package/dist-server/shared/computerControl.js +1 -0
- package/dist-server/shared/desktopEnvironment.js +1 -0
- package/dist-server/shared/desktopHost.js +1 -0
- package/dist-server/shared/executionEnvironment.js +1 -0
- package/dist-server/shared/fileTransfer.js +5 -0
- package/dist-server/shared/fileTransferEndpoint.mjs +133 -0
- package/dist-server/shared/grokAuth.js +1 -0
- package/dist-server/shared/hermesBridge.js +1 -0
- package/dist-server/shared/hostPaths.mjs +22 -0
- package/dist-server/shared/imageManagement.js +1 -0
- package/dist-server/shared/index.js +1 -0
- package/dist-server/shared/localVm.js +9 -0
- package/dist-server/shared/managedBrowser.js +1 -0
- package/dist-server/shared/messageFiles.js +90 -0
- package/dist-server/shared/openVikingSync.js +1 -0
- package/dist-server/shared/runner.js +2 -0
- package/dist-server/shared/serverFiles.js +55 -0
- package/dist-server/shared/serverIdentity.js +1 -0
- package/dist-server/shared/sse.js +47 -0
- package/dist-server/shared/types.js +8 -0
- package/dist-server/shared/workspace.js +61 -0
- package/dist-server/shared/workspaceKnowledge.js +1 -0
- package/dist-server/shared/workspaceLifecycle.js +1 -0
- package/dist-server/shared/workspaceMessagePatch.js +63 -0
- package/dist-server/shared/workspacePanels.js +1 -0
- package/dist-server/shared/workspacePlugins.js +1 -0
- package/licenses/LaoA-GrokBot/LICENSE +21 -0
- package/licenses/OpenMausBot/LICENSE +202 -0
- package/licenses/OpenMausBot/NOTICE +6 -0
- package/package.json +122 -0
- package/release.json +6 -0
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"""Private Compose desktop transport. No network port or Docker socket."""
|
|
2
|
+
import base64
|
|
3
|
+
import http.server
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import secrets
|
|
8
|
+
import selectors
|
|
9
|
+
import signal
|
|
10
|
+
import socketserver
|
|
11
|
+
import subprocess
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
import uuid
|
|
15
|
+
from skill_bundle import install as install_skill
|
|
16
|
+
|
|
17
|
+
DESKTOP_ID = os.environ.get('YAOYAO_COMPOSE_DESKTOP_ID')
|
|
18
|
+
ROOT = Path('/run/yaoyao-private')
|
|
19
|
+
BRIDGE = ROOT / 'bridge'
|
|
20
|
+
SOCKET = BRIDGE / 'desktop.sock'
|
|
21
|
+
INSTANCE = secrets.token_hex(24)
|
|
22
|
+
PID1 = None
|
|
23
|
+
RESET = BRIDGE / 'reset.json'
|
|
24
|
+
LOCK = threading.RLock()
|
|
25
|
+
LEASE = None
|
|
26
|
+
RESTARTING = False
|
|
27
|
+
DRIVER = '/usr/local/libexec/openmausbot/cua-driver'
|
|
28
|
+
CUA_SOCKET = '/run/user/1000/openmausbot-cua.sock'
|
|
29
|
+
BASE_ENV = {'PATH': '/opt/venv/bin:/usr/local/bin:/usr/bin:/bin', 'DISPLAY': ':1'}
|
|
30
|
+
ENV = {**BASE_ENV, 'HOME': '/home/cua', 'USER': 'cua'}
|
|
31
|
+
|
|
32
|
+
def reset_desktop():
|
|
33
|
+
global RESTARTING, LEASE
|
|
34
|
+
with LOCK:
|
|
35
|
+
if RESTARTING:
|
|
36
|
+
return
|
|
37
|
+
RESTARTING = True
|
|
38
|
+
LEASE = None
|
|
39
|
+
RESET.write_text(json.dumps({'pid1': PID1}))
|
|
40
|
+
# Compose restarts the same service and retains its workspace volume.
|
|
41
|
+
threading.Timer(0.1, lambda: os.kill(1, signal.SIGTERM)).start()
|
|
42
|
+
|
|
43
|
+
def current(body):
|
|
44
|
+
if RESTARTING or not LEASE or body.get('token') != LEASE['token'] or body.get('instance') != INSTANCE or LEASE['expires'] <= time.monotonic():
|
|
45
|
+
raise ValueError('桌面控制授权已失效')
|
|
46
|
+
return LEASE
|
|
47
|
+
|
|
48
|
+
def start(argv, cwd, user='cua'):
|
|
49
|
+
# The bridge itself runs as root; commands run in the explicitly selected
|
|
50
|
+
# guest account without acquiring additional container capabilities.
|
|
51
|
+
wrapper = 'import os,sys;os.chdir(sys.argv[1]);os.execvpe(sys.argv[2],sys.argv[2:],os.environ)'
|
|
52
|
+
uid, environment = (0, {**BASE_ENV, 'HOME': '/root', 'USER': 'root'}) if user == 'root' else (1000, ENV)
|
|
53
|
+
return subprocess.Popen(['python3','-c',wrapper,cwd,*argv], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment, user=uid, group=uid, extra_groups=[], start_new_session=True)
|
|
54
|
+
|
|
55
|
+
def stop_command(process):
|
|
56
|
+
# Every command owns a session/process group. Keep its leader unreaped until
|
|
57
|
+
# this signal, so its PID cannot be reused for an unrelated process group.
|
|
58
|
+
with process.__dict__.setdefault('_yaoyao_lock', threading.RLock()):
|
|
59
|
+
if process.returncode is not None:
|
|
60
|
+
return
|
|
61
|
+
try:
|
|
62
|
+
os.killpg(process.pid, signal.SIGKILL)
|
|
63
|
+
except ProcessLookupError:
|
|
64
|
+
pass
|
|
65
|
+
process.wait(timeout=5)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def collect(process, data, timeout):
|
|
69
|
+
# communicate() buffers without a limit; drain both pipes and feed stdin
|
|
70
|
+
# together so output and input backpressure cannot deadlock one another.
|
|
71
|
+
streams = selectors.DefaultSelector()
|
|
72
|
+
output = {'stdout': bytearray(), 'stderr': bytearray()}
|
|
73
|
+
pending = memoryview(data or b'')
|
|
74
|
+
deadline = time.monotonic() + timeout
|
|
75
|
+
size = 0
|
|
76
|
+
try:
|
|
77
|
+
for pipe, name in ((process.stdout, 'stdout'), (process.stderr, 'stderr')):
|
|
78
|
+
os.set_blocking(pipe.fileno(), False)
|
|
79
|
+
streams.register(pipe, selectors.EVENT_READ, name)
|
|
80
|
+
if pending:
|
|
81
|
+
os.set_blocking(process.stdin.fileno(), False)
|
|
82
|
+
streams.register(process.stdin, selectors.EVENT_WRITE, 'stdin')
|
|
83
|
+
else:
|
|
84
|
+
process.stdin.close()
|
|
85
|
+
while streams.get_map():
|
|
86
|
+
remaining = deadline - time.monotonic()
|
|
87
|
+
if remaining <= 0:
|
|
88
|
+
raise ValueError('桌面命令超时')
|
|
89
|
+
for key, _ in streams.select(remaining):
|
|
90
|
+
try:
|
|
91
|
+
if key.data == 'stdin':
|
|
92
|
+
try:
|
|
93
|
+
written = os.write(key.fd, pending[:65536])
|
|
94
|
+
pending = pending[written:]
|
|
95
|
+
except BrokenPipeError:
|
|
96
|
+
pending = pending[:0]
|
|
97
|
+
if not pending:
|
|
98
|
+
streams.unregister(key.fileobj)
|
|
99
|
+
key.fileobj.close()
|
|
100
|
+
else:
|
|
101
|
+
chunk = os.read(key.fd, 65536)
|
|
102
|
+
if not chunk:
|
|
103
|
+
streams.unregister(key.fileobj)
|
|
104
|
+
key.fileobj.close()
|
|
105
|
+
else:
|
|
106
|
+
size += len(chunk)
|
|
107
|
+
if size > 8 * 1024 * 1024:
|
|
108
|
+
raise ValueError('桌面命令输出超过限制')
|
|
109
|
+
output[key.data].extend(chunk)
|
|
110
|
+
except BlockingIOError:
|
|
111
|
+
pass
|
|
112
|
+
while True:
|
|
113
|
+
remaining = deadline - time.monotonic()
|
|
114
|
+
if remaining <= 0:
|
|
115
|
+
raise ValueError('桌面命令超时')
|
|
116
|
+
with process.__dict__.setdefault('_yaoyao_lock', threading.RLock()):
|
|
117
|
+
try:
|
|
118
|
+
process.wait(timeout=min(.05, remaining))
|
|
119
|
+
break
|
|
120
|
+
except subprocess.TimeoutExpired:
|
|
121
|
+
pass
|
|
122
|
+
return {**{name: value.decode('utf-8', 'replace') for name, value in output.items()}, 'exitCode': process.returncode}
|
|
123
|
+
except Exception:
|
|
124
|
+
try:
|
|
125
|
+
stop_command(process)
|
|
126
|
+
except Exception:
|
|
127
|
+
# Only an unconfirmed cleanup requires fencing the whole desktop.
|
|
128
|
+
reset_desktop()
|
|
129
|
+
raise ValueError('尚未确认桌面命令已停止')
|
|
130
|
+
raise
|
|
131
|
+
finally:
|
|
132
|
+
streams.close()
|
|
133
|
+
for pipe in (process.stdin, process.stdout, process.stderr):
|
|
134
|
+
pipe.close()
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def run(argv, cwd='/home/cua/workspace', data=None, timeout=30, user='cua'):
|
|
138
|
+
return collect(start(argv, cwd, user), data, timeout)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def operation_id(body):
|
|
142
|
+
value = body.get('operationId')
|
|
143
|
+
if not isinstance(value, str) or str(uuid.UUID(value)) != value:
|
|
144
|
+
raise ValueError('桌面命令标识无效')
|
|
145
|
+
return value
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def operations(lease):
|
|
149
|
+
entries = lease.setdefault('operations', {})
|
|
150
|
+
now = time.monotonic()
|
|
151
|
+
for key, value in list(entries.items()):
|
|
152
|
+
if value.get('finished', now) + 120 < now:
|
|
153
|
+
del entries[key]
|
|
154
|
+
return entries
|
|
155
|
+
|
|
156
|
+
class Handler(http.server.BaseHTTPRequestHandler):
|
|
157
|
+
def log_message(self, *args):
|
|
158
|
+
pass
|
|
159
|
+
|
|
160
|
+
def do_POST(self):
|
|
161
|
+
global LEASE
|
|
162
|
+
try:
|
|
163
|
+
length = int(self.headers.get('Content-Length', '0'))
|
|
164
|
+
if length > 36 * 1024 * 1024:
|
|
165
|
+
raise ValueError('请求过大')
|
|
166
|
+
body = json.loads(self.rfile.read(length) or b'{}')
|
|
167
|
+
if body.get('desktopId') != DESKTOP_ID:
|
|
168
|
+
raise ValueError('桌面身份不匹配')
|
|
169
|
+
op = self.path
|
|
170
|
+
if op == '/health':
|
|
171
|
+
ready = False
|
|
172
|
+
if not RESTARTING:
|
|
173
|
+
try:
|
|
174
|
+
result = run([DRIVER, 'call', 'health_report', '{}', '--socket', CUA_SOCKET], timeout=5)
|
|
175
|
+
ready = result['exitCode'] == 0
|
|
176
|
+
except Exception:
|
|
177
|
+
pass
|
|
178
|
+
result = {'id': DESKTOP_ID, 'protocol': 1, 'instance': INSTANCE, 'ready': ready, 'features': ['skills-v1', 'command-cancel-v1']}
|
|
179
|
+
elif op == '/acquire':
|
|
180
|
+
with LOCK:
|
|
181
|
+
if RESTARTING:
|
|
182
|
+
raise ValueError('桌面正在重置')
|
|
183
|
+
if LEASE:
|
|
184
|
+
if body.get('requestId') != LEASE['requestId'] or body.get('owner') != LEASE['owner']:
|
|
185
|
+
raise ValueError('共享桌面正在使用')
|
|
186
|
+
current({'token': LEASE['token'], 'instance': INSTANCE})
|
|
187
|
+
else:
|
|
188
|
+
if not isinstance(body.get('requestId'), str) or not isinstance(body.get('owner'), str):
|
|
189
|
+
raise ValueError('缺少桌面授权身份')
|
|
190
|
+
LEASE = {'requestId': body['requestId'], 'owner': body['owner'], 'token': secrets.token_hex(32), 'expires': time.monotonic() + 90, 'active': 0}
|
|
191
|
+
result = {'token': LEASE['token'], 'instance': INSTANCE}
|
|
192
|
+
elif op == '/renew':
|
|
193
|
+
with LOCK:
|
|
194
|
+
current(body)['expires'] = time.monotonic() + 90
|
|
195
|
+
result = {'ok': True}
|
|
196
|
+
elif op == '/release':
|
|
197
|
+
with LOCK:
|
|
198
|
+
current(body)
|
|
199
|
+
if LEASE['active'] and not body.get('cancel'):
|
|
200
|
+
raise ValueError('共享桌面仍有未结束操作')
|
|
201
|
+
LEASE = None
|
|
202
|
+
result = {'ok': True}
|
|
203
|
+
if body.get('cancel'):
|
|
204
|
+
reset_desktop()
|
|
205
|
+
elif op == '/frame':
|
|
206
|
+
path = '/tmp/yaoyao-compose-' + secrets.token_hex(12) + '.png'
|
|
207
|
+
try:
|
|
208
|
+
frame = run([DRIVER, 'call', 'get_desktop_state', '{}', '--socket', CUA_SOCKET, '--screenshot-out-file', path], timeout=10)
|
|
209
|
+
if frame['exitCode'] != 0:
|
|
210
|
+
raise ValueError('桌面画面尚未就绪')
|
|
211
|
+
data = Path(path).read_bytes()
|
|
212
|
+
if data[1:4] != b'PNG':
|
|
213
|
+
raise ValueError('桌面画面无效')
|
|
214
|
+
result = {'data': base64.b64encode(data).decode(), 'width': int.from_bytes(data[16:20], 'big'), 'height': int.from_bytes(data[20:24], 'big'), 'capturedAt': int(time.time()*1000)}
|
|
215
|
+
finally:
|
|
216
|
+
Path(path).unlink(missing_ok=True)
|
|
217
|
+
elif op == '/skills-install':
|
|
218
|
+
with LOCK:
|
|
219
|
+
current(body)
|
|
220
|
+
result = install_skill(body.get('bundle', {}))
|
|
221
|
+
current(body)
|
|
222
|
+
elif op == '/cancel':
|
|
223
|
+
key = operation_id(body)
|
|
224
|
+
with LOCK:
|
|
225
|
+
entries = operations(current(body))
|
|
226
|
+
command = entries.get(key)
|
|
227
|
+
if command is None:
|
|
228
|
+
if len(entries) >= 4096:
|
|
229
|
+
raise ValueError('桌面操作过多,请稍后重试')
|
|
230
|
+
# Cancellation may arrive before execute on another
|
|
231
|
+
# connection. The tombstone prevents that late launch.
|
|
232
|
+
command = entries[key] = {'finished': time.monotonic()}
|
|
233
|
+
command['cancelled'] = True
|
|
234
|
+
process = command.get('process')
|
|
235
|
+
if process is not None:
|
|
236
|
+
try:
|
|
237
|
+
stop_command(process)
|
|
238
|
+
except Exception:
|
|
239
|
+
raise ValueError('尚未确认桌面命令已停止')
|
|
240
|
+
result = {'ok': True, 'stopped': True, 'operationId': key}
|
|
241
|
+
elif op == '/execute':
|
|
242
|
+
argv = body.get('argv')
|
|
243
|
+
if not isinstance(argv, list) or not argv or len(argv) > 64 or any(not isinstance(x, str) or '\0' in x for x in argv) or sum(map(len, argv)) > 65536:
|
|
244
|
+
raise ValueError('桌面命令无效')
|
|
245
|
+
cwd = body.get('cwd', '/home/cua/workspace')
|
|
246
|
+
if not isinstance(cwd, str) or (cwd != '/home/cua/workspace' and not cwd.startswith('/home/cua/workspace/')) or '..' in Path(cwd).parts:
|
|
247
|
+
raise ValueError('Compose 桌面工作目录必须位于 /home/cua/workspace')
|
|
248
|
+
user = body.get('user', 'cua')
|
|
249
|
+
if user not in ('cua', 'root'):
|
|
250
|
+
raise ValueError('桌面命令用户无效')
|
|
251
|
+
data = base64.b64decode(body['input'], validate=True) if body.get('input') else None
|
|
252
|
+
timeout = min(60, max(1, body.get('timeout', 30000)/1000))
|
|
253
|
+
# Older runners can still execute without operationId; only
|
|
254
|
+
# callers supplying an ID can use targeted cancellation.
|
|
255
|
+
key = operation_id(body) if 'operationId' in body else str(uuid.uuid4())
|
|
256
|
+
with LOCK:
|
|
257
|
+
lease = current(body)
|
|
258
|
+
entries = operations(lease)
|
|
259
|
+
if key in entries:
|
|
260
|
+
raise ValueError('桌面命令已取消或已执行')
|
|
261
|
+
if len(entries) >= 4096:
|
|
262
|
+
raise ValueError('桌面操作过多,请稍后重试')
|
|
263
|
+
# Spawn while holding the lease lock, then release the lock
|
|
264
|
+
# before waiting so revocation can stop the container.
|
|
265
|
+
process = start(argv, cwd, user)
|
|
266
|
+
command = entries[key] = {'process': process, 'cancelled': False}
|
|
267
|
+
lease['active'] += 1
|
|
268
|
+
try:
|
|
269
|
+
result = collect(process, data, timeout)
|
|
270
|
+
with LOCK:
|
|
271
|
+
current(body)
|
|
272
|
+
if command['cancelled']:
|
|
273
|
+
raise ValueError('桌面命令已取消')
|
|
274
|
+
finally:
|
|
275
|
+
with LOCK:
|
|
276
|
+
command.pop('process', None)
|
|
277
|
+
command['finished'] = time.monotonic()
|
|
278
|
+
if LEASE is lease:
|
|
279
|
+
lease['active'] -= 1
|
|
280
|
+
else:
|
|
281
|
+
raise ValueError('桌面数量和创建删除由 Compose 管理')
|
|
282
|
+
payload = json.dumps(result).encode()
|
|
283
|
+
self.send_response(200)
|
|
284
|
+
except Exception as exc:
|
|
285
|
+
code = 'computer_busy' if str(exc) in ('共享桌面正在使用','共享桌面仍有未结束操作') else 'compose_desktop_error'
|
|
286
|
+
payload = json.dumps({'error': str(exc), 'code': code}, ensure_ascii=False).encode()
|
|
287
|
+
self.send_response(409)
|
|
288
|
+
self.send_header('Content-Type','application/json')
|
|
289
|
+
self.send_header('X-Yaoyao-Desktop-Id',DESKTOP_ID)
|
|
290
|
+
self.send_header('Content-Length',str(len(payload)))
|
|
291
|
+
self.end_headers()
|
|
292
|
+
try:
|
|
293
|
+
self.wfile.write(payload)
|
|
294
|
+
except BrokenPipeError:
|
|
295
|
+
pass
|
|
296
|
+
|
|
297
|
+
class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
|
|
298
|
+
daemon_threads = True
|
|
299
|
+
|
|
300
|
+
def expire():
|
|
301
|
+
while True:
|
|
302
|
+
time.sleep(5)
|
|
303
|
+
with LOCK:
|
|
304
|
+
expired = LEASE and LEASE['expires'] <= time.monotonic()
|
|
305
|
+
if expired:
|
|
306
|
+
reset_desktop()
|
|
307
|
+
|
|
308
|
+
def main():
|
|
309
|
+
global PID1
|
|
310
|
+
if not DESKTOP_ID:
|
|
311
|
+
return
|
|
312
|
+
ROOT.mkdir(exist_ok=True)
|
|
313
|
+
ROOT.chmod(0o700)
|
|
314
|
+
BRIDGE.mkdir(exist_ok=True)
|
|
315
|
+
BRIDGE.chmod(0o755)
|
|
316
|
+
PID1 = Path('/proc/1/stat').read_text().split()[21]
|
|
317
|
+
if RESET.exists() and json.loads(RESET.read_text()).get('pid1') == PID1:
|
|
318
|
+
raise SystemExit(1) # A new bridge process alone cannot fence old programs.
|
|
319
|
+
RESET.unlink(missing_ok=True)
|
|
320
|
+
SOCKET.unlink(missing_ok=True)
|
|
321
|
+
server = Server(str(SOCKET), Handler)
|
|
322
|
+
SOCKET.chmod(0o600)
|
|
323
|
+
os.chown(SOCKET,1000,1000)
|
|
324
|
+
threading.Thread(target=expire,daemon=True).start()
|
|
325
|
+
server.serve_forever()
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
if __name__ == '__main__':
|
|
329
|
+
main()
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
set -eu
|
|
3
|
+
if [ "${HTTP_PROXY:-}" = 'http://127.0.0.1:3128' ]; then
|
|
4
|
+
set -- "--proxy-server=$HTTP_PROXY" '--proxy-bypass-list=localhost;127.0.0.1;[::1]' --disable-quic "$@"
|
|
5
|
+
fi
|
|
6
|
+
exec /usr/bin/google-chrome --no-sandbox --no-first-run --no-default-browser-check --disable-dev-shm-usage --password-store=basic --user-data-dir=/home/cua/workspace/.browser-profiles/google-chrome "$@"
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Supervise the Cursor desktop using the existing uid, workspace and CUA socket contract."""
|
|
2
|
+
import os
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import signal
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
children = []
|
|
10
|
+
critical = []
|
|
11
|
+
stopping = False
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def stop(*_):
|
|
15
|
+
global stopping
|
|
16
|
+
stopping = True
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def spawn(argv, user=True, required=True):
|
|
20
|
+
child = subprocess.Popen(argv, user=1000 if user else None,
|
|
21
|
+
group=1000 if user else None,
|
|
22
|
+
extra_groups=[] if user else None)
|
|
23
|
+
children.append(child)
|
|
24
|
+
if required:
|
|
25
|
+
critical.append(child)
|
|
26
|
+
return child
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
signal.signal(signal.SIGTERM, stop)
|
|
30
|
+
signal.signal(signal.SIGINT, stop)
|
|
31
|
+
try:
|
|
32
|
+
# Run workspace setup as its owner; no extra DAC or CHOWN capability is needed.
|
|
33
|
+
setup = """
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
import os
|
|
36
|
+
root = Path('/home/cua/workspace/.browser-profiles/google-chrome')
|
|
37
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
38
|
+
for name in ['SingletonLock', 'SingletonSocket', 'SingletonCookie']:
|
|
39
|
+
(root / name).unlink(missing_ok=True)
|
|
40
|
+
config = Path('/home/cua/.config')
|
|
41
|
+
config.mkdir(exist_ok=True)
|
|
42
|
+
link = config / 'google-chrome'
|
|
43
|
+
if not link.is_symlink() and not link.exists():
|
|
44
|
+
link.symlink_to(root)
|
|
45
|
+
launchers = config / 'plank/dock1/launchers'
|
|
46
|
+
launchers.mkdir(parents=True, exist_ok=True)
|
|
47
|
+
for name in ['google-chrome', 'xfce4-terminal', 'thunar']:
|
|
48
|
+
(launchers / (name + '.dockitem')).write_text('[PlankDockItemPreferences]\\nLauncher=file:///usr/share/applications/' + name + '.desktop\\n')
|
|
49
|
+
"""
|
|
50
|
+
subprocess.run(['python3', '-c', setup], user=1000, group=1000, extra_groups=[], check=True)
|
|
51
|
+
for path in ['/tmp/.X1-lock', '/tmp/.X11-unix/X1', '/run/user/1000/openmausbot-cua.sock', '/run/user/1000/yaoyao-dbus']:
|
|
52
|
+
subprocess.run(['rm', '-f', path], user=1000, group=1000, extra_groups=[], check=True)
|
|
53
|
+
os.environ['DBUS_SESSION_BUS_ADDRESS'] = 'unix:path=/run/user/1000/yaoyao-dbus'
|
|
54
|
+
spawn(['dbus-daemon', '--session', '--nofork', '--address=' + os.environ['DBUS_SESSION_BUS_ADDRESS']])
|
|
55
|
+
spawn(['Xvfb', ':1', '-screen', '0', '1280x800x24', '-ac', '-nolisten', 'tcp', '-noreset'])
|
|
56
|
+
for _ in range(100):
|
|
57
|
+
if stopping or any(p.poll() is not None for p in children):
|
|
58
|
+
raise RuntimeError('桌面启动已中断')
|
|
59
|
+
if subprocess.run(['xset', 'q'], user=1000, group=1000, extra_groups=[], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0:
|
|
60
|
+
break
|
|
61
|
+
time.sleep(0.2)
|
|
62
|
+
else:
|
|
63
|
+
raise RuntimeError('X display :1 did not become ready')
|
|
64
|
+
spawn(['xfwm4', '--compositor=off'])
|
|
65
|
+
subprocess.run(['xsetroot', '-solid', '#202734'], user=1000, group=1000, extra_groups=[])
|
|
66
|
+
spawn(['plank'], required=False)
|
|
67
|
+
spawn(['/usr/local/libexec/openmausbot/cua-driver', 'serve', '--socket', '/run/user/1000/openmausbot-cua.sock', '--permission-mode', 'standard'])
|
|
68
|
+
# A visible browser gives this minimal desktop a usable initial surface.
|
|
69
|
+
spawn(['/usr/local/bin/yaoyao-browser', 'about:blank'], required=False)
|
|
70
|
+
if os.environ.get('YAOYAO_COMPOSE_DESKTOP_ID'):
|
|
71
|
+
spawn(['python3', '/usr/local/libexec/yaoyao/compose_bridge.py'], user=False)
|
|
72
|
+
while not stopping:
|
|
73
|
+
if any(p.poll() is not None for p in critical):
|
|
74
|
+
raise RuntimeError('桌面进程已退出,等待重新启动')
|
|
75
|
+
time.sleep(0.5)
|
|
76
|
+
except Exception as error:
|
|
77
|
+
print(error, file=sys.stderr, flush=True)
|
|
78
|
+
sys.exit(1)
|
|
79
|
+
finally:
|
|
80
|
+
# Stop the guest session without giving root CAP_KILL in managed containers.
|
|
81
|
+
subprocess.run(['python3', '-c', 'import os,signal; os.kill(-1,signal.SIGTERM)'], user=1000, group=1000, extra_groups=[])
|
|
82
|
+
for child in children:
|
|
83
|
+
try:
|
|
84
|
+
child.wait(timeout=3)
|
|
85
|
+
except subprocess.TimeoutExpired:
|
|
86
|
+
pass
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""A network namespace with only loopback + TUN. No physical/default internet NIC.
|
|
2
|
+
All TCP sockets belong to the authenticated parent broker. Guest processes never
|
|
3
|
+
receive proxy credentials. Fake DNS maps back to hostnames at the SOCKS boundary;
|
|
4
|
+
the parent resolves those through the upstream proxy and checks public addresses.
|
|
5
|
+
"""
|
|
6
|
+
import asyncio
|
|
7
|
+
import base64
|
|
8
|
+
import contextlib
|
|
9
|
+
import ipaddress
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
import secrets
|
|
14
|
+
import socket
|
|
15
|
+
import struct
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
import time
|
|
19
|
+
import uuid
|
|
20
|
+
|
|
21
|
+
SOCKS = 3129
|
|
22
|
+
DNS = '198.18.0.1'
|
|
23
|
+
|
|
24
|
+
class Tunnel:
|
|
25
|
+
def __init__(self, send):
|
|
26
|
+
self.send = send
|
|
27
|
+
self.streams = {}
|
|
28
|
+
self.names = {}
|
|
29
|
+
self.addresses = {}
|
|
30
|
+
|
|
31
|
+
def dns(self, packet):
|
|
32
|
+
if len(packet) < 12 or packet[2] & 0x80 or struct.unpack('!H', packet[4:6])[0] != 1:
|
|
33
|
+
raise ValueError('invalid DNS')
|
|
34
|
+
end, labels = 12, []
|
|
35
|
+
while end < len(packet) and packet[end]:
|
|
36
|
+
length = packet[end]
|
|
37
|
+
if length > 63 or end + length + 1 > len(packet): raise ValueError('invalid label')
|
|
38
|
+
labels.append(packet[end+1:end+1+length].decode('ascii'))
|
|
39
|
+
end += length + 1
|
|
40
|
+
end += 1
|
|
41
|
+
kind, cls = struct.unpack('!HH', packet[end:end+4])
|
|
42
|
+
question = packet[12:end+4]
|
|
43
|
+
name = '.'.join(labels).lower()
|
|
44
|
+
answer = b''
|
|
45
|
+
if cls == 1 and kind == 1 and name and len(name) <= 253:
|
|
46
|
+
if name not in self.names:
|
|
47
|
+
if len(self.names) >= 65000: raise ValueError('DNS limit')
|
|
48
|
+
address = str(ipaddress.IPv4Address(int(ipaddress.IPv4Address('198.19.0.1')) + len(self.names)))
|
|
49
|
+
self.names[name] = address
|
|
50
|
+
self.addresses[address] = name
|
|
51
|
+
answer = b'\xc0\x0c' + struct.pack('!HHIH', 1, 1, 60, 4) + socket.inet_aton(self.names[name])
|
|
52
|
+
return packet[:2] + struct.pack('!HHHHH', 0x8180, 1, bool(answer), 0, 0) + question + answer
|
|
53
|
+
|
|
54
|
+
async def socks(self, reader, writer):
|
|
55
|
+
identity = str(uuid.uuid4())
|
|
56
|
+
opened = asyncio.get_running_loop().create_future()
|
|
57
|
+
if len(self.streams) >= 32:
|
|
58
|
+
writer.close(); return
|
|
59
|
+
self.streams[identity] = (writer, opened)
|
|
60
|
+
try:
|
|
61
|
+
version, count = await asyncio.wait_for(reader.readexactly(2), 10)
|
|
62
|
+
methods = await reader.readexactly(count)
|
|
63
|
+
if version != 5 or 0 not in methods: raise ValueError('SOCKS version')
|
|
64
|
+
writer.write(b'\x05\x00'); await writer.drain()
|
|
65
|
+
version, command, reserved, kind = await reader.readexactly(4)
|
|
66
|
+
if version != 5 or command != 1 or reserved: raise ValueError('TCP CONNECT only')
|
|
67
|
+
if kind == 1: host = socket.inet_ntop(socket.AF_INET, await reader.readexactly(4))
|
|
68
|
+
elif kind == 4: host = socket.inet_ntop(socket.AF_INET6, await reader.readexactly(16))
|
|
69
|
+
elif kind == 3: host = (await reader.readexactly((await reader.readexactly(1))[0])).decode('ascii')
|
|
70
|
+
else: raise ValueError('SOCKS address')
|
|
71
|
+
port = struct.unpack('!H', await reader.readexactly(2))[0]
|
|
72
|
+
await self.send({'op':'open','id':identity,'host':self.addresses.get(host,host),'port':port})
|
|
73
|
+
await asyncio.wait_for(opened, 25)
|
|
74
|
+
writer.write(b'\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00'); await writer.drain()
|
|
75
|
+
while True:
|
|
76
|
+
data = await reader.read(32768)
|
|
77
|
+
if not data:
|
|
78
|
+
await self.send({'op':'end','id':identity}); break
|
|
79
|
+
await self.send({'op':'data','id':identity,'data':base64.b64encode(data).decode()})
|
|
80
|
+
except Exception:
|
|
81
|
+
with contextlib.suppress(Exception): writer.write(b'\x05\x01\x00\x01'+b'\x00'*6); await writer.drain()
|
|
82
|
+
finally:
|
|
83
|
+
self.streams.pop(identity,None); writer.close()
|
|
84
|
+
with contextlib.suppress(Exception): await self.send({'op':'close','id':identity})
|
|
85
|
+
|
|
86
|
+
async def receive(self, frame):
|
|
87
|
+
writer, opened = self.streams.get(frame.get('id'), (None,None))
|
|
88
|
+
if writer is None: return
|
|
89
|
+
if frame['op'] == 'opened':
|
|
90
|
+
if not opened.done(): opened.set_result(True)
|
|
91
|
+
elif frame['op'] == 'data':
|
|
92
|
+
data = base64.b64decode(frame['data'],validate=True)
|
|
93
|
+
if len(data) > 65536: raise ValueError('frame limit')
|
|
94
|
+
writer.write(data); await asyncio.wait_for(writer.drain(),10)
|
|
95
|
+
elif frame['op'] in ('error','end','close'):
|
|
96
|
+
if not opened.done(): opened.set_exception(ConnectionError('network unavailable'))
|
|
97
|
+
writer.close()
|
|
98
|
+
|
|
99
|
+
def close(self):
|
|
100
|
+
for writer, opened in list(self.streams.values()):
|
|
101
|
+
if not opened.done(): opened.cancel()
|
|
102
|
+
writer.close()
|
|
103
|
+
self.streams.clear()
|
|
104
|
+
|
|
105
|
+
class DNSProtocol(asyncio.DatagramProtocol):
|
|
106
|
+
def __init__(self, tunnel): self.tunnel=tunnel
|
|
107
|
+
def connection_made(self, transport): self.transport=transport
|
|
108
|
+
def datagram_received(self, data, addr):
|
|
109
|
+
with contextlib.suppress(Exception): self.transport.sendto(self.tunnel.dns(data),addr)
|
|
110
|
+
|
|
111
|
+
async def main():
|
|
112
|
+
tun_process = None
|
|
113
|
+
# This container has no workspace mounts or business processes.
|
|
114
|
+
if '--init' in sys.argv:
|
|
115
|
+
subprocess.run(['ip','tuntap','add','mode','tun','dev','tun0'],check=True)
|
|
116
|
+
subprocess.run(['ip','addr','add',DNS+'/15','dev','tun0'],check=True)
|
|
117
|
+
subprocess.run(['ip','link','set','tun0','up'],check=True)
|
|
118
|
+
subprocess.run(['ip','route','add','default','dev','tun0'],check=True)
|
|
119
|
+
argv=['tun2socks','--device','tun0','--proxy','socks5://127.0.0.1:'+str(SOCKS),'--loglevel','error']
|
|
120
|
+
if '--socket' not in sys.argv: os.execvp('tun2socks',argv)
|
|
121
|
+
tun_process=subprocess.Popen(argv,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
|
122
|
+
loop=asyncio.get_running_loop()
|
|
123
|
+
queue=asyncio.Queue(maxsize=128)
|
|
124
|
+
async def send(frame): await asyncio.wait_for(queue.put(frame),10)
|
|
125
|
+
tunnel=Tunnel(send)
|
|
126
|
+
tcp=await asyncio.start_server(tunnel.socks,'127.0.0.1',SOCKS)
|
|
127
|
+
dns,_=await loop.create_datagram_endpoint(lambda:DNSProtocol(tunnel),local_addr=(DNS,53))
|
|
128
|
+
async def dns_tcp(reader,writer):
|
|
129
|
+
try:
|
|
130
|
+
while True:
|
|
131
|
+
length=struct.unpack('!H',await reader.readexactly(2))[0]
|
|
132
|
+
answer=tunnel.dns(await reader.readexactly(length))
|
|
133
|
+
writer.write(struct.pack('!H',len(answer))+answer);await writer.drain()
|
|
134
|
+
except Exception: pass
|
|
135
|
+
finally: writer.close()
|
|
136
|
+
dns_server=await asyncio.start_server(dns_tcp,DNS,53)
|
|
137
|
+
try:
|
|
138
|
+
if '--socket' not in sys.argv:
|
|
139
|
+
transport,protocol=await loop.connect_write_pipe(asyncio.streams.FlowControlMixin,sys.stdout.buffer)
|
|
140
|
+
wire=asyncio.StreamWriter(transport,protocol,None,loop)
|
|
141
|
+
incoming=asyncio.StreamReader(limit=200000);await loop.connect_read_pipe(lambda:asyncio.StreamReaderProtocol(incoming),sys.stdin.buffer)
|
|
142
|
+
async def output():
|
|
143
|
+
while True: wire.write((json.dumps(await queue.get())+'\n').encode());await wire.drain()
|
|
144
|
+
task=asyncio.create_task(output());await send({'op':'ready','port':SOCKS})
|
|
145
|
+
try:
|
|
146
|
+
while True:
|
|
147
|
+
line=await incoming.readline()
|
|
148
|
+
if not line: break
|
|
149
|
+
await tunnel.receive(json.loads(line))
|
|
150
|
+
finally: task.cancel();wire.close()
|
|
151
|
+
else:
|
|
152
|
+
path=Path('/run/yaoyao-network/gateway.sock');path.parent.mkdir(parents=True,exist_ok=True)
|
|
153
|
+
path.unlink(missing_ok=True)
|
|
154
|
+
token=None;last_seen=0
|
|
155
|
+
async def http(reader,writer):
|
|
156
|
+
nonlocal token,last_seen
|
|
157
|
+
try:
|
|
158
|
+
header=await asyncio.wait_for(reader.readuntil(b'\r\n\r\n'),10)
|
|
159
|
+
lines=header.decode('ascii').split('\r\n');op=lines[0].split(' ')[1].removeprefix('/network-')
|
|
160
|
+
length=int(next(line.split(':',1)[1] for line in lines[1:] if line.lower().startswith('content-length:')))
|
|
161
|
+
if not 0<=length<=4*1024*1024: raise ValueError('limit')
|
|
162
|
+
body=json.loads(await reader.readexactly(length))
|
|
163
|
+
if body.get('desktopId')!=os.environ['YAOYAO_COMPOSE_DESKTOP_ID']: raise ValueError('identity')
|
|
164
|
+
if op=='health': result={'ready':Path('/sys/class/net/tun0').exists() and (tun_process is None or tun_process.poll() is None),'version':1}
|
|
165
|
+
elif op=='open':
|
|
166
|
+
if token and time.monotonic()-last_seen<30: raise ValueError('busy')
|
|
167
|
+
tunnel.close()
|
|
168
|
+
while not queue.empty(): queue.get_nowait()
|
|
169
|
+
token=secrets.token_hex(32);result={'token':token,'ready':True}
|
|
170
|
+
else:
|
|
171
|
+
if not token or not secrets.compare_digest(str(body.get('token','')),token): raise ValueError('token')
|
|
172
|
+
if op=='close': tunnel.close();token=None;result={'ok':True}
|
|
173
|
+
elif op=='exchange':
|
|
174
|
+
for frame in body.get('frames',[]): await tunnel.receive(frame)
|
|
175
|
+
frames=[]
|
|
176
|
+
if queue.empty():
|
|
177
|
+
with contextlib.suppress(asyncio.TimeoutError): frames.append(await asyncio.wait_for(queue.get(),1))
|
|
178
|
+
while not queue.empty() and len(frames)<32: frames.append(queue.get_nowait())
|
|
179
|
+
result={'frames':frames}
|
|
180
|
+
else: raise ValueError('operation')
|
|
181
|
+
last_seen=time.monotonic()
|
|
182
|
+
data=json.dumps(result).encode();status='200 OK'
|
|
183
|
+
except Exception: data=b'{"error":"network gateway unavailable"}';status='409 Conflict'
|
|
184
|
+
writer.write(('HTTP/1.1 '+status+'\r\nContent-Type: application/json\r\nx-yaoyao-desktop-id: '+os.environ['YAOYAO_COMPOSE_DESKTOP_ID']+'\r\nContent-Length: '+str(len(data))+'\r\nConnection: close\r\n\r\n').encode()+data)
|
|
185
|
+
with contextlib.suppress(Exception): await writer.drain()
|
|
186
|
+
writer.close()
|
|
187
|
+
async def watchdog():
|
|
188
|
+
nonlocal token
|
|
189
|
+
while True:
|
|
190
|
+
await asyncio.sleep(5)
|
|
191
|
+
if tun_process is not None and tun_process.poll() is not None: raise RuntimeError('TUN process stopped')
|
|
192
|
+
if token and time.monotonic()-last_seen>30: tunnel.close();token=None
|
|
193
|
+
server=await asyncio.start_unix_server(http,str(path));os.chmod(path,0o666)
|
|
194
|
+
async with server: await asyncio.gather(server.serve_forever(),watchdog())
|
|
195
|
+
finally: tcp.close();dns.close();dns_server.close();tunnel.close()
|
|
196
|
+
|
|
197
|
+
if __name__=='__main__': asyncio.run(main())
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
set -eu
|
|
3
|
+
profiles=/home/cua/workspace/.browser-profiles/firefox
|
|
4
|
+
mkdir -p "$profiles"
|
|
5
|
+
chmod 0700 "$profiles" 2>/dev/null || test -w "$profiles"
|
|
6
|
+
if [ -d "$HOME/.mozilla" ] && [ ! -L "$HOME/.mozilla" ] && [ -z "$(ls -A "$profiles")" ]; then
|
|
7
|
+
cp -a "$HOME/.mozilla/." "$profiles/"
|
|
8
|
+
fi
|
|
9
|
+
rm -rf "$HOME/.mozilla"
|
|
10
|
+
ln -s "$profiles" "$HOME/.mozilla"
|
|
11
|
+
find "$profiles" \( -name .parentlock -o -name parent.lock -o -name lock \) -delete
|