Skip to content

netresearch/matrix-skill / skills/matrix-communication

matrix-communication

Flagged

Use when communicating via Matrix chat, notifying teams, or managing E2EE. Triggers on #room:server references, Matrix URLs, and chat requests.

FileKindSize
README.mdmarkdown2.9 KB
SKILL.mdskill md6.7 KB
evals/evals.jsonconfig12.6 KB
references/agent-governance.mdmarkdown2.0 KB
references/api-reference.mdmarkdown7.3 KB
references/command-reference.mdmarkdown8.9 KB
references/e2ee-guide.mdmarkdown17.2 KB
references/hookshot-integration.mdmarkdown10.7 KB
references/messaging-guide.mdmarkdown13.8 KB
references/no-editorializing.mdmarkdown331 B
references/setup-guide.mdmarkdown11.1 KB
references/troubleshooting.mdmarkdown7.8 KB
scripts/_lib/__init__.pyscript3.6 KB
scripts/_lib/backup_mac.pyscript1.2 KB
scripts/_lib/config.pyscript4.6 KB
scripts/_lib/daemon_client.pyscript3.0 KB
scripts/_lib/deps.pyscript1.9 KB
scripts/_lib/downloads.pyscript1.1 KB
scripts/_lib/e2ee.pyscript13.2 KB
scripts/_lib/formatting.pyscript14.4 KB
scripts/_lib/http.pyscript4.8 KB
scripts/_lib/reactions.pyscript2.9 KB
scripts/_lib/roomlog.pyscript13.7 KB
scripts/_lib/rooms.pyscript15.5 KB
scripts/_lib/secret_input.pyscript2.0 KB
scripts/_lib/test_backup_mac.pyscript1.5 KB
scripts/_lib/test_config.pyscript7.1 KB
scripts/_lib/test_daemon_client.pyscript5.9 KB
scripts/_lib/test_downloads.pyscript2.3 KB
scripts/_lib/test_e2ee.pyscript14.3 KB
scripts/_lib/test_formatting.pyscript15.5 KB
scripts/_lib/test_http.pyscript4.1 KB
scripts/_lib/test_reactions.pyscript15.2 KB
scripts/_lib/test_roomlog.pyscript20.2 KB
scripts/_lib/test_rooms.pyscript13.7 KB
scripts/_lib/test_secret_input.pyscript2.2 KB
scripts/_lib/test_trust.pyscript8.3 KB
scripts/_lib/trust.pyscript5.3 KB
scripts/_lib/utils.pyscript1.7 KB
scripts/matrix-create-room.pyexecutablescript4.7 KB
scripts/matrix-doctor.pyexecutablescript22.2 KB
scripts/matrix-download-e2ee.pyexecutablescript7.7 KB
scripts/matrix-e2ee-setup.pyexecutablescript9.2 KB
scripts/matrix-e2ee-verify.pyexecutablescript29.2 KB
scripts/matrix-edit-e2ee.pyexecutablescript7.9 KB
scripts/matrix-edit.pyexecutablescript5.3 KB
scripts/matrix-fetch-keys.pyexecutablescript9.1 KB
scripts/matrix-invite.pyexecutablescript3.0 KB
scripts/matrix-key-backup.pyexecutablescript21.3 KB
scripts/matrix-power-level.pyexecutablescript7.0 KB
scripts/matrix-react.pyexecutablescript14.1 KB
scripts/matrix-read-e2ee.pyexecutablescript12.8 KB
scripts/matrix-read.pyexecutablescript4.7 KB
scripts/matrix-redact.pyexecutablescript5.0 KB
scripts/matrix-resolve.pyexecutablescript1.7 KB
scripts/matrix-rooms.pyexecutablescript3.8 KB
scripts/matrix-send-e2ee.pyexecutablescript19.4 KB
scripts/matrix-send.pyexecutablescript9.4 KB
scripts/matrix-watch.pyexecutablescript5.3 KB
scripts/matrix-watchd.pyexecutablescript23.5 KB
scripts/test_matrix_doctor.pyscript14.2 KB
scripts/test_matrix_read_e2ee.pyscript2.7 KB

scripts/_lib/http.py

View on GitHub
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: Netresearch DTT GmbH

"""HTTP-based Matrix API requests.

All functions use ONLY stdlib.
"""

import contextlib
import json
import socket
import urllib.error
import urllib.parse
import urllib.request

