content stringlengths 1 103k ⌀ | path stringlengths 8 216 | filename stringlengths 2 179 | language stringclasses 15
values | size_bytes int64 2 189k | quality_score float64 0.5 0.95 | complexity float64 0 1 | documentation_ratio float64 0 1 | repository stringclasses 5
values | stars int64 0 1k | created_date stringdate 2023-07-10 19:21:08 2025-07-09 19:11:45 | license stringclasses 4
values | is_test bool 2
classes | file_hash stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\bash_language_server.cpython-313.pyc | bash_language_server.cpython-313.pyc | Other | 1,872 | 0.8 | 0 | 0.045455 | python-kit | 450 | 2023-08-29T21:34:13.948913 | BSD-3-Clause | false | c5d7a80e10e25ad32c71e5b4ee67a451 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\dockerfile_language_server_nodejs.cpython-313.pyc | dockerfile_language_server_nodejs.cpython-313.pyc | Other | 1,339 | 0.8 | 0 | 0 | vue-tools | 441 | 2024-04-19T17:52:27.283509 | BSD-3-Clause | false | 823e96d196d3c0644340129b53b997f5 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\javascript_typescript_langserver.cpython-313.pyc | javascript_typescript_langserver.cpython-313.pyc | Other | 1,491 | 0.8 | 0 | 0 | awesome-app | 669 | 2024-07-08T11:53:41.221041 | MIT | false | 65904c70fb2db0eef19a6187e5f5888d |
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\jedi_language_server.cpython-313.pyc | jedi_language_server.cpython-313.pyc | Other | 1,021 | 0.8 | 0 | 0 | vue-tools | 46 | 2024-04-30T01:07:03.106252 | MIT | false | 6d03d09e75a977e4b0dd4991dccfae5f |
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\julia_language_server.cpython-313.pyc | julia_language_server.cpython-313.pyc | Other | 1,272 | 0.8 | 0.066667 | 0 | vue-tools | 649 | 2024-10-26T22:21:20.995471 | Apache-2.0 | false | 8b3374566905ae47aebb9e8298bea513 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\pyls.cpython-313.pyc | pyls.cpython-313.pyc | Other | 1,448 | 0.8 | 0 | 0 | awesome-app | 871 | 2025-05-24T16:09:09.399850 | GPL-3.0 | false | c2ce662d232be140f9ba058f8589189b |
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\pyright.cpython-313.pyc | pyright.cpython-313.pyc | Other | 1,256 | 0.95 | 0 | 0 | python-kit | 256 | 2023-09-10T20:24:39.486331 | GPL-3.0 | false | 626060f71971c948f31b349053c69e4b |
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\python_lsp_server.cpython-313.pyc | python_lsp_server.cpython-313.pyc | Other | 1,611 | 0.8 | 0 | 0 | react-lib | 855 | 2023-12-28T21:33:28.784241 | BSD-3-Clause | false | efc9e6aa4efe9bc9ddfdd5674a84ef51 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\r_languageserver.cpython-313.pyc | r_languageserver.cpython-313.pyc | Other | 2,198 | 0.95 | 0 | 0 | python-kit | 331 | 2024-02-09T09:05:08.466219 | GPL-3.0 | false | c4f3e30660b98e49ea335ffd203feb49 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\sql_language_server.cpython-313.pyc | sql_language_server.cpython-313.pyc | Other | 1,431 | 0.8 | 0 | 0 | node-utils | 836 | 2025-04-09T22:43:39.978233 | Apache-2.0 | false | 7610d98e4d07820e1a5ca6a4343a05f8 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\texlab.cpython-313.pyc | texlab.cpython-313.pyc | Other | 1,396 | 0.95 | 0.166667 | 0 | vue-tools | 770 | 2023-09-19T12:29:36.349355 | MIT | false | ec9ef055b39e6d7f3fdfb88165d96a8c |
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\typescript_language_server.cpython-313.pyc | typescript_language_server.cpython-313.pyc | Other | 1,580 | 0.8 | 0 | 0 | awesome-app | 724 | 2025-05-01T20:58:39.393037 | Apache-2.0 | false | 12ca657f0a1573f2807778fb66582592 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\unified_language_server.cpython-313.pyc | unified_language_server.cpython-313.pyc | Other | 1,295 | 0.8 | 0 | 0 | node-utils | 873 | 2025-03-07T11:31:43.081414 | MIT | false | 6a400e51374962a7b21637e6cf3ea57e |
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\utils.cpython-313.pyc | utils.cpython-313.pyc | Other | 6,725 | 0.95 | 0.051948 | 0 | react-lib | 196 | 2024-07-18T21:13:23.958689 | Apache-2.0 | false | 5dd90927ca8162cbe9b104373503b43b |
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\vscode_css_languageserver.cpython-313.pyc | vscode_css_languageserver.cpython-313.pyc | Other | 1,271 | 0.8 | 0 | 0 | react-lib | 453 | 2025-06-27T08:27:37.917980 | BSD-3-Clause | false | 858626b7ad0411593788ddaf5be3bdca |
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\vscode_html_languageserver.cpython-313.pyc | vscode_html_languageserver.cpython-313.pyc | Other | 1,235 | 0.8 | 0 | 0 | vue-tools | 871 | 2023-09-10T07:28:40.792445 | MIT | false | f0909531c737f216ba4dc780f7d8d7cc |
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\vscode_json_languageserver.cpython-313.pyc | vscode_json_languageserver.cpython-313.pyc | Other | 1,285 | 0.8 | 0 | 0 | react-lib | 633 | 2023-09-02T17:06:56.709929 | GPL-3.0 | false | e234da772c25e225e264ce1d1c436bcf |
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\yaml_language_server.cpython-313.pyc | yaml_language_server.cpython-313.pyc | Other | 1,310 | 0.8 | 0 | 0 | react-lib | 467 | 2024-03-11T07:10:54.283623 | BSD-3-Clause | false | eeeacc6d179fa4dbff96f1e2f08b24cf |
\n\n | .venv\Lib\site-packages\jupyter_lsp\specs\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 1,852 | 0.8 | 0 | 0 | python-kit | 941 | 2023-09-28T09:31:48.712162 | BSD-3-Clause | false | bd95c8ceced46f59f1c37cd8b79e5449 |
import json\nimport os\nimport pathlib\nimport shutil\nfrom pathlib import Path\nfrom typing import Text\n\nfrom jupyter_server.serverapp import ServerApp\nfrom pytest import fixture\nfrom tornado.httpserver import HTTPRequest\nfrom tornado.httputil import HTTPServerRequest\nfrom tornado.queues import Queue\nfrom tornado.web import Application\n\n# local imports\nfrom jupyter_lsp import LanguageServerManager\nfrom jupyter_lsp.constants import APP_CONFIG_D_SECTIONS\nfrom jupyter_lsp.handlers import LanguageServersHandler, LanguageServerWebSocketHandler\n\n# these should always be available in a test environment\nKNOWN_SERVERS = [\n "bash-language-server",\n "dockerfile-language-server-nodejs",\n "typescript-language-server",\n "pylsp",\n "unified-language-server",\n "sql-language-server",\n "vscode-css-languageserver-bin",\n "vscode-html-languageserver-bin",\n "vscode-json-languageserver-bin",\n "yaml-language-server",\n]\n\nCMD_BASED_SERVERS = {\n "Rscript": ["r-languageserver"],\n "texlab": ["texlab"],\n "jedi-language-server": ["jedi-language-server"],\n "julia": ["julia-language-server"],\n}\n\nKNOWN_SERVERS += sum(\n [langs for cmd, langs in CMD_BASED_SERVERS.items() if shutil.which(cmd)], []\n)\n\nKNOWN_UNKNOWN_SERVERS = ["foo-language-server"]\n\n\ndef extra_node_roots():\n root = Path(os.environ.get("JLSP_TEST_ROOT") or Path.cwd())\n return dict(extra_node_roots=[str(root)] if root else [])\n\n\n@fixture\ndef manager() -> LanguageServerManager:\n return LanguageServerManager(**extra_node_roots())\n\n\n@fixture\ndef echo_spec():\n return {"argv": ["echo", "no server here"], "languages": ["klingon"], "version": 2}\n\n\n@fixture\ndef echo_conf_json(echo_spec) -> str:\n return json.dumps(\n {"LanguageServerManager": {"language_servers": {"_echo_": echo_spec}}},\n indent=2,\n sort_keys=True,\n )\n\n\n@fixture(params=sorted(APP_CONFIG_D_SECTIONS))\ndef app_config_d(request, tmp_path, monkeypatch) -> pathlib.Path:\n conf_d = tmp_path / f"jupyter{request.param}config.d"\n conf_d.mkdir()\n monkeypatch.setenv("JUPYTER_CONFIG_PATH", f"{tmp_path}")\n return conf_d\n\n\n@fixture(params=sorted(KNOWN_SERVERS))\ndef known_server(request):\n return request.param\n\n\n@fixture(params=sorted(KNOWN_UNKNOWN_SERVERS))\ndef known_unknown_server(request):\n return request.param\n\n\n@fixture\ndef handlers(manager):\n ws_handler = MockWebsocketHandler()\n ws_handler.initialize(manager)\n handler = MockHandler()\n handler.initialize(manager)\n return handler, ws_handler\n\n\n@fixture\ndef jsonrpc_init_msg():\n return json.dumps(\n {\n "id": 0,\n "jsonrpc": "2.0",\n "method": "initialize",\n "params": {\n "capabilities": {\n # see: https://github.com/julia-vscode/LanguageServer.jl/issues/1008\n # LanguageServer.jl assumes that it is not missing\n "workspace": {"didChangeConfiguration": {}},\n # LanguageServer.jl assumes that it is not missing\n "textDocument": {},\n },\n "initializationOptions": None,\n "processId": None,\n "rootUri": pathlib.Path(__file__).parent.as_uri(),\n "workspaceFolders": None,\n },\n }\n )\n\n\n@fixture\ndef app():\n return MockServerApp()\n\n\n# mocks\nclass MockWebsocketHandler(LanguageServerWebSocketHandler):\n _messages_wrote = None # type: Queue\n _ping_sent = None # type: bool\n\n def __init__(self):\n self.request = HTTPServerRequest()\n self.application = Application()\n\n def initialize(self, manager):\n super().initialize(manager)\n self._messages_wrote = Queue()\n self._ping_sent = False\n\n def write_message(self, message: Text) -> None: # type: ignore\n self.log.warning("write_message %s", message)\n self._messages_wrote.put_nowait(message)\n\n def send_ping(self):\n self._ping_sent = True\n\n\nclass MockHandler(LanguageServersHandler):\n _payload = None\n _jupyter_current_user = "foo" # type:ignore[assignment]\n\n def __init__(self):\n self.request = HTTPRequest("GET")\n self.application = Application()\n\n def finish(self, payload):\n self._payload = payload\n\n\nclass MockServerApp(ServerApp):\n pass\n | .venv\Lib\site-packages\jupyter_lsp\tests\conftest.py | conftest.py | Python | 4,327 | 0.95 | 0.134969 | 0.048 | awesome-app | 331 | 2024-11-22T10:56:42.251827 | BSD-3-Clause | true | a35329f8ad29e3337da459ac7d351a33 |
async def dummy_listener(scope, message, language_server, manager):\n pass\n | .venv\Lib\site-packages\jupyter_lsp\tests\listener.py | listener.py | Python | 77 | 0.65 | 0.5 | 0 | node-utils | 743 | 2024-10-30T02:53:39.359464 | BSD-3-Clause | true | 0f1ed9dba4c91aeb701076d4931717c7 |
"""Integration tests of authorization running under jupyter-server."""\n\nimport json\nimport os\nimport socket\nimport subprocess\nimport sys\nimport time\nimport uuid\nfrom typing import Generator, Optional, Tuple\nfrom urllib.error import HTTPError, URLError\nfrom urllib.request import urlopen\n\nimport pytest\n\nfrom .conftest import KNOWN_SERVERS, extra_node_roots\n\nLOCALHOST = "127.0.0.1"\nREST_ROUTES = ["/lsp/status"]\nWS_ROUTES = [f"/lsp/ws/{ls}" for ls in KNOWN_SERVERS]\nSUBPROCESS_PREFIX = json.loads(\n os.environ.get("JLSP_TEST_SUBPROCESS_PREFIX", f"""["{sys.executable}", "-m"]""")\n)\n\n\n@pytest.mark.parametrize("route", REST_ROUTES)\ndef test_auth_rest(route: str, a_server_url_and_token: Tuple[str, str]) -> None:\n """Verify a REST route only provides access to an authenticated user."""\n base_url, token = a_server_url_and_token\n\n verify_response(base_url, route)\n\n raw_body = verify_response(base_url, f"{route}?token={token}", 200)\n\n assert raw_body is not None, f"no response received from {route}"\n\n decode_error = None\n\n try:\n json.loads(raw_body.decode("utf-8"))\n except json.decoder.JSONDecodeError as err: # pragma: no cover\n decode_error = err\n assert not decode_error, f"the response for {route} was not JSON: {decode_error}"\n\n\n@pytest.mark.parametrize("route", WS_ROUTES)\ndef test_auth_websocket(route: str, a_server_url_and_token: Tuple[str, str]) -> None:\n """Verify a WebSocket does not provide access to an unauthenticated user."""\n verify_response(a_server_url_and_token[0], route)\n\n\n@pytest.fixture(scope="module")\ndef a_server_url_and_token(\n tmp_path_factory: pytest.TempPathFactory,\n) -> Generator[Tuple[str, str], None, None]:\n """Start a temporary, isolated jupyter server."""\n token = str(uuid.uuid4())\n port = get_unused_port()\n\n root_dir = tmp_path_factory.mktemp("root_dir")\n home = tmp_path_factory.mktemp("home")\n server_conf = home / "etc/jupyter/jupyter_config.json"\n\n server_conf.parent.mkdir(parents=True)\n extensions = {"jupyter_lsp": True, "jupyterlab": False, "nbclassic": False}\n app = {"jpserver_extensions": extensions, "token": token}\n lsm = {**extra_node_roots()}\n config_data = {\n "ServerApp": app,\n "IdentityProvider": {"token": token},\n "LanguageServerManager": lsm,\n }\n\n server_conf.write_text(json.dumps(config_data), encoding="utf-8")\n args = [*SUBPROCESS_PREFIX, "jupyter_server", f"--port={port}", "--no-browser"]\n print("server args", args)\n env = dict(os.environ)\n env.update(\n HOME=str(home),\n USERPROFILE=str(home),\n JUPYTER_CONFIG_DIR=str(server_conf.parent),\n )\n proc = subprocess.Popen(args, cwd=str(root_dir), env=env, stdin=subprocess.PIPE)\n url = f"http://{LOCALHOST}:{port}"\n retries = 20\n ok = False\n while not ok and retries:\n try:\n ok = urlopen(f"{url}/favicon.ico")\n except URLError:\n print(f"[{retries} / 20] ...", flush=True)\n retries -= 1\n time.sleep(1)\n if not ok: # pragma: no cover\n raise RuntimeError("the server did not start")\n yield url, token\n try:\n print("shutting down with API...")\n urlopen(f"{url}/api/shutdown?token={token}", data=[])\n except URLError: # pragma: no cover\n print("shutting down the hard way...")\n proc.terminate()\n proc.communicate(b"y\n")\n proc.wait()\n proc.kill()\n proc.wait()\n assert proc.returncode is not None, "jupyter-server probably still running"\n\n\ndef get_unused_port():\n """Get an unused port by trying to listen to any random port.\n\n Probably could introduce race conditions if inside a tight loop.\n """\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.bind((LOCALHOST, 0))\n sock.listen(1)\n port = sock.getsockname()[1]\n sock.close()\n return port\n\n\ndef verify_response(\n base_url: str, route: str, expect_code: int = 403\n) -> Optional[bytes]:\n """Verify that a response returns the expected error."""\n body = None\n code = None\n url = f"{base_url}{route}"\n try:\n res = urlopen(url)\n code = res.getcode()\n body = res.read()\n except HTTPError as err:\n code = err.getcode()\n assert code == expect_code, f"HTTP {code} (not expected {expect_code}) for {url}"\n return body\n | .venv\Lib\site-packages\jupyter_lsp\tests\test_auth.py | test_auth.py | Python | 4,368 | 0.95 | 0.109489 | 0 | react-lib | 716 | 2024-03-01T23:53:47.298439 | BSD-3-Clause | true | 2f64497d75589b7eb41a595bfd33a17c |
import pytest\nimport traitlets\n\nfrom jupyter_lsp.session import LanguageServerSession\n\n\n@pytest.mark.parametrize(\n "spec",\n [\n {},\n {"argv": [], "languages": []},\n {"languages": None},\n {"languages": 1},\n {"languages": [1, "two"]},\n ],\n)\ndef test_bad_spec(spec):\n with pytest.raises(traitlets.TraitError):\n LanguageServerSession(spec=spec)\n | .venv\Lib\site-packages\jupyter_lsp\tests\test_bad_spec.py | test_bad_spec.py | Python | 394 | 0.85 | 0.052632 | 0 | vue-tools | 699 | 2024-08-31T18:00:37.362083 | BSD-3-Clause | true | 577f040ea4bc0742aefc834b820cbde0 |
def test_conf_d_language_servers(echo_conf_json, handlers, app_config_d):\n (app_config_d / "echo.json").write_text(echo_conf_json)\n handler, ws_handler = handlers\n manager = handler.manager\n manager.initialize()\n assert "_echo_" in [*manager.language_servers]\n | .venv\Lib\site-packages\jupyter_lsp\tests\test_conf_d.py | test_conf_d.py | Python | 275 | 0.85 | 0.166667 | 0 | python-kit | 761 | 2024-09-03T06:47:07.610458 | Apache-2.0 | true | e5fe0d99296e3d85a00fd17b26d1dc11 |
from jupyter_lsp.specs.r_languageserver import RLanguageServer\nfrom jupyter_lsp.specs.utils import PythonModuleSpec\n\n\ndef test_no_detect(manager):\n """should not enable anything by default"""\n manager.autodetect = False\n manager.initialize()\n assert not manager.language_servers\n assert not manager.sessions\n\n\ndef test_detect(manager):\n manager.initialize()\n assert len(manager.sessions) == len(manager.language_servers)\n\n\ndef test_r_package_detection():\n with_installed_server = RLanguageServer()\n assert with_installed_server.is_installed(mgr=None) is True\n\n class NonInstalledRServer(RLanguageServer):\n package = "languageserver-fork"\n\n non_installed_server = NonInstalledRServer()\n assert non_installed_server.is_installed(mgr=None) is False\n\n\ndef test_missing_python_module_spec():\n """Prevent failure in module detection raising error"""\n\n class NonInstalledPythonServer(PythonModuleSpec):\n python_module = "not_installed_python_module"\n key = "a_module"\n\n not_installed_server = NonInstalledPythonServer()\n\n assert not_installed_server.is_installed(mgr=None) is False\n\n # we ant the spec even when not installed\n assert "languages" in not_installed_server(mgr=None)["a_module"]\n | .venv\Lib\site-packages\jupyter_lsp\tests\test_detect.py | test_detect.py | Python | 1,260 | 0.95 | 0.146341 | 0.037037 | python-kit | 557 | 2025-01-19T00:48:47.644707 | GPL-3.0 | true | f5c3079891a662426c1f4219667d377c |
import os\n\n\ndef test_serverextension_path(app):\n import jupyter_lsp\n\n paths = jupyter_lsp._jupyter_server_extension_paths()\n for path in paths:\n assert __import__(path["module"])\n\n\ndef test_serverextension(app):\n app.initialize(\n ["--ServerApp.jpserver_extensions={'jupyter_lsp.serverextension': True}"]\n )\n assert app.language_server_manager\n found_lsp = False\n for r in app.web_app.default_router.rules:\n for rr in r.target.rules:\n if "/lsp/" in str(rr.matcher.regex):\n found_lsp = True\n\n assert found_lsp, "apparently didn't install the /lsp/ route"\n\n\ndef test_default_virtual_documents_dir(app):\n app.initialize(\n ["--ServerApp.jpserver_extensions={'jupyter_lsp.serverextension': True}"]\n )\n assert app.language_server_manager.virtual_documents_dir == ".virtual_documents"\n\n\ndef test_virtual_documents_dir_config(app):\n custom_dir = ".custom_virtual_dir"\n app.initialize(\n [\n "--ServerApp.jpserver_extensions={'jupyter_lsp.serverextension': True}",\n "--ServerApp.LanguageServerManager.virtual_documents_dir=" + custom_dir,\n ]\n )\n assert app.language_server_manager.virtual_documents_dir == custom_dir\n\n\ndef test_virtual_documents_dir_env(app):\n os.environ["JP_LSP_VIRTUAL_DIR"] = custom_dir = ".custom_virtual_dir"\n app.initialize(\n ["--ServerApp.jpserver_extensions={'jupyter_lsp.serverextension': True}"]\n )\n assert app.language_server_manager.virtual_documents_dir == custom_dir\n | .venv\Lib\site-packages\jupyter_lsp\tests\test_extension.py | test_extension.py | Python | 1,543 | 0.85 | 0.183673 | 0 | node-utils | 48 | 2024-06-05T07:47:52.599001 | Apache-2.0 | true | 7ee04a035af3c6bc716ea4c9e0617127 |
import asyncio\nimport re\n\nimport pytest\nimport traitlets\nfrom tornado.queues import Queue\n\nfrom jupyter_lsp import lsp_message_listener\n\n\n@pytest.mark.parametrize("bad_string", ["not-a-function", "jupyter_lsp.__version__"])\n@pytest.mark.asyncio\nasync def test_listener_bad_traitlets(bad_string, handlers):\n handler, ws_handler = handlers\n manager = handler.manager\n\n with pytest.raises(traitlets.TraitError):\n manager.all_listeners = [bad_string]\n\n\n@pytest.mark.asyncio\nasync def test_listeners(known_server, handlers, jsonrpc_init_msg):\n """will some listeners listen?"""\n handler, ws_handler = handlers\n manager = handler.manager\n\n manager.all_listeners = ["jupyter_lsp.tests.listener.dummy_listener"]\n\n manager.initialize()\n manager._listeners["client"] = [] # hide predefined client listeners\n\n assert len(manager._listeners["all"]) == 1\n\n dummy_listener = manager._listeners["all"][0]\n assert re.match(\n (\n "<MessageListener listener=<function dummy_listener at .*?>,"\n " method=None, language_server=None>"\n ),\n repr(dummy_listener),\n )\n\n handler_listened = Queue()\n server_listened = Queue()\n all_listened = Queue()\n\n # some client listeners\n @lsp_message_listener("client", language_server=known_server, method="initialize")\n async def client_listener(scope, message, language_server, manager):\n await handler_listened.put(message)\n\n @lsp_message_listener("client", method=r"not-a-method")\n async def other_client_listener(\n scope, message, language_server, manager\n ): # pragma: no cover\n await handler_listened.put(message)\n raise NotImplementedError("shouldn't get here")\n\n # some server listeners\n @lsp_message_listener("server", language_server=None, method=None)\n async def server_listener(scope, message, language_server, manager):\n await server_listened.put(message)\n\n @lsp_message_listener("server", language_server=r"not-a-language-server")\n async def other_server_listener(\n scope, message, language_server, manager\n ): # pragma: no cover\n await handler_listened.put(message)\n raise NotImplementedError("shouldn't get here")\n\n # an all listener\n @lsp_message_listener("all")\n async def all_listener(\n scope, message, language_server, manager\n ): # pragma: no cover\n await all_listened.put(message)\n\n assert len(manager._listeners["server"]) == 2\n assert len(manager._listeners["client"]) == 2\n assert len(manager._listeners["all"]) == 2\n\n await ws_handler.open(known_server)\n\n await ws_handler.on_message(jsonrpc_init_msg)\n\n results = await asyncio.wait_for(\n asyncio.gather(\n handler_listened.get(),\n server_listened.get(),\n all_listened.get(),\n all_listened.get(),\n return_exceptions=True,\n ),\n 240 if known_server == "julia-language-server" else 20,\n )\n assert all([isinstance(res, dict) for res in results])\n\n ws_handler.on_close()\n\n handler_listened.task_done()\n server_listened.task_done()\n all_listened.task_done()\n all_listened.task_done()\n\n [\n manager.unregister_message_listener(listener)\n for listener in [\n client_listener,\n other_client_listener,\n server_listener,\n other_server_listener,\n all_listener,\n ]\n ]\n\n assert not manager._listeners["server"]\n assert not manager._listeners["client"]\n assert len(manager._listeners["all"]) == 1\n | .venv\Lib\site-packages\jupyter_lsp\tests\test_listener.py | test_listener.py | Python | 3,595 | 0.95 | 0.101695 | 0.032258 | awesome-app | 581 | 2024-02-16T00:33:45.117896 | BSD-3-Clause | true | f6bd5494d3934442362f855c00e9f454 |
import pathlib\nimport platform\nimport sys\n\nimport pytest\n\nfrom ..paths import file_uri_to_path, is_relative, normalized_uri\n\nWIN = platform.system() == "Windows"\nHOME = pathlib.Path("~").expanduser()\nPY35 = sys.version_info[:2] == (3, 5)\n\n\n@pytest.mark.skipif(WIN, reason="can't test POSIX paths on Windows")\n@pytest.mark.parametrize("root_dir, expected_root_uri", [["~", HOME.as_uri()]])\ndef test_normalize_posix_path_home(root_dir, expected_root_uri): # pragma: no cover\n assert normalized_uri(root_dir) == expected_root_uri\n\n\n@pytest.mark.skipif(WIN, reason="can't test POSIX paths on Windows")\n@pytest.mark.parametrize(\n "root, path",\n [["~", "~/a"], ["~", "~/a/../b/"], ["/", "/"], ["/a", "/a/b"], ["/a", "/a/b/../c"]],\n)\ndef test_is_relative_ok(root, path):\n assert is_relative(root, path)\n\n\n@pytest.mark.skipif(WIN, reason="can't test POSIX paths on Windows")\n@pytest.mark.parametrize(\n "root, path",\n [\n ["~", "~/.."],\n ["~", "/"],\n ["/a", "/"],\n ["/a/b", "/a"],\n ["/a/b", "/a/b/.."],\n ["/a", "/a/../b"],\n ["/a", "a//"],\n ],\n)\ndef test_is_relative_not_ok(root, path):\n assert not is_relative(root, path)\n\n\n@pytest.mark.skipif(not WIN, reason="can't test Windows paths on POSIX")\n@pytest.mark.parametrize(\n "root, path",\n [\n ["c:\\Users\\user1", "c:\\Users\\"],\n ["c:\\Users\\user1", "d:\\"],\n ["c:\\Users", "c:\\Users\\.."],\n ],\n)\ndef test_is_relative_not_ok_win(root, path):\n assert not is_relative(root, path)\n\n\n@pytest.mark.skipif(PY35, reason="can't test non-existent paths on py35")\n@pytest.mark.skipif(WIN, reason="can't test POSIX paths on Windows")\n@pytest.mark.parametrize(\n "root_dir, expected_root_uri",\n [\n # probably need to try some other things\n [str(HOME / "foo"), (HOME / "foo").as_uri()]\n ],\n)\ndef test_normalize_posix_path_home_subdir(\n root_dir, expected_root_uri\n): # pragma: no cover\n assert normalized_uri(root_dir) == expected_root_uri\n\n\n@pytest.mark.skipif(not WIN, reason="can't test Windows paths on POSIX")\n@pytest.mark.parametrize(\n "root_dir, expected_root_uri",\n [\n ["c:\\Users\\user1", "file:///c:/Users/user1"],\n ["C:\\Users\\user1", "file:///c:/Users/user1"],\n ["//VBOXSVR/shared-folder", "file://vboxsvr/shared-folder/"],\n ],\n)\ndef test_normalize_windows_path_case(root_dir, expected_root_uri): # pragma: no cover\n try:\n normalized = normalized_uri(root_dir)\n except FileNotFoundError as err:\n if sys.version_info >= (3, 10):\n # apparently, this triggers resolving the path on win/py3.10\n return\n raise err\n\n assert normalized == expected_root_uri\n\n\n@pytest.mark.skipif(WIN, reason="can't test POSIX paths on Windows")\n@pytest.mark.parametrize(\n "file_uri, expected_posix_path",\n [\n ["file:///C:/Windows/System32/Drivers/etc", "/C:/Windows/System32/Drivers/etc"],\n ["file:///C:/some%20dir/some%20file.txt", "/C:/some dir/some file.txt"],\n ["file:///home/user/some%20file.txt", "/home/user/some file.txt"],\n ],\n)\ndef test_file_uri_to_path_posix(file_uri, expected_posix_path): # pragma: no cover\n assert file_uri_to_path(file_uri) == expected_posix_path\n\n\n@pytest.mark.skipif(not WIN, reason="can't test Windows paths on POSIX")\n@pytest.mark.parametrize(\n "file_uri, expected_windows_path",\n [\n # https://github.com/jupyter-lsp/jupyterlab-lsp/pull/305#issuecomment-665996145\n ["file:///C:/Windows/System32/Drivers/etc", "C:/Windows/System32/Drivers/etc"],\n ["file:///C:/some%20dir/some%20file.txt", "C:/some dir/some file.txt"],\n ],\n)\ndef test_file_uri_to_path_windows(file_uri, expected_windows_path): # pragma: no cover\n assert file_uri_to_path(file_uri) == expected_windows_path\n | .venv\Lib\site-packages\jupyter_lsp\tests\test_paths.py | test_paths.py | Python | 3,812 | 0.95 | 0.09322 | 0.030612 | python-kit | 67 | 2023-08-19T03:32:44.003046 | GPL-3.0 | true | 256425caab1a111fa157c7112fc54bc5 |
import asyncio\nimport os\n\nimport pytest\n\nfrom ..schema import SERVERS_RESPONSE\n\n\nasync def assert_status_set(handler, expected_statuses, language_server=None):\n await handler.get()\n payload = handler._payload\n\n errors = list(SERVERS_RESPONSE.iter_errors(payload))\n assert not errors\n\n statuses = {\n session["status"]\n for session_server, session in payload["sessions"].items()\n if language_server is None or language_server == session_server\n }\n assert statuses == expected_statuses, payload\n\n\n@pytest.mark.asyncio\nasync def test_start_known(known_server, handlers, jsonrpc_init_msg):\n """will a process start for a known server if a handler starts?"""\n handler, ws_handler = handlers\n manager = handler.manager\n\n manager.initialize()\n\n await assert_status_set(handler, {"not_started"})\n\n await ws_handler.open(known_server)\n session = manager.sessions[ws_handler.language_server]\n assert session.process is not None\n\n await assert_status_set(handler, {"started"}, known_server)\n\n await ws_handler.on_message(jsonrpc_init_msg)\n\n try:\n await asyncio.wait_for(\n ws_handler._messages_wrote.get(),\n 120 if known_server == "julia-language-server" else 20,\n )\n ws_handler._messages_wrote.task_done()\n finally:\n ws_handler.on_close()\n\n assert not session.handlers\n assert not session.process\n\n await assert_status_set(handler, {"stopped"}, known_server)\n await assert_status_set(handler, {"stopped", "not_started"})\n\n\n@pytest.mark.asyncio\nasync def test_start_unknown(known_unknown_server, handlers, jsonrpc_init_msg):\n """will a process not start for an unknown server if a handler starts?"""\n handler, ws_handler = handlers\n manager = handler.manager\n manager.initialize()\n\n await assert_status_set(handler, {"not_started"})\n\n await ws_handler.open(known_unknown_server)\n\n await assert_status_set(handler, {"not_started"})\n\n await ws_handler.on_message(jsonrpc_init_msg)\n await assert_status_set(handler, {"not_started"})\n ws_handler.on_close()\n\n assert not manager.sessions.get(ws_handler.language_server)\n await assert_status_set(handler, {"not_started"})\n\n\n@pytest.mark.asyncio\nasync def test_ping(handlers):\n """see https://github.com/jupyter-lsp/jupyterlab-lsp/issues/458"""\n a_server = "pylsp"\n\n handler, ws_handler = handlers\n manager = handler.manager\n\n manager.initialize()\n\n assert ws_handler.ping_interval > 0\n # the default ping interval is 30 seconds, too long for a test\n ws_handler.settings["ws_ping_interval"] = 0.1\n assert ws_handler.ping_interval == 0.1\n\n assert ws_handler._ping_sent is False\n\n await ws_handler.open(a_server)\n\n assert ws_handler.ping_callback is not None and ws_handler.ping_callback.is_running\n await asyncio.sleep(ws_handler.ping_interval * 3)\n\n assert ws_handler._ping_sent is True\n\n ws_handler.on_close()\n\n\n@pytest.mark.asyncio\nasync def test_substitute_env(handlers):\n """should not leak environment variables"""\n a_server = "pylsp"\n\n handler, ws_handler = handlers\n manager = handler.manager\n\n manager.initialize()\n\n await assert_status_set(handler, {"not_started"})\n\n await ws_handler.open(a_server)\n session = manager.sessions[ws_handler.language_server]\n new_env = session.substitute_env({"test-variable": "value"}, os.environ)\n\n assert "test-variable" in new_env\n assert "test-variable" not in os.environ\n\n ws_handler.on_close()\n | .venv\Lib\site-packages\jupyter_lsp\tests\test_session.py | test_session.py | Python | 3,528 | 0.95 | 0.112 | 0.011905 | awesome-app | 761 | 2024-02-20T18:45:14.556096 | BSD-3-Clause | true | f3cb27d145db4583e0321ae7daa841d3 |
import asyncio\nimport subprocess\nimport sys\n\nimport pytest\nfrom tornado.queues import Queue\n\nfrom jupyter_lsp.stdio import LspStdIoReader\n\nWRITER_TEMPLATE = """\nfrom time import sleep\n\nprint('Content-Length: {length}')\nprint()\n\nfor repeat in range({repeats}):\n sleep({interval})\n print('{message}', end='')\n\nif {add_excess}:\n print("extra", end='')\n\nprint()\n"""\n\n\nclass CommunicatorSpawner:\n def __init__(self, tmp_path):\n self.tmp_path = tmp_path\n\n def spawn_writer(\n self, message: str, repeats: int = 1, interval=None, add_excess=False\n ):\n length = len(message) * repeats\n commands_file = self.tmp_path / "writer.py"\n commands_file.write_text(\n WRITER_TEMPLATE.format(\n length=length,\n repeats=repeats,\n interval=interval or 0,\n message=message,\n add_excess=add_excess,\n )\n )\n return subprocess.Popen(\n [sys.executable, "-u", str(commands_file)],\n stdout=subprocess.PIPE,\n bufsize=0,\n )\n\n\n@pytest.fixture\ndef communicator_spawner(tmp_path):\n return CommunicatorSpawner(tmp_path)\n\n\nasync def join_process(process: subprocess.Popen, headstart=1, timeout=1):\n await asyncio.sleep(headstart)\n result = process.wait(timeout=timeout)\n if process.stdout:\n process.stdout.close()\n return result\n\n\n@pytest.mark.parametrize(\n "message,repeats,interval,add_excess",\n [\n ["short", 1, None, False],\n ["ab" * 10_0000, 1, None, False],\n ["ab", 2, 0.01, False],\n ["ab", 45, 0.01, False],\n ["message", 2, 0.01, True],\n ],\n ids=["short", "long", "intermittent", "intensive-intermittent", "with-excess"],\n)\n@pytest.mark.asyncio\nasync def test_reader(message, repeats, interval, add_excess, communicator_spawner):\n queue = Queue()\n\n process = communicator_spawner.spawn_writer(\n message=message, repeats=repeats, interval=interval, add_excess=add_excess\n )\n reader = LspStdIoReader(stream=process.stdout, queue=queue)\n\n await asyncio.gather(join_process(process, headstart=3, timeout=1), reader.read())\n\n result = queue.get_nowait()\n assert result == message * repeats\n | .venv\Lib\site-packages\jupyter_lsp\tests\test_stdio.py | test_stdio.py | Python | 2,254 | 0.85 | 0.102273 | 0 | react-lib | 36 | 2024-08-16T02:12:56.800384 | BSD-3-Clause | true | 800858d37ecdaab0e1fd1d2472f66fab |
import logging\nfrom pathlib import Path\nfrom types import SimpleNamespace\nfrom typing import List\n\nimport pytest\n\nfrom jupyter_lsp import LanguageServerManager\n\nfrom ..virtual_documents_shadow import (\n EditableFile,\n ShadowFilesystemError,\n extract_or_none,\n setup_shadow_filesystem,\n)\n\n\n@pytest.mark.asyncio\nasync def test_read(tmp_path):\n path = tmp_path / "existing.py"\n path.write_text("a\ntest")\n\n editable_file = EditableFile(path)\n\n await editable_file.read()\n\n assert editable_file.lines == ["a", "test"]\n\n\n@pytest.mark.asyncio\nasync def test_read_missing(tmp_path):\n path = tmp_path / "missing.py"\n missing_file = EditableFile(path)\n\n await missing_file.read()\n\n assert missing_file.lines == [""]\n\n\n@pytest.mark.asyncio\nasync def test_apply_change(tmp_path):\n # inserting text\n path = tmp_path / "test.py"\n editable_file = EditableFile(path)\n await editable_file.read()\n\n editable_file.apply_change("new\ntext", **editable_file.full_range)\n assert editable_file.lines == ["new", "text"]\n\n # modifying a range\n editable_file.apply_change(\n "ves", start={"line": 1, "character": 0}, end={"line": 1, "character": 3}\n )\n assert editable_file.lines == ["new", "vest"]\n\n editable_file.apply_change("", **editable_file.full_range)\n assert editable_file.lines == [""]\n\n\ndef test_extract_or_none():\n obj = {"nested": {"value": 1}}\n assert extract_or_none(obj, ["nested"]) == {"value": 1}\n assert extract_or_none(obj, ["nested", "value"]) == 1\n assert extract_or_none(obj, ["missing", "value"]) is None\n\n\ndef did_open(uri, text):\n return {\n "method": "textDocument/didOpen",\n "params": {"textDocument": {"uri": uri, "text": text}},\n }\n\n\ndef did_change(uri, changes: List):\n return {\n "method": "textDocument/didChange",\n "params": {"textDocument": {"uri": uri}, "contentChanges": changes},\n }\n\n\ndef did_save_with_text(uri, text):\n return {\n "method": "textDocument/didSave",\n "params": {"textDocument": {"uri": uri, "text": text}},\n }\n\n\ndef did_save_without_text(uri):\n return {"method": "textDocument/didSave", "params": {"textDocument": {"uri": uri}}}\n\n\n@pytest.fixture\ndef shadow_path(tmpdir):\n return str(tmpdir.mkdir(".virtual_documents"))\n\n\n@pytest.fixture\ndef manager():\n manager = LanguageServerManager()\n manager.language_servers = {\n "python-lsp-server": {\n "requires_documents_on_disk": True,\n "argv": [],\n "languages": ["python"],\n "version": 2,\n }\n }\n return manager\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\n "message_func, content, expected_content",\n [\n [did_open, "content\nof\nopened\nfile", "content\nof\nopened\nfile"],\n [did_change, [{"text": "content after change"}], "content after change"],\n [did_save_with_text, "content at save", "content at save"],\n ],\n)\nasync def test_shadow(shadow_path, message_func, content, expected_content, manager):\n shadow = setup_shadow_filesystem(Path(shadow_path).as_uri())\n ok_file_path = Path(shadow_path) / "test.py"\n\n message = message_func(ok_file_path.as_uri(), content)\n result = await shadow("client", message, "python-lsp-server", manager)\n assert isinstance(result, str)\n\n with open(ok_file_path) as f:\n assert f.read() == expected_content\n\n\n@pytest.mark.asyncio\nasync def test_no_shadow_for_well_behaved_server(\n shadow_path,\n):\n """We call server well behaved when it does not require a disk copy"""\n shadow_path_for_well = Path(shadow_path) / "well"\n shadow = setup_shadow_filesystem(Path(shadow_path_for_well).as_uri())\n ok_file_path = Path(shadow_path_for_well) / "test.py"\n\n manager = SimpleNamespace(\n language_servers={"python-lsp-server": {"requires_documents_on_disk": False}}\n )\n\n message = did_open(ok_file_path.as_uri(), "content\nof\nopened\nfile")\n result = await shadow("client", message, "python-lsp-server", manager)\n # should short-circuit for well behaved server\n assert result is None\n # should not create the directory\n assert not shadow_path_for_well.exists()\n\n\n@pytest.mark.asyncio\nasync def test_shadow_created_for_ill_behaved_server(\n shadow_path,\n):\n shadow_path_for_ill = Path(shadow_path) / "ill"\n shadow = setup_shadow_filesystem(shadow_path_for_ill.as_uri())\n ok_file_path = Path(shadow_path_for_ill) / "test.py"\n\n manager = SimpleNamespace(\n language_servers={"python-lsp-server": {"requires_documents_on_disk": True}}\n )\n\n message = did_open(ok_file_path.as_uri(), "content\nof\nopened\nfile")\n result = await shadow("client", message, "python-lsp-server", manager)\n assert result is not None\n # should create the directory at given path\n assert shadow_path_for_ill.exists()\n assert shadow_path_for_ill.is_dir()\n\n\n@pytest.mark.asyncio\nasync def test_shadow_failures(shadow_path, manager):\n shadow = setup_shadow_filesystem(Path(shadow_path).as_uri())\n ok_file_uri = (Path(shadow_path) / "test.py").as_uri()\n\n def run_shadow(message):\n return shadow("client", message, "python-lsp-server", manager)\n\n # missing textDocument\n with pytest.raises(ShadowFilesystemError, match="Could not get textDocument from"):\n await run_shadow({"method": "textDocument/didChange"})\n\n # missing URI\n with pytest.raises(ShadowFilesystemError, match="Could not get URI from"):\n await run_shadow(\n {"method": "textDocument/didChange", "params": {"textDocument": {}}}\n )\n\n # should ignore other methods\n result = await run_shadow({"method": "textDocument/completion"})\n assert result is None\n\n # should NOT intercept (nor shadow) files from location other than shadow_path\n result = await run_shadow(did_open("file:///other/path.py", "content"))\n assert result is None\n\n # should fail silently on missing text in didSave\n result = await run_shadow(did_save_without_text(ok_file_uri))\n assert result is None\n\n # should raise on missing changes in didChange\n with pytest.raises(ShadowFilesystemError, match=".* is missing contentChanges"):\n await run_shadow(\n {\n "method": "textDocument/didChange",\n "params": {"textDocument": {"uri": ok_file_uri}},\n }\n )\n\n\n@pytest.mark.asyncio\nasync def test_shadow_traversal(shadow_path, manager):\n file_beyond_shadow_root_uri = (Path(shadow_path) / ".." / "test.py").as_uri()\n\n shadow = setup_shadow_filesystem(Path(shadow_path).as_uri())\n\n def run_shadow(message):\n return shadow("client", message, "python-lsp-server", manager)\n\n with pytest.raises(\n ShadowFilesystemError, match="is not relative to shadow filesystem root"\n ):\n await run_shadow(did_open(file_beyond_shadow_root_uri, "content"))\n\n\n@pytest.fixture\ndef forbidden_shadow_path(tmpdir):\n path = Path(tmpdir) / "no_permission_dir"\n path.mkdir()\n path.chmod(0o000)\n\n yield path\n\n # re-adjust the permissions, see https://github.com/pytest-dev/pytest/issues/7821\n path.chmod(0o755)\n\n\n@pytest.mark.asyncio\nasync def test_io_failure(forbidden_shadow_path, manager, caplog):\n file_uri = (forbidden_shadow_path / "test.py").as_uri()\n\n shadow = setup_shadow_filesystem(forbidden_shadow_path.as_uri())\n\n def send_change():\n message = did_open(file_uri, "content")\n return shadow("client", message, "python-lsp-server", manager)\n\n with caplog.at_level(logging.WARNING):\n assert await send_change() is None\n assert await send_change() is None\n # no message should be emitted during the first two attempts\n assert caplog.text == ""\n\n # a warning should be emitted on third failure\n with caplog.at_level(logging.WARNING):\n assert await send_change() is None\n assert "initialization of shadow filesystem failed three times" in caplog.text\n assert "PermissionError" in caplog.text\n caplog.clear()\n\n # no message should be emitted in subsequent attempts\n with caplog.at_level(logging.WARNING):\n assert await send_change() is None\n assert caplog.text == ""\n | .venv\Lib\site-packages\jupyter_lsp\tests\test_virtual_documents_shadow.py | test_virtual_documents_shadow.py | Python | 8,193 | 0.95 | 0.078947 | 0.075758 | awesome-app | 881 | 2024-05-24T15:20:13.780856 | BSD-3-Clause | true | d75895c473b11a0ffa9b4b4e7e1aa076 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\tests\__pycache__\conftest.cpython-313.pyc | conftest.cpython-313.pyc | Other | 7,021 | 0.8 | 0 | 0 | python-kit | 839 | 2023-12-08T00:00:44.404905 | MIT | true | b3da16e4f401236b176395e728e42fa9 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\tests\__pycache__\listener.cpython-313.pyc | listener.cpython-313.pyc | Other | 356 | 0.8 | 0 | 0 | node-utils | 513 | 2024-06-13T00:32:45.963142 | MIT | true | f90301699f1a5a1054ecbe536229d379 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\tests\__pycache__\test_auth.cpython-313.pyc | test_auth.cpython-313.pyc | Other | 7,181 | 0.8 | 0.04 | 0.014925 | vue-tools | 644 | 2024-05-26T11:16:30.624439 | Apache-2.0 | true | 018947e6f63615724d2c28ebd3afbd3a |
\n\n | .venv\Lib\site-packages\jupyter_lsp\tests\__pycache__\test_bad_spec.cpython-313.pyc | test_bad_spec.cpython-313.pyc | Other | 872 | 0.7 | 0 | 0 | node-utils | 621 | 2024-02-25T23:39:56.607614 | GPL-3.0 | true | bdd0cacbd91cc66ed4236a3657190b27 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\tests\__pycache__\test_conf_d.cpython-313.pyc | test_conf_d.cpython-313.pyc | Other | 666 | 0.7 | 0 | 0 | awesome-app | 657 | 2024-12-12T13:20:35.825312 | Apache-2.0 | true | b2bbadf6300a075ab54af9c5e5d3cb25 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\tests\__pycache__\test_detect.cpython-313.pyc | test_detect.cpython-313.pyc | Other | 2,445 | 0.8 | 0 | 0 | awesome-app | 14 | 2024-02-08T04:48:49.709933 | MIT | true | 667d724a24f096d82a2b031ff4393aff |
\n\n | .venv\Lib\site-packages\jupyter_lsp\tests\__pycache__\test_extension.cpython-313.pyc | test_extension.cpython-313.pyc | Other | 2,471 | 0.95 | 0 | 0 | awesome-app | 424 | 2023-11-20T14:52:33.610466 | Apache-2.0 | true | 7bbc90ca0e09b456cce9bf07cf024d6e |
\n\n | .venv\Lib\site-packages\jupyter_lsp\tests\__pycache__\test_listener.cpython-313.pyc | test_listener.cpython-313.pyc | Other | 5,777 | 0.95 | 0.019231 | 0 | awesome-app | 329 | 2025-04-26T05:23:21.699401 | Apache-2.0 | true | 589671283bdb46e1a4fba5dbc50740c2 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\tests\__pycache__\test_paths.cpython-313.pyc | test_paths.cpython-313.pyc | Other | 5,253 | 0.8 | 0 | 0 | python-kit | 245 | 2024-03-12T17:34:30.825518 | GPL-3.0 | true | bed129c0804bcd6c11248347ae2ec037 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\tests\__pycache__\test_session.cpython-313.pyc | test_session.cpython-313.pyc | Other | 6,189 | 0.8 | 0.046512 | 0.024096 | node-utils | 293 | 2024-01-15T16:32:39.828631 | Apache-2.0 | true | 2eff30ef72de65c72653164efd792152 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\tests\__pycache__\test_stdio.cpython-313.pyc | test_stdio.cpython-313.pyc | Other | 3,708 | 0.95 | 0.027027 | 0.030303 | awesome-app | 490 | 2025-04-22T17:50:50.174959 | Apache-2.0 | true | 3e5dd48b8bd61b00dd88c4e8aedb556b |
\n\n | .venv\Lib\site-packages\jupyter_lsp\tests\__pycache__\test_virtual_documents_shadow.cpython-313.pyc | test_virtual_documents_shadow.cpython-313.pyc | Other | 12,437 | 0.95 | 0 | 0.046875 | react-lib | 95 | 2025-05-13T14:45:05.724546 | BSD-3-Clause | true | b9e32b256c9c3a3aa919e6bfbd5df7ee |
\n\n | .venv\Lib\site-packages\jupyter_lsp\tests\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 192 | 0.7 | 0 | 0 | awesome-app | 671 | 2024-05-24T16:07:31.953069 | MIT | true | 0c6e3787d9af9b451d6ef2a2c385b51a |
\n\n | .venv\Lib\site-packages\jupyter_lsp\__pycache__\constants.cpython-313.pyc | constants.cpython-313.pyc | Other | 551 | 0.8 | 0 | 0 | vue-tools | 324 | 2024-07-25T20:15:51.014542 | BSD-3-Clause | false | 95481513c7cceccf94c60d16d3974d23 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\__pycache__\handlers.cpython-313.pyc | handlers.cpython-313.pyc | Other | 7,891 | 0.8 | 0.029412 | 0 | vue-tools | 915 | 2024-04-04T15:13:51.215285 | BSD-3-Clause | false | a976cd598220af34ac950cb59218920d |
\n\n | .venv\Lib\site-packages\jupyter_lsp\__pycache__\manager.cpython-313.pyc | manager.cpython-313.pyc | Other | 14,142 | 0.95 | 0.017094 | 0 | awesome-app | 587 | 2025-06-14T00:06:15.701591 | MIT | false | 24cb37aa9c702035240a9b769a220e5b |
\n\n | .venv\Lib\site-packages\jupyter_lsp\__pycache__\non_blocking.cpython-313.pyc | non_blocking.cpython-313.pyc | Other | 1,992 | 0.8 | 0 | 0 | awesome-app | 104 | 2025-02-19T23:53:48.617129 | Apache-2.0 | false | c6f26cd84e1276e1840063db3f7a5adb |
\n\n | .venv\Lib\site-packages\jupyter_lsp\__pycache__\paths.cpython-313.pyc | paths.cpython-313.pyc | Other | 2,446 | 0.8 | 0.090909 | 0 | python-kit | 56 | 2024-07-31T01:44:22.126837 | GPL-3.0 | false | e5e4b3e92b6e66259442223e1e9e5dd5 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\__pycache__\serverextension.cpython-313.pyc | serverextension.cpython-313.pyc | Other | 4,094 | 0.95 | 0 | 0 | awesome-app | 768 | 2024-05-31T21:36:56.098970 | Apache-2.0 | false | e8e0080239af514a4cc6a7439b46a5a3 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\__pycache__\session.cpython-313.pyc | session.cpython-313.pyc | Other | 10,150 | 0.95 | 0.095238 | 0 | node-utils | 728 | 2023-11-09T18:58:03.141978 | BSD-3-Clause | false | 69bd57854111ce3c9a7cd9dbb34255d3 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\__pycache__\stdio.cpython-313.pyc | stdio.cpython-313.pyc | Other | 11,271 | 0.8 | 0.030303 | 0.045455 | python-kit | 868 | 2025-01-01T16:59:54.199559 | Apache-2.0 | false | 6fa905d3e38de8a7cff56d8b21afd11b |
\n\n | .venv\Lib\site-packages\jupyter_lsp\__pycache__\trait_types.cpython-313.pyc | trait_types.cpython-313.pyc | Other | 2,287 | 0.95 | 0.034483 | 0 | react-lib | 485 | 2025-03-07T10:42:45.579787 | MIT | false | c0f090b6a6404ecf958a8694cf4234fc |
\n\n | .venv\Lib\site-packages\jupyter_lsp\__pycache__\types.cpython-313.pyc | types.cpython-313.pyc | Other | 13,442 | 0.8 | 0.072993 | 0 | awesome-app | 96 | 2024-02-13T18:55:06.664116 | Apache-2.0 | false | ab5ea34b203f363ddfdc31a3acc249c6 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\__pycache__\virtual_documents_shadow.cpython-313.pyc | virtual_documents_shadow.cpython-313.pyc | Other | 9,317 | 0.95 | 0.08642 | 0 | vue-tools | 33 | 2023-07-25T06:32:44.786471 | Apache-2.0 | false | d3a2c6cd9463c7a71548055057c31f2b |
\n\n | .venv\Lib\site-packages\jupyter_lsp\__pycache__\_version.cpython-313.pyc | _version.cpython-313.pyc | Other | 281 | 0.7 | 0.333333 | 0 | node-utils | 527 | 2024-09-30T19:29:13.609071 | BSD-3-Clause | false | 25dbc29ec35603dbca04e2a70cece5a6 |
\n\n | .venv\Lib\site-packages\jupyter_lsp\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 798 | 0.7 | 0 | 0 | python-kit | 833 | 2023-07-23T16:06:23.484204 | Apache-2.0 | false | f2a5cc20a73bd4d8a4bb2eaf1f008fdb |
[jupyter_lsp_spec_v1]\nbash-language-server = jupyter_lsp.specs:bash\ndockerfile-language-server-nodejs = jupyter_lsp.specs:dockerfile\njavascript-typescript-langserver = jupyter_lsp.specs:ts_old\njedi-language-server = jupyter_lsp.specs:jedi\njulia-language-server = jupyter_lsp.specs:julia\npyright = jupyter_lsp.specs:pyright\npython-language-server = jupyter_lsp.specs:py_palantir\npython-lsp-server = jupyter_lsp.specs:py_lsp_server\nr-languageserver = jupyter_lsp.specs:r\nsql-language-server = jupyter_lsp.specs:sql\ntexlab = jupyter_lsp.specs:tex\ntypescript-language-server = jupyter_lsp.specs:ts\nunified-language-server = jupyter_lsp.specs:md\nvscode-css-languageserver-bin = jupyter_lsp.specs:css\nvscode-html-languageserver-bin = jupyter_lsp.specs:html\nvscode-json-languageserver-bin = jupyter_lsp.specs:json\nyaml-language-server = jupyter_lsp.specs:yaml\n | .venv\Lib\site-packages\jupyter_lsp-2.2.5.dist-info\entry_points.txt | entry_points.txt | Other | 853 | 0.7 | 0 | 0 | awesome-app | 367 | 2023-07-29T18:32:33.852311 | BSD-3-Clause | false | f7eaf1afd29e12b49963fadd5ad03b19 |
pip\n | .venv\Lib\site-packages\jupyter_lsp-2.2.5.dist-info\INSTALLER | INSTALLER | Other | 4 | 0.5 | 0 | 0 | node-utils | 404 | 2025-02-21T07:39:33.983596 | MIT | false | 365c9bfeb7d89244f2ce01c1de44cb85 |
BSD 3-Clause License\n\nCopyright (c) 2022, jupyter-lsp contributors\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n | .venv\Lib\site-packages\jupyter_lsp-2.2.5.dist-info\LICENSE | LICENSE | Other | 1,524 | 0.7 | 0 | 0.130435 | awesome-app | 521 | 2024-11-13T16:14:32.143727 | Apache-2.0 | false | 7c4ff345ebb091fcbc5290142e324da5 |
Metadata-Version: 2.1\nName: jupyter-lsp\nVersion: 2.2.5\nSummary: Multi-Language Server WebSocket proxy for Jupyter Notebook/Lab server\nAuthor: jupyter-lsp Contributors\nAuthor-email: project.jupyter@gmail.com\nLicense: BSD-3-Clause\nProject-URL: Bug Tracker, https://github.com/jupyter-lsp/jupyterlab-lsp/issues\nProject-URL: Documentation, https://jupyterlab-lsp.readthedocs.io/\nProject-URL: Source Code, https://github.com/jupyter-lsp/jupyterlab-lsp\nKeywords: Interactive,Language Server,LSP\nClassifier: Framework :: Jupyter\nClassifier: Intended Audience :: Developers\nClassifier: Intended Audience :: Information Technology\nClassifier: License :: OSI Approved :: BSD License\nClassifier: Programming Language :: Python\nRequires-Python: >=3.8\nDescription-Content-Type: text/markdown\nLicense-File: LICENSE\nRequires-Dist: jupyter-server >=1.1.2\nRequires-Dist: importlib-metadata >=4.8.3 ; python_version < "3.10"\n\n# jupyter-lsp\n\nMulti-[Language Server][language-server] WebSocket proxy for your Jupyter\n`notebook` or `lab` server. For Python 3.6+.\n\n> See the parent of this repository,\n> [jupyterlab-lsp](https://github.com/jupyter-lsp/jupyterlab-lsp) for the\n> reference client implementation for [JupyterLab][].\n\n# Language Servers\n\n`jupyter-lsp` does not come with any Language Servers! Learn more about installing\nand configuring [language servers][language servers docs]\n\n[language-server]: https://microsoft.github.io/language-server-protocol/specification\n[langserver]: https://langserver.org\n[lsp-implementations]: https://microsoft.github.io/language-server-protocol/implementors/servers\n[jupyter-lsp]: https://github.com/jupyter-lsp/jupyterlab-lsp.git\n[jupyterlab]: https://github.com/jupyterlab/jupyterlab\n[language servers docs]: https://jupyterlab-lsp.readthedocs.io/en/latest/Language%20Servers.html\n | .venv\Lib\site-packages\jupyter_lsp-2.2.5.dist-info\METADATA | METADATA | Other | 1,808 | 0.95 | 0.095238 | 0.055556 | python-kit | 633 | 2023-07-30T03:04:45.821342 | BSD-3-Clause | false | b9c924553ffeafac2b899ca215f1671b |
../../etc/jupyter/jupyter_server_config.d/jupyter-lsp-jupyter-server.json,sha256=9X-76sVbEN2Vk6AGRw5zq6hxV7NMVzR2UghXOoDj-mc,86\njupyter_lsp-2.2.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4\njupyter_lsp-2.2.5.dist-info/LICENSE,sha256=6mXGPsO0RBDySU3OuT3WrsPxUNIX1C2YxUamoIm8EpU,1524\njupyter_lsp-2.2.5.dist-info/METADATA,sha256=SviVPQxB0FxvyUY-we_J4dSkXtYxAiAcKgtyH1rkeq8,1808\njupyter_lsp-2.2.5.dist-info/RECORD,,\njupyter_lsp-2.2.5.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92\njupyter_lsp-2.2.5.dist-info/entry_points.txt,sha256=nvkHme-Pe1S1qZblLzXVk92ql4jVgKtTPR9MdoHQxfk,853\njupyter_lsp-2.2.5.dist-info/top_level.txt,sha256=dfcpiezOX-jfFIVtXZ-qAB2x32-e3HOQtVLb5qH5Tzw,12\njupyter_lsp/__init__.py,sha256=CvaaCJWqE1MzbReJObqkujSKijTyRNQss1aYlUzG-mo,486\njupyter_lsp/__pycache__/__init__.cpython-313.pyc,,\njupyter_lsp/__pycache__/_version.cpython-313.pyc,,\njupyter_lsp/__pycache__/constants.cpython-313.pyc,,\njupyter_lsp/__pycache__/handlers.cpython-313.pyc,,\njupyter_lsp/__pycache__/manager.cpython-313.pyc,,\njupyter_lsp/__pycache__/non_blocking.cpython-313.pyc,,\njupyter_lsp/__pycache__/paths.cpython-313.pyc,,\njupyter_lsp/__pycache__/serverextension.cpython-313.pyc,,\njupyter_lsp/__pycache__/session.cpython-313.pyc,,\njupyter_lsp/__pycache__/stdio.cpython-313.pyc,,\njupyter_lsp/__pycache__/trait_types.cpython-313.pyc,,\njupyter_lsp/__pycache__/types.cpython-313.pyc,,\njupyter_lsp/__pycache__/virtual_documents_shadow.cpython-313.pyc,,\njupyter_lsp/_version.py,sha256=A-_X4z-HIXDUNH8L0t23lBYFqseY8bhKN4BBx-2z4Vg,78\njupyter_lsp/constants.py,sha256=fcT25Q5JCW_R7cfPcrARfrq8GrCvUnlCvcPIjyS04Ns,498\njupyter_lsp/etc/jupyter-lsp-jupyter-server.json,sha256=9X-76sVbEN2Vk6AGRw5zq6hxV7NMVzR2UghXOoDj-mc,86\njupyter_lsp/handlers.py,sha256=sSnBVG8eincGAlmKmToN380oSZeaotx5wsmFfhIb_bs,4727\njupyter_lsp/manager.py,sha256=UjCNfgvlWAf6jABq8Maxy5fkgRmnYWwvT1sGXqcYWVI,10792\njupyter_lsp/non_blocking.py,sha256=DCYfXszZtpkSZyOzhLogAxECL-_QLuecfqAUQebLQzY,1546\njupyter_lsp/paths.py,sha256=IdKFv9XHkKGZlGBu8lyZ_r6CBPGRSOy0NRI7OhOgvYM,1405\njupyter_lsp/schema/__init__.py,sha256=PK7dJ18QRtbw_2PUsnPob_174uIpm_X6yULqdVZRXLI,666\njupyter_lsp/schema/__pycache__/__init__.cpython-313.pyc,,\njupyter_lsp/schema/schema.json,sha256=bDmCT_F-sDhdW7GkyCLwPpPthbR-lyjX4rmi_ah6w-M,8855\njupyter_lsp/serverextension.py,sha256=Aj16oTWZEyvj6CtNsl5tdmUihBaJE6YDEalF1919_Tc,2862\njupyter_lsp/session.py,sha256=A6tGmrZfEy6EBqBoBIoYl7wTIKtW-hXo1W2YTTtG7Do,5908\njupyter_lsp/specs/__init__.py,sha256=HrxtE-fTpPGE0FLQMJ-XLiDS1_fM_rPubJjFTXBEVqE,1540\njupyter_lsp/specs/__pycache__/__init__.cpython-313.pyc,,\njupyter_lsp/specs/__pycache__/bash_language_server.cpython-313.pyc,,\njupyter_lsp/specs/__pycache__/dockerfile_language_server_nodejs.cpython-313.pyc,,\njupyter_lsp/specs/__pycache__/javascript_typescript_langserver.cpython-313.pyc,,\njupyter_lsp/specs/__pycache__/jedi_language_server.cpython-313.pyc,,\njupyter_lsp/specs/__pycache__/julia_language_server.cpython-313.pyc,,\njupyter_lsp/specs/__pycache__/pyls.cpython-313.pyc,,\njupyter_lsp/specs/__pycache__/pyright.cpython-313.pyc,,\njupyter_lsp/specs/__pycache__/python_lsp_server.cpython-313.pyc,,\njupyter_lsp/specs/__pycache__/r_languageserver.cpython-313.pyc,,\njupyter_lsp/specs/__pycache__/sql_language_server.cpython-313.pyc,,\njupyter_lsp/specs/__pycache__/texlab.cpython-313.pyc,,\njupyter_lsp/specs/__pycache__/typescript_language_server.cpython-313.pyc,,\njupyter_lsp/specs/__pycache__/unified_language_server.cpython-313.pyc,,\njupyter_lsp/specs/__pycache__/utils.cpython-313.pyc,,\njupyter_lsp/specs/__pycache__/vscode_css_languageserver.cpython-313.pyc,,\njupyter_lsp/specs/__pycache__/vscode_html_languageserver.cpython-313.pyc,,\njupyter_lsp/specs/__pycache__/vscode_json_languageserver.cpython-313.pyc,,\njupyter_lsp/specs/__pycache__/yaml_language_server.cpython-313.pyc,,\njupyter_lsp/specs/bash_language_server.py,sha256=nXn7O4GrGsikCYRyjFlAg_Ewcf0SYqruw1w5Fcy2IEs,1131\njupyter_lsp/specs/config/__init__.py,sha256=_4pSKHblPbmgsYXrDl2otV6ujZH2fTmDzkygQ2ABXrE,237\njupyter_lsp/specs/config/__pycache__/__init__.cpython-313.pyc,,\njupyter_lsp/specs/config/bash-language-server.schema.json,sha256=xui__5uoYL8-NclhNgR-KfF5niIVmwRciE8460Vl5hQ,2142\njupyter_lsp/specs/config/dockerfile-language-server-nodejs.schema.json,sha256=-fj8zuhpfhKVsvvlP5dPPE1QUIFiHtKf-IH0OQa0Mmo,11154\njupyter_lsp/specs/config/julia-language-server.schema.json,sha256=vXlh7_7xWvMY-u0IaHUtLtsq9GWS1zn_cKCkSYdi3Qw,4070\njupyter_lsp/specs/config/pyls.schema.json,sha256=T-oED5dIDLQXQVHqRrvT_dzZBLXjWnckI1YzWk12_6A,7581\njupyter_lsp/specs/config/pylsp.schema.json,sha256=Epo05nErho5NfhszURw23kwbZppdI92RPmkDrbMIAE0,12070\njupyter_lsp/specs/config/pyright.schema.json,sha256=RD6rV-ge769DmXUB224ebq_GLxdxCaxRTfQ9WWllncs,27670\njupyter_lsp/specs/config/r-languageserver.schema.json,sha256=D0v5_TdxSWtEmoXw6bu4r8UFIKclQ0QApqv5HorGis8,1299\njupyter_lsp/specs/config/sql-language-server.schema.json,sha256=HjCQXNmkF0xNp3r_n_pVv8LBpf5O7wmEBp4pMi4FHbI,3992\njupyter_lsp/specs/config/texlab.schema.json,sha256=KJOKEdagLw6PFKIn6SYBTgATiuTk8Z6KPOM6nuRI308,2913\njupyter_lsp/specs/config/typescript-language-server.schema.json,sha256=u93N9Mnl-6CmwiZJerzc_VSWYbK2-pB7qc1bWAuOXyE,782\njupyter_lsp/specs/config/yaml-language-server.schema.json,sha256=0Yzjd17m6eYz6A46kFiMoAuv-V4nNdQuAY1aWN82f-Q,3483\njupyter_lsp/specs/dockerfile_language_server_nodejs.py,sha256=AL7CKJIsX5PsLjPjeYWDURC2CsZUjp1e4cAtwNxgCp4,768\njupyter_lsp/specs/javascript_typescript_langserver.py,sha256=fD_5Eg865qM_sM9KzppKwmYUyrx_skqR8MAkED2mz7o,1100\njupyter_lsp/specs/jedi_language_server.py,sha256=NLKJ8DpQzh6g0nCR_Wg-_fZt9xFJPi6CaN8UaoNhygk,632\njupyter_lsp/specs/julia_language_server.py,sha256=ykm-im6Vn5Qvu5hx98rdZTC505ws4FiRLFCYlJlHNTk,895\njupyter_lsp/specs/pyls.py,sha256=xTCOk-0l_uD-0T_dvYXTpAuWsWxz_3D1goEbvZIh9hc,1262\njupyter_lsp/specs/pyright.py,sha256=_hKHAn5hcYyBDPRjNr6a3gXSSp-mLcOXwUiDE_voKU0,776\njupyter_lsp/specs/python_lsp_server.py,sha256=Lc5t__3-7ioZAVJlDle7bEyj8UNsOe7wHFF8DNXIQ6c,1633\njupyter_lsp/specs/r_languageserver.py,sha256=s8OLVoFaz0y77Tv35V0x5u6eTAQ7yJWpi_5We8iOq2s,1518\njupyter_lsp/specs/sql_language_server.py,sha256=SVYtkKCve54YGvUVr7rozh184tCK42ERO1SVxfTmUew,973\njupyter_lsp/specs/texlab.py,sha256=ifDiXcMYQjgm-eNedFS3Tw4Di5JGGn-qG-VAtyz2CPs,984\njupyter_lsp/specs/typescript_language_server.py,sha256=Wl9EyOYTtErKDPl0D2VJZnD5S3fLundF8lWx7aW0ShM,1218\njupyter_lsp/specs/unified_language_server.py,sha256=FeZWsrlFgv8vycjB5dFO3UyQLaXQg1QWIHHlKOIP7m0,744\njupyter_lsp/specs/utils.py,sha256=mEutvJZU6BNxzEG65qmFOSXcCsotPglBTG2-WPdCTQc,4737\njupyter_lsp/specs/vscode_css_languageserver.py,sha256=x_zsgEYT4HqLA5pnlVDZBaLWGEb0xNuDQZGw2Xwc2DY,723\njupyter_lsp/specs/vscode_html_languageserver.py,sha256=G0jSdV9pGoExFLIWikEErI1xIUgq_rqllikqw3UiyqY,682\njupyter_lsp/specs/vscode_json_languageserver.py,sha256=UmVqLaas3tKdk0i2xZiZSmCt1wFsJnG4Fpk0w1_uhJk,734\njupyter_lsp/specs/yaml_language_server.py,sha256=1skIaXuAe0awv3Hla9b_pdR3iwxL_w7AkBI8IR1AWEg,754\njupyter_lsp/stdio.py,sha256=kpkmW2s-hzI5OkTkmlprktH8i1JWs7drZZEvzf6kddA,7031\njupyter_lsp/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\njupyter_lsp/tests/__pycache__/__init__.cpython-313.pyc,,\njupyter_lsp/tests/__pycache__/conftest.cpython-313.pyc,,\njupyter_lsp/tests/__pycache__/listener.cpython-313.pyc,,\njupyter_lsp/tests/__pycache__/test_auth.cpython-313.pyc,,\njupyter_lsp/tests/__pycache__/test_bad_spec.cpython-313.pyc,,\njupyter_lsp/tests/__pycache__/test_conf_d.cpython-313.pyc,,\njupyter_lsp/tests/__pycache__/test_detect.cpython-313.pyc,,\njupyter_lsp/tests/__pycache__/test_extension.cpython-313.pyc,,\njupyter_lsp/tests/__pycache__/test_listener.cpython-313.pyc,,\njupyter_lsp/tests/__pycache__/test_paths.cpython-313.pyc,,\njupyter_lsp/tests/__pycache__/test_session.cpython-313.pyc,,\njupyter_lsp/tests/__pycache__/test_stdio.cpython-313.pyc,,\njupyter_lsp/tests/__pycache__/test_virtual_documents_shadow.cpython-313.pyc,,\njupyter_lsp/tests/conftest.py,sha256=4DFqMItuw1-74oNu7SPOuQD70PiJQg6oot3AsQNGVKY,4327\njupyter_lsp/tests/listener.py,sha256=aIvhsi3l3lAND2ozrLJsNJZpebkEoYVHYuz2SyLWnBQ,77\njupyter_lsp/tests/test_auth.py,sha256=E2Y1lluyb1zJWGssoA4bF8t-fqHVHOIOaq59-CekiWE,4368\njupyter_lsp/tests/test_bad_spec.py,sha256=OBCxYAhSvMx0CDipNaGjgHAUXiUt2YFmEsUBPSqnFc4,394\njupyter_lsp/tests/test_conf_d.py,sha256=M7IhvJHHkHcMgFYt3XulC7RLhtCu-RsR9CEa4TCUG2A,275\njupyter_lsp/tests/test_detect.py,sha256=-1i26enhtWc1u1TwMdQoYdVka9NDFRfmohPDd6v6QTw,1260\njupyter_lsp/tests/test_extension.py,sha256=YwOqsy9s-8Cp0o9Bvn3lQH7dare16uJTQvgecL7_TBQ,1543\njupyter_lsp/tests/test_listener.py,sha256=WPOavsSkmVZU_fgJQlY5Sr4dB3QBtUUGKp4CnKFFHA4,3595\njupyter_lsp/tests/test_paths.py,sha256=1eez22zvTYk-Vo_jMulfd7ytdDqZFj1Yi-XAP8Jaoww,3812\njupyter_lsp/tests/test_session.py,sha256=smv7OHnFacFpdN8svGbVE8-29NUUIoYYxd0dRPsp90s,3528\njupyter_lsp/tests/test_stdio.py,sha256=7fxCQuFOrgYC3TfDrkNXbwJmMfRfnQzwkZPFNAP91QM,2254\njupyter_lsp/tests/test_virtual_documents_shadow.py,sha256=y5wwxKpGY2dhEwm8CbjQIg4UYIoOhW2eD12O6iTrI08,8193\njupyter_lsp/trait_types.py,sha256=4VSOU7UGJhXQVkZhdlrxxFjrm3HnatQKOoef16x5osQ,1076\njupyter_lsp/types.py,sha256=UVRA4MRWB0kKPC_m2Ldc8zx4n_Ntqhc7aV9X_6aBSz8,9538\njupyter_lsp/virtual_documents_shadow.py,sha256=IZ2Rtp3ql4Ej-Fqhq3jrMusjLmzfLT018LTr6Y7N93U,7359\n | .venv\Lib\site-packages\jupyter_lsp-2.2.5.dist-info\RECORD | RECORD | Other | 9,348 | 0.7 | 0 | 0 | react-lib | 165 | 2024-10-28T00:59:33.609734 | GPL-3.0 | false | 1a399cb2fc7277abc144e07a2d6552c6 |
jupyter_lsp\n | .venv\Lib\site-packages\jupyter_lsp-2.2.5.dist-info\top_level.txt | top_level.txt | Other | 12 | 0.5 | 0 | 0 | react-lib | 326 | 2024-03-22T00:08:33.372234 | MIT | false | 2c7531af3f9d73a6d86546f6e10e97e7 |
Wheel-Version: 1.0\nGenerator: bdist_wheel (0.43.0)\nRoot-Is-Purelib: true\nTag: py3-none-any\n\n | .venv\Lib\site-packages\jupyter_lsp-2.2.5.dist-info\WHEEL | WHEEL | Other | 92 | 0.5 | 0 | 0 | python-kit | 249 | 2024-03-20T17:15:14.231071 | BSD-3-Clause | false | 43136dde7dd276932f6197bb6d676ef4 |
"""Manager to read and modify config data in JSON files."""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport copy\nimport errno\nimport glob\nimport json\nimport os\nimport typing as t\n\nfrom traitlets.config import LoggingConfigurable\nfrom traitlets.traitlets import Bool, Unicode\n\nStrDict = dict[str, t.Any]\n\n\ndef recursive_update(target: StrDict, new: StrDict) -> None:\n """Recursively update one dictionary using another.\n\n None values will delete their keys.\n """\n for k, v in new.items():\n if isinstance(v, dict):\n if k not in target:\n target[k] = {}\n recursive_update(target[k], v)\n if not target[k]:\n # Prune empty subdicts\n del target[k]\n\n elif v is None:\n target.pop(k, None)\n\n else:\n target[k] = v\n\n\ndef remove_defaults(data: StrDict, defaults: StrDict) -> None:\n """Recursively remove items from dict that are already in defaults"""\n # copy the iterator, since data will be modified\n for key, value in list(data.items()):\n if key in defaults:\n if isinstance(value, dict):\n remove_defaults(data[key], defaults[key])\n if not data[key]: # prune empty subdicts\n del data[key]\n elif value == defaults[key]:\n del data[key]\n\n\nclass BaseJSONConfigManager(LoggingConfigurable):\n """General JSON config manager\n\n Deals with persisting/storing config in a json file with optionally\n default values in a {section_name}.d directory.\n """\n\n config_dir = Unicode(".")\n read_directory = Bool(True)\n\n def ensure_config_dir_exists(self) -> None:\n """Will try to create the config_dir directory."""\n try:\n os.makedirs(self.config_dir, 0o755)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n def file_name(self, section_name: str) -> str:\n """Returns the json filename for the section_name: {config_dir}/{section_name}.json"""\n return os.path.join(self.config_dir, section_name + ".json")\n\n def directory(self, section_name: str) -> str:\n """Returns the directory name for the section name: {config_dir}/{section_name}.d"""\n return os.path.join(self.config_dir, section_name + ".d")\n\n def get(self, section_name: str, include_root: bool = True) -> dict[str, t.Any]:\n """Retrieve the config data for the specified section.\n\n Returns the data as a dictionary, or an empty dictionary if the file\n doesn't exist.\n\n When include_root is False, it will not read the root .json file,\n effectively returning the default values.\n """\n paths = [self.file_name(section_name)] if include_root else []\n if self.read_directory:\n pattern = os.path.join(self.directory(section_name), "*.json")\n # These json files should be processed first so that the\n # {section_name}.json take precedence.\n # The idea behind this is that installing a Python package may\n # put a json file somewhere in the a .d directory, while the\n # .json file is probably a user configuration.\n paths = sorted(glob.glob(pattern)) + paths\n self.log.debug(\n "Paths used for configuration of %s: \n\t%s",\n section_name,\n "\n\t".join(paths),\n )\n data: dict[str, t.Any] = {}\n for path in paths:\n if os.path.isfile(path) and os.path.getsize(path):\n with open(path, encoding="utf-8") as f:\n try:\n recursive_update(data, json.load(f))\n except json.decoder.JSONDecodeError:\n self.log.warning("Invalid JSON in %s, skipping", path)\n return data\n\n def set(self, section_name: str, data: t.Any) -> None:\n """Store the given config data."""\n filename = self.file_name(section_name)\n self.ensure_config_dir_exists()\n\n if self.read_directory:\n # we will modify data in place, so make a copy\n data = copy.deepcopy(data)\n defaults = self.get(section_name, include_root=False)\n remove_defaults(data, defaults)\n\n # Generate the JSON up front, since it could raise an exception,\n # in order to avoid writing half-finished corrupted data to disk.\n json_content = json.dumps(data, indent=2)\n with open(filename, "w", encoding="utf-8") as f:\n f.write(json_content)\n\n def update(self, section_name: str, new_data: t.Any) -> dict[str, t.Any]:\n """Modify the config section by recursively updating it with new_data.\n\n Returns the modified config data as a dictionary.\n """\n data = self.get(section_name)\n recursive_update(data, new_data)\n self.set(section_name, data)\n return data\n | .venv\Lib\site-packages\jupyter_server\config_manager.py | config_manager.py | Python | 5,032 | 0.95 | 0.231884 | 0.107143 | react-lib | 661 | 2024-02-05T11:17:40.050884 | GPL-3.0 | false | a108fc8d6b10e1ce08c4205f20c56c5d |
"""Log utilities."""\n\n# -----------------------------------------------------------------------------\n# Copyright (c) Jupyter Development Team\n#\n# Distributed under the terms of the BSD License. The full license is in\n# the file LICENSE, distributed as part of this software.\n# -----------------------------------------------------------------------------\nimport json\nfrom urllib.parse import urlparse, urlunparse\n\nfrom tornado.log import access_log\n\nfrom .auth import User\nfrom .prometheus.log_functions import prometheus_log_method\n\n# url params to be scrubbed if seen\n# any url param that *contains* one of these\n# will be scrubbed from logs\n_SCRUB_PARAM_KEYS = {"token", "auth", "key", "code", "state", "xsrf"}\n\n\ndef _scrub_uri(uri: str) -> str:\n """scrub auth info from uri"""\n parsed = urlparse(uri)\n if parsed.query:\n # check for potentially sensitive url params\n # use manual list + split rather than parsing\n # to minimally perturb original\n parts = parsed.query.split("&")\n changed = False\n for i, s in enumerate(parts):\n key, sep, value = s.partition("=")\n for substring in _SCRUB_PARAM_KEYS:\n if substring in key:\n parts[i] = f"{key}{sep}[secret]"\n changed = True\n if changed:\n parsed = parsed._replace(query="&".join(parts))\n return urlunparse(parsed)\n return uri\n\n\ndef log_request(handler, record_prometheus_metrics=True):\n """log a bit more information about each request than tornado's default\n\n - move static file get success to debug-level (reduces noise)\n - get proxied IP instead of proxy IP\n - log referer for redirect and failed requests\n - log user-agent for failed requests\n\n if record_prometheus_metrics is true, will record a histogram prometheus\n metric (http_request_duration_seconds) for each request handler\n """\n status = handler.get_status()\n request = handler.request\n try:\n logger = handler.log\n except AttributeError:\n logger = access_log\n\n if status < 300 or status == 304:\n # Successes (or 304 FOUND) are debug-level\n log_method = logger.debug\n elif status < 400:\n log_method = logger.info\n elif status < 500:\n log_method = logger.warning\n else:\n log_method = logger.error\n\n request_time = 1000.0 * handler.request.request_time()\n ns = {\n "status": status,\n "method": request.method,\n "ip": request.remote_ip,\n "uri": _scrub_uri(request.uri),\n "request_time": request_time,\n }\n # log username\n # make sure we don't break anything\n # in case mixins cause current_user to not be a User somehow\n try:\n user = handler.current_user\n except Exception:\n user = None\n username = (user.username if isinstance(user, User) else "unknown") if user else ""\n ns["username"] = username\n\n msg = "{status} {method} {uri} ({username}@{ip}) {request_time:.2f}ms"\n if status >= 400:\n # log bad referrers\n ns["referer"] = _scrub_uri(request.headers.get("Referer", "None"))\n msg = msg + " referer={referer}"\n if status >= 500 and status != 502:\n # Log a subset of the headers if it caused an error.\n headers = {}\n for header in ["Host", "Accept", "Referer", "User-Agent"]:\n if header in request.headers:\n headers[header] = request.headers[header]\n log_method(json.dumps(headers, indent=2))\n log_method(msg.format(**ns))\n if record_prometheus_metrics:\n prometheus_log_method(handler)\n | .venv\Lib\site-packages\jupyter_server\log.py | log.py | Python | 3,633 | 0.95 | 0.230769 | 0.197802 | python-kit | 340 | 2025-04-01T18:00:53.150205 | GPL-3.0 | false | da7fa75d95f5d851c5f1b4cdf6237bc5 |
"""Pytest Fixtures exported by Jupyter Server."""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nimport json\nfrom pathlib import Path\n\nimport pytest\n\nfrom jupyter_server.services.contents.filemanager import AsyncFileContentsManager\nfrom jupyter_server.services.contents.largefilemanager import AsyncLargeFileManager\n\npytest_plugins = ["pytest_jupyter.jupyter_server"]\n\nsome_resource = "The very model of a modern major general"\nsample_kernel_json = {\n "argv": ["cat", "{connection_file}"],\n "display_name": "Test kernel",\n}\n\n\n@pytest.fixture # type:ignore[misc]\ndef jp_kernelspecs(jp_data_dir: Path) -> None:\n """Configures some sample kernelspecs in the Jupyter data directory."""\n spec_names = ["sample", "sample2", "bad"]\n for name in spec_names:\n sample_kernel_dir = jp_data_dir.joinpath("kernels", name)\n sample_kernel_dir.mkdir(parents=True)\n # Create kernel json file\n sample_kernel_file = sample_kernel_dir.joinpath("kernel.json")\n kernel_json = sample_kernel_json.copy()\n if name == "bad":\n kernel_json["argv"] = ["non_existent_path"]\n sample_kernel_file.write_text(json.dumps(kernel_json))\n # Create resources text\n sample_kernel_resources = sample_kernel_dir.joinpath("resource.txt")\n sample_kernel_resources.write_text(some_resource)\n\n\n@pytest.fixture(params=[True, False])\ndef jp_contents_manager(request, tmp_path):\n """Returns an AsyncFileContentsManager instance based on the use_atomic_writing parameter value."""\n return AsyncFileContentsManager(root_dir=str(tmp_path), use_atomic_writing=request.param)\n\n\n@pytest.fixture\ndef jp_large_contents_manager(tmp_path):\n """Returns an AsyncLargeFileManager instance."""\n return AsyncLargeFileManager(root_dir=str(tmp_path))\n | .venv\Lib\site-packages\jupyter_server\pytest_plugin.py | pytest_plugin.py | Python | 1,849 | 0.95 | 0.102041 | 0.105263 | awesome-app | 429 | 2025-03-04T07:08:02.615179 | Apache-2.0 | true | 4a341bb8eb60473ccee98e91cb486eb3 |
"""Custom trait types."""\n\nimport inspect\nfrom ast import literal_eval\n\nfrom traitlets import Any, ClassBasedTraitType, TraitError, Undefined\nfrom traitlets.utils.descriptions import describe\n\n\nclass TypeFromClasses(ClassBasedTraitType): # type:ignore[type-arg]\n """A trait whose value must be a subclass of a class in a specified list of classes."""\n\n default_value: Any\n\n def __init__(self, default_value=Undefined, klasses=None, **kwargs):\n """Construct a Type trait\n A Type trait specifies that its values must be subclasses of\n a class in a list of possible classes.\n If only ``default_value`` is given, it is used for the ``klasses`` as\n well. If neither are given, both default to ``object``.\n Parameters\n ----------\n default_value : class, str or None\n The default value must be a subclass of klass. If an str,\n the str must be a fully specified class name, like 'foo.bar.Bah'.\n The string is resolved into real class, when the parent\n :class:`HasTraits` class is instantiated.\n klasses : list of class, str [ default object ]\n Values of this trait must be a subclass of klass. The klass\n may be specified in a string like: 'foo.bar.MyClass'.\n The string is resolved into real class, when the parent\n :class:`HasTraits` class is instantiated.\n allow_none : bool [ default False ]\n Indicates whether None is allowed as an assignable value.\n """\n if default_value is Undefined:\n new_default_value = object if (klasses is None) else klasses\n else:\n new_default_value = default_value\n\n if klasses is None:\n if (default_value is None) or (default_value is Undefined):\n klasses = [object]\n else:\n klasses = [default_value]\n\n # OneOfType requires a list of klasses to be specified (different than Type).\n if not isinstance(klasses, (list, tuple, set)):\n msg = "`klasses` must be a list of class names (type is str) or classes."\n raise TraitError(msg)\n\n for klass in klasses:\n if not (inspect.isclass(klass) or isinstance(klass, str)):\n msg = "A OneOfType trait must specify a list of classes."\n raise TraitError(msg)\n\n # Store classes.\n self.klasses = klasses\n\n super().__init__(new_default_value, **kwargs)\n\n def subclass_from_klasses(self, value):\n """Check that a given class is a subclasses found in the klasses list."""\n return any(issubclass(value, klass) for klass in self.importable_klasses)\n\n def validate(self, obj, value):\n """Validates that the value is a valid object instance."""\n if isinstance(value, str):\n try:\n value = self._resolve_string(value)\n except ImportError as e:\n emsg = (\n f"The '{self.name}' trait of {obj} instance must be a type, but "\n f"{value!r} could not be imported"\n )\n raise TraitError(emsg) from e\n try:\n if self.subclass_from_klasses(value):\n return value\n except Exception:\n pass\n\n self.error(obj, value)\n\n def info(self):\n """Returns a description of the trait."""\n result = "a subclass of "\n for klass in self.klasses:\n if not isinstance(klass, str):\n klass = klass.__module__ + "." + klass.__name__ # noqa: PLW2901\n result += f"{klass} or "\n # Strip the last "or"\n result = result.strip(" or ") # noqa: B005\n if self.allow_none:\n return result + " or None"\n return result\n\n def instance_init(self, obj):\n """Initialize an instance."""\n self._resolve_classes()\n super().instance_init(obj)\n\n def _resolve_classes(self):\n """Resolve all string names to actual classes."""\n self.importable_klasses = []\n for klass in self.klasses:\n if isinstance(klass, str):\n # Try importing the classes to compare. Silently, ignore if not importable.\n try:\n klass = self._resolve_string(klass) # noqa: PLW2901\n self.importable_klasses.append(klass)\n except Exception:\n pass\n else:\n self.importable_klasses.append(klass)\n\n if isinstance(self.default_value, str):\n self.default_value = self._resolve_string(self.default_value) # type:ignore[arg-type]\n\n def default_value_repr(self):\n """The default value repr."""\n value = self.default_value\n if isinstance(value, str):\n return repr(value)\n else:\n return repr(f"{value.__module__}.{value.__name__}")\n\n\nclass InstanceFromClasses(ClassBasedTraitType): # type:ignore[type-arg]\n """A trait whose value must be an instance of a class in a specified list of classes.\n The value can also be an instance of a subclass of the specified classes.\n Subclasses can declare default classes by overriding the klass attribute\n """\n\n def __init__(self, klasses=None, args=None, kw=None, **kwargs):\n """Construct an Instance trait.\n This trait allows values that are instances of a particular\n class or its subclasses. Our implementation is quite different\n from that of enthough.traits as we don't allow instances to be used\n for klass and we handle the ``args`` and ``kw`` arguments differently.\n Parameters\n ----------\n klasses : list of classes or class_names (str)\n The class that forms the basis for the trait. Class names\n can also be specified as strings, like 'foo.bar.Bar'.\n args : tuple\n Positional arguments for generating the default value.\n kw : dict\n Keyword arguments for generating the default value.\n allow_none : bool [ default False ]\n Indicates whether None is allowed as a value.\n Notes\n -----\n If both ``args`` and ``kw`` are None, then the default value is None.\n If ``args`` is a tuple and ``kw`` is a dict, then the default is\n created as ``klass(*args, **kw)``. If exactly one of ``args`` or ``kw`` is\n None, the None is replaced by ``()`` or ``{}``, respectively.\n """\n # If class\n if klasses is None: # noqa: SIM114\n self.klasses = klasses\n # Verify all elements are either classes or strings.\n elif all(inspect.isclass(k) or isinstance(k, str) for k in klasses):\n self.klasses = klasses\n else:\n raise TraitError(\n "The klasses attribute must be a list of class names or classes"\n " not: %r" % klasses\n )\n\n if (kw is not None) and not isinstance(kw, dict):\n msg = "The 'kw' argument must be a dict or None."\n raise TraitError(msg)\n if (args is not None) and not isinstance(args, tuple):\n msg = "The 'args' argument must be a tuple or None."\n raise TraitError(msg)\n\n self.default_args = args\n self.default_kwargs = kw\n\n super().__init__(**kwargs)\n\n def instance_from_importable_klasses(self, value):\n """Check that a given class is a subclasses found in the klasses list."""\n return any(isinstance(value, klass) for klass in self.importable_klasses)\n\n def validate(self, obj, value):\n """Validate an instance."""\n if self.instance_from_importable_klasses(value):\n return value\n else:\n self.error(obj, value)\n\n def info(self):\n """Get the trait info."""\n result = "an instance of "\n assert self.klasses is not None\n for klass in self.klasses:\n if isinstance(klass, str):\n result += klass\n else:\n result += describe("a", klass)\n result += " or "\n result = result.strip(" or ") # noqa: B005\n if self.allow_none:\n result += " or None"\n return result\n\n def instance_init(self, obj):\n """Initialize the trait."""\n self._resolve_classes()\n super().instance_init(obj)\n\n def _resolve_classes(self):\n """Resolve all string names to actual classes."""\n self.importable_klasses = []\n assert self.klasses is not None\n for klass in self.klasses:\n if isinstance(klass, str):\n # Try importing the classes to compare. Silently, ignore if not importable.\n try:\n klass = self._resolve_string(klass) # noqa: PLW2901\n self.importable_klasses.append(klass)\n except Exception:\n pass\n else:\n self.importable_klasses.append(klass)\n\n def make_dynamic_default(self):\n """Make the dynamic default for the trait."""\n if (self.default_args is None) and (self.default_kwargs is None):\n return None\n return self.klass( # type:ignore[attr-defined]\n *(self.default_args or ()), **(self.default_kwargs or {})\n )\n\n def default_value_repr(self):\n """Get the default value repr."""\n return repr(self.make_dynamic_default())\n\n def from_string(self, s):\n """Convert from a string."""\n return literal_eval(s)\n | .venv\Lib\site-packages\jupyter_server\traittypes.py | traittypes.py | Python | 9,577 | 0.95 | 0.320988 | 0.038095 | react-lib | 184 | 2024-04-01T13:04:12.250857 | Apache-2.0 | false | 6f79aefc84902d6cb44f4920f229de99 |
"""Translation related utilities. When imported, injects _ to builtins"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nimport gettext\nimport os\nimport warnings\n\n\ndef _trans_gettext_deprecation_helper(*args, **kwargs):\n """The trans gettext deprecation helper."""\n warn_msg = "The alias `_()` will be deprecated. Use `_i18n()` instead."\n warnings.warn(warn_msg, FutureWarning, stacklevel=2)\n return trans.gettext(*args, **kwargs)\n\n\n# Set up message catalog access\nbase_dir = os.path.realpath(os.path.join(__file__, "..", ".."))\ntrans = gettext.translation(\n "notebook", localedir=os.path.join(base_dir, "notebook/i18n"), fallback=True\n)\n_ = _trans_gettext_deprecation_helper\n_i18n = trans.gettext\n | .venv\Lib\site-packages\jupyter_server\transutils.py | transutils.py | Python | 768 | 0.95 | 0.043478 | 0.166667 | vue-tools | 537 | 2024-11-24T18:27:22.593909 | MIT | false | 5b8ce77b8ae32dd98167774f1c70a0c5 |
"""Notebook related utilities"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport errno\nimport importlib.util\nimport os\nimport socket\nimport sys\nimport warnings\nfrom _frozen_importlib_external import _NamespacePath\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any, NewType\nfrom urllib.parse import (\n SplitResult,\n quote,\n unquote,\n urlparse,\n urlsplit,\n urlunsplit,\n)\nfrom urllib.parse import (\n urljoin as _urljoin,\n)\nfrom urllib.request import pathname2url as _pathname2url\n\nfrom jupyter_core.utils import ensure_async as _ensure_async\nfrom packaging.version import Version\nfrom tornado.httpclient import AsyncHTTPClient, HTTPClient, HTTPRequest, HTTPResponse\nfrom tornado.netutil import Resolver\n\nif TYPE_CHECKING:\n from collections.abc import Generator, Sequence\n\nApiPath = NewType("ApiPath", str)\n\n# Re-export\nurljoin = _urljoin\npathname2url = _pathname2url\nensure_async = _ensure_async\n\n\ndef url_path_join(*pieces: str) -> str:\n """Join components of url into a relative url\n\n Use to prevent double slash when joining subpath. This will leave the\n initial and final / in place\n """\n initial = pieces[0].startswith("/")\n final = pieces[-1].endswith("/")\n stripped = [s.strip("/") for s in pieces]\n result = "/".join(s for s in stripped if s)\n if initial:\n result = "/" + result\n if final:\n result = result + "/"\n if result == "//":\n result = "/"\n return result\n\n\ndef url_is_absolute(url: str) -> bool:\n """Determine whether a given URL is absolute"""\n return urlparse(url).path.startswith("/")\n\n\ndef path2url(path: str) -> str:\n """Convert a local file path to a URL"""\n pieces = [quote(p) for p in path.split(os.sep)]\n # preserve trailing /\n if pieces[-1] == "":\n pieces[-1] = "/"\n url = url_path_join(*pieces)\n return url\n\n\ndef url2path(url: str) -> str:\n """Convert a URL to a local file path"""\n pieces = [unquote(p) for p in url.split("/")]\n path = os.path.join(*pieces)\n return path\n\n\ndef url_escape(path: str) -> str:\n """Escape special characters in a URL path\n\n Turns '/foo bar/' into '/foo%20bar/'\n """\n parts = path.split("/")\n return "/".join([quote(p) for p in parts])\n\n\ndef url_unescape(path: str) -> str:\n """Unescape special characters in a URL path\n\n Turns '/foo%20bar/' into '/foo bar/'\n """\n return "/".join([unquote(p) for p in path.split("/")])\n\n\ndef samefile_simple(path: str, other_path: str) -> bool:\n """\n Fill in for os.path.samefile when it is unavailable (Windows+py2).\n\n Do a case-insensitive string comparison in this case\n plus comparing the full stat result (including times)\n because Windows + py2 doesn't support the stat fields\n needed for identifying if it's the same file (st_ino, st_dev).\n\n Only to be used if os.path.samefile is not available.\n\n Parameters\n ----------\n path : str\n representing a path to a file\n other_path : str\n representing a path to another file\n\n Returns\n -------\n same: Boolean that is True if both path and other path are the same\n """\n path_stat = os.stat(path)\n other_path_stat = os.stat(other_path)\n return path.lower() == other_path.lower() and path_stat == other_path_stat\n\n\ndef to_os_path(path: ApiPath, root: str = "") -> str:\n """Convert an API path to a filesystem path\n\n If given, root will be prepended to the path.\n root must be a filesystem path already.\n """\n parts = str(path).strip("/").split("/")\n parts = [p for p in parts if p != ""] # remove duplicate splits\n path_ = os.path.join(root, *parts)\n return os.path.normpath(path_)\n\n\ndef to_api_path(os_path: str, root: str = "") -> ApiPath:\n """Convert a filesystem path to an API path\n\n If given, root will be removed from the path.\n root must be a filesystem path already.\n """\n if os_path.startswith(root):\n os_path = os_path[len(root) :]\n parts = os_path.strip(os.path.sep).split(os.path.sep)\n parts = [p for p in parts if p != ""] # remove duplicate splits\n path = "/".join(parts)\n return ApiPath(path)\n\n\ndef check_version(v: str, check: str) -> bool:\n """check version string v >= check\n\n If dev/prerelease tags result in TypeError for string-number comparison,\n it is assumed that the dependency is satisfied.\n Users on dev branches are responsible for keeping their own packages up to date.\n """\n try:\n return bool(Version(v) >= Version(check))\n except TypeError:\n return True\n\n\n# Copy of IPython.utils.process.check_pid:\n\n\ndef _check_pid_win32(pid: int) -> bool:\n import ctypes\n\n # OpenProcess returns 0 if no such process (of ours) exists\n # positive int otherwise\n return bool(ctypes.windll.kernel32.OpenProcess(1, 0, pid)) # type:ignore[attr-defined]\n\n\ndef _check_pid_posix(pid: int) -> bool:\n """Copy of IPython.utils.process.check_pid"""\n try:\n os.kill(pid, 0)\n except OSError as err:\n if err.errno == errno.ESRCH:\n return False\n elif err.errno == errno.EPERM:\n # Don't have permission to signal the process - probably means it exists\n return True\n raise\n else:\n return True\n\n\nif sys.platform == "win32":\n check_pid = _check_pid_win32\nelse:\n check_pid = _check_pid_posix\n\n\nasync def run_sync_in_loop(maybe_async):\n """**DEPRECATED**: Use ``ensure_async`` from jupyter_core instead."""\n warnings.warn(\n "run_sync_in_loop is deprecated since Jupyter Server 2.0, use 'ensure_async' from jupyter_core instead",\n DeprecationWarning,\n stacklevel=2,\n )\n return ensure_async(maybe_async)\n\n\ndef urlencode_unix_socket_path(socket_path: str) -> str:\n """Encodes a UNIX socket path string from a socket path for the `http+unix` URI form."""\n return socket_path.replace("/", "%2F")\n\n\ndef urldecode_unix_socket_path(socket_path: str) -> str:\n """Decodes a UNIX sock path string from an encoded sock path for the `http+unix` URI form."""\n return socket_path.replace("%2F", "/")\n\n\ndef urlencode_unix_socket(socket_path: str) -> str:\n """Encodes a UNIX socket URL from a socket path for the `http+unix` URI form."""\n return "http+unix://%s" % urlencode_unix_socket_path(socket_path)\n\n\ndef unix_socket_in_use(socket_path: str) -> bool:\n """Checks whether a UNIX socket path on disk is in use by attempting to connect to it."""\n if not os.path.exists(socket_path):\n return False\n\n try:\n sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n sock.connect(socket_path)\n except OSError:\n return False\n else:\n return True\n finally:\n sock.close()\n\n\n@contextmanager\ndef _request_for_tornado_client(\n urlstring: str, method: str = "GET", body: Any = None, headers: Any = None\n) -> Generator[HTTPRequest, None, None]:\n """A utility that provides a context that handles\n HTTP, HTTPS, and HTTP+UNIX request.\n Creates a tornado HTTPRequest object with a URL\n that tornado's HTTPClients can accept.\n If the request is made to a unix socket, temporarily\n configure the AsyncHTTPClient to resolve the URL\n and connect to the proper socket.\n """\n parts = urlsplit(urlstring)\n if parts.scheme in ["http", "https"]:\n pass\n elif parts.scheme == "http+unix":\n # If unix socket, mimic HTTP.\n parts = SplitResult(\n scheme="http",\n netloc=parts.netloc,\n path=parts.path,\n query=parts.query,\n fragment=parts.fragment,\n )\n\n class UnixSocketResolver(Resolver):\n """A resolver that routes HTTP requests to unix sockets\n in tornado HTTP clients.\n Due to constraints in Tornados' API, the scheme of the\n must be `http` (not `http+unix`). Applications should replace\n the scheme in URLS before making a request to the HTTP client.\n """\n\n def initialize(self, resolver):\n self.resolver = resolver\n\n def close(self):\n self.resolver.close()\n\n async def resolve(self, host, port, *args, **kwargs):\n return [(socket.AF_UNIX, urldecode_unix_socket_path(host))]\n\n resolver = UnixSocketResolver(resolver=Resolver())\n AsyncHTTPClient.configure(None, resolver=resolver)\n else:\n msg = "Unknown URL scheme."\n raise Exception(msg)\n\n # Yield the request for the given client.\n url = urlunsplit(parts)\n request = HTTPRequest(url, method=method, body=body, headers=headers, validate_cert=False)\n yield request\n\n\ndef fetch(\n urlstring: str, method: str = "GET", body: Any = None, headers: Any = None\n) -> HTTPResponse:\n """\n Send a HTTP, HTTPS, or HTTP+UNIX request\n to a Tornado Web Server. Returns a tornado HTTPResponse.\n """\n with _request_for_tornado_client(\n urlstring, method=method, body=body, headers=headers\n ) as request:\n response = HTTPClient(AsyncHTTPClient).fetch(request)\n return response\n\n\nasync def async_fetch(\n urlstring: str, method: str = "GET", body: Any = None, headers: Any = None, io_loop: Any = None\n) -> HTTPResponse:\n """\n Send an asynchronous HTTP, HTTPS, or HTTP+UNIX request\n to a Tornado Web Server. Returns a tornado HTTPResponse.\n """\n with _request_for_tornado_client(\n urlstring, method=method, body=body, headers=headers\n ) as request:\n response = await AsyncHTTPClient(io_loop).fetch(request)\n return response\n\n\ndef is_namespace_package(namespace: str) -> bool | None:\n """Is the provided namespace a Python Namespace Package (PEP420).\n\n https://www.python.org/dev/peps/pep-0420/#specification\n\n Returns `None` if module is not importable.\n\n """\n # NOTE: using submodule_search_locations because the loader can be None\n try:\n spec = importlib.util.find_spec(namespace)\n except ValueError: # spec is not set - see https://docs.python.org/3/library/importlib.html#importlib.util.find_spec\n return None\n\n if not spec:\n # e.g. module not installed\n return None\n return isinstance(spec.submodule_search_locations, _NamespacePath)\n\n\ndef filefind(filename: str, path_dirs: Sequence[str]) -> str:\n """Find a file by looking through a sequence of paths.\n\n For use in FileFindHandler.\n\n Iterates through a sequence of paths looking for a file and returns\n the full, absolute path of the first occurrence of the file.\n\n Absolute paths are not accepted for inputs.\n\n This function does not automatically try any paths,\n such as the cwd or the user's home directory.\n\n Parameters\n ----------\n filename : str\n The filename to look for. Must be a relative path.\n path_dirs : sequence of str\n The sequence of paths to look in for the file.\n Walk through each element and join with ``filename``.\n Only after ensuring the path resolves within the directory is it checked for existence.\n\n Returns\n -------\n Raises :exc:`OSError` or returns absolute path to file.\n """\n file_path = Path(filename)\n\n # If the input is an absolute path, reject it\n if file_path.is_absolute():\n msg = f"{filename} is absolute, filefind only accepts relative paths."\n raise OSError(msg)\n\n for path_str in path_dirs:\n path = Path(path_str).absolute()\n test_path = path / file_path\n # os.path.abspath resolves '..', but Path.absolute() doesn't\n # Path.resolve() does, but traverses symlinks, which we don't want\n test_path = Path(os.path.abspath(test_path))\n if not test_path.is_relative_to(path):\n # points outside root, e.g. via `filename='../foo'`\n continue\n # make sure we don't call is_file before we know it's a file within a prefix\n # GHSA-hrw6-wg82-cm62 - can leak password hash on windows.\n if test_path.is_file():\n return os.path.abspath(test_path)\n\n msg = f"File {filename!r} does not exist in any of the search paths: {path_dirs!r}"\n raise OSError(msg)\n\n\ndef import_item(name: str) -> Any:\n """Import and return ``bar`` given the string ``foo.bar``.\n Calling ``bar = import_item("foo.bar")`` is the functional equivalent of\n executing the code ``from foo import bar``.\n Parameters\n ----------\n name : str\n The fully qualified name of the module/package being imported.\n Returns\n -------\n mod : module object\n The module that was imported.\n """\n\n parts = name.rsplit(".", 1)\n if len(parts) == 2:\n # called with 'foo.bar....'\n package, obj = parts\n module = __import__(package, fromlist=[obj])\n try:\n pak = getattr(module, obj)\n except AttributeError as e:\n raise ImportError("No module named %s" % obj) from e\n return pak\n else:\n # called with un-dotted string\n return __import__(parts[0])\n\n\nclass JupyterServerAuthWarning(RuntimeWarning):\n """Emitted when authentication configuration issue is detected.\n\n Intended for filtering out expected warnings in tests, including\n downstream tests, rather than for users to silence this warning.\n """\n | .venv\Lib\site-packages\jupyter_server\utils.py | utils.py | Python | 13,399 | 0.95 | 0.190698 | 0.058997 | awesome-app | 3 | 2024-07-14T17:38:13.068455 | BSD-3-Clause | false | fe56fae1110d139a52abc7f5101c5b0e |
"""\nUtilities for getting information about Jupyter and the system it's running in.\n"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nimport os\nimport platform\nimport subprocess\nimport sys\n\nimport jupyter_server\n\n\ndef pkg_commit_hash(pkg_path):\n """Get short form of commit hash given directory `pkg_path`\n\n We get the commit hash from git if it's a repo.\n\n If this fail, we return a not-found placeholder tuple\n\n Parameters\n ----------\n pkg_path : str\n directory containing package\n only used for getting commit from active repo\n\n Returns\n -------\n hash_from : str\n Where we got the hash from - description\n hash_str : str\n short form of hash\n """\n\n # maybe we are in a repository, check for a .git folder\n p = os.path\n cur_path = None\n par_path = pkg_path\n while cur_path != par_path:\n cur_path = par_path\n if p.exists(p.join(cur_path, ".git")):\n try:\n proc = subprocess.Popen(\n ["git", "rev-parse", "--short", "HEAD"], # noqa: S607\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n cwd=pkg_path,\n )\n repo_commit, _ = proc.communicate()\n except OSError:\n repo_commit = None\n\n if repo_commit:\n return "repository", repo_commit.strip().decode("ascii")\n else:\n return "", ""\n par_path = p.dirname(par_path)\n\n return "", ""\n\n\ndef pkg_info(pkg_path):\n """Return dict describing the context of this package\n\n Parameters\n ----------\n pkg_path : str\n path containing __init__.py for package\n\n Returns\n -------\n context : dict\n with named parameters of interest\n """\n src, hsh = pkg_commit_hash(pkg_path)\n return {\n "jupyter_server_version": jupyter_server.__version__,\n "jupyter_server_path": pkg_path,\n "commit_source": src,\n "commit_hash": hsh,\n "sys_version": sys.version,\n "sys_executable": sys.executable,\n "sys_platform": sys.platform,\n "platform": platform.platform(),\n "os_name": os.name,\n }\n\n\ndef get_sys_info():\n """Return useful information about the system as a dict."""\n p = os.path\n path = p.realpath(p.dirname(p.abspath(p.join(jupyter_server.__file__))))\n return pkg_info(path)\n | .venv\Lib\site-packages\jupyter_server\_sysinfo.py | _sysinfo.py | Python | 2,477 | 0.95 | 0.12766 | 0.038961 | awesome-app | 104 | 2023-07-11T20:53:28.608514 | MIT | false | b3ef4f8eafb9856420371d8eed284bf9 |
"""\nTimezone utilities\n\nJust UTC-awareness right now\n"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nfrom datetime import datetime, timedelta, timezone, tzinfo\n\n# constant for zero offset\nZERO = timedelta(0)\n\n\nclass tzUTC(tzinfo): # noqa: N801\n """tzinfo object for UTC (zero offset)"""\n\n def utcoffset(self, d: datetime | None) -> timedelta:\n """Compute utcoffset."""\n return ZERO\n\n def dst(self, d: datetime | None) -> timedelta:\n """Compute dst."""\n return ZERO\n\n\ndef utcnow() -> datetime:\n """Return timezone-aware UTC timestamp"""\n return datetime.now(timezone.utc)\n\n\ndef utcfromtimestamp(timestamp: float) -> datetime:\n return datetime.fromtimestamp(timestamp, timezone.utc)\n\n\nUTC = tzUTC() # type:ignore[abstract]\n\n\ndef isoformat(dt: datetime) -> str:\n """Return iso-formatted timestamp\n\n Like .isoformat(), but uses Z for UTC instead of +00:00\n """\n return dt.isoformat().replace("+00:00", "Z")\n | .venv\Lib\site-packages\jupyter_server\_tz.py | _tz.py | Python | 1,057 | 0.95 | 0.195652 | 0.103448 | python-kit | 938 | 2024-11-30T16:42:14.370017 | Apache-2.0 | false | 98b869bd62d4ba7628346f07148454c9 |
"""\nstore the current version info of the server.\n\n"""\n\nimport re\n\n# Version string must appear intact for automatic versioning\n__version__ = "2.16.0"\n\n# Build up version_info tuple for backwards compatibility\npattern = r"(?P<major>\d+).(?P<minor>\d+).(?P<patch>\d+)(?P<rest>.*)"\nmatch = re.match(pattern, __version__)\nassert match is not None\nparts: list[object] = [int(match[part]) for part in ["major", "minor", "patch"]]\nif match["rest"]:\n parts.append(match["rest"])\nversion_info = tuple(parts)\n | .venv\Lib\site-packages\jupyter_server\_version.py | _version.py | Python | 503 | 0.95 | 0.222222 | 0.142857 | vue-tools | 446 | 2024-07-07T06:59:01.399681 | Apache-2.0 | false | afe4a64e4e276b1058b9fd0f3db982b4 |
"""The Jupyter Server"""\n\nimport os\nimport pathlib\n\nDEFAULT_STATIC_FILES_PATH = os.path.join(os.path.dirname(__file__), "static")\nDEFAULT_TEMPLATE_PATH_LIST = [\n os.path.dirname(__file__),\n os.path.join(os.path.dirname(__file__), "templates"),\n]\n\nDEFAULT_JUPYTER_SERVER_PORT = 8888\nJUPYTER_SERVER_EVENTS_URI = "https://events.jupyter.org/jupyter_server"\nDEFAULT_EVENTS_SCHEMA_PATH = pathlib.Path(__file__).parent / "event_schemas"\n\nfrom ._version import __version__, version_info\nfrom .base.call_context import CallContext\n\n__all__ = [\n "DEFAULT_STATIC_FILES_PATH",\n "DEFAULT_TEMPLATE_PATH_LIST",\n "DEFAULT_JUPYTER_SERVER_PORT",\n "JUPYTER_SERVER_EVENTS_URI",\n "DEFAULT_EVENTS_SCHEMA_PATH",\n "__version__",\n "version_info",\n "CallContext",\n]\n | .venv\Lib\site-packages\jupyter_server\__init__.py | __init__.py | Python | 771 | 0.95 | 0 | 0 | python-kit | 650 | 2025-01-09T03:20:00.451661 | Apache-2.0 | false | c54305373ee5a19bfc6eb432f2e7d14b |
"""The main entry point for Jupyter Server."""\n\nif __name__ == "__main__":\n from jupyter_server import serverapp as app\n\n app.launch_new_instance()\n | .venv\Lib\site-packages\jupyter_server\__main__.py | __main__.py | Python | 154 | 0.85 | 0.333333 | 0 | node-utils | 511 | 2023-12-03T22:52:18.268101 | BSD-3-Clause | false | 6dc141e62b66d60d3c7d0ee4035e29a3 |
"""An Authorizer for use in the Jupyter server.\n\nThe default authorizer (AllowAllAuthorizer)\nallows all authenticated requests\n\n.. versionadded:: 2.0\n"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom traitlets import Instance\nfrom traitlets.config import LoggingConfigurable\n\nfrom .identity import IdentityProvider, User\n\nif TYPE_CHECKING:\n from collections.abc import Awaitable\n\n from jupyter_server.base.handlers import JupyterHandler\n\n\nclass Authorizer(LoggingConfigurable):\n """Base class for authorizing access to resources\n in the Jupyter Server.\n\n All authorizers used in Jupyter Server\n should inherit from this base class and, at the very minimum,\n implement an ``is_authorized`` method with the\n same signature as in this base class.\n\n The ``is_authorized`` method is called by the ``@authorized`` decorator\n in JupyterHandler. If it returns True, the incoming request\n to the server is accepted; if it returns False, the server\n returns a 403 (Forbidden) error code.\n\n The authorization check will only be applied to requests\n that have already been authenticated.\n\n .. versionadded:: 2.0\n """\n\n identity_provider = Instance(IdentityProvider)\n\n def is_authorized(\n self, handler: JupyterHandler, user: User, action: str, resource: str\n ) -> Awaitable[bool] | bool:\n """A method to determine if ``user`` is authorized to perform ``action``\n (read, write, or execute) on the ``resource`` type.\n\n Parameters\n ----------\n user : jupyter_server.auth.User\n An object representing the authenticated user,\n as returned by :meth:`jupyter_server.auth.IdentityProvider.get_user`.\n\n action : str\n the category of action for the current request: read, write, or execute.\n\n resource : str\n the type of resource (i.e. contents, kernels, files, etc.) the user is requesting.\n\n Returns\n -------\n bool\n True if user authorized to make request; False, otherwise\n """\n raise NotImplementedError\n\n\nclass AllowAllAuthorizer(Authorizer):\n """A no-op implementation of the Authorizer\n\n This authorizer allows all authenticated requests.\n\n .. versionadded:: 2.0\n """\n\n def is_authorized(\n self, handler: JupyterHandler, user: User, action: str, resource: str\n ) -> bool:\n """This method always returns True.\n\n All authenticated users are allowed to do anything in the Jupyter Server.\n """\n return True\n | .venv\Lib\site-packages\jupyter_server\auth\authorizer.py | authorizer.py | Python | 2,675 | 0.95 | 0.157303 | 0.031746 | vue-tools | 53 | 2025-05-07T07:18:34.648486 | Apache-2.0 | false | 7ab881c3478278b4c825029dd5b93c80 |
"""Decorator for layering authorization into JupyterHandlers."""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nimport asyncio\nfrom functools import wraps\nfrom typing import Any, Callable, Optional, TypeVar, Union, cast\n\nfrom jupyter_core.utils import ensure_async\nfrom tornado.log import app_log\nfrom tornado.web import HTTPError\n\nfrom .utils import HTTP_METHOD_TO_AUTH_ACTION\n\nFuncT = TypeVar("FuncT", bound=Callable[..., Any])\n\n\ndef authorized(\n action: Optional[Union[str, FuncT]] = None,\n resource: Optional[str] = None,\n message: Optional[str] = None,\n) -> FuncT:\n """A decorator for tornado.web.RequestHandler methods\n that verifies whether the current user is authorized\n to make the following request.\n\n Helpful for adding an 'authorization' layer to\n a REST API.\n\n .. versionadded:: 2.0\n\n Parameters\n ----------\n action : str\n the type of permission or action to check.\n\n resource: str or None\n the name of the resource the action is being authorized\n to access.\n\n message : str or none\n a message for the unauthorized action.\n """\n\n def wrapper(method):\n @wraps(method)\n async def inner(self, *args, **kwargs):\n # default values for action, resource\n nonlocal action\n nonlocal resource\n nonlocal message\n if action is None:\n http_method = self.request.method.upper()\n action = HTTP_METHOD_TO_AUTH_ACTION[http_method]\n if resource is None:\n resource = self.auth_resource\n if message is None:\n message = f"User is not authorized to {action} on resource: {resource}."\n\n user = self.current_user\n if not user:\n app_log.warning("Attempting to authorize request without authentication!")\n raise HTTPError(status_code=403, log_message=message)\n # If the user is allowed to do this action,\n # call the method.\n authorized = await ensure_async(\n self.authorizer.is_authorized(self, user, action, resource)\n )\n if authorized:\n out = method(self, *args, **kwargs)\n # If the method is a coroutine, await it\n if asyncio.iscoroutine(out):\n return await out\n return out\n # else raise an exception.\n else:\n raise HTTPError(status_code=403, log_message=message)\n\n return inner\n\n if callable(action):\n method = action\n action = None\n # no-arguments `@authorized` decorator called\n return cast(FuncT, wrapper(method))\n\n return cast(FuncT, wrapper)\n\n\ndef allow_unauthenticated(method: FuncT) -> FuncT:\n """A decorator for tornado.web.RequestHandler methods\n that allows any user to make the following request.\n\n Selectively disables the 'authentication' layer of REST API which\n is active when `ServerApp.allow_unauthenticated_access = False`.\n\n To be used exclusively on endpoints which may be considered public,\n for example the login page handler.\n\n .. versionadded:: 2.13\n\n Parameters\n ----------\n method : bound callable\n the endpoint method to remove authentication from.\n """\n\n @wraps(method)\n def wrapper(self, *args, **kwargs):\n return method(self, *args, **kwargs)\n\n setattr(wrapper, "__allow_unauthenticated", True)\n\n return cast(FuncT, wrapper)\n\n\ndef ws_authenticated(method: FuncT) -> FuncT:\n """A decorator for websockets derived from `WebSocketHandler`\n that authenticates user before allowing to proceed.\n\n Differently from tornado.web.authenticated, does not redirect\n to the login page, which would be meaningless for websockets.\n\n .. versionadded:: 2.13\n\n Parameters\n ----------\n method : bound callable\n the endpoint method to add authentication for.\n """\n\n @wraps(method)\n def wrapper(self, *args, **kwargs):\n user = self.current_user\n if user is None:\n self.log.warning("Couldn't authenticate WebSocket connection")\n raise HTTPError(403)\n return method(self, *args, **kwargs)\n\n setattr(wrapper, "__allow_unauthenticated", False)\n\n return cast(FuncT, wrapper)\n | .venv\Lib\site-packages\jupyter_server\auth\decorator.py | decorator.py | Python | 4,381 | 0.95 | 0.176056 | 0.073394 | react-lib | 319 | 2023-09-24T19:06:14.006011 | BSD-3-Clause | false | d1454571435fd9fa3d74c9dc046f57f5 |
"""Identity Provider interface\n\nThis defines the _authentication_ layer of Jupyter Server,\nto be used in combination with Authorizer for _authorization_.\n\n.. versionadded:: 2.0\n"""\n\nfrom __future__ import annotations\n\nimport binascii\nimport datetime\nimport json\nimport os\nimport re\nimport sys\nimport typing as t\nimport uuid\nfrom dataclasses import asdict, dataclass\nfrom http.cookies import Morsel\n\nfrom tornado import escape, httputil, web\nfrom traitlets import Bool, Dict, Type, Unicode, default\nfrom traitlets.config import LoggingConfigurable\n\nfrom jupyter_server.transutils import _i18n\n\nfrom .security import passwd_check, set_password\nfrom .utils import get_anonymous_username\n\n_non_alphanum = re.compile(r"[^A-Za-z0-9]")\n\n\n@dataclass\nclass User:\n """Object representing a User\n\n This or a subclass should be returned from IdentityProvider.get_user\n """\n\n username: str # the only truly required field\n\n # these fields are filled from username if not specified\n # name is the 'real' name of the user\n name: str = ""\n # display_name is a shorter name for us in UI,\n # if different from name. e.g. a nickname\n display_name: str = ""\n\n # these fields are left as None if undefined\n initials: str | None = None\n avatar_url: str | None = None\n color: str | None = None\n\n # TODO: extension fields?\n # ext: Dict[str, Dict[str, Any]] = field(default_factory=dict)\n\n def __post_init__(self):\n self.fill_defaults()\n\n def fill_defaults(self):\n """Fill out default fields in the identity model\n\n - Ensures all values are defined\n - Fills out derivative values for name fields fields\n - Fills out null values for optional fields\n """\n\n # username is the only truly required field\n if not self.username:\n msg = f"user.username must not be empty: {self}"\n raise ValueError(msg)\n\n # derive name fields from username -> name -> display name\n if not self.name:\n self.name = self.username\n if not self.display_name:\n self.display_name = self.name\n\n\ndef _backward_compat_user(got_user: t.Any) -> User:\n """Backward-compatibility for LoginHandler.get_user\n\n Prior to 2.0, LoginHandler.get_user could return anything truthy.\n\n Typically, this was either a simple string username,\n or a simple dict.\n\n Make some effort to allow common patterns to keep working.\n """\n if isinstance(got_user, str):\n return User(username=got_user)\n elif isinstance(got_user, dict):\n kwargs = {}\n if "username" not in got_user and "name" in got_user:\n kwargs["username"] = got_user["name"]\n for field in User.__dataclass_fields__:\n if field in got_user:\n kwargs[field] = got_user[field]\n try:\n return User(**kwargs)\n except TypeError:\n msg = f"Unrecognized user: {got_user}"\n raise ValueError(msg) from None\n else:\n msg = f"Unrecognized user: {got_user}"\n raise ValueError(msg)\n\n\nclass IdentityProvider(LoggingConfigurable):\n """\n Interface for providing identity management and authentication.\n\n Two principle methods:\n\n - :meth:`~jupyter_server.auth.IdentityProvider.get_user` returns a :class:`~.User` object\n for successful authentication, or None for no-identity-found.\n - :meth:`~jupyter_server.auth.IdentityProvider.identity_model` turns a :class:`~jupyter_server.auth.User` into a JSONable dict.\n The default is to use :py:meth:`dataclasses.asdict`,\n and usually shouldn't need override.\n\n Additional methods can customize authentication.\n\n .. versionadded:: 2.0\n """\n\n cookie_name: str | Unicode[str, str | bytes] = Unicode(\n "",\n config=True,\n help=_i18n("Name of the cookie to set for persisting login. Default: username-${Host}."),\n )\n\n cookie_options = Dict(\n config=True,\n help=_i18n(\n "Extra keyword arguments to pass to `set_secure_cookie`."\n " See tornado's set_secure_cookie docs for details."\n ),\n )\n\n secure_cookie: bool | Bool[bool | None, bool | int | None] = Bool(\n None,\n allow_none=True,\n config=True,\n help=_i18n(\n "Specify whether login cookie should have the `secure` property (HTTPS-only)."\n "Only needed when protocol-detection gives the wrong answer due to proxies."\n ),\n )\n\n get_secure_cookie_kwargs = Dict(\n config=True,\n help=_i18n(\n "Extra keyword arguments to pass to `get_secure_cookie`."\n " See tornado's get_secure_cookie docs for details."\n ),\n )\n\n token: str | Unicode[str, str | bytes] = Unicode(\n "<generated>",\n help=_i18n(\n """Token used for authenticating first-time connections to the server.\n\n The token can be read from the file referenced by JUPYTER_TOKEN_FILE or set directly\n with the JUPYTER_TOKEN environment variable.\n\n When no password is enabled,\n the default is to generate a new, random token.\n\n Setting to an empty string disables authentication altogether, which is NOT RECOMMENDED.\n\n Prior to 2.0: configured as ServerApp.token\n """\n ),\n ).tag(config=True)\n\n login_handler_class = Type(\n default_value="jupyter_server.auth.login.LoginFormHandler",\n klass=web.RequestHandler,\n config=True,\n help=_i18n("The login handler class to use, if any."),\n )\n\n logout_handler_class = Type(\n default_value="jupyter_server.auth.logout.LogoutHandler",\n klass=web.RequestHandler,\n config=True,\n help=_i18n("The logout handler class to use."),\n )\n\n token_generated = False\n\n @default("token")\n def _token_default(self):\n if os.getenv("JUPYTER_TOKEN"):\n self.token_generated = False\n return os.environ["JUPYTER_TOKEN"]\n if os.getenv("JUPYTER_TOKEN_FILE"):\n self.token_generated = False\n with open(os.environ["JUPYTER_TOKEN_FILE"]) as token_file:\n return token_file.read()\n if not self.need_token:\n # no token if password is enabled\n self.token_generated = False\n return ""\n else:\n self.token_generated = True\n return binascii.hexlify(os.urandom(24)).decode("ascii")\n\n need_token: bool | Bool[bool, t.Union[bool, int]] = Bool(True)\n\n def get_user(self, handler: web.RequestHandler) -> User | None | t.Awaitable[User | None]:\n """Get the authenticated user for a request\n\n Must return a :class:`jupyter_server.auth.User`,\n though it may be a subclass.\n\n Return None if the request is not authenticated.\n\n _may_ be a coroutine\n """\n return self._get_user(handler)\n\n # not sure how to have optional-async type signature\n # on base class with `async def` without splitting it into two methods\n\n async def _get_user(self, handler: web.RequestHandler) -> User | None:\n """Get the user."""\n if getattr(handler, "_jupyter_current_user", None):\n # already authenticated\n return t.cast(User, handler._jupyter_current_user) # type:ignore[attr-defined]\n _token_user: User | None | t.Awaitable[User | None] = self.get_user_token(handler)\n if isinstance(_token_user, t.Awaitable):\n _token_user = await _token_user\n token_user: User | None = _token_user # need second variable name to collapse type\n _cookie_user = self.get_user_cookie(handler)\n if isinstance(_cookie_user, t.Awaitable):\n _cookie_user = await _cookie_user\n cookie_user: User | None = _cookie_user\n # prefer token to cookie if both given,\n # because token is always explicit\n user = token_user or cookie_user\n\n if user is not None and token_user is not None:\n # if token-authenticated, persist user_id in cookie\n # if it hasn't already been stored there\n if user != cookie_user:\n self.set_login_cookie(handler, user)\n # Record that the current request has been authenticated with a token.\n # Used in is_token_authenticated above.\n handler._token_authenticated = True # type:ignore[attr-defined]\n\n if user is None:\n # If an invalid cookie was sent, clear it to prevent unnecessary\n # extra warnings. But don't do this on a request with *no* cookie,\n # because that can erroneously log you out (see gh-3365)\n cookie_name = self.get_cookie_name(handler)\n cookie = handler.get_cookie(cookie_name)\n if cookie is not None:\n self.log.warning(f"Clearing invalid/expired login cookie {cookie_name}")\n self.clear_login_cookie(handler)\n if not self.auth_enabled:\n # Completely insecure! No authentication at all.\n # No need to warn here, though; validate_security will have already done that.\n user = self.generate_anonymous_user(handler)\n # persist user on first request\n # so the user data is stable for a given browser session\n self.set_login_cookie(handler, user)\n\n return user\n\n def identity_model(self, user: User) -> dict[str, t.Any]:\n """Return a User as an Identity model"""\n # TODO: validate?\n return asdict(user)\n\n def get_handlers(self) -> list[tuple[str, object]]:\n """Return list of additional handlers for this identity provider\n\n For example, an OAuth callback handler.\n """\n handlers = []\n if self.login_available:\n handlers.append((r"/login", self.login_handler_class))\n if self.logout_available:\n handlers.append((r"/logout", self.logout_handler_class))\n return handlers\n\n def user_to_cookie(self, user: User) -> str:\n """Serialize a user to a string for storage in a cookie\n\n If overriding in a subclass, make sure to define user_from_cookie as well.\n\n Default is just the user's username.\n """\n # default: username is enough\n cookie = json.dumps(\n {\n "username": user.username,\n "name": user.name,\n "display_name": user.display_name,\n "initials": user.initials,\n "color": user.color,\n }\n )\n return cookie\n\n def user_from_cookie(self, cookie_value: str) -> User | None:\n """Inverse of user_to_cookie"""\n user = json.loads(cookie_value)\n return User(\n user["username"],\n user["name"],\n user["display_name"],\n user["initials"],\n None,\n user["color"],\n )\n\n def get_cookie_name(self, handler: web.RequestHandler) -> str:\n """Return the login cookie name\n\n Uses IdentityProvider.cookie_name, if defined.\n Default is to generate a string taking host into account to avoid\n collisions for multiple servers on one hostname with different ports.\n """\n if self.cookie_name:\n return self.cookie_name\n else:\n return _non_alphanum.sub("-", f"username-{handler.request.host}")\n\n def set_login_cookie(self, handler: web.RequestHandler, user: User) -> None:\n """Call this on handlers to set the login cookie for success"""\n cookie_options = {}\n cookie_options.update(self.cookie_options)\n cookie_options.setdefault("httponly", True)\n # tornado <4.2 has a bug that considers secure==True as soon as\n # 'secure' kwarg is passed to set_secure_cookie\n secure_cookie = self.secure_cookie\n if secure_cookie is None:\n secure_cookie = handler.request.protocol == "https"\n if secure_cookie:\n cookie_options.setdefault("secure", True)\n cookie_options.setdefault("path", handler.base_url) # type:ignore[attr-defined]\n cookie_name = self.get_cookie_name(handler)\n handler.set_secure_cookie(cookie_name, self.user_to_cookie(user), **cookie_options)\n\n def _force_clear_cookie(\n self, handler: web.RequestHandler, name: str, path: str = "/", domain: str | None = None\n ) -> None:\n """Deletes the cookie with the given name.\n\n Tornado's cookie handling currently (Jan 2018) stores cookies in a dict\n keyed by name, so it can only modify one cookie with a given name per\n response. The browser can store multiple cookies with the same name\n but different domains and/or paths. This method lets us clear multiple\n cookies with the same name.\n\n Due to limitations of the cookie protocol, you must pass the same\n path and domain to clear a cookie as were used when that cookie\n was set (but there is no way to find out on the server side\n which values were used for a given cookie).\n """\n name = escape.native_str(name)\n expires = datetime.datetime.now(tz=datetime.timezone.utc) - datetime.timedelta(days=365)\n\n morsel: Morsel[t.Any] = Morsel()\n morsel.set(name, "", '""')\n morsel["expires"] = httputil.format_timestamp(expires)\n morsel["path"] = path\n if domain:\n morsel["domain"] = domain\n handler.add_header("Set-Cookie", morsel.OutputString())\n\n def clear_login_cookie(self, handler: web.RequestHandler) -> None:\n """Clear the login cookie, effectively logging out the session."""\n cookie_options = {}\n cookie_options.update(self.cookie_options)\n path = cookie_options.setdefault("path", handler.base_url) # type:ignore[attr-defined]\n cookie_name = self.get_cookie_name(handler)\n handler.clear_cookie(cookie_name, path=path)\n if path and path != "/":\n # also clear cookie on / to ensure old cookies are cleared\n # after the change in path behavior.\n # N.B. This bypasses the normal cookie handling, which can't update\n # two cookies with the same name. See the method above.\n self._force_clear_cookie(handler, cookie_name)\n\n def get_user_cookie(\n self, handler: web.RequestHandler\n ) -> User | None | t.Awaitable[User | None]:\n """Get user from a cookie\n\n Calls user_from_cookie to deserialize cookie value\n """\n _user_cookie = handler.get_secure_cookie(\n self.get_cookie_name(handler),\n **self.get_secure_cookie_kwargs,\n )\n if not _user_cookie:\n return None\n user_cookie = _user_cookie.decode()\n # TODO: try/catch in case of change in config?\n try:\n return self.user_from_cookie(user_cookie)\n except Exception as e:\n # log bad cookie itself, only at debug-level\n self.log.debug(f"Error unpacking user from cookie: cookie={user_cookie}", exc_info=True)\n self.log.error(f"Error unpacking user from cookie: {e}")\n return None\n\n auth_header_pat = re.compile(r"(token|bearer)\s+(.+)", re.IGNORECASE)\n\n def get_token(self, handler: web.RequestHandler) -> str | None:\n """Get the user token from a request\n\n Default:\n\n - in URL parameters: ?token=<token>\n - in header: Authorization: token <token>\n """\n user_token = handler.get_argument("token", "")\n if not user_token:\n # get it from Authorization header\n m = self.auth_header_pat.match(handler.request.headers.get("Authorization", ""))\n if m:\n user_token = m.group(2)\n return user_token\n\n async def get_user_token(self, handler: web.RequestHandler) -> User | None:\n """Identify the user based on a token in the URL or Authorization header\n\n Returns:\n - uuid if authenticated\n - None if not\n """\n token = t.cast("str | None", handler.token) # type:ignore[attr-defined]\n if not token:\n return None\n # check login token from URL argument or Authorization header\n user_token = self.get_token(handler)\n authenticated = False\n if user_token == token:\n # token-authenticated, set the login cookie\n self.log.debug(\n "Accepting token-authenticated request from %s",\n handler.request.remote_ip,\n )\n authenticated = True\n\n if authenticated:\n # token does not correspond to user-id,\n # which is stored in a cookie.\n # still check the cookie for the user id\n _user = self.get_user_cookie(handler)\n if isinstance(_user, t.Awaitable):\n _user = await _user\n user: User | None = _user\n if user is None:\n user = self.generate_anonymous_user(handler)\n return user\n else:\n return None\n\n def generate_anonymous_user(self, handler: web.RequestHandler) -> User:\n """Generate a random anonymous user.\n\n For use when a single shared token is used,\n but does not identify a user.\n """\n user_id = uuid.uuid4().hex\n moon = get_anonymous_username()\n name = display_name = f"Anonymous {moon}"\n initials = f"A{moon[0]}"\n color = None\n handler.log.debug(f"Generating new user for token-authenticated request: {user_id}") # type:ignore[attr-defined]\n return User(user_id, name, display_name, initials, None, color)\n\n def should_check_origin(self, handler: web.RequestHandler) -> bool:\n """Should the Handler check for CORS origin validation?\n\n Origin check should be skipped for token-authenticated requests.\n\n Returns:\n - True, if Handler must check for valid CORS origin.\n - False, if Handler should skip origin check since requests are token-authenticated.\n """\n return not self.is_token_authenticated(handler)\n\n def is_token_authenticated(self, handler: web.RequestHandler) -> bool:\n """Returns True if handler has been token authenticated. Otherwise, False.\n\n Login with a token is used to signal certain things, such as:\n\n - permit access to REST API\n - xsrf protection\n - skip origin-checks for scripts\n """\n # ensure get_user has been called, so we know if we're token-authenticated\n handler.current_user # noqa: B018\n return getattr(handler, "_token_authenticated", False)\n\n def validate_security(\n self,\n app: t.Any,\n ssl_options: dict[str, t.Any] | None = None,\n ) -> None:\n """Check the application's security.\n\n Show messages, or abort if necessary, based on the security configuration.\n """\n if not app.ip:\n warning = "WARNING: The Jupyter server is listening on all IP addresses"\n if ssl_options is None:\n app.log.warning(f"{warning} and not using encryption. This is not recommended.")\n if not self.auth_enabled:\n app.log.warning(\n f"{warning} and not using authentication. "\n "This is highly insecure and not recommended."\n )\n elif not self.auth_enabled:\n app.log.warning(\n "All authentication is disabled."\n " Anyone who can connect to this server will be able to run code."\n )\n\n def process_login_form(self, handler: web.RequestHandler) -> User | None:\n """Process login form data\n\n Return authenticated User if successful, None if not.\n """\n typed_password = handler.get_argument("password", default="")\n user = None\n if not self.auth_enabled:\n self.log.warning("Accepting anonymous login because auth fully disabled!")\n return self.generate_anonymous_user(handler)\n\n if self.token and self.token == typed_password:\n return t.cast(User, self.user_for_token(typed_password)) # type:ignore[attr-defined]\n\n return user\n\n @property\n def auth_enabled(self):\n """Is authentication enabled?\n\n Should always be True, but may be False in rare, insecure cases\n where requests with no auth are allowed.\n\n Previously: LoginHandler.get_login_available\n """\n return True\n\n @property\n def login_available(self):\n """Whether a LoginHandler is needed - and therefore whether the login page should be displayed."""\n return self.auth_enabled\n\n @property\n def logout_available(self):\n """Whether a LogoutHandler is needed."""\n return True\n\n\nclass PasswordIdentityProvider(IdentityProvider):\n """A password identity provider."""\n\n hashed_password = Unicode(\n "",\n config=True,\n help=_i18n(\n """\n Hashed password to use for web authentication.\n\n To generate, type in a python/IPython shell:\n\n from jupyter_server.auth import passwd; passwd()\n\n The string should be of the form type:salt:hashed-password.\n """\n ),\n )\n\n password_required = Bool(\n False,\n config=True,\n help=_i18n(\n """\n Forces users to use a password for the Jupyter server.\n This is useful in a multi user environment, for instance when\n everybody in the LAN can access each other's machine through ssh.\n\n In such a case, serving on localhost is not secure since\n any user can connect to the Jupyter server via ssh.\n\n """\n ),\n )\n\n allow_password_change = Bool(\n True,\n config=True,\n help=_i18n(\n """\n Allow password to be changed at login for the Jupyter server.\n\n While logging in with a token, the Jupyter server UI will give the opportunity to\n the user to enter a new password at the same time that will replace\n the token login mechanism.\n\n This can be set to False to prevent changing password from the UI/API.\n """\n ),\n )\n\n @default("need_token")\n def _need_token_default(self):\n return not bool(self.hashed_password)\n\n @property\n def login_available(self) -> bool:\n """Whether a LoginHandler is needed - and therefore whether the login page should be displayed."""\n return self.auth_enabled\n\n @property\n def auth_enabled(self) -> bool:\n """Return whether any auth is enabled"""\n return bool(self.hashed_password or self.token)\n\n def passwd_check(self, password):\n """Check password against our stored hashed password"""\n return passwd_check(self.hashed_password, password)\n\n def process_login_form(self, handler: web.RequestHandler) -> User | None:\n """Process login form data\n\n Return authenticated User if successful, None if not.\n """\n typed_password = handler.get_argument("password", default="")\n new_password = handler.get_argument("new_password", default="")\n user = None\n if not self.auth_enabled:\n self.log.warning("Accepting anonymous login because auth fully disabled!")\n return self.generate_anonymous_user(handler)\n\n if self.passwd_check(typed_password) and not new_password:\n return self.generate_anonymous_user(handler)\n elif self.token and self.token == typed_password:\n user = self.generate_anonymous_user(handler)\n if new_password and self.allow_password_change:\n config_dir = handler.settings.get("config_dir", "")\n config_file = os.path.join(config_dir, "jupyter_server_config.json")\n self.hashed_password = set_password(new_password, config_file=config_file)\n self.log.info(_i18n("Wrote hashed password to {file}").format(file=config_file))\n\n return user\n\n def validate_security(\n self,\n app: t.Any,\n ssl_options: dict[str, t.Any] | None = None,\n ) -> None:\n """Handle security validation."""\n super().validate_security(app, ssl_options)\n if self.password_required and (not self.hashed_password):\n self.log.critical(\n _i18n("Jupyter servers are configured to only be run with a password.")\n )\n self.log.critical(_i18n("Hint: run the following command to set a password"))\n self.log.critical(_i18n("\t$ python -m jupyter_server.auth password"))\n sys.exit(1)\n\n\nclass LegacyIdentityProvider(PasswordIdentityProvider):\n """Legacy IdentityProvider for use with custom LoginHandlers\n\n Login configuration has moved from LoginHandler to IdentityProvider\n in Jupyter Server 2.0.\n """\n\n # settings must be passed for\n settings = Dict()\n\n @default("settings")\n def _default_settings(self):\n return {\n "token": self.token,\n "password": self.hashed_password,\n }\n\n @default("login_handler_class")\n def _default_login_handler_class(self):\n from .login import LegacyLoginHandler\n\n return LegacyLoginHandler\n\n @property\n def auth_enabled(self):\n return self.login_available\n\n def get_user(self, handler: web.RequestHandler) -> User | None:\n """Get the user."""\n user = self.login_handler_class.get_user(handler) # type:ignore[attr-defined]\n if user is None:\n return None\n return _backward_compat_user(user)\n\n @property\n def login_available(self) -> bool:\n return bool(\n self.login_handler_class.get_login_available( # type:ignore[attr-defined]\n self.settings\n )\n )\n\n def should_check_origin(self, handler: web.RequestHandler) -> bool:\n """Whether we should check origin."""\n return bool(self.login_handler_class.should_check_origin(handler)) # type:ignore[attr-defined]\n\n def is_token_authenticated(self, handler: web.RequestHandler) -> bool:\n """Whether we are token authenticated."""\n return bool(self.login_handler_class.is_token_authenticated(handler)) # type:ignore[attr-defined]\n\n def validate_security(\n self,\n app: t.Any,\n ssl_options: dict[str, t.Any] | None = None,\n ) -> None:\n """Validate security."""\n if self.password_required and (not self.hashed_password):\n self.log.critical(\n _i18n("Jupyter servers are configured to only be run with a password.")\n )\n self.log.critical(_i18n("Hint: run the following command to set a password"))\n self.log.critical(_i18n("\t$ python -m jupyter_server.auth password"))\n sys.exit(1)\n self.login_handler_class.validate_security( # type:ignore[attr-defined]\n app, ssl_options\n )\n | .venv\Lib\site-packages\jupyter_server\auth\identity.py | identity.py | Python | 27,077 | 0.95 | 0.202977 | 0.074013 | awesome-app | 905 | 2023-10-03T20:53:51.926089 | MIT | false | b3a50b411f175a84a5485e8e7d24994d |
"""Tornado handlers for logging into the Jupyter Server."""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nimport os\nimport re\nimport uuid\nfrom urllib.parse import urlparse\n\nfrom tornado.escape import url_escape\n\nfrom ..base.handlers import JupyterHandler\nfrom .decorator import allow_unauthenticated\nfrom .security import passwd_check, set_password\n\n\nclass LoginFormHandler(JupyterHandler):\n """The basic tornado login handler\n\n accepts login form, passed to IdentityProvider.process_login_form.\n """\n\n def _render(self, message=None):\n """Render the login form."""\n self.write(\n self.render_template(\n "login.html",\n next=url_escape(self.get_argument("next", default=self.base_url)),\n message=message,\n )\n )\n\n def _redirect_safe(self, url, default=None):\n """Redirect if url is on our PATH\n\n Full-domain redirects are allowed if they pass our CORS origin checks.\n\n Otherwise use default (self.base_url if unspecified).\n """\n if default is None:\n default = self.base_url\n # protect chrome users from mishandling unescaped backslashes.\n # \ is not valid in urls, but some browsers treat it as /\n # instead of %5C, causing `\\` to behave as `//`\n url = url.replace("\\", "%5C")\n # urllib and browsers interpret extra '/' in the scheme separator (`scheme:///host/path`)\n # differently.\n # urllib gives scheme=scheme, netloc='', path='/host/path', while\n # browsers get scheme=scheme, netloc='host', path='/path'\n # so make sure ':///*' collapses to '://' by splitting and stripping any additional leading slash\n # don't allow any kind of `:/` shenanigans by splitting on ':' only\n # and replacing `:/*` with exactly `://`\n if ":" in url:\n scheme, _, rest = url.partition(":")\n url = f"{scheme}://{rest.lstrip('/')}"\n parsed = urlparse(url)\n # full url may be `//host/path` (empty scheme == same scheme as request)\n # or `https://host/path`\n # or even `https:///host/path` (invalid, but accepted and ambiguously interpreted)\n if (parsed.scheme or parsed.netloc) or not (parsed.path + "/").startswith(self.base_url):\n # require that next_url be absolute path within our path\n allow = False\n # OR pass our cross-origin check\n if parsed.scheme or parsed.netloc:\n # if full URL, run our cross-origin check:\n origin = f"{parsed.scheme}://{parsed.netloc}"\n origin = origin.lower()\n if self.allow_origin:\n allow = self.allow_origin == origin\n elif self.allow_origin_pat:\n allow = bool(re.match(self.allow_origin_pat, origin))\n if not allow:\n # not allowed, use default\n self.log.warning("Not allowing login redirect to %r" % url)\n url = default\n self.redirect(url)\n\n @allow_unauthenticated\n def get(self):\n """Get the login form."""\n if self.current_user:\n next_url = self.get_argument("next", default=self.base_url)\n self._redirect_safe(next_url)\n else:\n self._render()\n\n @allow_unauthenticated\n def post(self):\n """Post a login."""\n user = self.current_user = self.identity_provider.process_login_form(self)\n if user is None:\n self.set_status(401)\n self._render(message={"error": "Invalid credentials"})\n return\n\n self.log.info(f"User {user.username} logged in.")\n self.identity_provider.set_login_cookie(self, user)\n next_url = self.get_argument("next", default=self.base_url)\n self._redirect_safe(next_url)\n\n\nclass LegacyLoginHandler(LoginFormHandler):\n """Legacy LoginHandler, implementing most custom auth configuration.\n\n Deprecated in jupyter-server 2.0.\n Login configuration has moved to IdentityProvider.\n """\n\n @property\n def hashed_password(self):\n return self.password_from_settings(self.settings)\n\n def passwd_check(self, a, b):\n """Check a passwd."""\n return passwd_check(a, b)\n\n @allow_unauthenticated\n def post(self):\n """Post a login form."""\n typed_password = self.get_argument("password", default="")\n new_password = self.get_argument("new_password", default="")\n\n if self.get_login_available(self.settings):\n if self.passwd_check(self.hashed_password, typed_password) and not new_password:\n self.set_login_cookie(self, uuid.uuid4().hex)\n elif self.token and self.token == typed_password:\n self.set_login_cookie(self, uuid.uuid4().hex)\n if new_password and getattr(self.identity_provider, "allow_password_change", False):\n config_dir = self.settings.get("config_dir", "")\n config_file = os.path.join(config_dir, "jupyter_server_config.json")\n if hasattr(self.identity_provider, "hashed_password"):\n self.identity_provider.hashed_password = self.settings["password"] = (\n set_password(new_password, config_file=config_file)\n )\n self.log.info("Wrote hashed password to %s" % config_file)\n else:\n self.set_status(401)\n self._render(message={"error": "Invalid credentials"})\n return\n\n next_url = self.get_argument("next", default=self.base_url)\n self._redirect_safe(next_url)\n\n @classmethod\n def set_login_cookie(cls, handler, user_id=None):\n """Call this on handlers to set the login cookie for success"""\n cookie_options = handler.settings.get("cookie_options", {})\n cookie_options.setdefault("httponly", True)\n # tornado <4.2 has a bug that considers secure==True as soon as\n # 'secure' kwarg is passed to set_secure_cookie\n if handler.settings.get("secure_cookie", handler.request.protocol == "https"):\n cookie_options.setdefault("secure", True)\n cookie_options.setdefault("path", handler.base_url)\n handler.set_secure_cookie(handler.cookie_name, user_id, **cookie_options)\n return user_id\n\n auth_header_pat = re.compile(r"token\s+(.+)", re.IGNORECASE)\n\n @classmethod\n def get_token(cls, handler):\n """Get the user token from a request\n\n Default:\n\n - in URL parameters: ?token=<token>\n - in header: Authorization: token <token>\n """\n\n user_token = handler.get_argument("token", "")\n if not user_token:\n # get it from Authorization header\n m = cls.auth_header_pat.match(handler.request.headers.get("Authorization", ""))\n if m:\n user_token = m.group(1)\n return user_token\n\n @classmethod\n def should_check_origin(cls, handler):\n """DEPRECATED in 2.0, use IdentityProvider API"""\n return not cls.is_token_authenticated(handler)\n\n @classmethod\n def is_token_authenticated(cls, handler):\n """DEPRECATED in 2.0, use IdentityProvider API"""\n if getattr(handler, "_user_id", None) is None:\n # ensure get_user has been called, so we know if we're token-authenticated\n handler.current_user # noqa: B018\n return getattr(handler, "_token_authenticated", False)\n\n @classmethod\n def get_user(cls, handler):\n """DEPRECATED in 2.0, use IdentityProvider API"""\n # Can't call this get_current_user because it will collide when\n # called on LoginHandler itself.\n if getattr(handler, "_user_id", None):\n return handler._user_id\n token_user_id = cls.get_user_token(handler)\n cookie_user_id = cls.get_user_cookie(handler)\n # prefer token to cookie if both given,\n # because token is always explicit\n user_id = token_user_id or cookie_user_id\n if token_user_id:\n # if token-authenticated, persist user_id in cookie\n # if it hasn't already been stored there\n if user_id != cookie_user_id:\n cls.set_login_cookie(handler, user_id)\n # Record that the current request has been authenticated with a token.\n # Used in is_token_authenticated above.\n handler._token_authenticated = True\n\n if user_id is None:\n # If an invalid cookie was sent, clear it to prevent unnecessary\n # extra warnings. But don't do this on a request with *no* cookie,\n # because that can erroneously log you out (see gh-3365)\n if handler.get_cookie(handler.cookie_name) is not None:\n handler.log.warning("Clearing invalid/expired login cookie %s", handler.cookie_name)\n handler.clear_login_cookie()\n if not handler.login_available:\n # Completely insecure! No authentication at all.\n # No need to warn here, though; validate_security will have already done that.\n user_id = "anonymous"\n\n # cache value for future retrievals on the same request\n handler._user_id = user_id\n return user_id\n\n @classmethod\n def get_user_cookie(cls, handler):\n """DEPRECATED in 2.0, use IdentityProvider API"""\n get_secure_cookie_kwargs = handler.settings.get("get_secure_cookie_kwargs", {})\n user_id = handler.get_secure_cookie(handler.cookie_name, **get_secure_cookie_kwargs)\n if user_id:\n user_id = user_id.decode()\n return user_id\n\n @classmethod\n def get_user_token(cls, handler):\n """DEPRECATED in 2.0, use IdentityProvider API"""\n token = handler.token\n if not token:\n return None\n # check login token from URL argument or Authorization header\n user_token = cls.get_token(handler)\n authenticated = False\n if user_token == token:\n # token-authenticated, set the login cookie\n handler.log.debug(\n "Accepting token-authenticated connection from %s",\n handler.request.remote_ip,\n )\n authenticated = True\n\n if authenticated:\n # token does not correspond to user-id,\n # which is stored in a cookie.\n # still check the cookie for the user id\n user_id = cls.get_user_cookie(handler)\n if user_id is None:\n # no cookie, generate new random user_id\n user_id = uuid.uuid4().hex\n handler.log.info(\n f"Generating new user_id for token-authenticated request: {user_id}"\n )\n return user_id\n else:\n return None\n\n @classmethod\n def validate_security(cls, app, ssl_options=None):\n """DEPRECATED in 2.0, use IdentityProvider API"""\n if not app.ip:\n warning = "WARNING: The Jupyter server is listening on all IP addresses"\n if ssl_options is None:\n app.log.warning(f"{warning} and not using encryption. This is not recommended.")\n if not app.password and not app.token:\n app.log.warning(\n f"{warning} and not using authentication. "\n "This is highly insecure and not recommended."\n )\n elif not app.password and not app.token:\n app.log.warning(\n "All authentication is disabled."\n " Anyone who can connect to this server will be able to run code."\n )\n\n @classmethod\n def password_from_settings(cls, settings):\n """DEPRECATED in 2.0, use IdentityProvider API"""\n return settings.get("password", "")\n\n @classmethod\n def get_login_available(cls, settings):\n """DEPRECATED in 2.0, use IdentityProvider API"""\n\n return bool(cls.password_from_settings(settings) or settings.get("token"))\n\n\n# deprecated import, so deprecated implementations get the Legacy class instead\nLoginHandler = LegacyLoginHandler\n | .venv\Lib\site-packages\jupyter_server\auth\login.py | login.py | Python | 12,274 | 0.95 | 0.214047 | 0.170543 | awesome-app | 297 | 2024-05-15T11:16:29.224030 | MIT | false | 1bcf6c3df4999e31605db41a14f28f04 |
"""Tornado handlers for logging out of the Jupyter Server."""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom ..base.handlers import JupyterHandler\nfrom .decorator import allow_unauthenticated\n\n\nclass LogoutHandler(JupyterHandler):\n """An auth logout handler."""\n\n @allow_unauthenticated\n def get(self):\n """Handle a logout."""\n self.identity_provider.clear_login_cookie(self)\n if self.login_available:\n message = {"info": "Successfully logged out."}\n else:\n message = {"warning": "Cannot log out. Jupyter Server authentication is disabled."}\n self.write(self.render_template("logout.html", message=message))\n\n\ndefault_handlers = [(r"/logout", LogoutHandler)]\n | .venv\Lib\site-packages\jupyter_server\auth\logout.py | logout.py | Python | 785 | 0.95 | 0.173913 | 0.117647 | awesome-app | 369 | 2025-03-02T23:47:01.384016 | BSD-3-Clause | false | 83a17347d5812a04b496119c3249a1ee |
"""\nPassword generation for the Jupyter Server.\n"""\n\nimport getpass\nimport hashlib\nimport json\nimport os\nimport random\nimport traceback\nimport warnings\nfrom contextlib import contextmanager\n\nfrom jupyter_core.paths import jupyter_config_dir\nfrom traitlets.config import Config\nfrom traitlets.config.loader import ConfigFileNotFound, JSONFileConfigLoader\n\n# Length of the salt in nr of hex chars, which implies salt_len * 4\n# bits of randomness.\nsalt_len = 12\n\n\ndef passwd(passphrase=None, algorithm="argon2"):\n """Generate hashed password and salt for use in server configuration.\n\n In the server configuration, set `c.ServerApp.password` to\n the generated string.\n\n Parameters\n ----------\n passphrase : str\n Password to hash. If unspecified, the user is asked to input\n and verify a password.\n algorithm : str\n Hashing algorithm to use (e.g, 'sha1' or any argument supported\n by :func:`hashlib.new`, or 'argon2').\n\n Returns\n -------\n hashed_passphrase : str\n Hashed password, in the format 'hash_algorithm:salt:passphrase_hash'.\n\n Examples\n --------\n >>> passwd("mypassword") # doctest: +ELLIPSIS\n 'argon2:...'\n\n """\n if passphrase is None:\n for _ in range(3):\n p0 = getpass.getpass("Enter password: ")\n p1 = getpass.getpass("Verify password: ")\n if p0 == p1:\n passphrase = p0\n break\n warnings.warn("Passwords do not match.", stacklevel=2)\n else:\n msg = "No matching passwords found. Giving up."\n raise ValueError(msg)\n\n if algorithm == "argon2":\n import argon2\n\n ph = argon2.PasswordHasher(\n memory_cost=10240,\n time_cost=10,\n parallelism=8,\n )\n h_ph = ph.hash(passphrase)\n\n return f"{algorithm}:{h_ph}"\n\n h = hashlib.new(algorithm)\n salt = ("%0" + str(salt_len) + "x") % random.getrandbits(4 * salt_len)\n h.update(passphrase.encode("utf-8") + salt.encode("ascii"))\n\n return f"{algorithm}:{salt}:{h.hexdigest()}"\n\n\ndef passwd_check(hashed_passphrase, passphrase):\n """Verify that a given passphrase matches its hashed version.\n\n Parameters\n ----------\n hashed_passphrase : str\n Hashed password, in the format returned by `passwd`.\n passphrase : str\n Passphrase to validate.\n\n Returns\n -------\n valid : bool\n True if the passphrase matches the hash.\n\n Examples\n --------\n >>> myhash = passwd("mypassword")\n >>> passwd_check(myhash, "mypassword")\n True\n\n >>> passwd_check(myhash, "otherpassword")\n False\n\n >>> passwd_check("sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a", "mypassword")\n True\n """\n if hashed_passphrase.startswith("argon2:"):\n import argon2\n import argon2.exceptions\n\n ph = argon2.PasswordHasher()\n\n try:\n return ph.verify(hashed_passphrase[7:], passphrase)\n except argon2.exceptions.VerificationError:\n return False\n\n try:\n algorithm, salt, pw_digest = hashed_passphrase.split(":", 2)\n except (ValueError, TypeError):\n return False\n\n try:\n h = hashlib.new(algorithm)\n except ValueError:\n return False\n\n if len(pw_digest) == 0:\n return False\n\n h.update(passphrase.encode("utf-8") + salt.encode("ascii"))\n\n return h.hexdigest() == pw_digest\n\n\n@contextmanager\ndef persist_config(config_file=None, mode=0o600):\n """Context manager that can be used to modify a config object\n\n On exit of the context manager, the config will be written back to disk,\n by default with user-only (600) permissions.\n """\n\n if config_file is None:\n config_file = os.path.join(jupyter_config_dir(), "jupyter_server_config.json")\n\n os.makedirs(os.path.dirname(config_file), exist_ok=True)\n\n loader = JSONFileConfigLoader(os.path.basename(config_file), os.path.dirname(config_file))\n try:\n config = loader.load_config()\n except ConfigFileNotFound:\n config = Config()\n\n yield config\n\n with open(config_file, "w", encoding="utf8") as f:\n f.write(json.dumps(config, indent=2))\n\n try:\n os.chmod(config_file, mode)\n except Exception:\n tb = traceback.format_exc()\n warnings.warn(\n f"Failed to set permissions on {config_file}:\n{tb}", RuntimeWarning, stacklevel=2\n )\n\n\ndef set_password(password=None, config_file=None):\n """Ask user for password, store it in JSON configuration file"""\n\n hashed_password = passwd(password)\n\n with persist_config(config_file) as config:\n config.IdentityProvider.hashed_password = hashed_password\n return hashed_password\n | .venv\Lib\site-packages\jupyter_server\auth\security.py | security.py | Python | 4,741 | 0.95 | 0.113636 | 0.014925 | node-utils | 373 | 2024-08-12T04:31:50.106895 | MIT | false | e2d93def736c4ca1c5663594d2f15f99 |
"""A module with various utility methods for authorization in Jupyter Server."""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nimport importlib\nimport random\nimport re\nimport warnings\n\n\ndef warn_disabled_authorization():\n """DEPRECATED, does nothing"""\n warnings.warn(\n "jupyter_server.auth.utils.warn_disabled_authorization is deprecated",\n DeprecationWarning,\n stacklevel=2,\n )\n\n\nHTTP_METHOD_TO_AUTH_ACTION = {\n "GET": "read",\n "HEAD": "read",\n "OPTIONS": "read",\n "POST": "write",\n "PUT": "write",\n "PATCH": "write",\n "DELETE": "write",\n "WEBSOCKET": "execute",\n}\n\n\ndef get_regex_to_resource_map():\n """Returns a dictionary with all of Jupyter Server's\n request handler URL regex patterns mapped to\n their resource name.\n\n e.g.\n { "/api/contents/<regex_pattern>": "contents", ...}\n """\n from jupyter_server.serverapp import JUPYTER_SERVICE_HANDLERS\n\n modules = []\n for mod_name in JUPYTER_SERVICE_HANDLERS.values():\n if mod_name:\n modules.extend(mod_name)\n resource_map = {}\n for handler_module in modules:\n mod = importlib.import_module(handler_module)\n name = mod.AUTH_RESOURCE\n for handler in mod.default_handlers:\n url_regex = handler[0]\n resource_map[url_regex] = name\n # terminal plugin doesn't have importable url patterns\n # get these from terminal/__init__.py\n for url_regex in [\n r"/terminals/websocket/(\w+)",\n "/api/terminals",\n r"/api/terminals/(\w+)",\n ]:\n resource_map[url_regex] = "terminals"\n return resource_map\n\n\ndef match_url_to_resource(url, regex_mapping=None):\n """Finds the JupyterHandler regex pattern that would\n match the given URL and returns the resource name (str)\n of that handler.\n\n e.g.\n /api/contents/... returns "contents"\n """\n if not regex_mapping:\n regex_mapping = get_regex_to_resource_map()\n for regex, auth_resource in regex_mapping.items():\n pattern = re.compile(regex)\n if pattern.fullmatch(url):\n return auth_resource\n\n\n# From https://en.wikipedia.org/wiki/Moons_of_Jupiter\nmoons_of_jupyter = [\n "Metis",\n "Adrastea",\n "Amalthea",\n "Thebe",\n "Io",\n "Europa",\n "Ganymede",\n "Callisto",\n "Themisto",\n "Leda",\n "Ersa",\n "Pandia",\n "Himalia",\n "Lysithea",\n "Elara",\n "Dia",\n "Carpo",\n "Valetudo",\n "Euporie",\n "Eupheme",\n # 'S/2003 J 18',\n # 'S/2010 J 2',\n "Helike",\n # 'S/2003 J 16',\n # 'S/2003 J 2',\n "Euanthe",\n # 'S/2017 J 7',\n "Hermippe",\n "Praxidike",\n "Thyone",\n "Thelxinoe",\n # 'S/2017 J 3',\n "Ananke",\n "Mneme",\n # 'S/2016 J 1',\n "Orthosie",\n "Harpalyke",\n "Iocaste",\n # 'S/2017 J 9',\n # 'S/2003 J 12',\n # 'S/2003 J 4',\n "Erinome",\n "Aitne",\n "Herse",\n "Taygete",\n # 'S/2017 J 2',\n # 'S/2017 J 6',\n "Eukelade",\n "Carme",\n # 'S/2003 J 19',\n "Isonoe",\n # 'S/2003 J 10',\n "Autonoe",\n "Philophrosyne",\n "Cyllene",\n "Pasithee",\n # 'S/2010 J 1',\n "Pasiphae",\n "Sponde",\n # 'S/2017 J 8',\n "Eurydome",\n # 'S/2017 J 5',\n "Kalyke",\n "Hegemone",\n "Kale",\n "Kallichore",\n # 'S/2011 J 1',\n # 'S/2017 J 1',\n "Chaldene",\n "Arche",\n "Eirene",\n "Kore",\n # 'S/2011 J 2',\n # 'S/2003 J 9',\n "Megaclite",\n "Aoede",\n # 'S/2003 J 23',\n "Callirrhoe",\n "Sinope",\n]\n\n\ndef get_anonymous_username() -> str:\n """\n Get a random user-name based on the moons of Jupyter.\n This function returns names like "Anonymous Io" or "Anonymous Metis".\n """\n return moons_of_jupyter[random.randint(0, len(moons_of_jupyter) - 1)] # noqa: S311\n | .venv\Lib\site-packages\jupyter_server\auth\utils.py | utils.py | Python | 3,807 | 0.95 | 0.08284 | 0.176471 | awesome-app | 885 | 2024-01-05T19:31:43.513800 | MIT | false | 2b464488cd62ca2f42b2125d678a8b8b |
from .authorizer import *\nfrom .decorator import authorized\nfrom .identity import *\nfrom .security import passwd\n | .venv\Lib\site-packages\jupyter_server\auth\__init__.py | __init__.py | Python | 113 | 0.85 | 0 | 0 | python-kit | 786 | 2023-09-09T11:52:47.534620 | Apache-2.0 | false | ae8459acfb2ae78c2b2fd4d78f62d0ed |
"""The cli for auth."""\n\nimport argparse\nimport sys\nimport warnings\nfrom getpass import getpass\n\nfrom jupyter_core.paths import jupyter_config_dir\nfrom traitlets.log import get_logger\n\nfrom jupyter_server.auth import passwd # type:ignore[attr-defined]\nfrom jupyter_server.config_manager import BaseJSONConfigManager\n\n\ndef set_password(args):\n """Set a password."""\n password = args.password\n\n while not password:\n password1 = getpass("" if args.quiet else "Provide password: ")\n password_repeat = getpass("" if args.quiet else "Repeat password: ")\n if password1 != password_repeat:\n warnings.warn("Passwords do not match, try again", stacklevel=2)\n elif len(password1) < 4:\n warnings.warn("Please provide at least 4 characters", stacklevel=2)\n else:\n password = password1\n\n password_hash = passwd(password)\n cfg = BaseJSONConfigManager(config_dir=jupyter_config_dir())\n cfg.update(\n "jupyter_server_config",\n {\n "ServerApp": {\n "password": password_hash,\n }\n },\n )\n if not args.quiet:\n log = get_logger()\n log.info("password stored in config dir: %s" % jupyter_config_dir())\n\n\ndef main(argv):\n """The main cli handler."""\n parser = argparse.ArgumentParser(argv[0])\n subparsers = parser.add_subparsers()\n parser_password = subparsers.add_parser(\n "password", help="sets a password for your jupyter server"\n )\n parser_password.add_argument(\n "password",\n help="password to set, if not given, a password will be queried for (NOTE: this may not be safe)",\n nargs="?",\n )\n parser_password.add_argument("--quiet", help="suppress messages", action="store_true")\n parser_password.set_defaults(function=set_password)\n args = parser.parse_args(argv[1:])\n args.function(args)\n\n\nif __name__ == "__main__":\n main(sys.argv)\n | .venv\Lib\site-packages\jupyter_server\auth\__main__.py | __main__.py | Python | 1,940 | 0.95 | 0.238095 | 0 | node-utils | 938 | 2024-09-08T21:20:59.616251 | GPL-3.0 | false | dcfb9dd1c116f39e566e8c9fb4e35365 |
\n\n | .venv\Lib\site-packages\jupyter_server\auth\__pycache__\authorizer.cpython-313.pyc | authorizer.cpython-313.pyc | Other | 3,297 | 0.95 | 0.121622 | 0 | vue-tools | 326 | 2025-04-20T21:32:58.229532 | Apache-2.0 | false | eb58078049028327c44568dfc1ed51e9 |
\n\n | .venv\Lib\site-packages\jupyter_server\auth\__pycache__\decorator.cpython-313.pyc | decorator.cpython-313.pyc | Other | 5,237 | 0.8 | 0.125 | 0 | vue-tools | 588 | 2024-09-17T23:59:05.788553 | GPL-3.0 | false | df9996e6167695d65e1469b0fa9f3c3c |
\n\n | .venv\Lib\site-packages\jupyter_server\auth\__pycache__\identity.cpython-313.pyc | identity.cpython-313.pyc | Other | 30,901 | 0.95 | 0.114362 | 0.003106 | vue-tools | 798 | 2025-03-16T04:41:01.228199 | GPL-3.0 | false | 791df5239309aa711073774c591db461 |
\n\n | .venv\Lib\site-packages\jupyter_server\auth\__pycache__\login.cpython-313.pyc | login.cpython-313.pyc | Other | 13,492 | 0.8 | 0.059406 | 0 | node-utils | 946 | 2023-11-12T02:20:30.328023 | Apache-2.0 | false | 6639eb7da3bf6503ae2c5767feecce81 |
\n\n | .venv\Lib\site-packages\jupyter_server\auth\__pycache__\logout.cpython-313.pyc | logout.cpython-313.pyc | Other | 1,330 | 0.7 | 0.111111 | 0 | python-kit | 786 | 2025-02-08T12:38:33.064894 | BSD-3-Clause | false | 629b4b8faa364c4be0a863790870433b |
\n\n | .venv\Lib\site-packages\jupyter_server\auth\__pycache__\security.cpython-313.pyc | security.cpython-313.pyc | Other | 6,673 | 0.8 | 0.029412 | 0.008403 | vue-tools | 862 | 2023-10-04T14:30:20.442063 | BSD-3-Clause | false | 2bcfa09d640b9897766495ddfd1e98b4 |
\n\n | .venv\Lib\site-packages\jupyter_server\auth\__pycache__\utils.cpython-313.pyc | utils.cpython-313.pyc | Other | 3,486 | 0.95 | 0.044444 | 0 | react-lib | 999 | 2023-07-27T15:57:18.544310 | Apache-2.0 | false | e1c32e6958c97f4e232327cf2c375a54 |
\n\n | .venv\Lib\site-packages\jupyter_server\auth\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 334 | 0.7 | 0 | 0 | awesome-app | 57 | 2023-08-15T12:04:12.347050 | MIT | false | 32627bf08a90f5f913b474867e069da4 |
\n\n | .venv\Lib\site-packages\jupyter_server\auth\__pycache__\__main__.cpython-313.pyc | __main__.cpython-313.pyc | Other | 2,842 | 0.95 | 0.176471 | 0 | awesome-app | 491 | 2024-02-24T05:02:38.585618 | BSD-3-Clause | false | fcdfbf4f128b19d5504cec45199f9f31 |
"""Provides access to variables pertaining to specific call contexts."""\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom contextvars import Context, ContextVar, copy_context\nfrom typing import Any\n\n\nclass CallContext:\n """CallContext essentially acts as a namespace for managing context variables.\n\n Although not required, it is recommended that any "file-spanning" context variable\n names (i.e., variables that will be set or retrieved from multiple files or services) be\n added as constants to this class definition.\n """\n\n # Add well-known (file-spanning) names here.\n #: Provides access to the current request handler once set.\n JUPYTER_HANDLER: str = "JUPYTER_HANDLER"\n\n # A map of variable name to value is maintained as the single ContextVar. This also enables\n # easier management over maintaining a set of ContextVar instances, since the Context is a\n # map of ContextVar instances to their values, and the "name" is no longer a lookup key.\n _NAME_VALUE_MAP = "_name_value_map"\n _name_value_map: ContextVar[dict[str, Any]] = ContextVar(_NAME_VALUE_MAP)\n\n @classmethod\n def get(cls, name: str) -> Any:\n """Returns the value corresponding the named variable relative to this context.\n\n If the named variable doesn't exist, None will be returned.\n\n Parameters\n ----------\n name : str\n The name of the variable to get from the call context\n\n Returns\n -------\n value: Any\n The value associated with the named variable for this call context\n """\n name_value_map = CallContext._get_map()\n\n if name in name_value_map:\n return name_value_map[name]\n return None # TODO: should this raise `LookupError` (or a custom error derived from said)\n\n @classmethod\n def set(cls, name: str, value: Any) -> None:\n """Sets the named variable to the specified value in the current call context.\n\n Parameters\n ----------\n name : str\n The name of the variable to store into the call context\n value : Any\n The value of the variable to store into the call context\n\n Returns\n -------\n None\n """\n name_value_map = CallContext._get_map()\n name_value_map[name] = value\n\n @classmethod\n def context_variable_names(cls) -> list[str]:\n """Returns a list of variable names set for this call context.\n\n Returns\n -------\n names: List[str]\n A list of variable names set for this call context.\n """\n name_value_map = CallContext._get_map()\n return list(name_value_map.keys())\n\n @classmethod\n def _get_map(cls) -> dict[str, Any]:\n """Get the map of names to their values from the _NAME_VALUE_MAP context var.\n\n If the map does not exist in the current context, an empty map is created and returned.\n """\n ctx: Context = copy_context()\n if CallContext._name_value_map not in ctx:\n CallContext._name_value_map.set({})\n return CallContext._name_value_map.get()\n | .venv\Lib\site-packages\jupyter_server\base\call_context.py | call_context.py | Python | 3,178 | 0.95 | 0.136364 | 0.1 | react-lib | 825 | 2024-03-04T13:39:31.494772 | Apache-2.0 | false | 6767c128300c89c656a4264ba7cb482a |
"""Base Tornado handlers for the Jupyter server."""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport functools\nimport inspect\nimport ipaddress\nimport json\nimport mimetypes\nimport os\nimport re\nimport types\nimport warnings\nfrom collections.abc import Awaitable, Coroutine, Sequence\nfrom http.client import responses\nfrom logging import Logger\nfrom typing import TYPE_CHECKING, Any, cast\nfrom urllib.parse import urlparse\n\nimport prometheus_client\nfrom jinja2 import TemplateNotFound\nfrom jupyter_core.paths import is_hidden\nfrom tornado import web\nfrom tornado.log import app_log\nfrom traitlets.config import Application\n\nimport jupyter_server\nfrom jupyter_server import CallContext\nfrom jupyter_server._sysinfo import get_sys_info\nfrom jupyter_server._tz import utcnow\nfrom jupyter_server.auth.decorator import allow_unauthenticated, authorized\nfrom jupyter_server.auth.identity import User\nfrom jupyter_server.i18n import combine_translations\nfrom jupyter_server.services.security import csp_report_uri\nfrom jupyter_server.utils import (\n ensure_async,\n filefind,\n url_escape,\n url_is_absolute,\n url_path_join,\n urldecode_unix_socket_path,\n)\n\nif TYPE_CHECKING:\n from jupyter_client.kernelspec import KernelSpecManager\n from jupyter_events import EventLogger\n from jupyter_server_terminals.terminalmanager import TerminalManager\n from tornado.concurrent import Future\n\n from jupyter_server.auth.authorizer import Authorizer\n from jupyter_server.auth.identity import IdentityProvider\n from jupyter_server.serverapp import ServerApp\n from jupyter_server.services.config.manager import ConfigManager\n from jupyter_server.services.contents.manager import ContentsManager\n from jupyter_server.services.kernels.kernelmanager import AsyncMappingKernelManager\n from jupyter_server.services.sessions.sessionmanager import SessionManager\n\n# -----------------------------------------------------------------------------\n# Top-level handlers\n# -----------------------------------------------------------------------------\n\n_sys_info_cache = None\n\n\ndef json_sys_info():\n """Get sys info as json."""\n global _sys_info_cache # noqa: PLW0603\n if _sys_info_cache is None:\n _sys_info_cache = json.dumps(get_sys_info())\n return _sys_info_cache\n\n\ndef log() -> Logger:\n """Get the application log."""\n if Application.initialized():\n return cast(Logger, Application.instance().log)\n else:\n return app_log\n\n\nclass AuthenticatedHandler(web.RequestHandler):\n """A RequestHandler with an authenticated user."""\n\n @property\n def base_url(self) -> str:\n return cast(str, self.settings.get("base_url", "/"))\n\n @property\n def content_security_policy(self) -> str:\n """The default Content-Security-Policy header\n\n Can be overridden by defining Content-Security-Policy in settings['headers']\n """\n if "Content-Security-Policy" in self.settings.get("headers", {}):\n # user-specified, don't override\n return cast(str, self.settings["headers"]["Content-Security-Policy"])\n\n return "; ".join(\n [\n "frame-ancestors 'self'",\n # Make sure the report-uri is relative to the base_url\n "report-uri "\n + self.settings.get("csp_report_uri", url_path_join(self.base_url, csp_report_uri)),\n ]\n )\n\n def set_default_headers(self) -> None:\n """Set the default headers."""\n headers = {}\n headers["X-Content-Type-Options"] = "nosniff"\n headers.update(self.settings.get("headers", {}))\n\n headers["Content-Security-Policy"] = self.content_security_policy\n\n # Allow for overriding headers\n for header_name, value in headers.items():\n try:\n self.set_header(header_name, value)\n except Exception as e:\n # tornado raise Exception (not a subclass)\n # if method is unsupported (websocket and Access-Control-Allow-Origin\n # for example, so just ignore)\n self.log.exception( # type:ignore[attr-defined]\n "Could not set default headers: %s", e\n )\n\n @property\n def cookie_name(self) -> str:\n warnings.warn(\n """JupyterHandler.login_handler is deprecated in 2.0,\n use JupyterHandler.identity_provider.\n """,\n DeprecationWarning,\n stacklevel=2,\n )\n return self.identity_provider.get_cookie_name(self)\n\n def force_clear_cookie(self, name: str, path: str = "/", domain: str | None = None) -> None:\n """Force a cookie clear."""\n warnings.warn(\n """JupyterHandler.login_handler is deprecated in 2.0,\n use JupyterHandler.identity_provider.\n """,\n DeprecationWarning,\n stacklevel=2,\n )\n self.identity_provider._force_clear_cookie(self, name, path=path, domain=domain)\n\n def clear_login_cookie(self) -> None:\n """Clear a login cookie."""\n warnings.warn(\n """JupyterHandler.login_handler is deprecated in 2.0,\n use JupyterHandler.identity_provider.\n """,\n DeprecationWarning,\n stacklevel=2,\n )\n self.identity_provider.clear_login_cookie(self)\n\n def get_current_user(self) -> str:\n """Get the current user."""\n clsname = self.__class__.__name__\n msg = (\n f"Calling `{clsname}.get_current_user()` directly is deprecated in jupyter-server 2.0."\n " Use `self.current_user` instead (works in all versions)."\n )\n if hasattr(self, "_jupyter_current_user"):\n # backward-compat: return _jupyter_current_user\n warnings.warn(\n msg,\n DeprecationWarning,\n stacklevel=2,\n )\n return cast(str, self._jupyter_current_user)\n # haven't called get_user in prepare, raise\n raise RuntimeError(msg)\n\n def skip_check_origin(self) -> bool:\n """Ask my login_handler if I should skip the origin_check\n\n For example: in the default LoginHandler, if a request is token-authenticated,\n origin checking should be skipped.\n """\n if self.request.method == "OPTIONS":\n # no origin-check on options requests, which are used to check origins!\n return True\n return not self.identity_provider.should_check_origin(self)\n\n @property\n def token_authenticated(self) -> bool:\n """Have I been authenticated with a token?"""\n return self.identity_provider.is_token_authenticated(self)\n\n @property\n def logged_in(self) -> bool:\n """Is a user currently logged in?"""\n user = self.current_user\n return bool(user and user != "anonymous")\n\n @property\n def login_handler(self) -> Any:\n """Return the login handler for this application, if any."""\n warnings.warn(\n """JupyterHandler.login_handler is deprecated in 2.0,\n use JupyterHandler.identity_provider.\n """,\n DeprecationWarning,\n stacklevel=2,\n )\n return self.identity_provider.login_handler_class\n\n @property\n def token(self) -> str | None:\n """Return the login token for this application, if any."""\n return self.identity_provider.token\n\n @property\n def login_available(self) -> bool:\n """May a user proceed to log in?\n\n This returns True if login capability is available, irrespective of\n whether the user is already logged in or not.\n\n """\n return cast(bool, self.identity_provider.login_available)\n\n @property\n def authorizer(self) -> Authorizer:\n if "authorizer" not in self.settings:\n warnings.warn(\n "The Tornado web application does not have an 'authorizer' defined "\n "in its settings. In future releases of jupyter_server, this will "\n "be a required key for all subclasses of `JupyterHandler`. For an "\n "example, see the jupyter_server source code for how to "\n "add an authorizer to the tornado settings: "\n "https://github.com/jupyter-server/jupyter_server/blob/"\n "653740cbad7ce0c8a8752ce83e4d3c2c754b13cb/jupyter_server/serverapp.py"\n "#L234-L256",\n stacklevel=2,\n )\n from jupyter_server.auth import AllowAllAuthorizer\n\n self.settings["authorizer"] = AllowAllAuthorizer(\n config=self.settings.get("config", None),\n identity_provider=self.identity_provider,\n )\n\n return cast("Authorizer", self.settings.get("authorizer"))\n\n @property\n def identity_provider(self) -> IdentityProvider:\n if "identity_provider" not in self.settings:\n warnings.warn(\n "The Tornado web application does not have an 'identity_provider' defined "\n "in its settings. In future releases of jupyter_server, this will "\n "be a required key for all subclasses of `JupyterHandler`. For an "\n "example, see the jupyter_server source code for how to "\n "add an identity provider to the tornado settings: "\n "https://github.com/jupyter-server/jupyter_server/blob/v2.0.0/"\n "jupyter_server/serverapp.py#L242",\n stacklevel=2,\n )\n from jupyter_server.auth import IdentityProvider\n\n # no identity provider set, load default\n self.settings["identity_provider"] = IdentityProvider(\n config=self.settings.get("config", None)\n )\n return cast("IdentityProvider", self.settings["identity_provider"])\n\n\nclass JupyterHandler(AuthenticatedHandler):\n """Jupyter-specific extensions to authenticated handling\n\n Mostly property shortcuts to Jupyter-specific settings.\n """\n\n @property\n def config(self) -> dict[str, Any] | None:\n return cast("dict[str, Any] | None", self.settings.get("config", None))\n\n @property\n def log(self) -> Logger:\n """use the Jupyter log by default, falling back on tornado's logger"""\n return log()\n\n @property\n def jinja_template_vars(self) -> dict[str, Any]:\n """User-supplied values to supply to jinja templates."""\n return cast("dict[str, Any]", self.settings.get("jinja_template_vars", {}))\n\n @property\n def serverapp(self) -> ServerApp | None:\n return cast("ServerApp | None", self.settings["serverapp"])\n\n # ---------------------------------------------------------------\n # URLs\n # ---------------------------------------------------------------\n\n @property\n def version_hash(self) -> str:\n """The version hash to use for cache hints for static files"""\n return cast(str, self.settings.get("version_hash", ""))\n\n @property\n def mathjax_url(self) -> str:\n url = cast(str, self.settings.get("mathjax_url", ""))\n if not url or url_is_absolute(url):\n return url\n return url_path_join(self.base_url, url)\n\n @property\n def mathjax_config(self) -> str:\n return cast(str, self.settings.get("mathjax_config", "TeX-AMS-MML_HTMLorMML-full,Safe"))\n\n @property\n def default_url(self) -> str:\n return cast(str, self.settings.get("default_url", ""))\n\n @property\n def ws_url(self) -> str:\n return cast(str, self.settings.get("websocket_url", ""))\n\n @property\n def contents_js_source(self) -> str:\n self.log.debug(\n "Using contents: %s",\n self.settings.get("contents_js_source", "services/contents"),\n )\n return cast(str, self.settings.get("contents_js_source", "services/contents"))\n\n # ---------------------------------------------------------------\n # Manager objects\n # ---------------------------------------------------------------\n\n @property\n def kernel_manager(self) -> AsyncMappingKernelManager:\n return cast("AsyncMappingKernelManager", self.settings["kernel_manager"])\n\n @property\n def contents_manager(self) -> ContentsManager:\n return cast("ContentsManager", self.settings["contents_manager"])\n\n @property\n def session_manager(self) -> SessionManager:\n return cast("SessionManager", self.settings["session_manager"])\n\n @property\n def terminal_manager(self) -> TerminalManager:\n return cast("TerminalManager", self.settings["terminal_manager"])\n\n @property\n def kernel_spec_manager(self) -> KernelSpecManager:\n return cast("KernelSpecManager", self.settings["kernel_spec_manager"])\n\n @property\n def config_manager(self) -> ConfigManager:\n return cast("ConfigManager", self.settings["config_manager"])\n\n @property\n def event_logger(self) -> EventLogger:\n return cast("EventLogger", self.settings["event_logger"])\n\n # ---------------------------------------------------------------\n # CORS\n # ---------------------------------------------------------------\n\n @property\n def allow_origin(self) -> str:\n """Normal Access-Control-Allow-Origin"""\n return cast(str, self.settings.get("allow_origin", ""))\n\n @property\n def allow_origin_pat(self) -> str | None:\n """Regular expression version of allow_origin"""\n return cast("str | None", self.settings.get("allow_origin_pat", None))\n\n @property\n def allow_credentials(self) -> bool:\n """Whether to set Access-Control-Allow-Credentials"""\n return cast(bool, self.settings.get("allow_credentials", False))\n\n def set_default_headers(self) -> None:\n """Add CORS headers, if defined"""\n super().set_default_headers()\n\n def set_cors_headers(self) -> None:\n """Add CORS headers, if defined\n\n Now that current_user is async (jupyter-server 2.0),\n must be called at the end of prepare(), instead of in set_default_headers.\n """\n if self.allow_origin:\n self.set_header("Access-Control-Allow-Origin", self.allow_origin)\n elif self.allow_origin_pat:\n origin = self.get_origin()\n if origin and re.match(self.allow_origin_pat, origin):\n self.set_header("Access-Control-Allow-Origin", origin)\n elif self.token_authenticated and "Access-Control-Allow-Origin" not in self.settings.get(\n "headers", {}\n ):\n # allow token-authenticated requests cross-origin by default.\n # only apply this exception if allow-origin has not been specified.\n self.set_header("Access-Control-Allow-Origin", self.request.headers.get("Origin", ""))\n\n if self.allow_credentials:\n self.set_header("Access-Control-Allow-Credentials", "true")\n\n def set_attachment_header(self, filename: str) -> None:\n """Set Content-Disposition: attachment header\n\n As a method to ensure handling of filename encoding\n """\n escaped_filename = url_escape(filename)\n self.set_header(\n "Content-Disposition",\n f"attachment; filename*=utf-8''{escaped_filename}",\n )\n\n def get_origin(self) -> str | None:\n # Handle WebSocket Origin naming convention differences\n # The difference between version 8 and 13 is that in 8 the\n # client sends a "Sec-Websocket-Origin" header and in 13 it's\n # simply "Origin".\n if "Origin" in self.request.headers:\n origin = self.request.headers.get("Origin")\n else:\n origin = self.request.headers.get("Sec-Websocket-Origin", None)\n return origin\n\n # origin_to_satisfy_tornado is present because tornado requires\n # check_origin to take an origin argument, but we don't use it\n def check_origin(self, origin_to_satisfy_tornado: str = "") -> bool:\n """Check Origin for cross-site API requests, including websockets\n\n Copied from WebSocket with changes:\n\n - allow unspecified host/origin (e.g. scripts)\n - allow token-authenticated requests\n """\n if self.allow_origin == "*" or self.skip_check_origin():\n return True\n\n host = self.request.headers.get("Host")\n origin = self.request.headers.get("Origin")\n\n # If no header is provided, let the request through.\n # Origin can be None for:\n # - same-origin (IE, Firefox)\n # - Cross-site POST form (IE, Firefox)\n # - Scripts\n # The cross-site POST (XSRF) case is handled by tornado's xsrf_token\n if origin is None or host is None:\n return True\n\n origin = origin.lower()\n origin_host = urlparse(origin).netloc\n\n # OK if origin matches host\n if origin_host == host:\n return True\n\n # Check CORS headers\n if self.allow_origin:\n allow = bool(self.allow_origin == origin)\n elif self.allow_origin_pat:\n allow = bool(re.match(self.allow_origin_pat, origin))\n else:\n # No CORS headers deny the request\n allow = False\n if not allow:\n self.log.warning(\n "Blocking Cross Origin API request for %s. Origin: %s, Host: %s",\n self.request.path,\n origin,\n host,\n )\n return allow\n\n def check_referer(self) -> bool:\n """Check Referer for cross-site requests.\n Disables requests to certain endpoints with\n external or missing Referer.\n If set, allow_origin settings are applied to the Referer\n to whitelist specific cross-origin sites.\n Used on GET for api endpoints and /files/\n to block cross-site inclusion (XSSI).\n """\n if self.allow_origin == "*" or self.skip_check_origin():\n return True\n\n host = self.request.headers.get("Host")\n referer = self.request.headers.get("Referer")\n\n if not host:\n self.log.warning("Blocking request with no host")\n return False\n if not referer:\n self.log.warning("Blocking request with no referer")\n return False\n\n referer_url = urlparse(referer)\n referer_host = referer_url.netloc\n if referer_host == host:\n return True\n\n # apply cross-origin checks to Referer:\n origin = f"{referer_url.scheme}://{referer_url.netloc}"\n if self.allow_origin:\n allow = self.allow_origin == origin\n elif self.allow_origin_pat:\n allow = bool(re.match(self.allow_origin_pat, origin))\n else:\n # No CORS settings, deny the request\n allow = False\n\n if not allow:\n self.log.warning(\n "Blocking Cross Origin request for %s. Referer: %s, Host: %s",\n self.request.path,\n origin,\n host,\n )\n return allow\n\n def check_xsrf_cookie(self) -> None:\n """Bypass xsrf cookie checks when token-authenticated"""\n if not hasattr(self, "_jupyter_current_user"):\n # Called too early, will be checked later\n return None\n if self.token_authenticated or self.settings.get("disable_check_xsrf", False):\n # Token-authenticated requests do not need additional XSRF-check\n # Servers without authentication are vulnerable to XSRF\n return None\n try:\n return super().check_xsrf_cookie()\n except web.HTTPError as e:\n if self.request.method in {"GET", "HEAD"}:\n # Consider Referer a sufficient cross-origin check for GET requests\n if not self.check_referer():\n referer = self.request.headers.get("Referer")\n if referer:\n msg = f"Blocking Cross Origin request from {referer}."\n else:\n msg = "Blocking request from unknown origin"\n raise web.HTTPError(403, msg) from e\n else:\n raise\n\n def check_host(self) -> bool:\n """Check the host header if remote access disallowed.\n\n Returns True if the request should continue, False otherwise.\n """\n if self.settings.get("allow_remote_access", False):\n return True\n\n # Remove port (e.g. ':8888') from host\n match = re.match(r"^(.*?)(:\d+)?$", self.request.host)\n assert match is not None\n host = match.group(1)\n\n # Browsers format IPv6 addresses like [::1]; we need to remove the []\n if host.startswith("[") and host.endswith("]"):\n host = host[1:-1]\n\n # UNIX socket handling\n check_host = urldecode_unix_socket_path(host)\n if check_host.startswith("/") and os.path.exists(check_host):\n allow = True\n else:\n try:\n addr = ipaddress.ip_address(host)\n except ValueError:\n # Not an IP address: check against hostnames\n allow = host in self.settings.get("local_hostnames", ["localhost"])\n else:\n allow = addr.is_loopback\n\n if not allow:\n self.log.warning(\n (\n "Blocking request with non-local 'Host' %s (%s). "\n "If the server should be accessible at that name, "\n "set ServerApp.allow_remote_access to disable the check."\n ),\n host,\n self.request.host,\n )\n return allow\n\n async def prepare(self, *, _redirect_to_login=True) -> Awaitable[None] | None: # type:ignore[override]\n """Prepare a response."""\n # Set the current Jupyter Handler context variable.\n CallContext.set(CallContext.JUPYTER_HANDLER, self)\n\n if not self.check_host():\n self.current_user = self._jupyter_current_user = None\n raise web.HTTPError(403)\n\n from jupyter_server.auth import IdentityProvider\n\n mod_obj = inspect.getmodule(self.get_current_user)\n assert mod_obj is not None\n user: User | None = None\n\n if type(self.identity_provider) is IdentityProvider and mod_obj.__name__ != __name__:\n # check for overridden get_current_user + default IdentityProvider\n # deprecated way to override auth (e.g. JupyterHub < 3.0)\n # allow deprecated, overridden get_current_user\n warnings.warn(\n "Overriding JupyterHandler.get_current_user is deprecated in jupyter-server 2.0."\n " Use an IdentityProvider class.",\n DeprecationWarning,\n stacklevel=1,\n )\n user = User(self.get_current_user())\n else:\n _user = self.identity_provider.get_user(self)\n if isinstance(_user, Awaitable):\n # IdentityProvider.get_user _may_ be async\n _user = await _user\n user = _user\n\n # self.current_user for tornado's @web.authenticated\n # self._jupyter_current_user for backward-compat in deprecated get_current_user calls\n # and our own private checks for whether .current_user has been set\n self.current_user = self._jupyter_current_user = user\n # complete initial steps which require auth to resolve first:\n self.set_cors_headers()\n if self.request.method not in {"GET", "HEAD", "OPTIONS"}:\n self.check_xsrf_cookie()\n\n if not self.settings.get("allow_unauthenticated_access", False):\n if not self.request.method:\n raise HTTPError(403)\n method = getattr(self, self.request.method.lower())\n if not getattr(method, "__allow_unauthenticated", False):\n if _redirect_to_login:\n # reuse `web.authenticated` logic, which redirects to the login\n # page on GET and HEAD and otherwise raises 403\n return web.authenticated(lambda _: super().prepare())(self)\n else:\n # raise 403 if user is not known without redirecting to login page\n user = self.current_user\n if user is None:\n self.log.warning(\n f"Couldn't authenticate {self.__class__.__name__} connection"\n )\n raise web.HTTPError(403)\n\n return super().prepare()\n\n # ---------------------------------------------------------------\n # template rendering\n # ---------------------------------------------------------------\n\n def get_template(self, name):\n """Return the jinja template object for a given name"""\n return self.settings["jinja2_env"].get_template(name)\n\n def render_template(self, name, **ns):\n """Render a template by name."""\n ns.update(self.template_namespace)\n template = self.get_template(name)\n return template.render(**ns)\n\n @property\n def template_namespace(self) -> dict[str, Any]:\n return dict(\n base_url=self.base_url,\n default_url=self.default_url,\n ws_url=self.ws_url,\n logged_in=self.logged_in,\n allow_password_change=getattr(self.identity_provider, "allow_password_change", False),\n auth_enabled=self.identity_provider.auth_enabled,\n login_available=self.identity_provider.login_available,\n token_available=bool(self.token),\n static_url=self.static_url,\n sys_info=json_sys_info(),\n contents_js_source=self.contents_js_source,\n version_hash=self.version_hash,\n xsrf_form_html=self.xsrf_form_html,\n token=self.token,\n xsrf_token=self.xsrf_token.decode("utf8"),\n nbjs_translations=json.dumps(\n combine_translations(self.request.headers.get("Accept-Language", ""))\n ),\n **self.jinja_template_vars,\n )\n\n def get_json_body(self) -> dict[str, Any] | None:\n """Return the body of the request as JSON data."""\n if not self.request.body:\n return None\n # Do we need to call body.decode('utf-8') here?\n body = self.request.body.strip().decode("utf-8")\n try:\n model = json.loads(body)\n except Exception as e:\n self.log.debug("Bad JSON: %r", body)\n self.log.error("Couldn't parse JSON", exc_info=True)\n raise web.HTTPError(400, "Invalid JSON in body of request") from e\n return cast("dict[str, Any]", model)\n\n def write_error(self, status_code: int, **kwargs: Any) -> None:\n """render custom error pages"""\n exc_info = kwargs.get("exc_info")\n message = ""\n status_message = responses.get(status_code, "Unknown HTTP Error")\n\n if exc_info:\n exception = exc_info[1]\n # get the custom message, if defined\n try:\n message = exception.log_message % exception.args\n except Exception:\n pass\n\n # construct the custom reason, if defined\n reason = getattr(exception, "reason", "")\n if reason:\n status_message = reason\n else:\n exception = "(unknown)"\n\n # build template namespace\n ns = {\n "status_code": status_code,\n "status_message": status_message,\n "message": message,\n "exception": exception,\n }\n\n self.set_header("Content-Type", "text/html")\n # render the template\n try:\n html = self.render_template("%s.html" % status_code, **ns)\n except TemplateNotFound:\n html = self.render_template("error.html", **ns)\n\n self.write(html)\n\n\nclass APIHandler(JupyterHandler):\n """Base class for API handlers"""\n\n async def prepare(self) -> None: # type:ignore[override]\n """Prepare an API response."""\n await super().prepare()\n if not self.check_origin():\n raise web.HTTPError(404)\n\n def write_error(self, status_code: int, **kwargs: Any) -> None:\n """APIHandler errors are JSON, not human pages"""\n self.set_header("Content-Type", "application/json")\n message = responses.get(status_code, "Unknown HTTP Error")\n reply: dict[str, Any] = {\n "message": message,\n }\n exc_info = kwargs.get("exc_info")\n if exc_info:\n e = exc_info[1]\n if isinstance(e, HTTPError):\n reply["message"] = e.log_message or message\n reply["reason"] = e.reason\n else:\n reply["message"] = "Unhandled error"\n reply["reason"] = None\n # backward-compatibility: traceback field is present,\n # but always empty\n reply["traceback"] = ""\n self.log.warning("wrote error: %r", reply["message"], exc_info=True)\n self.finish(json.dumps(reply))\n\n def get_login_url(self) -> str:\n """Get the login url."""\n # if get_login_url is invoked in an API handler,\n # that means @web.authenticated is trying to trigger a redirect.\n # instead of redirecting, raise 403 instead.\n if not self.current_user:\n raise web.HTTPError(403)\n return super().get_login_url()\n\n @property\n def content_security_policy(self) -> str:\n csp = "; ".join( # noqa: FLY002\n [\n super().content_security_policy,\n "default-src 'none'",\n ]\n )\n return csp\n\n # set _track_activity = False on API handlers that shouldn't track activity\n _track_activity = True\n\n def update_api_activity(self) -> None:\n """Update last_activity of API requests"""\n # record activity of authenticated requests\n if (\n self._track_activity\n and getattr(self, "_jupyter_current_user", None)\n and self.get_argument("no_track_activity", None) is None\n ):\n self.settings["api_last_activity"] = utcnow()\n\n def finish(self, *args: Any, **kwargs: Any) -> Future[Any]:\n """Finish an API response."""\n self.update_api_activity()\n # Allow caller to indicate content-type...\n set_content_type = kwargs.pop("set_content_type", "application/json")\n self.set_header("Content-Type", set_content_type)\n return super().finish(*args, **kwargs)\n\n @allow_unauthenticated\n def options(self, *args: Any, **kwargs: Any) -> None:\n """Get the options."""\n if "Access-Control-Allow-Headers" in self.settings.get("headers", {}):\n self.set_header(\n "Access-Control-Allow-Headers",\n self.settings["headers"]["Access-Control-Allow-Headers"],\n )\n else:\n self.set_header(\n "Access-Control-Allow-Headers",\n "accept, content-type, authorization, x-xsrftoken",\n )\n self.set_header("Access-Control-Allow-Methods", "GET, PUT, POST, PATCH, DELETE, OPTIONS")\n\n # if authorization header is requested,\n # that means the request is token-authenticated.\n # avoid browser-side rejection of the preflight request.\n # only allow this exception if allow_origin has not been specified\n # and Jupyter server authentication is enabled.\n # If the token is not valid, the 'real' request will still be rejected.\n requested_headers = self.request.headers.get("Access-Control-Request-Headers", "").split(\n ","\n )\n if (\n requested_headers\n and any(h.strip().lower() == "authorization" for h in requested_headers)\n and (\n # FIXME: it would be even better to check specifically for token-auth,\n # but there is currently no API for this.\n self.login_available\n )\n and (\n self.allow_origin\n or self.allow_origin_pat\n or "Access-Control-Allow-Origin" in self.settings.get("headers", {})\n )\n ):\n self.set_header("Access-Control-Allow-Origin", self.request.headers.get("Origin", ""))\n\n\nclass Template404(JupyterHandler):\n """Render our 404 template"""\n\n async def prepare(self) -> None: # type:ignore[override]\n """Prepare a 404 response."""\n await super().prepare()\n raise web.HTTPError(404)\n\n\nclass AuthenticatedFileHandler(JupyterHandler, web.StaticFileHandler):\n """static files should only be accessible when logged in"""\n\n auth_resource = "contents"\n\n @property\n def content_security_policy(self) -> str:\n # In case we're serving HTML/SVG, confine any Javascript to a unique\n # origin so it can't interact with the Jupyter server.\n return super().content_security_policy + "; sandbox allow-scripts"\n\n @web.authenticated\n @authorized\n def head(self, path: str) -> Awaitable[None]: # type:ignore[override]\n """Get the head response for a path."""\n self.check_xsrf_cookie()\n return super().head(path)\n\n @web.authenticated\n @authorized\n def get( # type:ignore[override]\n self, path: str, **kwargs: Any\n ) -> Awaitable[None]:\n """Get a file by path."""\n self.check_xsrf_cookie()\n if os.path.splitext(path)[1] == ".ipynb" or self.get_argument("download", None):\n name = path.rsplit("/", 1)[-1]\n self.set_attachment_header(name)\n\n return web.StaticFileHandler.get(self, path, **kwargs)\n\n def get_content_type(self) -> str:\n """Get the content type."""\n assert self.absolute_path is not None\n path = self.absolute_path.strip("/")\n if "/" in path:\n _, name = path.rsplit("/", 1)\n else:\n name = path\n if name.endswith(".ipynb"):\n return "application/x-ipynb+json"\n else:\n cur_mime = mimetypes.guess_type(name)[0]\n if cur_mime == "text/plain":\n return "text/plain; charset=UTF-8"\n else:\n return super().get_content_type()\n\n def set_headers(self) -> None:\n """Set the headers."""\n super().set_headers()\n # disable browser caching, rely on 304 replies for savings\n if "v" not in self.request.arguments:\n self.add_header("Cache-Control", "no-cache")\n\n def compute_etag(self) -> str | None:\n """Compute the etag."""\n return None\n\n def validate_absolute_path(self, root: str, absolute_path: str) -> str:\n """Validate and return the absolute path.\n\n Requires tornado 3.1\n\n Adding to tornado's own handling, forbids the serving of hidden files.\n """\n abs_path = super().validate_absolute_path(root, absolute_path)\n abs_root = os.path.abspath(root)\n assert abs_path is not None\n if not self.contents_manager.allow_hidden and is_hidden(abs_path, abs_root):\n self.log.info(\n "Refusing to serve hidden file, via 404 Error, use flag 'ContentsManager.allow_hidden' to enable"\n )\n raise web.HTTPError(404)\n return abs_path\n\n\ndef json_errors(method: Any) -> Any: # pragma: no cover\n """Decorate methods with this to return GitHub style JSON errors.\n\n This should be used on any JSON API on any handler method that can raise HTTPErrors.\n\n This will grab the latest HTTPError exception using sys.exc_info\n and then:\n\n 1. Set the HTTP status code based on the HTTPError\n 2. Create and return a JSON body with a message field describing\n the error in a human readable form.\n """\n warnings.warn(\n "@json_errors is deprecated in notebook 5.2.0. Subclass APIHandler instead.",\n DeprecationWarning,\n stacklevel=2,\n )\n\n @functools.wraps(method)\n def wrapper(self, *args, **kwargs):\n self.write_error = types.MethodType(APIHandler.write_error, self)\n return method(self, *args, **kwargs)\n\n return wrapper\n\n\n# -----------------------------------------------------------------------------\n# File handler\n# -----------------------------------------------------------------------------\n\n# to minimize subclass changes:\nHTTPError = web.HTTPError\n\n\nclass FileFindHandler(JupyterHandler, web.StaticFileHandler):\n """subclass of StaticFileHandler for serving files from a search path\n\n The setting "static_immutable_cache" can be set up to serve some static\n file as immutable (e.g. file name containing a hash). The setting is a\n list of base URL, every static file URL starting with one of those will\n be immutable.\n """\n\n # cache search results, don't search for files more than once\n _static_paths: dict[str, str] = {}\n root: tuple[str] # type:ignore[assignment]\n\n def set_headers(self) -> None:\n """Set the headers."""\n super().set_headers()\n\n immutable_paths = self.settings.get("static_immutable_cache", [])\n\n # allow immutable cache for files\n if any(self.request.path.startswith(path) for path in immutable_paths):\n self.set_header("Cache-Control", "public, max-age=31536000, immutable")\n\n # disable browser caching, rely on 304 replies for savings\n elif "v" not in self.request.arguments or any(\n self.request.path.startswith(path) for path in self.no_cache_paths\n ):\n self.set_header("Cache-Control", "no-cache")\n\n def initialize(\n self,\n path: str | list[str],\n default_filename: str | None = None,\n no_cache_paths: list[str] | None = None,\n ) -> None:\n """Initialize the file find handler."""\n self.no_cache_paths = no_cache_paths or []\n\n if isinstance(path, str):\n path = [path]\n\n self.root = tuple(os.path.abspath(os.path.expanduser(p)) + os.sep for p in path) # type:ignore[assignment]\n self.default_filename = default_filename\n\n def compute_etag(self) -> str | None:\n """Compute the etag."""\n return None\n\n # access is allowed as this class is used to serve static assets on login page\n # TODO: create an allow-list of files used on login page and remove this decorator\n @allow_unauthenticated\n def get(self, path: str, include_body: bool = True) -> Coroutine[Any, Any, None]:\n return super().get(path, include_body)\n\n # access is allowed as this class is used to serve static assets on login page\n # TODO: create an allow-list of files used on login page and remove this decorator\n @allow_unauthenticated\n def head(self, path: str) -> Awaitable[None]:\n return super().head(path)\n\n @classmethod\n def get_absolute_path(cls, roots: Sequence[str], path: str) -> str:\n """locate a file to serve on our static file search path"""\n with cls._lock:\n if path in cls._static_paths:\n return cls._static_paths[path]\n try:\n abspath = os.path.abspath(filefind(path, roots))\n except OSError:\n # IOError means not found\n return ""\n\n cls._static_paths[path] = abspath\n\n log().debug(f"Path {path} served from {abspath}")\n return abspath\n\n def validate_absolute_path(self, root: str, absolute_path: str) -> str | None:\n """check if the file should be served (raises 404, 403, etc.)"""\n if not absolute_path:\n raise web.HTTPError(404)\n\n for root in self.root:\n if (absolute_path + os.sep).startswith(root):\n break\n\n return super().validate_absolute_path(root, absolute_path)\n\n\nclass APIVersionHandler(APIHandler):\n """An API handler for the server version."""\n\n _track_activity = False\n\n @allow_unauthenticated\n def get(self) -> None:\n """Get the server version info."""\n # not authenticated, so give as few info as possible\n self.finish(json.dumps({"version": jupyter_server.__version__}))\n\n\nclass TrailingSlashHandler(web.RequestHandler):\n """Simple redirect handler that strips trailing slashes\n\n This should be the first, highest priority handler.\n """\n\n @allow_unauthenticated\n def get(self) -> None:\n """Handle trailing slashes in a get."""\n assert self.request.uri is not None\n path, *rest = self.request.uri.partition("?")\n # trim trailing *and* leading /\n # to avoid misinterpreting repeated '//'\n path = "/" + path.strip("/")\n new_uri = "".join([path, *rest])\n self.redirect(new_uri)\n\n post = put = get\n\n\nclass MainHandler(JupyterHandler):\n """Simple handler for base_url."""\n\n @allow_unauthenticated\n def get(self) -> None:\n """Get the main template."""\n html = self.render_template("main.html")\n self.write(html)\n\n post = put = get\n\n\nclass FilesRedirectHandler(JupyterHandler):\n """Handler for redirecting relative URLs to the /files/ handler"""\n\n @staticmethod\n async def redirect_to_files(self: Any, path: str) -> None:\n """make redirect logic a reusable static method\n\n so it can be called from other handlers.\n """\n cm = self.contents_manager\n if await ensure_async(cm.dir_exists(path)):\n # it's a *directory*, redirect to /tree\n url = url_path_join(self.base_url, "tree", url_escape(path))\n else:\n orig_path = path\n # otherwise, redirect to /files\n parts = path.split("/")\n\n if not await ensure_async(cm.file_exists(path=path)) and "files" in parts:\n # redirect without files/ iff it would 404\n # this preserves pre-2.0-style 'files/' links\n self.log.warning("Deprecated files/ URL: %s", orig_path)\n parts.remove("files")\n path = "/".join(parts)\n\n if not await ensure_async(cm.file_exists(path=path)):\n raise web.HTTPError(404)\n\n url = url_path_join(self.base_url, "files", url_escape(path))\n self.log.debug("Redirecting %s to %s", self.request.path, url)\n self.redirect(url)\n\n @allow_unauthenticated\n async def get(self, path: str = "") -> None:\n return await self.redirect_to_files(self, path)\n\n\nclass RedirectWithParams(web.RequestHandler):\n """Same as web.RedirectHandler, but preserves URL parameters"""\n\n def initialize(self, url: str, permanent: bool = True) -> None:\n """Initialize a redirect handler."""\n self._url = url\n self._permanent = permanent\n\n @allow_unauthenticated\n def get(self) -> None:\n """Get a redirect."""\n sep = "&" if "?" in self._url else "?"\n url = sep.join([self._url, self.request.query])\n self.redirect(url, permanent=self._permanent)\n\n\nclass PrometheusMetricsHandler(JupyterHandler):\n """\n Return prometheus metrics for this server\n """\n\n @allow_unauthenticated\n def get(self) -> None:\n """Get prometheus metrics."""\n if self.settings["authenticate_prometheus"] and not self.logged_in:\n raise web.HTTPError(403)\n\n self.set_header("Content-Type", prometheus_client.CONTENT_TYPE_LATEST)\n self.write(prometheus_client.generate_latest(prometheus_client.REGISTRY))\n\n\nclass PublicStaticFileHandler(web.StaticFileHandler):\n """Same as web.StaticFileHandler, but decorated to acknowledge that auth is not required."""\n\n @allow_unauthenticated\n def head(self, path: str) -> Awaitable[None]:\n return super().head(path)\n\n @allow_unauthenticated\n def get(self, path: str, include_body: bool = True) -> Coroutine[Any, Any, None]:\n return super().get(path, include_body)\n\n\n# -----------------------------------------------------------------------------\n# URL pattern fragments for reuse\n# -----------------------------------------------------------------------------\n\n# path matches any number of `/foo[/bar...]` or just `/` or ''\npath_regex = r"(?P<path>(?:(?:/[^/]+)+|/?))"\n\n# -----------------------------------------------------------------------------\n# URL to handler mappings\n# -----------------------------------------------------------------------------\n\n\ndefault_handlers = [\n (r".*/", TrailingSlashHandler),\n (r"api", APIVersionHandler),\n (r"/(robots\.txt|favicon\.ico)", PublicStaticFileHandler),\n (r"/metrics", PrometheusMetricsHandler),\n]\n | .venv\Lib\site-packages\jupyter_server\base\handlers.py | handlers.py | Python | 44,835 | 0.95 | 0.197684 | 0.116883 | python-kit | 365 | 2024-09-16T06:58:14.142066 | GPL-3.0 | false | fcfb06f58a613133fd9009e14fba778e |
"""Base websocket classes."""\n\nimport re\nimport warnings\nfrom typing import Optional, no_type_check\nfrom urllib.parse import urlparse\n\nfrom tornado import ioloop, web\nfrom tornado.iostream import IOStream\n\nfrom jupyter_server.base.handlers import JupyterHandler\nfrom jupyter_server.utils import JupyterServerAuthWarning\n\n# ping interval for keeping websockets alive (30 seconds)\nWS_PING_INTERVAL = 30000\n\n\nclass WebSocketMixin:\n """Mixin for common websocket options"""\n\n ping_callback = None\n last_ping = 0.0\n last_pong = 0.0\n stream: Optional[IOStream] = None\n\n @property\n def ping_interval(self):\n """The interval for websocket keep-alive pings.\n\n Set ws_ping_interval = 0 to disable pings.\n """\n return self.settings.get("ws_ping_interval", WS_PING_INTERVAL) # type:ignore[attr-defined]\n\n @property\n def ping_timeout(self):\n """If no ping is received in this many milliseconds,\n close the websocket connection (VPNs, etc. can fail to cleanly close ws connections).\n Default is max of 3 pings or 30 seconds.\n """\n return self.settings.get( # type:ignore[attr-defined]\n "ws_ping_timeout", max(3 * self.ping_interval, WS_PING_INTERVAL)\n )\n\n @no_type_check\n def check_origin(self, origin: Optional[str] = None) -> bool:\n """Check Origin == Host or Access-Control-Allow-Origin.\n\n Tornado >= 4 calls this method automatically, raising 403 if it returns False.\n """\n\n if self.allow_origin == "*" or (\n hasattr(self, "skip_check_origin") and self.skip_check_origin()\n ):\n return True\n\n host = self.request.headers.get("Host")\n if origin is None:\n origin = self.get_origin()\n\n # If no origin or host header is provided, assume from script\n if origin is None or host is None:\n return True\n\n origin = origin.lower()\n origin_host = urlparse(origin).netloc\n\n # OK if origin matches host\n if origin_host == host:\n return True\n\n # Check CORS headers\n if self.allow_origin:\n allow = self.allow_origin == origin\n elif self.allow_origin_pat:\n allow = bool(re.match(self.allow_origin_pat, origin))\n else:\n # No CORS headers deny the request\n allow = False\n if not allow:\n self.log.warning(\n "Blocking Cross Origin WebSocket Attempt. Origin: %s, Host: %s",\n origin,\n host,\n )\n return allow\n\n def clear_cookie(self, *args, **kwargs):\n """meaningless for websockets"""\n\n @no_type_check\n def _maybe_auth(self):\n """Verify authentication if required.\n\n Only used when the websocket class does not inherit from JupyterHandler.\n """\n if not self.settings.get("allow_unauthenticated_access", False):\n if not self.request.method:\n raise web.HTTPError(403)\n method = getattr(self, self.request.method.lower())\n if not getattr(method, "__allow_unauthenticated", False):\n # rather than re-using `web.authenticated` which also redirects\n # to login page on GET, just raise 403 if user is not known\n user = self.current_user\n if user is None:\n self.log.warning("Couldn't authenticate WebSocket connection")\n raise web.HTTPError(403)\n\n @no_type_check\n def prepare(self, *args, **kwargs):\n """Handle a get request."""\n if not isinstance(self, JupyterHandler):\n should_authenticate = not self.settings.get("allow_unauthenticated_access", False)\n if "identity_provider" in self.settings and should_authenticate:\n warnings.warn(\n "WebSocketMixin sub-class does not inherit from JupyterHandler"\n " preventing proper authentication using custom identity provider.",\n JupyterServerAuthWarning,\n stacklevel=2,\n )\n self._maybe_auth()\n return super().prepare(*args, **kwargs)\n return super().prepare(*args, **kwargs, _redirect_to_login=False)\n\n @no_type_check\n def open(self, *args, **kwargs):\n """Open the websocket."""\n self.log.debug("Opening websocket %s", self.request.path)\n\n # start the pinging\n if self.ping_interval > 0:\n loop = ioloop.IOLoop.current()\n self.last_ping = loop.time() # Remember time of last ping\n self.last_pong = self.last_ping\n self.ping_callback = ioloop.PeriodicCallback(\n self.send_ping,\n self.ping_interval,\n )\n self.ping_callback.start()\n return super().open(*args, **kwargs)\n\n @no_type_check\n def send_ping(self):\n """send a ping to keep the websocket alive"""\n if self.ws_connection is None and self.ping_callback is not None:\n self.ping_callback.stop()\n return\n\n if self.ws_connection.client_terminated:\n self.close()\n return\n\n # check for timeout on pong. Make sure that we really have sent a recent ping in\n # case the machine with both server and client has been suspended since the last ping.\n now = ioloop.IOLoop.current().time()\n since_last_pong = 1e3 * (now - self.last_pong)\n since_last_ping = 1e3 * (now - self.last_ping)\n if since_last_ping < 2 * self.ping_interval and since_last_pong > self.ping_timeout:\n self.log.warning("WebSocket ping timeout after %i ms.", since_last_pong)\n self.close()\n return\n\n self.ping(b"")\n self.last_ping = now\n\n def on_pong(self, data):\n """Handle a pong message."""\n self.last_pong = ioloop.IOLoop.current().time()\n | .venv\Lib\site-packages\jupyter_server\base\websocket.py | websocket.py | Python | 5,952 | 0.95 | 0.221557 | 0.072464 | awesome-app | 378 | 2024-12-20T03:02:08.677096 | BSD-3-Clause | false | 9317c43d815d56b81d13cb94d9f2faa0 |
"""This module is deprecated in Jupyter Server 2.0"""\n\n# Raise a warning that this module is deprecated.\nimport warnings\n\nfrom tornado.websocket import WebSocketHandler\n\nfrom jupyter_server.base.websocket import WebSocketMixin\nfrom jupyter_server.services.kernels.connection.base import (\n deserialize_binary_message,\n deserialize_msg_from_ws_v1,\n serialize_binary_message,\n serialize_msg_to_ws_v1,\n)\n\nwarnings.warn(\n "jupyter_server.base.zmqhandlers module is deprecated in Jupyter Server 2.0",\n DeprecationWarning,\n stacklevel=2,\n)\n | .venv\Lib\site-packages\jupyter_server\base\zmqhandlers.py | zmqhandlers.py | Python | 555 | 0.95 | 0 | 0.0625 | react-lib | 97 | 2024-04-18T16:07:53.828110 | BSD-3-Clause | false | b0e2b90aeee159d007d0d236ecec0b67 |
\n\n | .venv\Lib\site-packages\jupyter_server\base\__pycache__\call_context.cpython-313.pyc | call_context.cpython-313.pyc | Other | 3,465 | 0.95 | 0.096154 | 0 | awesome-app | 991 | 2024-05-07T16:22:28.982663 | GPL-3.0 | false | 6f17b837941eca1b45f52faa0a09f8e7 |
\n\n | .venv\Lib\site-packages\jupyter_server\base\__pycache__\handlers.cpython-313.pyc | handlers.cpython-313.pyc | Other | 57,364 | 0.75 | 0.077982 | 0 | react-lib | 650 | 2024-10-25T01:15:31.910641 | Apache-2.0 | false | cd033b6d731c99dcd1ea24e26f15efd3 |
\n\n | .venv\Lib\site-packages\jupyter_server\base\__pycache__\websocket.cpython-313.pyc | websocket.cpython-313.pyc | Other | 8,057 | 0.95 | 0.107692 | 0 | awesome-app | 153 | 2023-07-14T20:15:46.307823 | Apache-2.0 | false | 769f428c6f801ee74b0d953aed87451a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.