summaryrefslogtreecommitdiff
path: root/timelord/utils/env_helper.py
blob: b5fe8199402c6327294db062a840d6378599efc8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""
Environment detection, port management, and process context for TIMELORD.
Enables running multiple universes concurrently without port collisions.
"""

import os
import platform
import re
import socket
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional, Set

# Keys to sanitize from snapshots for security
SENSITIVE_KEY_PATTERNS = [
    r"key",
    r"secret",
    r"token",
    r"password",
    r"auth",
    r"private",
    r"credential",
]


def is_sensitive(key: str) -> bool:
    key_lower = key.lower()
    return any(
        re.search(pat, key_lower) for pat in SENSITIVE_KEY_PATTERNS
    )


def get_system_metadata() -> Dict[str, Any]:
    """Captures system runtime metadata (Python, OS, host)."""
    node_version = None
    try:
        import subprocess

        res = subprocess.run(["node", "--version"], capture_output=True, text=True)
        if res.returncode == 0:
            node_version = res.stdout.strip()
    except Exception:
        pass

    return {
        "os": platform.system(),
        "os_release": platform.release(),
        "arch": platform.machine(),
        "python_version": sys.version.split()[0],
        "node_version": node_version,
    }


def get_safe_env_vars() -> Dict[str, str]:
    """Returns safe, non-sensitive environment variables for temporal capture."""
    safe_vars = {}
    important_vars = {
        "PATH",
        "VIRTUAL_ENV",
        "NODE_ENV",
        "PYTHONPATH",
        "PORT",
        "HOST",
        "SHELL",
        "EDITOR",
        "TIMELORD_UNIVERSE",
    }

    for key, value in os.environ.items():
        if key in important_vars or not is_sensitive(key):
            # Limit length to avoid bloating
            if len(value) < 1024:
                safe_vars[key] = value

    return safe_vars


def detect_configured_ports(project_dir: Path) -> List[int]:
    """Scans .env, package.json, and docker-compose for configured ports."""
    ports: Set[int] = set()

    # Check .env files
    for env_name in [".env", ".env.local", ".env.development"]:
        env_file = project_dir / env_name
        if env_file.is_file():
            try:
                content = env_file.read_text(encoding="utf-8", errors="ignore")
                for match in re.finditer(r"PORT\s*=\s*(\d+)", content, re.IGNORECASE):
                    ports.add(int(match.group(1)))
            except Exception:
                pass

    # Check package.json scripts (e.g. -p 3000, --port 3000)
    pkg_file = project_dir / "package.json"
    if pkg_file.is_file():
        try:
            content = pkg_file.read_text(encoding="utf-8", errors="ignore")
            for match in re.finditer(r"(?:--port|-p)\s+(\d+)", content):
                ports.add(int(match.group(1)))
        except Exception:
            pass

    return sorted(list(ports))


def is_port_in_use(port: int, host: str = "127.0.0.1") -> bool:
    """Checks if a TCP port is currently open and bound."""
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.settimeout(0.5)
        return s.connect_ex((host, port)) == 0


def patch_env_ports_in_universe(universe_dir: Path, port_offset: int) -> Dict[str, int]:
    """
    Adjusts PORT definitions in universe .env files by the given offset
    so parallel universe dev servers do not conflict with Prime.
    """
    remapped = {}
    for env_name in [".env", ".env.local", ".env.development"]:
        env_file = universe_dir / env_name
        if not env_file.is_file():
            continue

        try:
            content = env_file.read_text(encoding="utf-8", errors="ignore")
            new_lines = []
            for line in content.splitlines():
                match = re.match(r"^(\s*PORT\s*=\s*)(\d+)(.*)$", line, re.IGNORECASE)
                if match:
                    prefix, old_port_str, suffix = match.groups()
                    old_port = int(old_port_str)
                    new_port = old_port + port_offset
                    remapped[f"{env_name}:PORT"] = new_port
                    new_lines.append(f"{prefix}{new_port}{suffix}")
                else:
                    new_lines.append(line)

            env_file.write_text("\n".join(new_lines) + "\n", encoding="utf-8")
        except Exception:
            pass

    return remapped