_ALLOWED_SCHEMES = frozenset({"http", "https"})


def _require_http_scheme(url: str) -> None:
    scheme = urllib.parse.urlparse(url).scheme
    if scheme not in _ALLOWED_SCHEMES:
        raise ValueError(
            f"Refusing to fetch URL with scheme {scheme!r}; only http/https allowed"
        )


def _origin(url: str) -> tuple:
    parts = urllib.parse.urlsplit(url)
    scheme = parts.scheme.lower()
    return (
        scheme,
        (parts.hostname or "").lower(),
        parts.port or (443 if scheme == "https" else 80),
    )


class _SameOriginAuthRedirectHandler(urllib.request.HTTPRedirectHandler):
    """Follow redirects, but send the Authorization header only to the same origin.

    urllib copies every request header onto the redirected request, so a
    redirect to another scheme, host or port would receive the access token.
    """

    def redirect_request(self, req, fp, code, msg, headers, newurl):
        new = super().redirect_request(req, fp, code, msg, headers, newurl)
        if new is not None and _origin(req.full_url) != _origin(newurl):
            new.remove_header("Authorization")
        return new


_OPENER = urllib.request.build_opener(_SameOriginAuthRedirectHandler)


@contextlib.contextmanager
def _prefer_ipv4():
    """Temporarily prefer IPv4 addresses in DNS resolution.

    Workaround for WSL2 environments where IPv6 routes are often
    unreachable while IPv4 works fine.
    """
    original = socket.getaddrinfo

    def patched(*args, **kwargs):
        results = original(*args, **kwargs)
        return sorted(results, key=lambda r: r[0] != socket.AF_INET)

    socket.getaddrinfo = patched
    try:
        yield
    finally:
        socket.getaddrinfo = original


def _do_request(req: urllib.request.Request) -> dict:
    """Execute a request and return parsed JSON response.

    The caller must have validated the URL scheme via
    ``_require_http_scheme`` before constructing ``req``.
    """
    _require_http_scheme(req.full_url)
    # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected
    with _OPENER.open(req) as response:
        return json.loads(response.read().decode())


def _parse_http_error(e: urllib.error.HTTPError) -> dict:
    """Parse an HTTPError into a result dict."""
    error_body = e.read().decode()
    try:
        error_json = json.loads(error_body)
        return {
            "error": error_json.get("error", error_body),
            "errcode": error_json.get("errcode"),
        }
    except json.JSONDecodeError:
        return {"error": error_body, "errcode": str(e.code)}


def matrix_request(
    config: dict,
    method: str,
    endpoint: str,
    data: dict | None = None,
    api_version: str = "v3",
) -> dict:
    """Make a Matrix API request.

    Args:
        config: Dict with homeserver and access_token
        method: HTTP method (GET, POST, PUT, DELETE)
        endpoint: API endpoint (e.g., /joined_rooms)
        data: Optional dict to send as JSON body
        api_version: Client-API version in the path; the relations endpoint
            exists only under v1

    Returns:
        Response dict, or dict with 'error' key on failure
    """
    url = f"{config['homeserver']}/_matrix/client/{api_version}{endpoint}"
    _require_http_scheme(url)
    headers = {
        "Authorization": f"Bearer {config['access_token']}",
        "Content-Type": "application/json",
    }

    body = json.dumps(data).encode() if data is not None else None
    req = urllib.request.Request(url, data=body, headers=headers, method=method)

    try:
        return _do_request(req)
    except urllib.error.HTTPError as e:
        return _parse_http_error(e)
    except OSError as e:
        if e.errno not in (101, 113):  # ENETUNREACH, EHOSTUNREACH
            return {"error": str(e)}
        # IPv6 likely unreachable — retry with IPv4 preference
        try:
            with _prefer_ipv4():
                req2 = urllib.request.Request(
                    url, data=body, headers=headers, method=method
                )
                return _do_request(req2)
        except urllib.error.HTTPError as e2:
            return _parse_http_error(e2)
        except OSError as e2:
            return {"error": str(e2)}


def path_segment(value: str) -> str:
    """URL-encode one path segment (room ID, user ID, event ID).

    Room and event IDs contain characters such as ``!``, ``$``, ``:`` and may
    contain ``/`` or ``?``; unencoded, they can change which endpoint a
    request reaches.
    """
    return urllib.parse.quote(str(value), safe="")
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 197kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall