codis 1.1.1__py3-none-any.whl
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.
- codis-1.1.1.dist-info/METADATA +194 -0
- codis-1.1.1.dist-info/RECORD +329 -0
- codis-1.1.1.dist-info/WHEEL +5 -0
- codis-1.1.1.dist-info/entry_points.txt +5 -0
- codis-1.1.1.dist-info/licenses/LICENSE +21 -0
- codis-1.1.1.dist-info/top_level.txt +2 -0
- run.py +190 -0
- src/__init__.py +1 -0
- src/__main__.py +81 -0
- src/_app_build.py +1507 -0
- src/_app_editor.py +1274 -0
- src/_app_kui.py +825 -0
- src/_app_lsp.py +625 -0
- src/_app_recovery.py +189 -0
- src/_app_settings.py +1385 -0
- src/_app_tools.py +2471 -0
- src/_app_webpreview.py +126 -0
- src/_font_safety.py +127 -0
- src/_shells.py +172 -0
- src/app.py +1488 -0
- src/chat/__init__.py +1 -0
- src/chat/adapters/__init__.py +33 -0
- src/chat/adapters/base.py +209 -0
- src/chat/adapters/discord.py +190 -0
- src/chat/adapters/http.py +78 -0
- src/chat/adapters/irc.py +360 -0
- src/chat/adapters/matrix.py +219 -0
- src/chat/adapters/mattermost.py +178 -0
- src/chat/adapters/mqtt.py +165 -0
- src/chat/adapters/slack.py +204 -0
- src/chat/adapters/telegram.py +117 -0
- src/chat/adapters/ws.py +154 -0
- src/chat/adapters/xmpp.py +337 -0
- src/chat/history.py +76 -0
- src/chat/models.py +207 -0
- src/chat/probe.py +79 -0
- src/chat/session.py +446 -0
- src/chat/util.py +125 -0
- src/collab/__init__.py +1 -0
- src/collab/net.py +411 -0
- src/collab/ot.py +311 -0
- src/collab/session.py +141 -0
- src/collab/tk_adapter.py +134 -0
- src/config.py +335 -0
- src/constants.py +2552 -0
- src/dep_catalog.py +446 -0
- src/diff/__init__.py +1 -0
- src/diff/engine.py +247 -0
- src/dpi.py +30 -0
- src/editor/__init__.py +1 -0
- src/editor/_pane_lsp.py +2937 -0
- src/editor/_pane_utils.py +171 -0
- src/editor/autocomplete.py +607 -0
- src/editor/code_folding.py +836 -0
- src/editor/color_preview.py +382 -0
- src/editor/complexity_lens.py +281 -0
- src/editor/diff_pane.py +623 -0
- src/editor/file_watcher.py +144 -0
- src/editor/focus_block.py +236 -0
- src/editor/heatmap.py +141 -0
- src/editor/inlay_hints.py +366 -0
- src/editor/inline_blame.py +429 -0
- src/editor/kdocs.py +3376 -0
- src/editor/large_file.py +488 -0
- src/editor/ligatures.py +180 -0
- src/editor/line_numbers.py +598 -0
- src/editor/minimap.py +691 -0
- src/editor/multi_cursor.py +269 -0
- src/editor/pane.py +2082 -0
- src/editor/rhythm.py +206 -0
- src/editor/save_hooks.py +43 -0
- src/editor/smart_selection.py +425 -0
- src/editor/smart_tips.py +719 -0
- src/editor/snippets.py +411 -0
- src/editor/sticky_note_gutter.py +410 -0
- src/editor/sticky_scroll.py +385 -0
- src/editor/suggest.py +464 -0
- src/editor/text_transforms.py +310 -0
- src/editor/vim_mode.py +1074 -0
- src/events/__init__.py +84 -0
- src/events/bus.py +427 -0
- src/events/correlator.py +244 -0
- src/events/kinds.py +125 -0
- src/events/pipeline.py +264 -0
- src/events/stream.py +416 -0
- src/events/window.py +204 -0
- src/extcompat/__init__.py +19 -0
- src/extcompat/code/__init__.py +13 -0
- src/extcompat/code/consent.py +162 -0
- src/extcompat/code/host.py +353 -0
- src/extcompat/code/hosts/py_host.py +763 -0
- src/extcompat/code/locate.py +105 -0
- src/extcompat/code/manager.py +325 -0
- src/extcompat/code/permissions.py +154 -0
- src/extcompat/code/sandbox.py +60 -0
- src/extcompat/colors.py +131 -0
- src/extcompat/common.py +184 -0
- src/extcompat/cson.py +269 -0
- src/extcompat/formats/__init__.py +22 -0
- src/extcompat/formats/_tm.py +189 -0
- src/extcompat/formats/_util.py +31 -0
- src/extcompat/formats/base16.py +66 -0
- src/extcompat/formats/brackets.py +172 -0
- src/extcompat/formats/eclipse.py +193 -0
- src/extcompat/formats/emacs.py +361 -0
- src/extcompat/formats/geany.py +147 -0
- src/extcompat/formats/generic.py +184 -0
- src/extcompat/formats/gtksource.py +117 -0
- src/extcompat/formats/helix.py +91 -0
- src/extcompat/formats/jetbrains.py +343 -0
- src/extcompat/formats/kate.py +130 -0
- src/extcompat/formats/micro.py +131 -0
- src/extcompat/formats/nano.py +111 -0
- src/extcompat/formats/notepadpp.py +140 -0
- src/extcompat/formats/pulsar.py +165 -0
- src/extcompat/formats/pyides.py +163 -0
- src/extcompat/formats/sublime.py +340 -0
- src/extcompat/jsonc.py +65 -0
- src/extcompat/lessish.py +128 -0
- src/extcompat/manager.py +122 -0
- src/extcompat/market/__init__.py +63 -0
- src/extcompat/market/sources.py +211 -0
- src/extcompat/model.py +88 -0
- src/extcompat/net.py +228 -0
- src/extcompat/openvsx.py +63 -0
- src/extcompat/readers.py +362 -0
- src/extcompat/registry.py +73 -0
- src/extcompat/safexml.py +63 -0
- src/extcompat/sexp.py +187 -0
- src/extcompat/sources.py +105 -0
- src/extcompat/store.py +276 -0
- src/extcompat/textmate.py +214 -0
- src/extcompat/themes.py +487 -0
- src/extcompat/yamlite.py +294 -0
- src/fileio.py +94 -0
- src/fs_ops.py +106 -0
- src/i18n.py +233 -0
- src/ia/__init__.py +1 -0
- src/ia/actions.py +295 -0
- src/ia/approval_gate.py +672 -0
- src/ia/checkpoints.py +308 -0
- src/ia/context_builder.py +921 -0
- src/ia/dialdiff.py +408 -0
- src/ia/iaspace.py +2078 -0
- src/ia/pair.py +296 -0
- src/ia/providers.py +954 -0
- src/ia/session.py +335 -0
- src/ia/toolbox.py +2524 -0
- src/launcher_actions.py +204 -0
- src/lint/__init__.py +1 -0
- src/lint/manager.py +1058 -0
- src/locales/.translate_manifest.json +64170 -0
- src/locales/de.json +4936 -0
- src/locales/en.json +4936 -0
- src/locales/es.json +4936 -0
- src/locales/fr.json +4936 -0
- src/locales/it.json +4936 -0
- src/locales/ja.json +4936 -0
- src/locales/ko.json +4936 -0
- src/locales/nl.json +4936 -0
- src/locales/pl.json +4936 -0
- src/locales/pt-BR.json +4936 -0
- src/locales/ru.json +4936 -0
- src/locales/tr.json +4936 -0
- src/locales/uk.json +4936 -0
- src/locales/zh-CN.json +4936 -0
- src/lsp/__init__.py +26 -0
- src/lsp/client.py +2300 -0
- src/lsp/dap_client.py +480 -0
- src/lsp/edits.py +84 -0
- src/lsp/framing.py +73 -0
- src/lsp/protocol.py +931 -0
- src/main.py +260 -0
- src/memtrim.py +91 -0
- src/plugins/__init__.py +1 -0
- src/plugins/api.py +1761 -0
- src/plugins/loader.py +571 -0
- src/plugins/process_runner.py +519 -0
- src/plugins/registry.py +342 -0
- src/plugins/safety.py +367 -0
- src/plugins/startup.py +195 -0
- src/plugins/store.py +1178 -0
- src/proc_registry.py +278 -0
- src/pyexec.py +394 -0
- src/recovery.py +259 -0
- src/stall_trace.py +92 -0
- src/standalone.py +1070 -0
- src/startup_profile.py +35 -0
- src/syntax/__init__.py +1 -0
- src/syntax/highlighter.py +776 -0
- src/syntax/patterns.py +584 -0
- src/system_profile.py +430 -0
- src/terminal/backends.py +658 -0
- src/terminal/internal.py +346 -0
- src/terminal/keys.py +138 -0
- src/terminal/palette.py +67 -0
- src/terminal/session.py +283 -0
- src/terminal/shells.py +79 -0
- src/terminal/view.py +489 -0
- src/terminal/vt.py +870 -0
- src/textfmt.py +22 -0
- src/theme/__init__.py +1 -0
- src/theme/base.py +1281 -0
- src/theme/colors.py +49 -0
- src/theme/manager.py +602 -0
- src/theme/utils.py +312 -0
- src/toolbox.py +329 -0
- src/trash_core.py +531 -0
- src/ui/__init__.py +1 -0
- src/ui/_perf_utils.py +285 -0
- src/ui/_persistence_utils.py +93 -0
- src/ui/accessibility.py +843 -0
- src/ui/activity_bar.py +860 -0
- src/ui/app_embed.py +434 -0
- src/ui/archive_panel.py +608 -0
- src/ui/bookmarks.py +314 -0
- src/ui/breadcrumb.py +383 -0
- src/ui/calculator_panel.py +982 -0
- src/ui/calendar_panel.py +1218 -0
- src/ui/chat_panel.py +1271 -0
- src/ui/chat_profile_dialog.py +278 -0
- src/ui/chat_render.py +128 -0
- src/ui/clock_panel.py +810 -0
- src/ui/code_outline.py +364 -0
- src/ui/code_runner.py +729 -0
- src/ui/code_stats.py +546 -0
- src/ui/collab_panel.py +1009 -0
- src/ui/color_picker.py +547 -0
- src/ui/command_palette.py +452 -0
- src/ui/cursor_manager.py +750 -0
- src/ui/custom_keywords_panel.py +413 -0
- src/ui/debug_panel.py +1037 -0
- src/ui/dependency_graph.py +692 -0
- src/ui/diff_panel.py +381 -0
- src/ui/docs_panel.py +514 -0
- src/ui/doom_embed.py +349 -0
- src/ui/dropdown.py +321 -0
- src/ui/easter_eggs.py +979 -0
- src/ui/env_manager.py +666 -0
- src/ui/extcode_bridge.py +215 -0
- src/ui/extcode_dialogs.py +412 -0
- src/ui/extcompat_dialog.py +583 -0
- src/ui/file_timeline.py +319 -0
- src/ui/file_tree.py +1208 -0
- src/ui/find_in_files.py +1355 -0
- src/ui/flowchart_panel.py +727 -0
- src/ui/formatter_panel.py +490 -0
- src/ui/git_auth.py +763 -0
- src/ui/git_clone_dialog.py +487 -0
- src/ui/git_panel.py +1483 -0
- src/ui/grab_safe.py +84 -0
- src/ui/internal_python_dialog.py +98 -0
- src/ui/k_ui/__init__.py +1305 -0
- src/ui/k_ui/_bgrenderer.py +317 -0
- src/ui/k_ui/_colors.py +213 -0
- src/ui/k_ui/_dock.py +545 -0
- src/ui/k_ui/_easter.py +290 -0
- src/ui/k_ui/_engine.py +5448 -0
- src/ui/k_ui/_perf.py +333 -0
- src/ui/k_ui/_tkutil.py +7 -0
- src/ui/k_ui/_tooltip.py +365 -0
- src/ui/k_ui/_widgets.py +1204 -0
- src/ui/k_ui/_world.py +837 -0
- src/ui/key_remapper.py +856 -0
- src/ui/launcher.py +1252 -0
- src/ui/lazy_panel.py +73 -0
- src/ui/macro_recorder.py +610 -0
- src/ui/menu_bar.py +898 -0
- src/ui/output_panel.py +321 -0
- src/ui/paint_canvas.py +1000 -0
- src/ui/paint_engine.py +535 -0
- src/ui/paint_panel.py +888 -0
- src/ui/panel_detach.py +112 -0
- src/ui/performance_panel.py +861 -0
- src/ui/pip_manager.py +1758 -0
- src/ui/plugin_panel.py +1586 -0
- src/ui/pomodoro_panel.py +447 -0
- src/ui/problems.py +566 -0
- src/ui/process_manager.py +1657 -0
- src/ui/project_templates.py +775 -0
- src/ui/recovery_dialog.py +122 -0
- src/ui/regex_playground.py +304 -0
- src/ui/remote_adapters.py +1398 -0
- src/ui/remote_browser.py +1224 -0
- src/ui/remote_profile_dialog.py +342 -0
- src/ui/render_panel.py +1293 -0
- src/ui/rest_client.py +549 -0
- src/ui/scratchpad.py +548 -0
- src/ui/search_bar.py +1274 -0
- src/ui/settings_editor.py +3349 -0
- src/ui/settings_window.py +1554 -0
- src/ui/snippets_panel.py +597 -0
- src/ui/sql_studio.py +1815 -0
- src/ui/status_bar.py +438 -0
- src/ui/tab_bar.py +654 -0
- src/ui/task_manager.py +1773 -0
- src/ui/terminal.py +525 -0
- src/ui/theme_preview_panel.py +851 -0
- src/ui/thread_safe_tk.py +152 -0
- src/ui/time_tracker.py +574 -0
- src/ui/tkbind.py +43 -0
- src/ui/todo_panel.py +358 -0
- src/ui/toolbox_panels.py +658 -0
- src/ui/trash_manager.py +657 -0
- src/ui/ui_scale.py +294 -0
- src/ui/ux_enhancements.py +41 -0
- src/ui/web_preview.py +397 -0
- src/ui/webdev.py +630 -0
- src/ui/welcome.py +567 -0
- src/ui/window_embed.py +1500 -0
- src/ui/wizard.py +1550 -0
- src/ui/workspace_switcher.py +418 -0
- src/ui/workspace_trust.py +370 -0
- src/ui/zen_audio.py +354 -0
- src/ui/zen_media.py +2271 -0
- src/ui/zen_media_client.py +303 -0
- src/ui/zen_media_host.py +329 -0
- src/ui/zen_player.py +907 -0
- src/ui/zen_player_widgets.py +700 -0
- src/updater/__init__.py +11 -0
- src/updater/assets.py +145 -0
- src/updater/backup.py +101 -0
- src/updater/channel.py +221 -0
- src/updater/dialog.py +492 -0
- src/updater/integrity.py +111 -0
- src/updater/manager.py +727 -0
- src/updater/result.py +114 -0
- src/venv_runtime.py +531 -0
- src/workspace_state.py +25 -0
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Localiza os runtimes externos (Node, Python) que executam o código das extensões."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import functools
|
|
6
|
+
import re
|
|
7
|
+
import shutil
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
PROBE_TIMEOUT = 8
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class RuntimeInfo:
|
|
18
|
+
kind: str # "node" ou "python"
|
|
19
|
+
path: str
|
|
20
|
+
version: str
|
|
21
|
+
# Flag de isolamento que este runtime aceita (modelo de permissões do Node 20+).
|
|
22
|
+
isolation: tuple[str, ...] = ()
|
|
23
|
+
# Por que o isolamento foi desligado (o autoteste do runtime falhou com ele), se for o caso.
|
|
24
|
+
note: str = ""
|
|
25
|
+
# Flags ``--allow-*`` que este Node aceita junto do modelo de permissões.
|
|
26
|
+
allows: tuple[str, ...] = ()
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def isolated(self) -> bool:
|
|
30
|
+
return bool(self.isolation)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _run(cmd: list[str]) -> subprocess.CompletedProcess[str] | None:
|
|
34
|
+
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
|
35
|
+
try:
|
|
36
|
+
return subprocess.run( # noqa: S603 - executável escolhido pelo usuário, sem shell
|
|
37
|
+
cmd, capture_output=True, text=True, timeout=PROBE_TIMEOUT, creationflags=flags, check=False
|
|
38
|
+
)
|
|
39
|
+
except (OSError, subprocess.SubprocessError):
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _version(path: str, pattern: str) -> tuple[int, ...] | None:
|
|
44
|
+
done = _run([path, "--version"])
|
|
45
|
+
if done is None or done.returncode != 0:
|
|
46
|
+
return None
|
|
47
|
+
m = re.search(pattern, done.stdout + done.stderr)
|
|
48
|
+
return tuple(int(x) for x in m.groups()) if m else None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@functools.lru_cache(maxsize=16)
|
|
52
|
+
def _permission_flag(node: str) -> str | None:
|
|
53
|
+
"""Flag do modelo de permissões do Node (``--permission`` desde a v23, experimental antes)."""
|
|
54
|
+
for flag in ("--permission", "--experimental-permission"):
|
|
55
|
+
done = _run([node, flag, "-e", "0"])
|
|
56
|
+
if done is not None and done.returncode == 0:
|
|
57
|
+
return flag
|
|
58
|
+
return None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
_ALLOW_FLAGS = ("--allow-child-process", "--allow-worker", "--allow-addons")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@functools.lru_cache(maxsize=16)
|
|
65
|
+
def _allow_flags(node: str, permission_flag: str) -> tuple[str, ...]:
|
|
66
|
+
"""Quais ``--allow-*`` o Node aceita; versões mais antigas do modelo de permissões não têm todas."""
|
|
67
|
+
ok = []
|
|
68
|
+
for flag in _ALLOW_FLAGS:
|
|
69
|
+
done = _run([node, permission_flag, flag, "-e", "0"])
|
|
70
|
+
if done is not None and done.returncode == 0:
|
|
71
|
+
ok.append(flag)
|
|
72
|
+
return tuple(ok)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _candidates(kind: str, configured: str | None) -> list[str]:
|
|
76
|
+
found: list[str] = [configured] if configured else []
|
|
77
|
+
if kind == "node":
|
|
78
|
+
found += [shutil.which(n) or "" for n in ("node", "node.exe")]
|
|
79
|
+
else:
|
|
80
|
+
if not getattr(sys, "frozen", False):
|
|
81
|
+
found.append(sys.executable)
|
|
82
|
+
found += [shutil.which(n) or "" for n in ("python3", "python", "python.exe")]
|
|
83
|
+
return [c for c in dict.fromkeys(found) if c]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def find(kind: str, configured: str | None = None) -> RuntimeInfo | None:
|
|
87
|
+
"""Primeiro executável utilizável do tipo pedido, ou ``None``.
|
|
88
|
+
|
|
89
|
+
``configured`` (escolhido pelo usuário) tem prioridade. Node precisa ser 18 ou mais novo e
|
|
90
|
+
Python 3.8 ou mais novo.
|
|
91
|
+
"""
|
|
92
|
+
for cand in _candidates(kind, configured):
|
|
93
|
+
if not Path(cand).is_file():
|
|
94
|
+
continue
|
|
95
|
+
if kind == "node":
|
|
96
|
+
ver = _version(cand, r"v?(\d+)\.(\d+)")
|
|
97
|
+
if ver is None or ver[0] < 18:
|
|
98
|
+
continue
|
|
99
|
+
flag = _permission_flag(cand) if ver[0] >= 20 else None
|
|
100
|
+
allows = _allow_flags(cand, flag) if flag else ()
|
|
101
|
+
return RuntimeInfo("node", cand, f"{ver[0]}.{ver[1]}", (flag,) if flag else (), allows=allows)
|
|
102
|
+
ver = _version(cand, r"Python (\d+)\.(\d+)")
|
|
103
|
+
if ver is not None and ver >= (3, 8):
|
|
104
|
+
return RuntimeInfo("python", cand, f"{ver[0]}.{ver[1]}", ("-I", "-B"))
|
|
105
|
+
return None
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
"""Coordena a execução de código das extensões: confirmações, runtimes, processos e comandos na paleta."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
import logging
|
|
7
|
+
import tempfile
|
|
8
|
+
import threading
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, Protocol
|
|
13
|
+
|
|
14
|
+
from ..model import Extension
|
|
15
|
+
from ..store import ExtensionStore
|
|
16
|
+
from . import consent, locate, permissions, sandbox
|
|
17
|
+
from .host import ExtensionHost, HostError, HostSpec
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger("Codis")
|
|
20
|
+
|
|
21
|
+
HOSTS_DIR = Path(__file__).parent / "hosts"
|
|
22
|
+
_HOST_FILES = {"node": "node_host.js", "python": "py_host.py"}
|
|
23
|
+
RUNTIME_LABEL = {"node": "Node.js", "python": "Python"}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class CodeBridge(Protocol):
|
|
27
|
+
"""O que a interface oferece ao código da extensão. Os métodos rodam em threads de apoio."""
|
|
28
|
+
|
|
29
|
+
def context(self) -> dict[str, Any]: ...
|
|
30
|
+
|
|
31
|
+
def request(self, ext_id: str, op: str, payload: dict[str, Any]) -> Any: ...
|
|
32
|
+
|
|
33
|
+
def event(self, ext_id: str, op: str, payload: dict[str, Any]) -> None: ...
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class CommandSink(Protocol):
|
|
37
|
+
def add(self, owner: str, cmd_id: str, label: str, category: str, handler: Callable[[], Any]) -> None: ...
|
|
38
|
+
|
|
39
|
+
def remove(self, owner: str) -> None: ...
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class RuntimeCheck:
|
|
44
|
+
"""Resultado do autoteste de um runtime: o que de fato vale (talvez sem isolamento) e o problema, se houver."""
|
|
45
|
+
|
|
46
|
+
runtime: locate.RuntimeInfo
|
|
47
|
+
problem: str = ""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class CodeStatus:
|
|
52
|
+
state: str # none, off, no_runtime, unconfirmed, changed, ready, active, running
|
|
53
|
+
text: str
|
|
54
|
+
runtime: locate.RuntimeInfo | None = None
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def can_confirm(self) -> bool:
|
|
58
|
+
return self.state in ("unconfirmed", "changed")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class CodeManager:
|
|
62
|
+
def __init__(
|
|
63
|
+
self,
|
|
64
|
+
state: consent.CodeState,
|
|
65
|
+
store: ExtensionStore,
|
|
66
|
+
sink: CommandSink,
|
|
67
|
+
bridge: CodeBridge,
|
|
68
|
+
data_root: Path | None = None,
|
|
69
|
+
) -> None:
|
|
70
|
+
self.state = state
|
|
71
|
+
self.store = store
|
|
72
|
+
self.sink = sink
|
|
73
|
+
self.bridge = bridge
|
|
74
|
+
self.data_root = data_root or store.root.parent / "extension_data"
|
|
75
|
+
self._hosts: dict[str, ExtensionHost] = {}
|
|
76
|
+
self._locks: dict[str, threading.Lock] = {}
|
|
77
|
+
self._last_output: dict[str, list[str]] = {}
|
|
78
|
+
self._checks: dict[str, RuntimeCheck] = {}
|
|
79
|
+
self._guard = threading.Lock()
|
|
80
|
+
|
|
81
|
+
# --- consulta ------------------------------------------------------------------------
|
|
82
|
+
|
|
83
|
+
def runtime_for(self, ext: Extension) -> locate.RuntimeInfo | None:
|
|
84
|
+
if ext.code is None:
|
|
85
|
+
return None
|
|
86
|
+
return locate.find(ext.code.runtime, self.state.runtime_path(ext.code.runtime))
|
|
87
|
+
|
|
88
|
+
def fingerprint(self, ext: Extension) -> tuple[str, int, int] | None:
|
|
89
|
+
return consent.fingerprint(ext.path)
|
|
90
|
+
|
|
91
|
+
def permissions(self, ext: Extension) -> frozenset[str]:
|
|
92
|
+
return self.state.permissions(ext.id)
|
|
93
|
+
|
|
94
|
+
def launch_plan(self, runtime: locate.RuntimeInfo, granted: frozenset[str]) -> sandbox.LaunchPlan:
|
|
95
|
+
"""O que o runtime vai impor a uma extensão com estas permissões (para avisar antes de confirmar)."""
|
|
96
|
+
return sandbox.plan(runtime, granted)
|
|
97
|
+
|
|
98
|
+
def status(self, ext: Extension) -> CodeStatus:
|
|
99
|
+
if ext.code is None:
|
|
100
|
+
return CodeStatus("none", "sem código executável")
|
|
101
|
+
label = RUNTIME_LABEL.get(ext.code.runtime, ext.code.runtime)
|
|
102
|
+
if not self.state.enabled:
|
|
103
|
+
return CodeStatus("off", "execução de código desligada")
|
|
104
|
+
runtime = self.runtime_for(ext)
|
|
105
|
+
if runtime is None:
|
|
106
|
+
return CodeStatus("no_runtime", f"{label} não encontrado (escolha o executável)")
|
|
107
|
+
digest = self.fingerprint(ext)
|
|
108
|
+
if digest is None:
|
|
109
|
+
return CodeStatus("changed", "código grande demais para auditar; recusado", runtime)
|
|
110
|
+
if not self.state.granted(ext.id, digest[0]):
|
|
111
|
+
known = ext.id in self.state._data["extensions"]
|
|
112
|
+
return CodeStatus("changed" if known else "unconfirmed",
|
|
113
|
+
"o código mudou desde a sua confirmação" if known else "aguardando a sua confirmação", runtime)
|
|
114
|
+
host = self._hosts.get(ext.id)
|
|
115
|
+
if host is not None and host.alive:
|
|
116
|
+
return CodeStatus("running", f"em execução ({label} {runtime.version})", runtime)
|
|
117
|
+
if self.state.active(ext.id):
|
|
118
|
+
return CodeStatus("active", f"ativo, inicia ao usar um comando ({label} {runtime.version})", runtime)
|
|
119
|
+
return CodeStatus("ready", f"confirmado, mas desligado ({label} {runtime.version})", runtime)
|
|
120
|
+
|
|
121
|
+
def output(self, ext_id: str) -> list[str]:
|
|
122
|
+
host = self._hosts.get(ext_id)
|
|
123
|
+
return list(host.output) if host is not None else list(self._last_output.get(ext_id, []))
|
|
124
|
+
|
|
125
|
+
# --- confirmação e ativação ------------------------------------------------------------
|
|
126
|
+
|
|
127
|
+
def confirm(self, ext: Extension, granted: frozenset[str] | set[str] = frozenset()) -> None:
|
|
128
|
+
"""Registra a confirmação do usuário e as permissões extras (a interface já exibiu os avisos e conferiu as frases).
|
|
129
|
+
|
|
130
|
+
Se as permissões mudaram, o processo em execução é encerrado: ele sobe de novo, já com as novas, no próximo comando.
|
|
131
|
+
"""
|
|
132
|
+
digest = self.fingerprint(ext)
|
|
133
|
+
if digest is None:
|
|
134
|
+
raise HostError("o código é grande demais para ser auditado")
|
|
135
|
+
wanted = permissions.parse(granted)
|
|
136
|
+
changed = wanted != self.state.permissions(ext.id)
|
|
137
|
+
self.state.grant(ext.id, digest[0], ext.version, wanted)
|
|
138
|
+
if changed:
|
|
139
|
+
self._stop_host(ext.id)
|
|
140
|
+
|
|
141
|
+
def activate(self, ext: Extension) -> None:
|
|
142
|
+
status = self.status(ext)
|
|
143
|
+
if status.state not in ("ready", "active", "running"):
|
|
144
|
+
raise HostError(status.text)
|
|
145
|
+
assert ext.code is not None
|
|
146
|
+
self._register_commands(ext)
|
|
147
|
+
self.state.set_active(ext.id, True)
|
|
148
|
+
|
|
149
|
+
def deactivate(self, ext_id: str) -> None:
|
|
150
|
+
self._stop_host(ext_id)
|
|
151
|
+
self.sink.remove(f"ext:{ext_id}")
|
|
152
|
+
self.state.set_active(ext_id, False)
|
|
153
|
+
|
|
154
|
+
def revoke(self, ext_id: str) -> None:
|
|
155
|
+
self.deactivate(ext_id)
|
|
156
|
+
self.state.revoke(ext_id)
|
|
157
|
+
|
|
158
|
+
def forget(self, ext_id: str) -> None:
|
|
159
|
+
"""Extensão removida: pára o processo e apaga a confirmação."""
|
|
160
|
+
self.revoke(ext_id)
|
|
161
|
+
|
|
162
|
+
def restore(self) -> list[str]:
|
|
163
|
+
"""Na abertura do Codis: recoloca na paleta os comandos das extensões ativas e ainda confirmadas.
|
|
164
|
+
|
|
165
|
+
Nenhum processo é iniciado aqui; isso só acontece quando o usuário usa um comando.
|
|
166
|
+
"""
|
|
167
|
+
restored = []
|
|
168
|
+
if not self.state.enabled:
|
|
169
|
+
return restored
|
|
170
|
+
by_id = {e.id: e for e in self.store.installed()}
|
|
171
|
+
for ext_id in self.state.active_ids():
|
|
172
|
+
ext = by_id.get(ext_id)
|
|
173
|
+
if ext is None or ext.code is None:
|
|
174
|
+
continue
|
|
175
|
+
if self.status(ext).state in ("ready", "active"):
|
|
176
|
+
self._register_commands(ext)
|
|
177
|
+
restored.append(ext_id)
|
|
178
|
+
return restored
|
|
179
|
+
|
|
180
|
+
def _register_commands(self, ext: Extension) -> None:
|
|
181
|
+
owner = f"ext:{ext.id}"
|
|
182
|
+
self.sink.remove(owner)
|
|
183
|
+
assert ext.code is not None
|
|
184
|
+
for cmd in ext.code.commands:
|
|
185
|
+
cmd_id = f"ext.{ext.id}.{cmd.id}"
|
|
186
|
+
self.sink.add(owner, cmd_id, cmd.title, cmd.category or ext.name, self._handler(ext, cmd.id, cmd.args))
|
|
187
|
+
|
|
188
|
+
def _handler(self, ext: Extension, command: str, args: dict[str, Any]) -> Callable[[], Any]:
|
|
189
|
+
def run() -> None:
|
|
190
|
+
threading.Thread(target=self._run_safely, args=(ext, command, args), daemon=True, name=f"ext-cmd-{ext.id}").start()
|
|
191
|
+
|
|
192
|
+
return run
|
|
193
|
+
|
|
194
|
+
def _run_safely(self, ext: Extension, command: str, args: dict[str, Any]) -> None:
|
|
195
|
+
try:
|
|
196
|
+
self.run(ext, command, args)
|
|
197
|
+
except HostError as exc:
|
|
198
|
+
self.bridge.event(ext.id, "error", {"text": str(exc)})
|
|
199
|
+
except Exception:
|
|
200
|
+
logger.exception("Falha inesperada ao executar o comando %s da extensão %s", command, ext.id)
|
|
201
|
+
self.bridge.event(ext.id, "error", {"text": "falha inesperada (veja o registro do Codis)"})
|
|
202
|
+
|
|
203
|
+
# --- execução ---------------------------------------------------------------------------
|
|
204
|
+
|
|
205
|
+
def run(self, ext: Extension, command: str, args: dict[str, Any] | None = None) -> Any:
|
|
206
|
+
"""Executa um comando da extensão, iniciando o processo se for preciso. Bloqueia até terminar."""
|
|
207
|
+
status = self.status(ext)
|
|
208
|
+
if status.state not in ("ready", "active", "running"):
|
|
209
|
+
raise HostError(status.text)
|
|
210
|
+
with self._lock_for(ext.id):
|
|
211
|
+
host = self._ensure_host(ext, status.runtime)
|
|
212
|
+
payload = [args] if args else []
|
|
213
|
+
return host.execute(command, payload, self.bridge.context())
|
|
214
|
+
|
|
215
|
+
def _lock_for(self, ext_id: str) -> threading.Lock:
|
|
216
|
+
with self._guard:
|
|
217
|
+
return self._locks.setdefault(ext_id, threading.Lock())
|
|
218
|
+
|
|
219
|
+
def _spec(
|
|
220
|
+
self, kind: str, ext_dir: Path, storage: Path, runtime: locate.RuntimeInfo, granted: frozenset[str] = frozenset()
|
|
221
|
+
) -> HostSpec:
|
|
222
|
+
host_file = str(HOSTS_DIR / _HOST_FILES[kind])
|
|
223
|
+
ext_dir, storage = ext_dir.resolve(), storage.resolve()
|
|
224
|
+
launch = sandbox.plan(runtime, granted, read=(ext_dir, HOSTS_DIR, storage), write=(storage,))
|
|
225
|
+
argv = [runtime.path, *launch.flags]
|
|
226
|
+
if kind == "node":
|
|
227
|
+
argv += ["--max-old-space-size=256", host_file, str(ext_dir), str(storage)]
|
|
228
|
+
else:
|
|
229
|
+
argv += [host_file, str(ext_dir), str(storage), ",".join(permissions.ordered(granted))]
|
|
230
|
+
return HostSpec(argv=argv, cwd=storage, home=storage, permissions=granted)
|
|
231
|
+
|
|
232
|
+
# --- autoteste do runtime ----------------------------------------------------------------
|
|
233
|
+
|
|
234
|
+
def check_runtime(self, runtime: locate.RuntimeInfo) -> RuntimeCheck:
|
|
235
|
+
"""Sobe o host com uma extensão vazia para ver se este runtime funciona de verdade aqui.
|
|
236
|
+
|
|
237
|
+
Se o Node falha só com o modelo de permissões ligado (acontece em algumas versões e
|
|
238
|
+
sistemas), o resultado devolve o runtime sem isolamento e a razão em ``note``, para que a
|
|
239
|
+
confirmação mostre isso ao usuário. O resultado fica em cache por executável.
|
|
240
|
+
"""
|
|
241
|
+
key = f"{runtime.path}|{runtime.isolation}"
|
|
242
|
+
cached = self._checks.get(key)
|
|
243
|
+
if cached is not None:
|
|
244
|
+
return cached
|
|
245
|
+
problem = self._selftest(runtime)
|
|
246
|
+
if not problem:
|
|
247
|
+
result = RuntimeCheck(runtime)
|
|
248
|
+
elif runtime.kind == "node" and runtime.isolation:
|
|
249
|
+
bare = dataclasses.replace(runtime, isolation=())
|
|
250
|
+
if not self._selftest(bare):
|
|
251
|
+
result = RuntimeCheck(dataclasses.replace(bare, note=problem.splitlines()[0][:300]))
|
|
252
|
+
else:
|
|
253
|
+
result = RuntimeCheck(runtime, problem)
|
|
254
|
+
else:
|
|
255
|
+
result = RuntimeCheck(runtime, problem)
|
|
256
|
+
self._checks[key] = result
|
|
257
|
+
return result
|
|
258
|
+
|
|
259
|
+
def _selftest(self, runtime: locate.RuntimeInfo) -> str:
|
|
260
|
+
with tempfile.TemporaryDirectory(prefix="codis-selftest-", ignore_cleanup_errors=True) as tmp:
|
|
261
|
+
ext_dir, storage = Path(tmp) / "ext", Path(tmp) / "data"
|
|
262
|
+
ext_dir.mkdir()
|
|
263
|
+
if runtime.kind == "node":
|
|
264
|
+
(ext_dir / "package.json").write_text('{"name": "selftest", "publisher": "codis", "version": "0"}', encoding="utf-8")
|
|
265
|
+
(ext_dir / "extension.js").write_text("exports.activate = function () {};\n", encoding="utf-8")
|
|
266
|
+
main = "extension.js"
|
|
267
|
+
else:
|
|
268
|
+
(ext_dir / "plugin.py").write_text(
|
|
269
|
+
"import sublime_plugin\n\n\nclass PingCommand(sublime_plugin.ApplicationCommand):\n def run(self):\n pass\n",
|
|
270
|
+
encoding="utf-8",
|
|
271
|
+
)
|
|
272
|
+
main = "."
|
|
273
|
+
host = ExtensionHost("selftest", self._spec(runtime.kind, ext_dir, storage, runtime), lambda op, m: None, lambda op, m: None)
|
|
274
|
+
try:
|
|
275
|
+
host.start({"t": "init", "main": main, "workspace": [], "settings": {}}, timeout=25)
|
|
276
|
+
return ""
|
|
277
|
+
except HostError as exc:
|
|
278
|
+
return str(exc) or "falha sem mensagem"
|
|
279
|
+
finally:
|
|
280
|
+
host.stop()
|
|
281
|
+
|
|
282
|
+
def _ensure_host(self, ext: Extension, runtime: locate.RuntimeInfo | None) -> ExtensionHost:
|
|
283
|
+
host = self._hosts.get(ext.id)
|
|
284
|
+
if host is not None and host.alive:
|
|
285
|
+
return host
|
|
286
|
+
if host is not None:
|
|
287
|
+
self._last_output[ext.id] = list(host.output)
|
|
288
|
+
assert ext.code is not None and runtime is not None
|
|
289
|
+
check = self.check_runtime(runtime)
|
|
290
|
+
if check.problem:
|
|
291
|
+
label = RUNTIME_LABEL.get(runtime.kind, runtime.kind)
|
|
292
|
+
raise HostError(f"O {label} em {runtime.path} não conseguiu iniciar o host das extensões:\n\n{check.problem}")
|
|
293
|
+
runtime = check.runtime
|
|
294
|
+
# O código pode ter mudado entre a confirmação e este início: confere de novo.
|
|
295
|
+
digest = self.fingerprint(ext)
|
|
296
|
+
if digest is None or not self.state.granted(ext.id, digest[0]):
|
|
297
|
+
raise HostError("o código mudou desde a sua confirmação")
|
|
298
|
+
(self.data_root / ext.id).mkdir(parents=True, exist_ok=True)
|
|
299
|
+
granted = self.state.permissions(ext.id)
|
|
300
|
+
host = ExtensionHost(
|
|
301
|
+
ext.id,
|
|
302
|
+
self._spec(ext.code.runtime, ext.path, self.data_root / ext.id, runtime, granted),
|
|
303
|
+
on_request=lambda op, msg, eid=ext.id: self.bridge.request(eid, op, msg),
|
|
304
|
+
on_event=lambda op, msg, eid=ext.id: self.bridge.event(eid, op, msg),
|
|
305
|
+
)
|
|
306
|
+
ctx = self.bridge.context()
|
|
307
|
+
host.start({
|
|
308
|
+
"t": "init", "main": ext.code.entry, "workspace": ctx.get("workspace", []), "settings": {},
|
|
309
|
+
"permissions": permissions.ordered(granted),
|
|
310
|
+
})
|
|
311
|
+
self._hosts[ext.id] = host
|
|
312
|
+
return host
|
|
313
|
+
|
|
314
|
+
def _stop_host(self, ext_id: str) -> None:
|
|
315
|
+
host = self._hosts.pop(ext_id, None)
|
|
316
|
+
if host is not None:
|
|
317
|
+
self._last_output[ext_id] = list(host.output)
|
|
318
|
+
host.stop()
|
|
319
|
+
|
|
320
|
+
def stop(self, ext_id: str) -> None:
|
|
321
|
+
self._stop_host(ext_id)
|
|
322
|
+
|
|
323
|
+
def stop_all(self) -> None:
|
|
324
|
+
for ext_id in list(self._hosts):
|
|
325
|
+
self._stop_host(ext_id)
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Permissões por extensão: o que o código de uma extensão pode fazer além do padrão.
|
|
2
|
+
|
|
3
|
+
Sem nenhuma permissão a extensão roda no isolamento básico (lê só a própria pasta, grava só na
|
|
4
|
+
pasta de dados, não abre processos, não carrega código nativo e recebe um ambiente sem
|
|
5
|
+
credenciais). Cada permissão abaixo remove uma dessas restrições, e só para aquela extensão,
|
|
6
|
+
quando o usuário concede de forma consciente. ``unrestricted`` equivale a todas as outras e ainda
|
|
7
|
+
desliga o modelo de permissões do Node e o gancho de auditoria do Python.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
from collections.abc import Iterable
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
PROCESS = "process"
|
|
19
|
+
FILES = "files"
|
|
20
|
+
NATIVE = "native"
|
|
21
|
+
ENV = "env"
|
|
22
|
+
UNRESTRICTED = "unrestricted"
|
|
23
|
+
|
|
24
|
+
NONE, MEDIUM, HIGH, CRITICAL = "none", "medium", "high", "critical"
|
|
25
|
+
_RANK = {NONE: 0, MEDIUM: 1, HIGH: 2, CRITICAL: 3}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class Permission:
|
|
30
|
+
id: str
|
|
31
|
+
label: str
|
|
32
|
+
risk: str
|
|
33
|
+
grants: str # o que a permissão libera
|
|
34
|
+
danger: str # o que pode dar errado
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
CATALOG: tuple[Permission, ...] = (
|
|
38
|
+
Permission(
|
|
39
|
+
PROCESS, "Processos", HIGH,
|
|
40
|
+
"Abrir outros programas e threads (child_process, worker_threads e cluster no Node; subprocess, "
|
|
41
|
+
"os.system e multiprocessing no Python).",
|
|
42
|
+
"Pode executar qualquer comando com os seus privilégios, inclusive baixar e rodar outros programas.",
|
|
43
|
+
),
|
|
44
|
+
Permission(
|
|
45
|
+
FILES, "Arquivos", HIGH,
|
|
46
|
+
"Ler e gravar em qualquer pasta que o seu usuário alcança, e não só na pasta de dados da extensão.",
|
|
47
|
+
"Pode ler chaves SSH, documentos e senhas salvas, e alterar ou apagar arquivos.",
|
|
48
|
+
),
|
|
49
|
+
Permission(
|
|
50
|
+
NATIVE, "Módulos nativos", HIGH,
|
|
51
|
+
"Carregar código compilado (.node, DLL, .so; ctypes e registro do Windows no Python).",
|
|
52
|
+
"Código nativo roda fora de qualquer verificação e pode travar o Codis ou corromper o sistema.",
|
|
53
|
+
),
|
|
54
|
+
Permission(
|
|
55
|
+
ENV, "Variáveis de ambiente", MEDIUM,
|
|
56
|
+
"Receber todas as variáveis de ambiente do Codis. Por padrão a extensão recebe só um conjunto "
|
|
57
|
+
"mínimo, sem tokens nem credenciais.",
|
|
58
|
+
"Variáveis de ambiente costumam guardar tokens de API, senhas e chaves de acesso.",
|
|
59
|
+
),
|
|
60
|
+
Permission(
|
|
61
|
+
UNRESTRICTED, "Sem isolamento", CRITICAL,
|
|
62
|
+
"Libera tudo o que está acima e desliga o modelo de permissões do Node e o gancho de auditoria do Python.",
|
|
63
|
+
"A extensão passa a ter os mesmos poderes de qualquer programa que você abre. Não sobra nenhuma "
|
|
64
|
+
"barreira entre ela e o seu computador.",
|
|
65
|
+
),
|
|
66
|
+
)
|
|
67
|
+
BY_ID = {p.id: p for p in CATALOG}
|
|
68
|
+
ALL = tuple(BY_ID)
|
|
69
|
+
LEVEL_LABEL = {NONE: "padrão (isolamento básico)", MEDIUM: "médio", HIGH: "alto", CRITICAL: "crítico"}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def parse(values: Iterable[object] | None) -> frozenset[str]:
|
|
73
|
+
"""Só os identificadores conhecidos; o que vier de um arquivo editado à mão é ignorado."""
|
|
74
|
+
return frozenset(v for v in (values or ()) if isinstance(v, str) and v in BY_ID)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def effective(perms: Iterable[str]) -> frozenset[str]:
|
|
78
|
+
granted = parse(perms)
|
|
79
|
+
return frozenset(ALL) if UNRESTRICTED in granted else granted
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def allows(perms: Iterable[str], perm: str) -> bool:
|
|
83
|
+
return perm in effective(perms)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def ordered(perms: Iterable[str]) -> list[str]:
|
|
87
|
+
granted = parse(perms)
|
|
88
|
+
return [p for p in ALL if p in granted]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def level(perms: Iterable[str]) -> str:
|
|
92
|
+
found = [BY_ID[p].risk for p in parse(perms)]
|
|
93
|
+
return max(found, key=_RANK.__getitem__, default=NONE)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def describe(perms: Iterable[str]) -> str:
|
|
97
|
+
names = [BY_ID[p].label for p in ordered(perms)]
|
|
98
|
+
return ", ".join(names) if names else "nenhuma (isolamento básico)"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# --- sugestões a partir do código ----------------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
_SCAN_FILES = 4000
|
|
104
|
+
_SCAN_BYTES = 512 * 1024
|
|
105
|
+
_SOURCE_SUFFIXES = {".js", ".cjs", ".mjs", ".py"}
|
|
106
|
+
_BINARY_SUFFIXES = {".node", ".dll", ".so", ".dylib", ".pyd"}
|
|
107
|
+
_PATTERNS = {
|
|
108
|
+
PROCESS: re.compile(
|
|
109
|
+
rb"child_process|worker_threads|require\(['\"]cluster|\bsubprocess\b|\bmultiprocessing\b"
|
|
110
|
+
rb"|\bos\.(?:system|popen|exec\w*|spawn\w*|fork)\b"
|
|
111
|
+
),
|
|
112
|
+
NATIVE: re.compile(rb"process\.dlopen|\bctypes\b|\bwinreg\b|\b_winreg\b|\bcffi\b"),
|
|
113
|
+
ENV: re.compile(rb"process\.env\b(?!\.NODE_ENV)|\bos\.environ\b|\bos\.getenv\b"),
|
|
114
|
+
FILES: re.compile(rb"\bhomedir\(|\bexpanduser\(|\bPath\.home\(|process\.env\.(?:HOME|USERPROFILE)|\.ssh\b"),
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def detect(root: Path) -> dict[str, list[str]]:
|
|
119
|
+
"""Permissões que o código parece precisar, com até três arquivos de exemplo cada.
|
|
120
|
+
|
|
121
|
+
É uma busca textual por nomes de API, então serve de pista para o usuário decidir e não prova
|
|
122
|
+
nada: um nome citado em comentário aparece, e um acesso montado em tempo de execução não.
|
|
123
|
+
"""
|
|
124
|
+
found: dict[str, list[str]] = {}
|
|
125
|
+
|
|
126
|
+
def note(perm: str, rel: str) -> None:
|
|
127
|
+
shown = found.setdefault(perm, [])
|
|
128
|
+
if len(shown) < 3 and rel not in shown:
|
|
129
|
+
shown.append(rel)
|
|
130
|
+
|
|
131
|
+
seen = 0
|
|
132
|
+
for base, dirs, names in os.walk(root, followlinks=False):
|
|
133
|
+
dirs[:] = [d for d in dirs if d != ".git"]
|
|
134
|
+
for name in names:
|
|
135
|
+
path = Path(base) / name
|
|
136
|
+
if path.is_symlink():
|
|
137
|
+
continue
|
|
138
|
+
seen += 1
|
|
139
|
+
if seen > _SCAN_FILES:
|
|
140
|
+
return found
|
|
141
|
+
suffix = path.suffix.lower()
|
|
142
|
+
rel = path.relative_to(root).as_posix()
|
|
143
|
+
if suffix in _BINARY_SUFFIXES:
|
|
144
|
+
note(NATIVE, rel)
|
|
145
|
+
elif suffix in _SOURCE_SUFFIXES:
|
|
146
|
+
try:
|
|
147
|
+
with open(path, "rb") as handle:
|
|
148
|
+
data = handle.read(_SCAN_BYTES)
|
|
149
|
+
except OSError:
|
|
150
|
+
continue
|
|
151
|
+
for perm, pattern in _PATTERNS.items():
|
|
152
|
+
if pattern.search(data):
|
|
153
|
+
note(perm, rel)
|
|
154
|
+
return found
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Traduz as permissões concedidas a uma extensão nos argumentos do runtime que a executa."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from . import permissions as perms_mod
|
|
10
|
+
from .locate import RuntimeInfo
|
|
11
|
+
|
|
12
|
+
# Cada permissão do Codis e as flags do modelo de permissões do Node que a liberam.
|
|
13
|
+
_NODE_FLAGS = {
|
|
14
|
+
perms_mod.PROCESS: ("--allow-child-process", "--allow-worker"),
|
|
15
|
+
perms_mod.NATIVE: ("--allow-addons",),
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class LaunchPlan:
|
|
21
|
+
flags: tuple[str, ...] # argumentos do runtime, antes do script do host
|
|
22
|
+
isolated: bool # o runtime impõe os limites sozinho (Node com permissões, Python com auditoria)
|
|
23
|
+
notes: tuple[str, ...] = () # avisos para mostrar ao usuário antes de confirmar
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def plan(
|
|
27
|
+
runtime: RuntimeInfo,
|
|
28
|
+
granted: Iterable[str],
|
|
29
|
+
read: Iterable[Path] = (),
|
|
30
|
+
write: Iterable[Path] = (),
|
|
31
|
+
) -> LaunchPlan:
|
|
32
|
+
"""``read`` e ``write`` são as pastas do isolamento básico (extensão, host e dados)."""
|
|
33
|
+
perms = perms_mod.parse(granted)
|
|
34
|
+
wide = perms_mod.UNRESTRICTED in perms
|
|
35
|
+
if runtime.kind != "node":
|
|
36
|
+
return LaunchPlan(("-B",) if wide else ("-I", "-B"), not wide)
|
|
37
|
+
if wide:
|
|
38
|
+
return LaunchPlan((), False)
|
|
39
|
+
if not runtime.isolation:
|
|
40
|
+
why = f" (o teste com o modelo de permissões falhou aqui: {runtime.note})" if runtime.note else ""
|
|
41
|
+
return LaunchPlan((), False, (f"Este Node.js roda SEM o modelo de permissões{why}: o código pode ler e gravar arquivos livremente.",))
|
|
42
|
+
|
|
43
|
+
flags = [runtime.isolation[0]]
|
|
44
|
+
if perms_mod.FILES in perms:
|
|
45
|
+
flags += ["--allow-fs-read=*", "--allow-fs-write=*"]
|
|
46
|
+
else:
|
|
47
|
+
flags += [f"--allow-fs-read={p}" for p in read] + [f"--allow-fs-write={p}" for p in write]
|
|
48
|
+
for perm, needed in _NODE_FLAGS.items():
|
|
49
|
+
if perm not in perms:
|
|
50
|
+
continue
|
|
51
|
+
missing = [f for f in needed if f not in runtime.allows]
|
|
52
|
+
if missing:
|
|
53
|
+
label = perms_mod.BY_ID[perm].label
|
|
54
|
+
return LaunchPlan((), False, (
|
|
55
|
+
f"Este Node.js (v{runtime.version}) não consegue liberar só \"{label}\" ({', '.join(missing)} ausente): "
|
|
56
|
+
"para atender a permissão ele rodará SEM o modelo de permissões, com acesso livre a arquivos. "
|
|
57
|
+
"Use um Node.js mais novo ou desmarque a permissão.",
|
|
58
|
+
))
|
|
59
|
+
flags += needed
|
|
60
|
+
return LaunchPlan(tuple(flags), True)
|