From a803f8c7459f8a1f904590151c59ee8c59b44621 Mon Sep 17 00:00:00 2001 From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Tue, 28 Jul 2026 04:22:51 +0330 Subject: [PATCH] feat: add project-level env configuration for collector --- .env.example | 9 +++ .gitignore | 1 + README.md | 33 ++++---- tests/test_tools.py | 52 +++++++++++++ web/collector.php | 181 ++++++++++++++++++++++++++++++++++++++++---- web/index.php | 3 +- 6 files changed, 249 insertions(+), 30 deletions(-) create mode 100644 .env.example diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..48ebfac --- /dev/null +++ b/.env.example @@ -0,0 +1,9 @@ +# Copy this file to .env and replace the credentials. +PANEL_LOGIN_USERNAME="your-tci-username" +PANEL_LOGIN_PASSWORD="your-tci-password" + +# Optional collector settings: +PANEL_BASE_URL="https://internet.tci.ir" +PANEL_REQUEST_TIMEOUT="10" +# Use an absolute path on PHP-FPM deployments. Leave unset for ./dataset. +# OCR_DATASET_DIR="/srv/tci-ocr/dataset" diff --git a/.gitignore b/.gitignore index af96756..b553f44 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .idea/ .venv/ +.env __pycache__/ *.py[cod] .pytest_cache/ diff --git a/README.md b/README.md index 44f3027..b05877d 100644 --- a/README.md +++ b/README.md @@ -120,15 +120,18 @@ and Arabic digits are accepted and normalized to ASCII. The next challenge is loaded without a page refresh so the numeric keyboard stays open on phones. By default the collector connects to the TCI customer panel at -`https://internet.tci.ir/panel/` and appends to `dataset/labels.csv`. Set your -TCI credentials through the process environment: +`https://internet.tci.ir/panel/` and appends to `dataset/labels.csv`. Create a +project-level `.env` file for your TCI credentials: ```bash -PANEL_LOGIN_USERNAME='your-user' \ -PANEL_LOGIN_PASSWORD='your-password' \ -php -S 127.0.0.1:8080 -t web +cp .env.example .env ``` +Edit `.env` and replace `your-tci-username` and `your-tci-password`. Quoted +values may contain spaces, `#`, or `$`. The `.env` file is ignored by Git. +Existing PHP-FPM, Nginx FastCGI, or process environment settings take precedence +over values in `.env`. + The supported settings are: - `PANEL_BASE_URL` — panel origin; defaults to `https://internet.tci.ir`. @@ -144,8 +147,18 @@ If the dataset directory or CSV has been removed, it is recreated automatically. Legacy `verification.sqlite` files are ignored. Keep the collector private: it has no user authentication and holds the panel -credentials in the PHP process environment. The PHP user needs write permission -for the dataset directory. Do not expose `dataset/` as a public web directory. +credentials. The PHP user needs read permission for `.env` and write permission +for the dataset directory. On a typical Debian/Ubuntu PHP-FPM server, protect the +file with: + +```bash +sudo chown root:www-data .env +sudo chmod 640 .env +``` + +Use your PHP-FPM worker group instead of `www-data` when it differs. Keep the +Nginx document root set to the repository's `web/` directory so `.env` and +`dataset/` cannot be downloaded. ### Minimal Nginx configuration @@ -164,9 +177,6 @@ server { include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root/index.php; fastcgi_param OCR_DATASET_DIR /srv/tci-ocr/dataset; - fastcgi_param PANEL_BASE_URL https://internet.tci.ir; - fastcgi_param PANEL_LOGIN_USERNAME your-user; - fastcgi_param PANEL_LOGIN_PASSWORD your-password; fastcgi_pass unix:/run/php/php8.3-fpm.sock; } @@ -175,6 +185,3 @@ server { } } ``` - -Prefer protected PHP-FPM environment configuration for real secrets instead of -putting them directly in a shared Nginx configuration. diff --git a/tests/test_tools.py b/tests/test_tools.py index 6e30609..1c37932 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -218,6 +218,58 @@ class ToolTests(unittest.TestCase): self.assertTrue(original_one.is_file()) self.assertTrue(original_two.is_file()) + def test_php_collector_loads_project_env_with_server_precedence(self): + php = shutil.which("php") + if php is None: + self.skipTest("PHP is not installed") + + with tempfile.TemporaryDirectory() as temp: + env_path = Path(temp) / ".env" + env_path.write_text( + "\n".join( + [ + '# Collector settings', + 'PANEL_LOGIN_USERNAME="project user"', + 'PANEL_LOGIN_PASSWORD="p@ss # $word"', + 'PANEL_BASE_URL="https://example.test/panel/"', + 'PANEL_REQUEST_TIMEOUT=17 # seconds', + 'OCR_DATASET_DIR="/srv/tci dataset"', + 'UNRELATED_SETTING="ignored"', + ] + ), + encoding="utf-8", + ) + environment = os.environ.copy() + for name in ( + "PANEL_LOGIN_PASSWORD", + "PANEL_BASE_URL", + "PANEL_REQUEST_TIMEOUT", + "OCR_DATASET_DIR", + ): + environment.pop(name, None) + environment["PANEL_LOGIN_USERNAME"] = "server-user" + script = ( + f"require {json.dumps(str(PROJECT / 'web' / 'collector.php'))};" + "$config = collectorConfig($argv[1]);" + "echo json_encode($config, JSON_THROW_ON_ERROR);" + ) + result = subprocess.run( + [php, "-r", script, str(env_path)], + text=True, + capture_output=True, + env=environment, + ) + self.assertEqual(result.returncode, 0, result.stderr) + config = json.loads(result.stdout) + self.assertEqual(config["panel_username"], "server-user") + self.assertEqual(config["panel_password"], "p@ss # $word") + self.assertEqual( + config["panel_base_url"], + "https://example.test/panel", + ) + self.assertEqual(config["timeout"], 17) + self.assertEqual(config["dataset"], "/srv/tci dataset") + def test_php_panel_collector_validates_and_appends_samples(self): php = shutil.which("php") if php is None: diff --git a/web/collector.php b/web/collector.php index b02e553..6b9d3d4 100644 --- a/web/collector.php +++ b/web/collector.php @@ -41,12 +41,159 @@ final class PanelResponse } } -function collectorConfig(): array +/** + * @return array + */ +function readProjectEnvironment(string $path): array { - $configuredDataset = $_SERVER['OCR_DATASET_DIR'] ?? getenv('OCR_DATASET_DIR') ?: ''; - $timeoutValue = $_SERVER['PANEL_REQUEST_TIMEOUT'] - ?? getenv('PANEL_REQUEST_TIMEOUT') - ?: '10'; + if (!file_exists($path)) { + return []; + } + if (!is_file($path) || !is_readable($path)) { + throw new CollectorError('The project .env file is not readable.', 500); + } + + $contents = @file_get_contents($path); + if ($contents === false) { + throw new CollectorError('Could not read the project .env file.', 500); + } + if (strlen($contents) > 65_536) { + throw new CollectorError('The project .env file is unexpectedly large.', 500); + } + + $supported = array_fill_keys([ + 'PANEL_BASE_URL', + 'PANEL_LOGIN_USERNAME', + 'PANEL_LOGIN_PASSWORD', + 'PANEL_REQUEST_TIMEOUT', + 'OCR_DATASET_DIR', + ], true); + $values = []; + $lines = preg_split('/\R/', $contents); + if ($lines === false) { + throw new CollectorError('Could not parse the project .env file.', 500); + } + + foreach ($lines as $index => $line) { + if ($index === 0) { + $line = preg_replace('/^\xEF\xBB\xBF/', '', $line) ?? $line; + } + $trimmed = trim($line); + if ($trimmed === '' || str_starts_with($trimmed, '#')) { + continue; + } + if ( + preg_match( + '/^(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=\s*(.*)$/D', + $trimmed, + $matches, + ) !== 1 + ) { + throw new CollectorError( + 'Invalid project .env syntax on line ' . ($index + 1) . '.', + 500, + ); + } + + $name = $matches[1]; + if (!isset($supported[$name])) { + continue; + } + $values[$name] = parseProjectEnvironmentValue( + $matches[2], + $index + 1, + ); + } + + return $values; +} + +function parseProjectEnvironmentValue(string $raw, int $line): string +{ + $raw = ltrim($raw); + if ($raw === '') { + return ''; + } + + $quote = $raw[0]; + if ($quote !== '"' && $quote !== "'") { + return trim(preg_replace('/\s+#.*$/', '', $raw) ?? $raw); + } + + $value = ''; + $escaped = false; + $length = strlen($raw); + for ($index = 1; $index < $length; $index++) { + $character = $raw[$index]; + if ($quote === '"' && $escaped) { + $value .= match ($character) { + 'n' => "\n", + 'r' => "\r", + 't' => "\t", + '"', '\\', '$' => $character, + default => '\\' . $character, + }; + $escaped = false; + continue; + } + if ($quote === '"' && $character === '\\') { + $escaped = true; + continue; + } + if ($character !== $quote) { + $value .= $character; + continue; + } + + $remainder = trim(substr($raw, $index + 1)); + if ($remainder !== '' && !str_starts_with($remainder, '#')) { + throw new CollectorError( + "Invalid project .env value on line {$line}.", + 500, + ); + } + return $value; + } + + throw new CollectorError( + "Unclosed quote in project .env on line {$line}.", + 500, + ); +} + +function collectorSetting( + string $name, + array $projectEnvironment, + string $default = '', +): string { + $serverValue = $_SERVER[$name] ?? null; + if (is_string($serverValue) && $serverValue !== '') { + return $serverValue; + } + + $processValue = getenv($name); + if ($processValue !== false && $processValue !== '') { + return $processValue; + } + + $projectValue = $projectEnvironment[$name] ?? ''; + return $projectValue !== '' ? $projectValue : $default; +} + +function collectorConfig(?string $projectEnvPath = null): array +{ + $projectEnvironment = readProjectEnvironment( + $projectEnvPath ?? dirname(__DIR__) . '/.env', + ); + $configuredDataset = collectorSetting( + 'OCR_DATASET_DIR', + $projectEnvironment, + ); + $timeoutValue = collectorSetting( + 'PANEL_REQUEST_TIMEOUT', + $projectEnvironment, + '10', + ); $timeout = filter_var($timeoutValue, FILTER_VALIDATE_INT); return [ @@ -55,20 +202,22 @@ function collectorConfig(): array DIRECTORY_SEPARATOR, ), 'panel_base_url' => rtrim( - $_SERVER['PANEL_BASE_URL'] - ?? getenv('PANEL_BASE_URL') - ?: 'https://internet.tci.ir', + collectorSetting( + 'PANEL_BASE_URL', + $projectEnvironment, + 'https://internet.tci.ir', + ), '/', ), - 'panel_username' => (string) ( - $_SERVER['PANEL_LOGIN_USERNAME'] - ?? getenv('PANEL_LOGIN_USERNAME') - ?: 'username' + 'panel_username' => collectorSetting( + 'PANEL_LOGIN_USERNAME', + $projectEnvironment, + 'username', ), - 'panel_password' => (string) ( - $_SERVER['PANEL_LOGIN_PASSWORD'] - ?? getenv('PANEL_LOGIN_PASSWORD') - ?: 'password' + 'panel_password' => collectorSetting( + 'PANEL_LOGIN_PASSWORD', + $projectEnvironment, + 'password', ), 'timeout' => $timeout === false ? 10 : max(1, min(60, $timeout)), ]; diff --git a/web/index.php b/web/index.php index 0fe9ee0..eef00ce 100644 --- a/web/index.php +++ b/web/index.php @@ -17,11 +17,12 @@ session_start(); sendSecurityHeaders(); -$config = collectorConfig(); $method = strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET')); $action = scalarRequestValue('action', 32) ?? ''; try { + $config = collectorConfig(); + if ($method === 'GET' && $action === 'captcha') { servePendingCaptcha(); }