From 6f0fe138dfb3e16a02c88dcf03fb39a896d2eabd Mon Sep 17 00:00:00 2001 From: EduForge Date: Mon, 16 Nov 2026 16:34:33 +0200 Subject: [PATCH] =?UTF-8?q?EduForge:=20SheerID=20verification=20combine=20?= =?UTF-8?q?=E2=80=94=20API=20engine,=20doc=20generators,=20Transcript=20St?= =?UTF-8?q?udio=20(288=20schools),=20RU/EN=20dashboard?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 14 + LICENSE | 21 + README.md | 93 + docker/Dockerfile | 20 + docker/docker-compose.yml | 13 + requirements.txt | 8 + server/__init__.py | 0 server/config.py | 105 + server/engine/__init__.py | 0 server/engine/antidetect.py | 958 +++++ server/engine/client.py | 170 + server/gendocs.py | 49 + server/generators/__init__.py | 0 server/generators/docgen.py | 592 +++ server/generators/names.py | 114 + server/generators/psu.py | 407 ++ server/generators/teacher.py | 75 + server/main.py | 169 + server/storage.py | 60 + web/index.html | 250 ++ web/transcript/index.html | 7127 +++++++++++++++++++++++++++++++++ 21 files changed, 10245 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 docker/Dockerfile create mode 100644 docker/docker-compose.yml create mode 100644 requirements.txt create mode 100644 server/__init__.py create mode 100644 server/config.py create mode 100644 server/engine/__init__.py create mode 100644 server/engine/antidetect.py create mode 100644 server/engine/client.py create mode 100644 server/gendocs.py create mode 100644 server/generators/__init__.py create mode 100644 server/generators/docgen.py create mode 100644 server/generators/names.py create mode 100644 server/generators/psu.py create mode 100644 server/generators/teacher.py create mode 100644 server/main.py create mode 100644 server/storage.py create mode 100644 web/index.html create mode 100644 web/transcript/index.html diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5948a1e --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +__pycache__/ +*.pyc +.venv/ +venv/ +data/*.db +data/*.db-* +*.log +.env +node_modules/ +.DS_Store +out/ +samples/ +test_*.png +test_hdr.txt diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c0e853e --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 EduForge contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..3e1b7bb --- /dev/null +++ b/README.md @@ -0,0 +1,93 @@ +# EduForge + +Комбайн для верификации студенческих/учительских офферов через SheerID: единый движок API-флоу, генераторы документов, очередь задач и веб-дашборд. Интерфейс RU/EN, без китайского. + +## Возможности + +- **Движок верификации** — полный флоу SheerID по API: отправка личной информации → пропуск SSO → запрос загрузки → PUT в S3 → completeDocUpload → опрос статуса. TLS-имперсонация (curl_cffi) + NewRelic-заголовки, ротация User-Agent, поддержка прокси. +- **Генераторы документов** — Student ID, транскрипт, бейдж учителя, PDF-сертификат учителя, PSU LionPATH-карта (Pillow / xhtml2pdf / Playwright). +- **Transcript Studio** — отдельный модуль: 288 школ, 8 макетов, 20 стран, 15 систем оценок, рендер в браузере и экспорт PDF (`/transcript/`). +- **Очередь задач** — асинхронная очередь с ограничением конкуренции, SQLite-история, автообновление статуса в дашборде. +- **Дашборд** — тёмная тема, RU/EN, разделы: Запуск / Очередь / Документы / Transcript Studio / Программы / Настройки. + +## Программы (programId проверены живым запросом) + +| Ключ | Program ID | Оффер | +|------|-----------|-------| +| student | 67c8c14f5f17a83b745e3f82 | An Exclusive Student Offer | +| student_alt | 681d40e03e7a8077098cb1b6 | Verify Student Status | +| student_br | 623e8edc19a65d5a7db2969a | Oferta exclusiva para estudantes (PT) | +| teachers | 68d47554aa292d20b9bec8f7 | Special Offer Just For Teachers | +| veterans | 690415d58971e73ca187d8c9 | Honoring All Who Served | +| generic | 5b0721a52094bf13b4024c5d | SheerID Verification | + +Мёртвые (404): Bolt.new `68cc6a2e…`, Google One legacy `67c88d2e…`, Cursor student `681044b7…` (программа закрыта 25.06.2026). + +## Установка + +```bash +python -m venv .venv +.venv/Scripts/python -m pip install -r requirements.txt # Windows +# .venv/bin/python -m pip install -r requirements.txt # Linux +.venv/Scripts/python -m playwright install chromium # для PNG-генераторов +``` + +## Запуск + +```bash +python -m server.main +# http://127.0.0.1:8895 +``` + +Переменные окружения: +- `EDUFORGE_PORT` — порт (по умолчанию 8895) +- `EDUFORGE_CONCURRENCY` — одновременных задач (по умолчанию 3) +- `EDUFORGE_TOKEN` — admin-токен; если задан, `/api/verify` и `/api/generate` требуют заголовок `X-Admin-Token` + +## API + +- `GET /health` +- `GET /api/programs` · `GET /api/schools` · `GET /api/doc_types` +- `POST /api/generate` `{doc_type, first, last, school_id, dob}` → файл документа +- `POST /api/verify` `{url|vid, program, school_id, doc_type, first, last, email, birth_date, proxy, skip_sso}` → `{task_id}` +- `GET /api/tasks` · `GET /api/task/{id}` +- `GET /api/status/{vid}` — живой статус заявки + +## Как это работает + +1. На стороне вендора (Google/Spotify/ChatGPT и т.д.) запускаешь верификацию — открывается виджет SheerID, в URL появляется `verificationId` (24 hex). +2. Копируешь ссылку в дашборд → выбираешь программу, школу и тип документа → «Запустить». +3. Движок генерирует документ, проходит шаги API и загружает файл. Статус заявки опрашивается через `my.sheerid.com/rest/v2/verification/{vid}`. + +> Некоторые вендоры ставят собственный гейт ДО SheerID (например, ChatGPT for Teachers требует школьный email-домен). В таком случае заявка SheerID не создаётся и комбайн не поможет — нужен реальный домен. + +## Docker + +```bash +docker compose -f docker/docker-compose.yml up --build +``` + +## Структура + +``` +server/ + main.py FastAPI-приложение + config.py программы, школы, эндпоинты + gendocs.py диспетчер генераторов + синтетическая личность + storage.py SQLite-очередь/история + engine/ + client.py SheerID API-флоу + antidetect.py TLS-имперсонация, NewRelic, UA-ротация, прокси + generators/ + docgen.py Student ID / транскрипт / бейдж (Pillow) + teacher.py PDF/PNG-сертификат учителя + psu.py PSU LionPATH-карта + names.py генератор имён/email/дат +web/ + index.html дашборд (RU/EN) + transcript/ Transcript Studio (288 школ) +``` + +## Лицензия + +MIT \ No newline at end of file diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..49f8db0 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,20 @@ +FROM python:3.11-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 PIP_NO_CACHE_DIR=1 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + libnss3 libnspr4 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 \ + libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 \ + libgbm1 libpango-1.0-0 libcairo2 libasound2 fonts-liberation \ + && rm -rf /var/lib/apt/lists/* + +COPY requirements.txt . +RUN pip install -r requirements.txt && python -m playwright install chromium + +COPY server ./server +COPY web ./web +RUN mkdir -p data + +EXPOSE 8895 +CMD ["python", "-m", "uvicorn", "server.main:app", "--host", "0.0.0.0", "--port", "8895"] \ No newline at end of file diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml new file mode 100644 index 0000000..6454229 --- /dev/null +++ b/docker/docker-compose.yml @@ -0,0 +1,13 @@ +services: + eduforge: + build: + context: .. + dockerfile: docker/Dockerfile + ports: + - "8895:8895" + environment: + - EDUFORGE_CONCURRENCY=3 + # - EDUFORGE_TOKEN=change-me + volumes: + - ../data:/app/data + restart: unless-stopped \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..679f512 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,8 @@ +fastapi>=0.110 +uvicorn>=0.29 +pydantic>=2.6 +httpx>=0.27 +curl_cffi>=0.7 +Pillow>=10.0 +xhtml2pdf>=0.2.11 +playwright>=1.44 diff --git a/server/__init__.py b/server/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/server/config.py b/server/config.py new file mode 100644 index 0000000..f1ee272 --- /dev/null +++ b/server/config.py @@ -0,0 +1,105 @@ +"""EduForge configuration — programs, schools, API endpoints. + +Program IDs below were live-checked against services.sheerid.com (HTTP 200). +Dead programs are kept in PROGRAMS_DEAD for reference only. +""" + +SHEERID_BASE = "https://services.sheerid.com" +MY_SHEERID = "https://my.sheerid.com" +MAX_FILE_SIZE = 1 * 1024 * 1024 # 1 MB upload cap + +# kind: student | teacher | military +PROGRAMS = { + "student": { + "programId": "67c8c14f5f17a83b745e3f82", + "title": "An Exclusive Student Offer", + "kind": "student", + "infoStep": "collectStudentPersonalInfo", + "docTypes": ["student_id", "transcript"], + "note": "Generic student offer (Google / Spotify / YouTube style flows).", + }, + "student_alt": { + "programId": "681d40e03e7a8077098cb1b6", + "title": "Verify Student Status", + "kind": "student", + "infoStep": "collectStudentPersonalInfo", + "docTypes": ["student_id", "transcript"], + "note": "Alternate student verification program.", + }, + "student_br": { + "programId": "623e8edc19a65d5a7db2969a", + "title": "Oferta exclusiva para estudantes (PT)", + "kind": "student", + "infoStep": "collectStudentPersonalInfo", + "docTypes": ["student_id", "transcript"], + "note": "Portuguese-language student offer.", + }, + "teachers": { + "programId": "68d47554aa292d20b9bec8f7", + "title": "Special Offer Just For Teachers", + "kind": "teacher", + "infoStep": "collectTeacherPersonalInfo", + "docTypes": ["teacher_badge", "teacher_pdf"], + "note": "K-12 teacher offer. Vendor may gate on school email domain before SheerID.", + }, + "veterans": { + "programId": "690415d58971e73ca187d8c9", + "title": "Honoring All Who Served", + "kind": "military", + "infoStep": "collectMilitaryPersonalInfo", + "docTypes": ["student_id"], + "note": "Military / veteran offer.", + }, + "generic": { + "programId": "5b0721a52094bf13b4024c5d", + "title": "SheerID Verification", + "kind": "student", + "infoStep": "collectStudentPersonalInfo", + "docTypes": ["student_id", "transcript"], + "note": "Generic verification entry.", + }, +} + +PROGRAMS_DEAD = { + "68cc6a2e64f55220de204448": "Bolt.new (404)", + "67c88d2e0536336550bc3bd6": "Google One legacy (404)", + "681044b7729fba7beccd3565": "Cursor student (404, program closed 2026-06-25)", +} + +# Penn State multi-campus registry (id / idExtended used by SheerID organization). +SCHOOLS = { + "2565": {"id": 2565, "idExtended": "2565", "name": "Pennsylvania State University-Main Campus", + "city": "University Park", "state": "PA", "country": "US", "domain": "PSU.EDU"}, + "651379": {"id": 651379, "idExtended": "651379", "name": "Pennsylvania State University-World Campus", + "city": "University Park", "state": "PA", "country": "US", "domain": "PSU.EDU"}, + "8387": {"id": 8387, "idExtended": "8387", "name": "Pennsylvania State University-Penn State Harrisburg", + "city": "Middletown", "state": "PA", "country": "US", "domain": "PSU.EDU"}, + "8382": {"id": 8382, "idExtended": "8382", "name": "Pennsylvania State University-Penn State Altoona", + "city": "Altoona", "state": "PA", "country": "US", "domain": "PSU.EDU"}, +} +DEFAULT_SCHOOL_ID = "2565" + +# currentStep -> normalized status (mirrors the public SheerID widget mapping) +STEP_STATUS = { + "success": "verified", + "docUpload": "document_required", + "sso": "sso_required", + "emailLoop": "email_required", + "pending": "pending", + "error": "rejected", + "collectStudentPersonalInfo": "validation_failed", + "collectTeacherPersonalInfo": "validation_failed", +} + +SUBMISSION_OPT_IN = ( + "By submitting the personal information above, I acknowledge that my personal " + "information is being collected under the privacy policy of the business from " + "which I am seeking a discount" +) + +FLAGS = ( + '{"collect-info-step-email-first":"default","doc-upload-considerations":"default",' + '"doc-upload-may24":"default","doc-upload-redesign-use-legacy-message-keys":false,' + '"docUpload-assertion-checklist":"default","font-size":"default",' + '"include-cvec-field-france-student":"not-labeled-optional"}' +) \ No newline at end of file diff --git a/server/engine/__init__.py b/server/engine/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/server/engine/antidetect.py b/server/engine/antidetect.py new file mode 100644 index 0000000..562a53f --- /dev/null +++ b/server/engine/antidetect.py @@ -0,0 +1,958 @@ +""" +Anti-Detection Module for SheerID Verification Tools +Shared module for better anti-fraud bypass + +Features: +- Random User-Agent rotation (Chrome, Firefox, Edge, Safari) +- Browser-like headers with proper ordering +- Random fingerprint generation +- Request delay randomization +- TLS fingerprint spoofing with Chrome impersonation (curl_cffi) +- NewRelic tracking headers (required for SheerID) +- Canvas/WebGL fingerprint simulation +- Proxy validation and formatting + +Usage: + from anti_detect import get_headers, get_fingerprint, random_delay, create_session + from anti_detect import generate_newrelic_headers # For SheerID API calls + from anti_detect import make_request # High-level request with impersonation + +CRITICAL: For best results, install curl_cffi: + pip install curl_cffi + +Without curl_cffi, SheerID can detect Python's TLS fingerprint and reject requests. +""" + +import random +import hashlib +import time +import uuid +import base64 +import json +import sys + +# ============ CHROME IMPERSONATION VERSIONS ============ +# These are the Chrome versions that curl_cffi can impersonate +# Updated Jan 2026 - use latest stable versions +CHROME_VERSIONS = [ + "chrome131", # Chrome 131 (stable) + "chrome130", # Chrome 130 + "chrome124", # Chrome 124 + "chrome123", # Chrome 123 + "chrome120", # Chrome 120 + "chrome119", # Chrome 119 + "chrome116", # Chrome 116 + "chrome110", # Chrome 110 + "chrome107", # Chrome 107 + "chrome104", # Chrome 104 + "chrome101", # Chrome 101 + "chrome100", # Chrome 100 + "chrome99", # Chrome 99 +] + +# Multiple browser types for rotation (curl_cffi supports these) +IMPERSONATE_OPTIONS = { + "chrome": ["chrome131", "chrome130", "chrome124", "chrome120"], + "edge": ["edge131", "edge127", "edge101"], + "safari": ["safari18", "safari17_2_ios", "safari17_0"], +} + +# Default impersonation - use latest stable +DEFAULT_IMPERSONATE = "chrome131" + +# ============ USER AGENTS ============ +# Real browser User-Agents (updated Jan 2026) +# IMPORTANT: These must match the Chrome version we're impersonating +USER_AGENTS_CHROME = [ + # Chrome 131 Windows (matches chrome131 impersonation) + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", + # Chrome 131 Mac + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", + # Chrome 130 Windows + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36", + # Chrome 130 Mac + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36", +] + +# Legacy list for backwards compatibility +USER_AGENTS = [ + # Chrome Windows + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36", + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36", + # Chrome Mac + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36", + # Chrome Linux + "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", + # Edge Windows (Chromium-based) + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0", +] + +# ============ SCREEN RESOLUTIONS ============ +RESOLUTIONS = [ + "1920x1080", + "1366x768", + "1536x864", + "1440x900", + "1280x720", + "2560x1440", + "1600x900", + "1680x1050", + "1280x800", + "1024x768", +] + +# ============ TIMEZONES ============ +TIMEZONES = [-8, -7, -6, -5, -4, -3, 0, 1, 2, 3, 5.5, 8, 9, 10] + +# ============ LANGUAGES ============ +LANGUAGES = [ + "en-US,en;q=0.9", + "en-US,en;q=0.9,es;q=0.8", + "en-GB,en;q=0.9", + "en-CA,en;q=0.9", + "en-AU,en;q=0.9", +] + +# ============ PLATFORMS ============ +# Must match User-Agent for consistency +PLATFORMS = [ + ( + "Windows", + '"Windows"', + '"Chromium";v="131", "Google Chrome";v="131", "Not_A Brand";v="24"', + ), + ( + "Windows", + '"Windows"', + '"Chromium";v="130", "Google Chrome";v="130", "Not_A Brand";v="24"', + ), + ( + "macOS", + '"macOS"', + '"Chromium";v="131", "Google Chrome";v="131", "Not_A Brand";v="24"', + ), + ( + "Linux", + '"Linux"', + '"Chromium";v="131", "Google Chrome";v="131", "Not_A Brand";v="24"', + ), +] + +# ============ WEBGL VENDORS ============ +WEBGL_VENDORS = [ + "Google Inc. (NVIDIA)", + "Google Inc. (Intel)", + "Google Inc. (AMD)", + "Google Inc. (Apple)", +] + +WEBGL_RENDERERS = [ + "ANGLE (NVIDIA GeForce GTX 1080 Direct3D11 vs_5_0 ps_5_0)", + "ANGLE (NVIDIA GeForce RTX 3060 Direct3D11 vs_5_0 ps_5_0)", + "ANGLE (Intel(R) UHD Graphics 630 Direct3D11 vs_5_0 ps_5_0)", + "ANGLE (AMD Radeon RX 580 Direct3D11 vs_5_0 ps_5_0)", + "ANGLE (Apple M1 Pro)", +] + + +def get_random_user_agent() -> str: + """Get a random User-Agent string""" + return random.choice(USER_AGENTS) + + +def get_fingerprint() -> str: + """Generate realistic browser fingerprint hash""" + components = [ + str(int(time.time() * 1000)), + str(random.random()), + random.choice(RESOLUTIONS), + str(random.choice(TIMEZONES)), + random.choice(LANGUAGES).split(",")[0], + random.choice(["Win32", "MacIntel", "Linux x86_64"]), + random.choice(["Google Inc.", "Apple Computer, Inc.", ""]), + str(random.randint(2, 16)), # CPU cores + str(random.randint(4, 32)), # Device memory + str(random.randint(0, 1)), # Touch support + str(uuid.uuid4()), # Session ID + ] + return hashlib.md5("|".join(components).encode()).hexdigest() + + +def get_canvas_fingerprint() -> str: + """Generate a realistic canvas fingerprint hash""" + # Simulate canvas toDataURL hash + seed = str(time.time()) + str(random.random()) + return hashlib.sha256(seed.encode()).hexdigest()[:32] + + +def get_webgl_fingerprint() -> dict: + """Generate WebGL fingerprint data""" + return { + "vendor": random.choice(WEBGL_VENDORS), + "renderer": random.choice(WEBGL_RENDERERS), + "hash": hashlib.md5(str(random.random()).encode()).hexdigest(), + } + + +def get_audio_fingerprint() -> str: + """Generate audio context fingerprint""" + # Simulate AudioContext fingerprint + return str(random.uniform(124.0, 124.1))[:15] + + +def get_full_fingerprint() -> dict: + """Generate complete browser fingerprint for anti-detection""" + screen = random.choice(RESOLUTIONS) + width, height = screen.split("x") + + return { + "hash": get_fingerprint(), + "canvas": get_canvas_fingerprint(), + "webgl": get_webgl_fingerprint(), + "audio": get_audio_fingerprint(), + "screen": { + "width": int(width), + "height": int(height), + "colorDepth": random.choice([24, 32]), + "pixelRatio": random.choice([1, 1.25, 1.5, 2]), + }, + "timezone": random.choice(TIMEZONES), + "language": random.choice(LANGUAGES).split(",")[0], + "platform": random.choice(["Win32", "MacIntel", "Linux x86_64"]), + "cpuCores": random.randint(2, 16), + "memory": random.randint(4, 32), + "touchSupport": random.choice([True, False]), + "sessionId": str(uuid.uuid4()), + } + + +def generate_newrelic_headers() -> dict: + """ + Generate NewRelic tracking headers required by SheerID API + These headers help make requests look like they're from real browsers + """ + trace_id = uuid.uuid4().hex + uuid.uuid4().hex[:8] + trace_id = trace_id[:32] + span_id = uuid.uuid4().hex[:16] + timestamp = int(time.time() * 1000) + + payload = { + "v": [0, 1], + "d": { + "ty": "Browser", + "ac": "364029", + "ap": "134291347", + "id": span_id, + "tr": trace_id, + "ti": timestamp, + }, + } + + return { + "newrelic": base64.b64encode(json.dumps(payload).encode()).decode(), + "traceparent": f"00-{trace_id}-{span_id}-01", + "tracestate": f"364029@nr=0-1-364029-134291347-{span_id}----{timestamp}", + } + + +def get_headers(for_sheerid: bool = True, with_auth: str = None) -> dict: + """ + Generate browser-like headers with proper ordering + + Args: + for_sheerid: If True, use SheerID-specific headers + with_auth: Bearer token for Authorization header + """ + ua = get_random_user_agent() + platform = random.choice(PLATFORMS) + language = random.choice(LANGUAGES) + + # Base headers (proper ordering like real browser) + headers = { + "accept": "application/json, text/plain, */*", + "accept-encoding": "gzip, deflate, br, zstd", + "accept-language": language, + "cache-control": "no-cache", + "pragma": "no-cache", + "sec-ch-ua": platform[2], + "sec-ch-ua-mobile": "?0", + "sec-ch-ua-platform": platform[1], + "sec-fetch-dest": "empty", + "sec-fetch-mode": "cors", + "sec-fetch-site": "same-origin", + "user-agent": ua, + } + + if for_sheerid: + nr_headers = generate_newrelic_headers() + headers.update( + { + "content-type": "application/json", + "clientversion": "2.158.0", + "clientname": "jslib", + "origin": "https://services.sheerid.com", + "referer": "https://services.sheerid.com/", + **nr_headers, # Include NewRelic tracking headers + } + ) + + if with_auth: + headers["authorization"] = f"Bearer {with_auth}" + headers["origin"] = "https://chatgpt.com" + headers["referer"] = "https://chatgpt.com/" + headers["oai-device-id"] = str(uuid.uuid4()) + headers["oai-language"] = "en-US" + + return headers + + +def random_delay(min_ms: int = 300, max_ms: int = 1200): + """ + Random delay with gamma distribution to mimic human behavior + Gamma distribution is more realistic than uniform random + """ + try: + import numpy as np + + # Gamma distribution mimics human reaction times better + shape, scale = 2.0, (max_ms - min_ms) / 4000 + delay = min_ms / 1000 + np.random.gamma(shape, scale) + delay = min(delay, max_ms / 1000) # Cap at max + except ImportError: + # Fallback to basic random with slight variation + delay = random.randint(min_ms, max_ms) / 1000 + delay += random.uniform(0, 0.15) # Add extra randomness + + time.sleep(delay) + + +def get_random_impersonate(browser_type: str = None) -> str: + """ + Get random browser impersonation string for variety + + Args: + browser_type: 'chrome', 'edge', 'safari' or None for weighted random + + Returns: + Impersonation string like 'chrome131' + """ + if browser_type and browser_type in IMPERSONATE_OPTIONS: + return random.choice(IMPERSONATE_OPTIONS[browser_type]) + + # Weight towards Chrome (most common, safest) + weights = [0.75, 0.15, 0.10] + browser = random.choices(["chrome", "edge", "safari"], weights=weights)[0] + return random.choice(IMPERSONATE_OPTIONS[browser]) + + +def validate_proxy(proxy: str) -> str: + """Validate and format proxy string""" + if not proxy: + return None + + proxy = proxy.strip() + + # Already has scheme + if "://" in proxy: + return proxy + + parts = proxy.split(":") + + # host:port format + if len(parts) == 2: + return f"http://{parts[0]}:{parts[1]}" + + # host:port:user:pass format + elif len(parts) == 4: + return f"http://{parts[2]}:{parts[3]}@{parts[0]}:{parts[1]}" + + # user:pass@host:port format (already correct, just add scheme) + elif "@" in proxy: + return f"http://{proxy}" + + print(f"[WARN] Invalid proxy format: {proxy}") + return None + + +def check_proxy_type(proxy: str) -> str: + """ + Check if proxy is datacenter or residential + Returns: 'residential', 'datacenter', 'unknown' + """ + # This is a heuristic - actual check would require IP database lookup + datacenter_indicators = [ + "vultr", + "digitalocean", + "linode", + "aws", + "azure", + "gcp", + "ovh", + "hetzner", + "contabo", + "hostinger", + ] + + residential_indicators = [ + "residential", + "mobile", + "isp", + "roxy", + "bright", + "oxylabs", + "smartproxy", + "geosurf", + ] + + proxy_lower = proxy.lower() + + for ind in residential_indicators: + if ind in proxy_lower: + return "residential" + + for ind in datacenter_indicators: + if ind in proxy_lower: + return "datacenter" + + return "unknown" + + +def get_proxy_country(proxy: str) -> str: + """ + Try to determine proxy country from hostname + Returns country code (US, NL, UK, etc.) or 'unknown' + """ + country_indicators = { + "us": ["us.", "-us-", ".us.", "america", "united-states"], + "nl": ["nl.", "-nl-", ".nl.", "netherlands", "dutch", "amsterdam"], + "uk": ["uk.", "-uk-", ".uk.", "london", "britain", "england"], + "de": ["de.", "-de-", ".de.", "germany", "frankfurt", "berlin"], + "fr": ["fr.", "-fr-", ".fr.", "france", "paris"], + "ca": ["ca.", "-ca-", ".ca.", "canada", "toronto"], + "au": ["au.", "-au-", ".au.", "australia", "sydney"], + } + + proxy_lower = proxy.lower() + + for country, indicators in country_indicators.items(): + for ind in indicators: + if ind in proxy_lower: + return country.upper() + + return "unknown" + + +def get_matched_proxy(target_country: str, proxies: list) -> str: + """ + Get proxy matching target country (for university location matching) + + Args: + target_country: Country code (US, NL, UK, etc.) + proxies: List of proxy URLs + + Returns: + Matched proxy URL or random proxy if no match + """ + if not proxies: + return None + + target = target_country.upper() + matched = [] + + for proxy in proxies: + proxy_country = get_proxy_country(proxy) + if proxy_country == target: + matched.append(proxy) + + if matched: + return random.choice(matched) + + # No match - return random residential if available + residential = [p for p in proxies if check_proxy_type(p) == "residential"] + if residential: + return random.choice(residential) + + return random.choice(proxies) + + +def create_session(proxy: str = None, impersonate: str = None): + """ + Create HTTP session with best available library + Priority: curl_cffi (with impersonation) > cloudscraper > httpx > requests + + CRITICAL: curl_cffi with Chrome impersonation is STRONGLY recommended. + Without it, SheerID can detect Python's TLS fingerprint (JA3/JA4). + + Args: + proxy: Proxy URL (will be formatted if needed) + impersonate: Chrome version to impersonate (e.g., "chrome131") + If None, uses DEFAULT_IMPERSONATE + + Returns: + tuple: (session, library_name, impersonate_version) + """ + # Validate and format proxy + proxy = validate_proxy(proxy) + proxies = None + if proxy: + proxies = {"http": proxy, "https": proxy, "all://": proxy} + + # Warn if using datacenter proxy + proxy_type = check_proxy_type(proxy) + if proxy_type == "datacenter": + print("[WARN] ⚠️ Datacenter proxy detected! SheerID may reject requests.") + print("[WARN] Residential proxies are STRONGLY recommended.") + + # Determine impersonation version + imp_version = impersonate or DEFAULT_IMPERSONATE + + # Try curl_cffi first (BEST - TLS fingerprint spoofing) + try: + from curl_cffi import requests as curl_requests + + # Test if impersonation is supported + try: + if proxies: + session = curl_requests.Session( + proxies=proxies, impersonate=imp_version + ) + else: + session = curl_requests.Session(impersonate=imp_version) + + print(f"[Anti-Detect] ✅ Using curl_cffi with {imp_version} impersonation") + print(f"[Anti-Detect] TLS fingerprint will match real Chrome browser") + return session, "curl_cffi", imp_version + + except Exception as e: + # Try without impersonation if version not supported + print( + f"[WARN] Impersonation '{imp_version}' not supported, trying fallback..." + ) + + # Try older versions + for fallback_ver in ["chrome120", "chrome110", "chrome100"]: + try: + if proxies: + session = curl_requests.Session( + proxies=proxies, impersonate=fallback_ver + ) + else: + session = curl_requests.Session(impersonate=fallback_ver) + print( + f"[Anti-Detect] ✅ Using curl_cffi with {fallback_ver} impersonation" + ) + return session, "curl_cffi", fallback_ver + except: + continue + + # Last resort - no impersonation + if proxies: + session = curl_requests.Session(proxies=proxies) + else: + session = curl_requests.Session() + print("[Anti-Detect] ⚠️ curl_cffi loaded but impersonation failed") + print("[Anti-Detect] TLS fingerprint may be detectable!") + return session, "curl_cffi", None + + except ImportError: + print("\n" + "=" * 60) + print("⚠️ CRITICAL: curl_cffi NOT INSTALLED!") + print("=" * 60) + print("Without curl_cffi, your TLS fingerprint is DETECTABLE.") + print("SheerID will likely REJECT your verification attempts.") + print("") + print("Install now with: pip install curl_cffi") + print("=" * 60 + "\n") + + # Try cloudscraper (Cloudflare bypass, but no TLS spoofing) + try: + import cloudscraper + + session = cloudscraper.create_scraper( + browser={"browser": "chrome", "platform": "windows", "mobile": False} + ) + if proxies: + session.proxies = proxies + print("[Anti-Detect] ⚠️ Using cloudscraper (no TLS impersonation)") + return session, "cloudscraper", None + except ImportError: + pass + + # Try httpx (async support, but detectable TLS) + try: + import httpx + + proxy_url = proxies.get("all://") if proxies else None + session = httpx.Client(timeout=30, proxy=proxy_url) + print("[Anti-Detect] ⚠️ Using httpx (TLS fingerprint DETECTABLE!)") + print( + "[Anti-Detect] Expected success rate: ~20-40% (vs 60-80% with curl_cffi)" + ) + return session, "httpx", None + except ImportError: + pass + + # Fallback to requests (most detectable) + import requests + + session = requests.Session() + if proxies: + session.proxies = proxies + print("[Anti-Detect] ❌ Using requests (VERY HIGH detection risk!)") + print("[Anti-Detect] Expected success rate: ~5-20%") + print("[Anti-Detect] Run: pip install curl_cffi") + return session, "requests", None + + +def print_anti_detect_info(): + """Print info about anti-detection configuration""" + session, lib, imp = create_session() + print(f"\n{'=' * 50}") + print(f"Anti-Detection Configuration") + print(f"{'=' * 50}") + print(f" HTTP Library: {lib}") + print(f" Impersonation: {imp or 'None (detectable!)'}") + print(f" User-Agents: {len(USER_AGENTS)} variants") + print(f" Resolutions: {len(RESOLUTIONS)} variants") + print(f" Chrome Versions: {len(CHROME_VERSIONS)} available") + + if lib == "curl_cffi" and imp: + print(f"\n ✅ TLS Fingerprint: Spoofed as {imp}") + print(f" ✅ Detection Risk: LOW") + elif lib == "curl_cffi": + print(f"\n ⚠️ TLS Fingerprint: Partially spoofed") + print(f" ⚠️ Detection Risk: MEDIUM") + else: + print(f"\n ❌ TLS Fingerprint: Python signature (detectable)") + print(f" ❌ Detection Risk: HIGH") + + print(f"{'=' * 50}\n") + + # Cleanup + if hasattr(session, "close"): + session.close() + + +def make_request(session, method: str, url: str, impersonate: str = None, **kwargs): + """ + Make HTTP request with proper impersonation for curl_cffi + + This is a helper to ensure impersonation is used per-request + for libraries that support it. + + Args: + session: HTTP session from create_session() + method: HTTP method (GET, POST, PUT, DELETE) + url: Request URL + impersonate: Chrome version to impersonate (for curl_cffi) + **kwargs: Additional arguments (json, headers, etc.) + + Returns: + Response object + """ + imp = impersonate or DEFAULT_IMPERSONATE + + # Check if this is a curl_cffi session + session_type = type(session).__module__ + + if "curl_cffi" in session_type: + # curl_cffi supports per-request impersonation + try: + return session.request(method, url, impersonate=imp, **kwargs) + except TypeError: + # Older version doesn't support per-request impersonate + return session.request(method, url, **kwargs) + else: + # Other libraries - just make the request + return session.request(method, url, **kwargs) + + +def get_matched_ua_for_impersonate(impersonate: str = None) -> str: + """ + Get a User-Agent that matches the Chrome version we're impersonating + + IMPORTANT: The User-Agent MUST match the TLS fingerprint version, + otherwise SheerID can detect the mismatch. + """ + imp = impersonate or DEFAULT_IMPERSONATE + + # Extract version number + version = imp.replace("chrome", "").replace("edge", "").replace("safari", "") + + # Find matching UA + for ua in USER_AGENTS_CHROME: + if f"Chrome/{version}." in ua: + return ua + + # Fallback to first Chrome UA + return USER_AGENTS_CHROME[0] + + +def warm_session(session, program_id: str = None, headers: dict = None): + """ + Warm up session before verification attempt + Makes requests look more like a real browser by establishing session first + + Args: + session: HTTP session from create_session() + program_id: SheerID program ID (optional) + headers: Headers to use (optional) + + Returns: + session: Warmed up session + """ + base_url = "https://services.sheerid.com" + hdrs = headers or get_headers(for_sheerid=True) + + try: + # Step 1: Load main API (like browser would on page load) + session.get(f"{base_url}/rest/v2/config", headers=hdrs, timeout=10) + random_delay(500, 1000) + except: + pass + + if program_id: + try: + # Step 2: Load program info + session.get( + f"{base_url}/rest/v2/program/{program_id}", headers=hdrs, timeout=10 + ) + random_delay(300, 700) + except: + pass + + try: + # Step 3: Check organization endpoint (search with empty term) + params = {"country": "US", "term": ""} + if program_id: + params["programId"] = program_id + session.get( + f"{base_url}/rest/v2/organization/search", + params=params, + headers=hdrs, + timeout=10, + ) + random_delay(200, 500) + except: + pass + + return session + + +def generate_student_email( + first_name: str, last_name: str, university: dict = None +) -> str: + """ + Generate realistic student email matching university domain + + Args: + first_name: Student first name + last_name: Student last name + university: University dict with 'domain' key (optional) + + Returns: + Generated email address + """ + first = first_name.lower().strip() + last = last_name.lower().strip() + + domain = university.get("domain", "") if university else "" + + if not domain: + # Generic email providers + domains = ["gmail.com", "outlook.com", "yahoo.com", "icloud.com"] + domain = random.choice(domains) + + # Common university email patterns + patterns = [ + f"{first[0]}{last}@{domain}", # jsmith@university.edu + f"{first}.{last}@{domain}", # john.smith@university.edu + f"{first}{last[0]}@{domain}", # johns@university.edu + f"{first}_{last}@{domain}", # john_smith@university.edu + f"{last}{first[0]}@{domain}", # smithj@university.edu + f"{first}{random.randint(1, 99)}@{domain}", # john42@university.edu + ] + + return random.choice(patterns) + + +FRAUD_ERROR_HELP = """\ +🚨 Fraud Rule Rejection Detected (fraudRulesReject) + +SheerID's fraud/risk engine rejected this attempt. This is usually triggered by one or more risk signals: +- TLS fingerprint mismatch (Python http stacks vs real browsers) +- Datacenter / flagged IP reputation +- Reused device fingerprint / headers / NewRelic patterns across attempts +- High retry velocity or repeated failures from the same IP +- Geo mismatch (IP country/region vs organization) + +✅ Workarounds (try these, in order): + 1) Install curl_cffi for TLS spoofing: + pip install curl_cffi + 2) Use a residential proxy instead of a datacenter proxy + 3) Wait 24-48 hours before retrying (risk score often cools down) + 4) Try a different university/organization (some are stricter) + 5) Check if your IP is blacklisted (switch IP / provider if needed) + +Notes: +- Retrying instantly with the same IP + fingerprint can make the block stick longer. +- If you cannot install curl_cffi, expect a much higher fraud reject rate. +""" + + +def should_retry_fraud(retry_count: int): + """Decide whether to retry after a fraudRulesReject. + + Implements a capped exponential backoff schedule: + - 30s, 60s, 120s + - max 3 retries + + Args: + retry_count: Number of retries already attempted (0-based). + + Returns: + (should_retry, delay_seconds) + """ + if retry_count < 0: + retry_count = 0 + + backoff_schedule = [30, 60, 120] + + if retry_count >= len(backoff_schedule): + return False, 0 + + return True, backoff_schedule[retry_count] + + +def handle_fraud_rejection( + *, + retry_count: int = 0, + error_payload=None, + message: str = None, +): + """Print a visible fraud banner + actionable help, then return retry guidance. + + This handler is intended to be called when SheerID responds with + the `fraudRulesReject` error. + + Args: + retry_count: Number of retries already attempted (0-based). + error_payload: Optional API error JSON payload to display (best-effort). + message: Optional human-readable message/context to display. + + Returns: + (should_retry, delay_seconds) + """ + # ANSI colors (no external deps). If terminal doesn't support ANSI, output is still readable. + red = "\x1b[31m" + yellow = "\x1b[33m" + cyan = "\x1b[36m" + bold = "\x1b[1m" + reset = "\x1b[0m" + + banner = "\n".join( + [ + "+--------------------------------------------------------------+", + "| !!! FRAUD DETECTION HIT !!! |", + "| SheerID returned fraudRulesReject |", + "+--------------------------------------------------------------+", + ] + ) + + print(f"\n{red}{bold}{banner}{reset}") + print(f"{yellow}❌ Verification blocked by SheerID fraud rules.{reset}") + + if message: + print(f"{cyan}🧾 Context:{reset} {message}") + + # Best-effort extraction of useful fields without assuming a strict schema. + if isinstance(error_payload, dict) and error_payload: + interesting_keys = [ + "code", + "errorCode", + "message", + "detail", + "details", + "error", + "errors", + ] + extracted = {} + for k in interesting_keys: + if k in error_payload and error_payload.get(k) not in (None, ""): + extracted[k] = error_payload.get(k) + + if extracted: + # Keep this compact to avoid dumping huge payloads into the console. + print(f"{cyan}🔎 SheerID error payload (high-signal fields):{reset}") + for k, v in extracted.items(): + v_str = str(v) + if len(v_str) > 400: + v_str = v_str[:400] + "..." + print(f" - {k}: {v_str}") + + print("\n" + "=" * 62) + print(FRAUD_ERROR_HELP) + print("=" * 62) + + should_retry, delay_seconds = should_retry_fraud(retry_count) + if should_retry: + print( + f"{yellow}⏳ Suggested retry:{reset} attempt #{retry_count + 1}/3 in {delay_seconds}s" + ) + print( + f"{yellow}💡 Tip:{reset} rotate IP/fingerprint before retrying; avoid rapid-fire retries." + ) + else: + print(f"{red}🛑 Max retries reached.{reset} Do NOT keep spamming requests.") + print( + f"{yellow}✅ Best next step:{reset} wait 24-48h and change IP/fingerprint." + ) + + return should_retry, delay_seconds + + +if __name__ == "__main__": + # Test + print("\n" + "=" * 60) + print(" Anti-Detection Module Test ") + print("=" * 60 + "\n") + + print_anti_detect_info() + + print(f"Sample Fingerprints:") + print(f" Basic Hash: {get_fingerprint()}") + print(f" Canvas FP: {get_canvas_fingerprint()}") + print(f" Audio FP: {get_audio_fingerprint()}") + + webgl = get_webgl_fingerprint() + print(f" WebGL Vendor: {webgl['vendor']}") + print(f" WebGL Renderer: {webgl['renderer'][:40]}...") + + print(f"\nSample User-Agent:") + ua = get_matched_ua_for_impersonate() + print(f" {ua[:70]}...") + + print(f"\nSample Headers (SheerID):") + headers = get_headers(for_sheerid=True) + for k, v in list(headers.items())[:8]: + print(f" {k}: {str(v)[:50]}{'...' if len(str(v)) > 50 else ''}") + + print(f"\nNewRelic Headers:") + nr = generate_newrelic_headers() + print(f" traceparent: {nr['traceparent'][:50]}...") + + print("\n" + "=" * 60) + print(" Recommendations ") + print("=" * 60) + print(""" +1. Install curl_cffi for TLS spoofing: + pip install curl_cffi + +2. Use residential proxies (datacenter IPs are often blocked) + +3. Match proxy location to university country + +4. Generate unique fingerprints for each verification attempt +""") diff --git a/server/engine/client.py b/server/engine/client.py new file mode 100644 index 0000000..31e262c --- /dev/null +++ b/server/engine/client.py @@ -0,0 +1,170 @@ +"""SheerID verification engine — API flow with TLS impersonation. + +Flow (mirrors the public widget): + 1. POST /rest/v2/verification/{vid}/step/collect{Student|Teacher}PersonalInfo + 2. DELETE /step/sso (skip SSO when offered) + 3. POST /step/docUpload -> presigned S3 uploadUrl + 4. PUT uploadUrl (document bytes) + 5. POST /step/completeDocUpload + 6. GET my.sheerid.com/rest/v2/verification/{vid} (status polling) +""" +import re +import random +import logging +from typing import Optional, Dict, Tuple + +from .. import config +from . import antidetect + +logger = logging.getLogger("eduforge.engine") + + +def parse_verification_id(url: str) -> Optional[str]: + m = re.search(r"verificationId=([a-f0-9]{24})", url or "", re.IGNORECASE) + if m: + return m.group(1).lower() + if re.fullmatch(r"[a-f0-9]{24}", (url or "").strip().lower()): + return url.strip().lower() + return None + + +def device_fingerprint() -> str: + return "".join(random.choice("0123456789abcdef") for _ in range(32)) + + +class SheerIDClient: + def __init__(self, proxy: Optional[str] = None): + self.proxy = proxy + self.session, self.lib, self.impersonate = antidetect.create_session(proxy=proxy) + + def _req(self, method: str, url: str, body: Optional[Dict] = None, + raw: Optional[bytes] = None, content_type: str = "application/json") -> Tuple[object, int]: + headers = antidetect.get_headers(for_sheerid=True) + headers["Content-Type"] = content_type + kwargs = {"headers": headers} + if body is not None: + kwargs["json"] = body + if raw is not None: + kwargs["data"] = raw + resp = antidetect.make_request(self.session, method, url, + impersonate=self.impersonate, **kwargs) + try: + data = resp.json() + except Exception: + data = resp.text + return data, resp.status_code + + def status(self, vid: str) -> Dict: + data, code = self._req("GET", f"{config.MY_SHEERID}/rest/v2/verification/{vid}") + if code != 200 or not isinstance(data, dict): + return {"ok": False, "http": code, "raw": data} + step = data.get("currentStep", "") + return { + "ok": True, + "http": code, + "currentStep": step, + "status": config.STEP_STATUS.get(step, step or "unknown"), + "redirectUrl": data.get("redirectUrl"), + "errorIds": data.get("errorIds", []), + "raw": data, + } + + def submit_info(self, vid: str, program: Dict, identity: Dict, school: Dict) -> Dict: + body = { + "firstName": identity["first_name"], + "lastName": identity["last_name"], + "birthDate": identity.get("birth_date", ""), + "email": identity["email"], + "phoneNumber": identity.get("phone", ""), + "organization": { + "id": int(school["id"]), + "idExtended": str(school["idExtended"]), + "name": school["name"], + }, + "deviceFingerprintHash": identity.get("fingerprint") or device_fingerprint(), + "locale": identity.get("locale", "en-US"), + "metadata": { + "marketConsentValue": False, + "refererUrl": f"{config.SHEERID_BASE}/verify/{program['programId']}/?verificationId={vid}", + "verificationId": vid, + "flags": config.FLAGS, + "submissionOptIn": config.SUBMISSION_OPT_IN, + }, + } + if program["kind"] == "teacher": + body["employeeId"] = identity.get("employee_id", "") + data, code = self._req( + "POST", + f"{config.SHEERID_BASE}/rest/v2/verification/{vid}/step/{program['infoStep']}", + body, + ) + return {"http": code, "data": data} + + def skip_sso(self, vid: str) -> Dict: + data, code = self._req("DELETE", f"{config.SHEERID_BASE}/rest/v2/verification/{vid}/step/sso") + return {"http": code, "data": data} + + def request_upload(self, vid: str, filename: str, size: int, mime: str = "image/png") -> Dict: + body = {"files": [{"fileName": filename, "mimeType": mime, "fileSize": size}]} + data, code = self._req( + "POST", f"{config.SHEERID_BASE}/rest/v2/verification/{vid}/step/docUpload", body) + return {"http": code, "data": data} + + def upload_s3(self, upload_url: str, payload: bytes, mime: str = "image/png") -> bool: + _, code = self._req("PUT", upload_url, raw=payload, content_type=mime) + return 200 <= code < 300 + + def complete_upload(self, vid: str) -> Dict: + data, code = self._req( + "POST", f"{config.SHEERID_BASE}/rest/v2/verification/{vid}/step/completeDocUpload") + return {"http": code, "data": data} + + def run(self, vid: str, program: Dict, identity: Dict, school: Dict, + doc_bytes: bytes, filename: str = "document.png", + mime: str = "image/png", skip_sso: bool = True) -> Dict: + """Execute the full submission flow. Returns a result dict; never raises.""" + log = [] + try: + r = self.submit_info(vid, program, identity, school) + log.append({"step": "info", "http": r["http"]}) + if r["http"] != 200: + return {"success": False, "stage": "info", "detail": r["data"], "log": log} + data = r["data"] if isinstance(r["data"], dict) else {} + if data.get("currentStep") == "error": + return {"success": False, "stage": "info", + "detail": data.get("errorIds", ["unknown"]), "log": log} + step = data.get("currentStep", "") + + if skip_sso and step in ("sso", program["infoStep"]): + r = self.skip_sso(vid) + log.append({"step": "sso", "http": r["http"]}) + if isinstance(r["data"], dict): + step = r["data"].get("currentStep", step) + + r = self.request_upload(vid, filename, len(doc_bytes), mime) + log.append({"step": "docUpload", "http": r["http"]}) + docs = (r["data"] or {}).get("documents") if isinstance(r["data"], dict) else None + if not docs: + return {"success": False, "stage": "docUpload", "detail": r["data"], "log": log} + upload_url = docs[0]["uploadUrl"] + + if not self.upload_s3(upload_url, doc_bytes, mime): + return {"success": False, "stage": "s3", "detail": "upload failed", "log": log} + log.append({"step": "s3", "ok": True, "bytes": len(doc_bytes)}) + + r = self.complete_upload(vid) + log.append({"step": "complete", "http": r["http"]}) + final = r["data"] if isinstance(r["data"], dict) else {} + return { + "success": r["http"] == 200, + "pending": True, + "stage": "submitted", + "verification_id": vid, + "currentStep": final.get("currentStep"), + "status": config.STEP_STATUS.get(final.get("currentStep", ""), "pending"), + "redirectUrl": final.get("redirectUrl"), + "log": log, + } + except Exception as e: + logger.exception("engine run failed") + return {"success": False, "stage": "exception", "detail": str(e), "log": log} \ No newline at end of file diff --git a/server/gendocs.py b/server/gendocs.py new file mode 100644 index 0000000..da6135a --- /dev/null +++ b/server/gendocs.py @@ -0,0 +1,49 @@ +"""Document generation dispatch + synthetic identity helpers.""" +import random +from typing import Tuple, Dict + +from .generators import docgen, teacher, psu, names + + +def make_identity(first: str = None, last: str = None, email: str = None, + birth_date: str = None, school_domain: str = "psu.edu") -> Dict: + n = names.NameGenerator.generate() + first = first or n["first_name"] + last = last or n["last_name"] + if not email: + try: + email = psu.generate_psu_email(first, last) + except Exception: + email = f"{first.lower()}.{last.lower()}{random.randint(10, 99)}@{school_domain}" + birth_date = birth_date or names.generate_birth_date() + return {"first_name": first, "last_name": last, "email": email, + "birth_date": birth_date, "employee_id": str(random.randint(100000, 999999))} + + +def generate_doc(doc_type: str, first: str, last: str, school_name: str, + dob: str = "", school_id: str = "2565") -> Tuple[bytes, str, str]: + """Return (payload_bytes, filename, mime_type).""" + if doc_type == "student_id": + return docgen.generate_student_id(first, last, school_name), "student_id.png", "image/png" + if doc_type == "transcript": + return docgen.generate_transcript(first, last, dob or "2002-05-14", school_name), "transcript.png", "image/png" + if doc_type == "teacher_badge": + return docgen.generate_teacher_badge(first, last, school_name), "teacher_badge.png", "image/png" + if doc_type == "teacher_pdf": + return teacher.generate_teacher_pdf(first, last), "teacher_certificate.pdf", "application/pdf" + if doc_type == "teacher_png": + return teacher.generate_teacher_png(first, last), "teacher_certificate.png", "image/png" + if doc_type == "psu_card": + return psu.generate_image(first, last, school_id), "psu_card.png", "image/png" + raise ValueError(f"unknown doc_type: {doc_type}") + + +DOC_TYPES = { + "student_id": {"label": "Student ID card", "mime": "image/png", "engine": "pillow"}, + "transcript": {"label": "Transcript (quick)", "mime": "image/png", "engine": "pillow"}, + "teacher_badge": {"label": "Teacher badge", "mime": "image/png", "engine": "pillow"}, + "teacher_pdf": {"label": "Teacher certificate (PDF)", "mime": "application/pdf", "engine": "xhtml2pdf"}, + "teacher_png": {"label": "Teacher certificate (PNG)", "mime": "image/png", "engine": "playwright"}, + "psu_card": {"label": "PSU LionPATH card", "mime": "image/png", "engine": "playwright"}, + "transcript_studio": {"label": "Transcript Studio (288 schools)", "mime": "image/png", "engine": "browser"}, +} \ No newline at end of file diff --git a/server/generators/__init__.py b/server/generators/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/server/generators/docgen.py b/server/generators/docgen.py new file mode 100644 index 0000000..2f28b16 --- /dev/null +++ b/server/generators/docgen.py @@ -0,0 +1,592 @@ +""" +Enhanced Document Generator Module +Shared module for generating verification documents with anti-detection features + +Features: +- Random noise injection to avoid template detection +- Color variation for uniqueness +- Dynamic layout positioning +- Multiple document types (Student ID, Transcript, Teacher Badge, Invoice) +- Font variation and randomization + +Usage: + from doc_generator import generate_student_id, generate_transcript, generate_teacher_badge + + # Generate student ID with noise + doc_bytes = generate_student_id("John", "Doe", "MIT") + + # Generate transcript + doc_bytes = generate_transcript("John", "Doe", "2005-03-15", "MIT") + +""" + +import random +import time +import hashlib +from io import BytesIO +from typing import Tuple, Optional + +try: + from PIL import Image, ImageDraw, ImageFont, ImageFilter +except ImportError: + print("❌ Error: Pillow required. Install: pip install Pillow") + raise + + +# ============ COLOR PALETTES ============ +# Multiple color schemes to avoid detection +COLOR_SCHEMES = [ + # Classic blue + {"primary": (0, 51, 102), "secondary": (51, 102, 153), "accent": (255, 255, 255), "text": (51, 51, 51)}, + # Dark blue + {"primary": (25, 45, 85), "secondary": (45, 85, 125), "accent": (255, 255, 255), "text": (40, 40, 40)}, + # Navy + {"primary": (0, 0, 80), "secondary": (30, 30, 110), "accent": (255, 255, 255), "text": (45, 45, 45)}, + # Maroon + {"primary": (128, 0, 32), "secondary": (160, 40, 72), "accent": (255, 255, 255), "text": (50, 50, 50)}, + # Forest Green + {"primary": (34, 85, 51), "secondary": (51, 119, 68), "accent": (255, 255, 255), "text": (48, 48, 48)}, + # Purple + {"primary": (75, 0, 130), "secondary": (100, 30, 160), "accent": (255, 255, 255), "text": (55, 55, 55)}, +] + + +def get_random_color_scheme() -> dict: + """Get a random color scheme""" + return random.choice(COLOR_SCHEMES) + + +def add_noise(img: Image.Image, intensity: float = 0.02) -> Image.Image: + """ + Add subtle noise to image to avoid template detection + + Args: + img: PIL Image object + intensity: Noise intensity (0.0 - 1.0) + + Returns: + Image with noise applied + """ + import numpy as np + + # Convert to numpy array + arr = np.array(img, dtype=np.float32) + + # Generate noise + noise = np.random.normal(0, intensity * 255, arr.shape) + + # Add noise + arr = arr + noise + + # Clip values + arr = np.clip(arr, 0, 255).astype(np.uint8) + + return Image.fromarray(arr) + + +def add_simple_noise(img: Image.Image, intensity: int = 3) -> Image.Image: + """ + Add simple noise without numpy dependency + + Args: + img: PIL Image object + intensity: Max pixel variation (+/-) + + Returns: + Image with noise applied + """ + pixels = img.load() + width, height = img.size + + # Only modify a subset of pixels for performance + for _ in range(width * height // 10): + x = random.randint(0, width - 1) + y = random.randint(0, height - 1) + + try: + r, g, b = pixels[x, y][:3] + r = max(0, min(255, r + random.randint(-intensity, intensity))) + g = max(0, min(255, g + random.randint(-intensity, intensity))) + b = max(0, min(255, b + random.randint(-intensity, intensity))) + + if len(pixels[x, y]) == 4: + pixels[x, y] = (r, g, b, pixels[x, y][3]) + else: + pixels[x, y] = (r, g, b) + except: + pass + + return img + + +def randomize_position(base_x: int, base_y: int, variance: int = 3) -> Tuple[int, int]: + """Add small random offset to position""" + return ( + base_x + random.randint(-variance, variance), + base_y + random.randint(-variance, variance) + ) + + +def get_font(size: int, bold: bool = False) -> ImageFont.FreeTypeFont: + """ + Get font with fallback to default + + Args: + size: Font size + bold: Whether to use bold font + + Returns: + ImageFont object + """ + # Try different font paths + font_paths = [ + "arial.ttf", + "Arial.ttf", + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + "/System/Library/Fonts/Helvetica.ttc", + "C:\\Windows\\Fonts\\arial.ttf", + ] + + if bold: + font_paths = [ + "arialbd.ttf", + "Arial Bold.ttf", + "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", + "C:\\Windows\\Fonts\\arialbd.ttf", + ] + font_paths + + for path in font_paths: + try: + return ImageFont.truetype(path, size) + except: + continue + + return ImageFont.load_default() + + +def generate_barcode(draw: ImageDraw.Draw, x: int, y: int, width: int = 140, height_range: Tuple[int, int] = (30, 50)): + """Generate fake barcode pattern""" + bar_count = random.randint(20, 30) + bar_width = width // bar_count + + for i in range(bar_count): + if random.random() > 0.3: # Not all bars + bar_x = x + i * bar_width + bar_height = random.randint(height_range[0], height_range[1]) + bar_w = random.randint(1, max(2, bar_width - 1)) + draw.rectangle([(bar_x, y), (bar_x + bar_w, y + bar_height)], fill=(0, 0, 0)) + + +def generate_qr_placeholder(draw: ImageDraw.Draw, x: int, y: int, size: int = 60): + """Generate fake QR code pattern""" + cell_size = size // 10 + + # Draw border + draw.rectangle([(x, y), (x + size, y + size)], outline=(0, 0, 0), width=2) + + # Draw random pattern + for i in range(10): + for j in range(10): + if random.random() > 0.5: + cell_x = x + i * cell_size + cell_y = y + j * cell_size + draw.rectangle([(cell_x, cell_y), (cell_x + cell_size, cell_y + cell_size)], fill=(0, 0, 0)) + + # Draw position markers (corners) + for corner in [(x, y), (x + size - 20, y), (x, y + size - 20)]: + draw.rectangle([corner, (corner[0] + 20, corner[1] + 20)], fill=(0, 0, 0)) + draw.rectangle([(corner[0] + 5, corner[1] + 5), (corner[0] + 15, corner[1] + 15)], fill=(255, 255, 255)) + draw.rectangle([(corner[0] + 8, corner[1] + 8), (corner[0] + 12, corner[1] + 12)], fill=(0, 0, 0)) + + +def generate_student_id(first: str, last: str, school: str, add_noise: bool = True) -> bytes: + """ + Generate fake student ID card with anti-detection features + + Args: + first: First name + last: Last name + school: School name + add_noise: Whether to add noise for anti-detection + + Returns: + PNG image bytes + """ + # Randomize dimensions slightly + w = random.randint(640, 660) + h = random.randint(390, 410) + + # Random background color (slight off-white) + bg_color = ( + 255 - random.randint(0, 8), + 255 - random.randint(0, 8), + 255 - random.randint(0, 8) + ) + + img = Image.new("RGB", (w, h), bg_color) + draw = ImageDraw.Draw(img) + + # Get random color scheme + colors = get_random_color_scheme() + + # Get fonts + font_lg = get_font(random.randint(22, 26)) + font_md = get_font(random.randint(16, 20)) + font_sm = get_font(random.randint(12, 15)) + + # Header with slight position variance + header_height = random.randint(55, 65) + draw.rectangle([(0, 0), (w, header_height)], fill=colors["primary"]) + + title = random.choice([ + "STUDENT IDENTIFICATION CARD", + "STUDENT ID CARD", + "UNIVERSITY STUDENT CARD", + "STUDENT IDENTIFICATION" + ]) + title_pos = randomize_position(w // 2, header_height // 2, variance=2) + draw.text(title_pos, title, fill=colors["accent"], font=font_lg, anchor="mm") + + # School name + school_y = header_height + random.randint(25, 35) + school_display = school[:50] if len(school) > 50 else school + draw.text((w // 2, school_y), school_display, fill=colors["primary"], font=font_md, anchor="mm") + + # Photo placeholder + photo_x = random.randint(25, 35) + photo_y = random.randint(115, 125) + photo_w = random.randint(115, 125) + photo_h = random.randint(155, 165) + draw.rectangle([(photo_x, photo_y), (photo_x + photo_w, photo_y + photo_h)], + outline=(180, 180, 180), width=2) + draw.text((photo_x + photo_w // 2, photo_y + photo_h // 2), + "PHOTO", fill=(180, 180, 180), font=font_md, anchor="mm") + + # Student info + student_id = f"STU{random.randint(100000, 999999)}" + current_year = int(time.strftime('%Y')) + + info_x = photo_x + photo_w + random.randint(20, 30) + info_y = random.randint(125, 135) + + majors = ["Computer Science", "Business Administration", "Engineering", + "Mathematics", "Biology", "Economics", "Psychology", "Chemistry"] + + info_lines = [ + f"Name: {first} {last}", + f"ID: {student_id}", + f"Status: {random.choice(['Full-time Student', 'Undergraduate', 'Graduate Student'])}", + f"Major: {random.choice(majors)}", + f"Valid: {current_year}-{current_year + 1}" + ] + + for line in info_lines: + pos = randomize_position(info_x, info_y, variance=1) + draw.text(pos, line, fill=colors["text"], font=font_md) + info_y += random.randint(26, 32) + + # Footer + footer_y = h - random.randint(38, 45) + draw.rectangle([(0, footer_y), (w, h)], fill=colors["primary"]) + footer_text = random.choice([ + "Property of University", + "Official Student Identification", + "This card is property of the institution" + ]) + draw.text((w // 2, (footer_y + h) // 2), footer_text, + fill=colors["accent"], font=font_sm, anchor="mm") + + # Barcode + barcode_x = w - random.randint(160, 180) + barcode_y = photo_y + photo_h - random.randint(55, 65) + generate_barcode(draw, barcode_x, barcode_y) + + # Add noise if requested + if add_noise: + img = add_simple_noise(img, intensity=random.randint(2, 4)) + + # Slight blur for more realistic look + if random.random() > 0.5: + img = img.filter(ImageFilter.GaussianBlur(radius=0.3)) + + # Save + buf = BytesIO() + # Random quality for variation + img.save(buf, format="PNG", optimize=True) + return buf.getvalue() + + +def generate_transcript(first: str, last: str, dob: str, school: str, add_noise: bool = True) -> bytes: + """ + Generate fake academic transcript + + Args: + first: First name + last: Last name + dob: Date of birth (YYYY-MM-DD) + school: School name + add_noise: Whether to add noise + + Returns: + PNG image bytes + """ + # A4-ish proportions + w = random.randint(800, 850) + h = random.randint(1100, 1150) + + bg_color = (255 - random.randint(0, 5), 255 - random.randint(0, 5), 255 - random.randint(0, 5)) + img = Image.new("RGB", (w, h), bg_color) + draw = ImageDraw.Draw(img) + + colors = get_random_color_scheme() + + font_title = get_font(random.randint(24, 28), bold=True) + font_header = get_font(random.randint(18, 22), bold=True) + font_text = get_font(random.randint(12, 14)) + font_small = get_font(random.randint(10, 12)) + + y = 50 + + # School name header + draw.text((w // 2, y), school.upper(), fill=colors["primary"], font=font_title, anchor="mm") + y += 40 + + # Title + draw.text((w // 2, y), "OFFICIAL ACADEMIC TRANSCRIPT", fill=colors["text"], font=font_header, anchor="mm") + y += 50 + + # Horizontal line + draw.line([(50, y), (w - 50, y)], fill=colors["primary"], width=2) + y += 30 + + # Student info + student_id = f"S{random.randint(1000000, 9999999)}" + current_year = int(time.strftime('%Y')) + + info = [ + ("Name:", f"{first} {last}"), + ("Student ID:", student_id), + ("Date of Birth:", dob), + ("Program:", random.choice(["Bachelor of Science", "Bachelor of Arts", "Master of Science"])), + ("Major:", random.choice(["Computer Science", "Business", "Engineering", "Mathematics"])), + ("Academic Year:", f"{current_year - 1}-{current_year}"), + ] + + for label, value in info: + draw.text((60, y), label, fill=colors["text"], font=font_text) + draw.text((200, y), value, fill=colors["text"], font=font_text) + y += 25 + + y += 20 + + # Course table header + draw.rectangle([(50, y), (w - 50, y + 30)], fill=colors["primary"]) + draw.text((60, y + 8), "COURSE", fill=colors["accent"], font=font_text) + draw.text((400, y + 8), "CREDITS", fill=colors["accent"], font=font_text) + draw.text((500, y + 8), "GRADE", fill=colors["accent"], font=font_text) + draw.text((600, y + 8), "POINTS", fill=colors["accent"], font=font_text) + y += 35 + + # Generate random courses + courses = [ + "Introduction to Computer Science", + "Calculus I", + "English Composition", + "General Chemistry", + "Physics I", + "Data Structures", + "Linear Algebra", + "Statistics", + "Database Systems", + "Software Engineering", + ] + + random.shuffle(courses) + grades = ["A", "A-", "B+", "B", "B-", "A", "A-"] + total_credits = 0 + total_points = 0 + + for course in courses[:random.randint(6, 8)]: + credits = random.choice([3, 4]) + grade = random.choice(grades) + grade_points = {"A": 4.0, "A-": 3.7, "B+": 3.3, "B": 3.0, "B-": 2.7}[grade] + points = credits * grade_points + + total_credits += credits + total_points += points + + draw.text((60, y), course, fill=colors["text"], font=font_text) + draw.text((420, y), str(credits), fill=colors["text"], font=font_text) + draw.text((520, y), grade, fill=colors["text"], font=font_text) + draw.text((620, y), f"{points:.1f}", fill=colors["text"], font=font_text) + y += 22 + + # GPA + gpa = total_points / total_credits if total_credits > 0 else 0 + y += 20 + draw.line([(50, y), (w - 50, y)], fill=colors["primary"], width=1) + y += 15 + draw.text((60, y), f"TOTAL CREDITS: {total_credits}", fill=colors["text"], font=font_text) + draw.text((400, y), f"GPA: {gpa:.2f}", fill=colors["primary"], font=font_header) + + # Footer + y = h - 100 + draw.text((60, y), "This is an official transcript issued by the Registrar's Office.", + fill=colors["text"], font=font_small) + y += 20 + draw.text((60, y), f"Issue Date: {time.strftime('%B %d, %Y')}", fill=colors["text"], font=font_small) + + # Add noise + if add_noise: + img = add_simple_noise(img, intensity=random.randint(2, 4)) + + buf = BytesIO() + img.save(buf, format="PNG", optimize=True) + return buf.getvalue() + + +def generate_teacher_badge(first: str, last: str, school: str, add_noise: bool = True) -> bytes: + """ + Generate fake teacher/faculty badge + + Args: + first: First name + last: Last name + school: School name + add_noise: Whether to add noise + + Returns: + PNG image bytes + """ + w = random.randint(490, 510) + h = random.randint(340, 360) + + bg_color = (255 - random.randint(0, 8), 255 - random.randint(0, 8), 255 - random.randint(0, 8)) + img = Image.new("RGB", (w, h), bg_color) + draw = ImageDraw.Draw(img) + + # Use green color scheme for faculty + colors = { + "primary": (34, random.randint(100, 139), 34), + "secondary": (51, random.randint(150, 180), 68), + "accent": (255, 255, 255), + "text": (51, 51, 51) + } + + font_title = get_font(random.randint(20, 24)) + font_text = get_font(random.randint(14, 17)) + font_small = get_font(random.randint(11, 13)) + + # Header + header_h = random.randint(45, 55) + draw.rectangle([(0, 0), (w, header_h)], fill=colors["primary"]) + + title = random.choice(["STAFF IDENTIFICATION", "FACULTY ID CARD", "EMPLOYEE BADGE"]) + draw.text((w // 2, header_h // 2), title, fill=colors["accent"], font=font_title, anchor="mm") + + # School name + school_y = header_h + random.randint(20, 30) + draw.text((w // 2, school_y), school[:45], fill=colors["primary"], font=font_text, anchor="mm") + + # Photo placeholder + photo_x = random.randint(20, 30) + photo_y = random.randint(95, 105) + photo_w = random.randint(95, 105) + photo_h = random.randint(115, 125) + draw.rectangle([(photo_x, photo_y), (photo_x + photo_w, photo_y + photo_h)], + outline=(200, 200, 200), width=2) + draw.text((photo_x + photo_w // 2, photo_y + photo_h // 2), + "PHOTO", fill=(200, 200, 200), font=font_text, anchor="mm") + + # Teacher info + teacher_id = f"T{random.randint(10000, 99999)}" + current_year = int(time.strftime('%Y')) + + info_x = photo_x + photo_w + random.randint(15, 25) + info_y = photo_y + + departments = ["Education", "Mathematics", "Science", "English", "History", "Computer Science"] + + info_lines = [ + f"Name: {first} {last}", + f"ID: {teacher_id}", + f"Position: {random.choice(['Teacher', 'Instructor', 'Faculty Member'])}", + f"Department: {random.choice(departments)}", + f"Status: Active" + ] + + for line in info_lines: + draw.text(randomize_position(info_x, info_y, 1), line, fill=colors["text"], font=font_text) + info_y += random.randint(20, 25) + + # Valid date + draw.text((info_x, info_y + 10), f"Valid: {current_year}-{current_year + 1} School Year", + fill=(100, 100, 100), font=font_small) + + # Footer + footer_y = h - random.randint(32, 40) + draw.rectangle([(0, footer_y), (w, h)], fill=colors["primary"]) + draw.text((w // 2, (footer_y + h) // 2), "Property of School District", + fill=colors["accent"], font=font_small, anchor="mm") + + # Add noise + if add_noise: + img = add_simple_noise(img, intensity=random.randint(2, 4)) + + buf = BytesIO() + img.save(buf, format="PNG", optimize=True) + return buf.getvalue() + + +# ============ UTILITY FUNCTIONS ============ + +def get_document_type_weights() -> dict: + """ + Get recommended document type weights based on success rates + Transcripts generally have higher success rates than IDs + """ + return { + "transcript": 70, + "student_id": 20, + "enrollment_letter": 10 + } + + +def select_document_type() -> str: + """Select document type based on weights""" + weights = get_document_type_weights() + total = sum(weights.values()) + r = random.uniform(0, total) + + cumulative = 0 + for doc_type, weight in weights.items(): + cumulative += weight + if r <= cumulative: + return doc_type + return "transcript" + + +if __name__ == "__main__": + print("Document Generator Test") + print("-" * 50) + + # Test student ID + print("\n1. Generating Student ID...") + student_id = generate_student_id("John", "Doe", "Massachusetts Institute of Technology") + print(f" Size: {len(student_id) / 1024:.1f} KB") + + # Test transcript + print("\n2. Generating Transcript...") + transcript = generate_transcript("Jane", "Smith", "2003-05-15", "Stanford University") + print(f" Size: {len(transcript) / 1024:.1f} KB") + + # Test teacher badge + print("\n3. Generating Teacher Badge...") + badge = generate_teacher_badge("Robert", "Johnson", "Stuyvesant High School") + print(f" Size: {len(badge) / 1024:.1f} KB") + + print("\n" + "-" * 50) + print("All documents generated successfully!") + print("\nDocument Type Weights:") + for doc_type, weight in get_document_type_weights().items(): + print(f" {doc_type}: {weight}%") diff --git a/server/generators/names.py b/server/generators/names.py new file mode 100644 index 0000000..2591abf --- /dev/null +++ b/server/generators/names.py @@ -0,0 +1,114 @@ +"""Random name generator""" +import random + + +class NameGenerator: + """English name generator""" + + ROOTS = { + 'prefixes': ['Al', 'Bri', 'Car', 'Dan', 'El', 'Fer', 'Gar', 'Har', 'Jes', 'Kar', + 'Lar', 'Mar', 'Nor', 'Par', 'Quin', 'Ros', 'Sar', 'Tar', 'Val', 'Wil'], + 'middles': ['an', 'en', 'in', 'on', 'ar', 'er', 'or', 'ur', 'al', 'el', + 'il', 'ol', 'am', 'em', 'im', 'om', 'ay', 'ey', 'oy', 'ian'], + 'suffixes': ['ton', 'son', 'man', 'ley', 'field', 'ford', 'wood', 'stone', 'worth', 'berg', + 'stein', 'bach', 'heim', 'gard', 'land', 'wick', 'shire', 'dale', 'brook', 'ridge'], + 'name_roots': ['Alex', 'Bern', 'Crist', 'Dav', 'Edw', 'Fred', 'Greg', 'Henr', 'Ivan', 'John', + 'Ken', 'Leon', 'Mich', 'Nick', 'Oliv', 'Paul', 'Rich', 'Step', 'Thom', 'Will'], + 'name_endings': ['a', 'e', 'i', 'o', 'y', 'ie', 'ey', 'an', 'en', 'in', + 'on', 'er', 'ar', 'or', 'el', 'al', 'iel', 'ael', 'ine', 'lyn'] + } + + PATTERNS = { + 'first_name': [ + ['prefix', 'ending'], + ['name_root', 'ending'], + ['prefix', 'middle', 'ending'], + ['name_root', 'middle', 'ending'] + ], + 'last_name': [ + ['prefix', 'suffix'], + ['name_root', 'suffix'], + ['prefix', 'middle', 'suffix'], + ['compound'] + ] + } + + @classmethod + def _generate_component(cls, pattern): + """Generate name components per pattern""" + components = [] + for part in pattern: + if part == 'prefix': + component = random.choice(cls.ROOTS['prefixes']) + elif part == 'middle': + component = random.choice(cls.ROOTS['middles']) + elif part == 'suffix': + component = random.choice(cls.ROOTS['suffixes']) + elif part == 'name_root': + component = random.choice(cls.ROOTS['name_roots']) + elif part == 'ending': + component = random.choice(cls.ROOTS['name_endings']) + elif part == 'compound': + part1 = random.choice(cls.ROOTS['prefixes']) + part2 = random.choice(cls.ROOTS['suffixes']) + component = part1 + part2 + else: + component = '' + + components.append(component) + + return ''.join(components) + + @classmethod + def _format_name(cls, name): + """Format name (capitalize)""" + return name.capitalize() + + @classmethod + def generate(cls): + """ + Generate random English name + + Returns: + dict: contains first_name, last_name, full_name + """ + first_name_pattern = random.choice(cls.PATTERNS['first_name']) + last_name_pattern = random.choice(cls.PATTERNS['last_name']) + + first_name = cls._generate_component(first_name_pattern) + last_name = cls._generate_component(last_name_pattern) + + return { + 'first_name': cls._format_name(first_name), + 'last_name': cls._format_name(last_name), + 'full_name': f"{cls._format_name(first_name)} {cls._format_name(last_name)}" + } + + +def generate_email(school_domain='MIT.EDU'): + """ + Generate random school email + + Args: + school_domain: school domain + + Returns: + str: email address + """ + chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' + username = ''.join(random.choice(chars) for _ in range(8)) + return f"{username}@{school_domain}" + + +def generate_birth_date(): + """ + Generate random birth date (2000-2005) + + Returns: + str: YYYY-MM-DD formatted date + """ + year = 2000 + random.randint(0, 5) + month = str(random.randint(1, 12)).zfill(2) + day = str(random.randint(1, 28)).zfill(2) + return f"{year}-{month}-{day}" + diff --git a/server/generators/psu.py b/server/generators/psu.py new file mode 100644 index 0000000..5fd4f2c --- /dev/null +++ b/server/generators/psu.py @@ -0,0 +1,407 @@ +"""PNG Student ID card generator - Penn State LionPATH""" +import random +from datetime import datetime +from io import BytesIO +import base64 + + +def generate_psu_id(): + """Generate random PSU ID (9digits)""" + return f"9{random.randint(10000000, 99999999)}" + + +def generate_psu_email(first_name, last_name): + """ + Generate PSU email + format: firstName.lastName + 3-4digits @psu.edu + """ + digit_count = random.choice([3, 4]) + digits = ''.join([str(random.randint(0, 9)) for _ in range(digit_count)]) + email = f"{first_name.lower()}.{last_name.lower()}{digits}@psu.edu" + return email + + +def generate_html(first_name, last_name, school_id='2565'): + """ + Generate Penn State LionPATH HTML + + Args: + first_name: First name + last_name: Last name + school_id: School ID + + Returns: + str: HTML content + """ + psu_id = generate_psu_id() + name = f"{first_name} {last_name}" + date = datetime.now().strftime('%m/%d/%Y, %I:%M:%S %p') + + # Random major selection + majors = [ + 'Computer Science (BS)', + 'Software Engineering (BS)', + 'Information Sciences and Technology (BS)', + 'Data Science (BS)', + 'Electrical Engineering (BS)', + 'Mechanical Engineering (BS)', + 'Business Administration (BS)', + 'Psychology (BA)' + ] + major = random.choice(majors) + + html = f""" + + + + + LionPATH - Student Home + + + + +
+
+
+ +
LionPATH
+
+
+ Welcome, {name} + | + Sign Out +
+
+ + + +
+ + +
+
+
Student Name
+
{name}
+
+
+
PSU ID
+
{psu_id}
+
+
+
Academic Program
+
{major}
+
+
+
Enrollment Status
+
✅ Enrolled
+
+
+ +
+ Data retrieved: {date} +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Class NbrCourseTitleDays & TimesRoomUnits
14920CMPSC 465Data Structures and AlgorithmsMoWeFr 10:10AM - 11:00AMWillard 0623.00
18233MATH 230Calculus and Vector AnalysisTuTh 1:35PM - 2:50PMThomas 1024.00
20491CMPSC 473Operating Systems DesignMoWe 2:30PM - 3:45PMWestgate E2013.00
11029ENGL 202CTechnical WritingFr 1:25PM - 2:15PMBoucke 3043.00
15502STAT 318Elementary ProbabilityTuTh 9:05AM - 10:20AMOsmond 1123.00
+ +
+ © 2025 The Pennsylvania State University. All rights reserved.
+ LionPATH is the student information system for Penn State. +
+
+
+ + + +""" + + return html + + +def generate_image(first_name, last_name, school_id='2565'): + """ + Generate Penn State LionPATH screenshot PNG + + Args: + first_name: First name + last_name: Last name + school_id: School ID + + Returns: + bytes: PNG image data + """ + try: + from playwright.sync_api import sync_playwright + + # Generate HTML + html_content = generate_html(first_name, last_name, school_id) + + # Playwright screenshot (replaces Selenium) + with sync_playwright() as p: + browser = p.chromium.launch(headless=True) + page = browser.new_page(viewport={'width': 1200, 'height': 900}) + page.set_content(html_content, wait_until='load') + page.wait_for_timeout(500) # Wait for styles to load + screenshot_bytes = page.screenshot(type='png', full_page=True) + browser.close() + + return screenshot_bytes + + except ImportError: + raise Exception("playwright required: pip install playwright && playwright install chromium") + except Exception as e: + raise Exception(f"Image generation failed: {str(e)}") + + +if __name__ == '__main__': + # Test code + import sys + import io + + # Fix Windows console encoding + if sys.platform == 'win32': + sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') + + print("Testing PSU image generation...") + + first_name = "John" + last_name = "Smith" + + print(f"Name: {first_name} {last_name}") + print(f"PSU ID: {generate_psu_id()}") + print(f"Email: {generate_psu_email(first_name, last_name)}") + + try: + img_data = generate_image(first_name, last_name) + + # Save test image + with open('test_psu_card.png', 'wb') as f: + f.write(img_data) + + print(f"✓ Image generated! Size: {len(img_data)} bytes") + print("✓ Saved as test_psu_card.png") + + except Exception as e: + print(f"✗ Error: {e}") diff --git a/server/generators/teacher.py b/server/generators/teacher.py new file mode 100644 index 0000000..dce8fb4 --- /dev/null +++ b/server/generators/teacher.py @@ -0,0 +1,75 @@ +"""Teacher certificate generation (PDF + PNG)""" +import random +from datetime import datetime +from io import BytesIO +from pathlib import Path + +from xhtml2pdf import pisa + + +def _render_template(first_name: str, last_name: str) -> str: + """Read template, replace name/employee ID/date, and expand CSS variables.""" + full_name = f"{first_name} {last_name}" + employee_id = random.randint(1000000, 9999999) + current_date = datetime.now().strftime("%m/%d/%Y %I:%M %p") + + template_path = Path(__file__).parent / "card-temp.html" + html = template_path.read_text(encoding="utf-8") + + # Expand CSS variables for xhtml2pdf + color_map = { + "var(--primary-blue)": "#0056b3", + "var(--border-gray)": "#dee2e6", + "var(--bg-gray)": "#f8f9fa", + } + for placeholder, color in color_map.items(): + html = html.replace(placeholder, color) + + # Replace sample name / employee ID / date (name appears twice in template + span) + html = html.replace("Sarah J. Connor", full_name) + html = html.replace("E-9928104", f"E-{employee_id}") + html = html.replace('id="currentDate">', f'id="currentDate">{current_date}') + + return html + + +def generate_teacher_pdf(first_name: str, last_name: str) -> bytes: + """Generate teacher certificate PDF bytes.""" + html = _render_template(first_name, last_name) + + output = BytesIO() + pisa_status = pisa.CreatePDF(html, dest=output, encoding="utf-8") + if pisa_status.err: + raise Exception("PDF Generation failed") + + pdf_data = output.getvalue() + output.close() + return pdf_data + + +def generate_teacher_png(first_name: str, last_name: str) -> bytes: + """Generate PNG via Playwright screenshot (requires playwright + chromium installed).""" + try: + from playwright.sync_api import sync_playwright + except ImportError as exc: + raise RuntimeError( + "playwright required, run `pip install playwright` then `playwright install chromium`" + ) from exc + + html = _render_template(first_name, last_name) + + with sync_playwright() as p: + browser = p.chromium.launch(headless=True) + page = browser.new_page(viewport={"width": 1200, "height": 1000}) + page.set_content(html, wait_until="load") + page.wait_for_timeout(500) # let styles settle + card = page.locator(".browser-mockup") + png_bytes = card.screenshot(type="png") + browser.close() + + return png_bytes + + +# Legacy compat: default to PDF +def generate_teacher_image(first_name: str, last_name: str) -> bytes: + return generate_teacher_pdf(first_name, last_name) diff --git a/server/main.py b/server/main.py new file mode 100644 index 0000000..d50a3e9 --- /dev/null +++ b/server/main.py @@ -0,0 +1,169 @@ +"""EduForge — verification combine server (FastAPI). + +Run: python -m server.main (or uvicorn server.main:app --port 8890) +""" +import os +import uuid +import asyncio +import logging +from concurrent.futures import ThreadPoolExecutor +from typing import Optional + +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse, Response, FileResponse +from fastapi.staticfiles import StaticFiles +from pydantic import BaseModel + +from . import config, storage, gendocs +from .engine.client import SheerIDClient, parse_verification_id + +logging.basicConfig(level=logging.INFO, format="[%(asctime)s] %(levelname)s %(name)s: %(message)s") +log = logging.getLogger("eduforge") + +app = FastAPI(title="EduForge", version="1.0.0") +storage.init() + +POOL = ThreadPoolExecutor(max_workers=6) +SEM = asyncio.Semaphore(int(os.environ.get("EDUFORGE_CONCURRENCY", "3"))) +ADMIN_TOKEN = os.environ.get("EDUFORGE_TOKEN", "") +WEB_DIR = os.path.join(os.path.dirname(__file__), "..", "web") + + +def _guard(req: Request): + if ADMIN_TOKEN and req.headers.get("x-admin-token") != ADMIN_TOKEN: + raise HTTPException(401, "invalid admin token") + + +class GenerateReq(BaseModel): + doc_type: str = "student_id" + first: Optional[str] = None + last: Optional[str] = None + school_id: str = config.DEFAULT_SCHOOL_ID + dob: Optional[str] = None + + +class VerifyReq(BaseModel): + url: Optional[str] = None + vid: Optional[str] = None + program: str = "student" + school_id: str = config.DEFAULT_SCHOOL_ID + doc_type: str = "student_id" + first: Optional[str] = None + last: Optional[str] = None + email: Optional[str] = None + birth_date: Optional[str] = None + proxy: Optional[str] = None + skip_sso: bool = True + + +@app.get("/health") +def health(): + return {"ok": True, "service": "eduforge", "programs": len(config.PROGRAMS), + "schools": len(config.SCHOOLS)} + + +@app.get("/api/programs") +def programs(): + return {"programs": config.PROGRAMS, "dead": config.PROGRAMS_DEAD} + + +@app.get("/api/schools") +def schools(): + return {"schools": config.SCHOOLS, "default": config.DEFAULT_SCHOOL_ID} + + +@app.get("/api/doc_types") +def doc_types(): + return {"doc_types": gendocs.DOC_TYPES} + + +@app.post("/api/generate") +def generate(req: GenerateReq, request: Request): + _guard(request) + school = config.SCHOOLS.get(req.school_id) + if not school: + raise HTTPException(400, "unknown school_id") + ident = gendocs.make_identity(req.first, req.last, birth_date=req.dob) + try: + payload, filename, mime = gendocs.generate_doc( + req.doc_type, ident["first_name"], ident["last_name"], + school["name"], ident["birth_date"], req.school_id) + except Exception as e: + raise HTTPException(500, f"generation failed: {e}") + return Response(content=payload, media_type=mime, + headers={"Content-Disposition": f'attachment; filename="{filename}"', + "X-Identity": f'{ident["first_name"]} {ident["last_name"]} <{ident["email"]}>'}) + + +def _run_verify(tid: str, req: VerifyReq, vid: str): + program = config.PROGRAMS[req.program] + school = config.SCHOOLS.get(req.school_id, config.SCHOOLS[config.DEFAULT_SCHOOL_ID]) + ident = gendocs.make_identity(req.first, req.last, req.email, req.birth_date, + school.get("domain", "psu.edu").lower()) + storage.update_task(tid, "generating", {"identity": {k: ident[k] for k in ("first_name", "last_name", "email", "birth_date")}}) + try: + payload, filename, mime = gendocs.generate_doc( + req.doc_type, ident["first_name"], ident["last_name"], + school["name"], ident["birth_date"], req.school_id) + except Exception as e: + storage.update_task(tid, "failed", {"stage": "generate", "error": str(e)}) + return + storage.update_task(tid, "submitting", {"doc_bytes": len(payload), "filename": filename}) + client = SheerIDClient(proxy=req.proxy) + result = client.run(vid, program, ident, school, payload, filename, mime, req.skip_sso) + storage.update_task(tid, "submitted" if result.get("success") else "failed", result) + + +@app.post("/api/verify") +async def verify(req: VerifyReq, request: Request): + _guard(request) + vid = req.vid or parse_verification_id(req.url or "") + if not vid: + raise HTTPException(400, "provide url with verificationId or a 24-hex vid") + if req.program not in config.PROGRAMS: + raise HTTPException(400, "unknown program") + tid = uuid.uuid4().hex[:12] + storage.add_task(tid, "verify", req.program, vid, req.model_dump()) + + async def worker(): + async with SEM: + storage.update_task(tid, "running", {}) + await asyncio.get_event_loop().run_in_executor(POOL, _run_verify, tid, req, vid) + + asyncio.create_task(worker()) + return {"task_id": tid, "vid": vid, "status": "queued"} + + +@app.get("/api/tasks") +def tasks(limit: int = 100): + return {"tasks": storage.list_tasks(limit)} + + +@app.get("/api/task/{tid}") +def task(tid: str): + t = storage.get_task(tid) + if not t: + raise HTTPException(404, "task not found") + return t + + +@app.get("/api/status/{vid}") +def status(vid: str, proxy: Optional[str] = None): + if not parse_verification_id(vid): + raise HTTPException(400, "invalid verification id") + client = SheerIDClient(proxy=proxy) + return client.status(vid) + + +@app.get("/") +def index(): + return FileResponse(os.path.join(WEB_DIR, "index.html")) + + +app.mount("/transcript", StaticFiles(directory=os.path.join(WEB_DIR, "transcript"), html=True), name="transcript") +app.mount("/static", StaticFiles(directory=WEB_DIR), name="static") + + +if __name__ == "__main__": + import uvicorn + uvicorn.run(app, host="127.0.0.1", port=int(os.environ.get("EDUFORGE_PORT", "8895"))) \ No newline at end of file diff --git a/server/storage.py b/server/storage.py new file mode 100644 index 0000000..eb58b68 --- /dev/null +++ b/server/storage.py @@ -0,0 +1,60 @@ +"""SQLite task store.""" +import os +import json +import time +import sqlite3 +import threading + +DB_PATH = os.path.join(os.path.dirname(__file__), "..", "data", "eduforge.db") +_lock = threading.Lock() + + +def _conn(): + os.makedirs(os.path.dirname(DB_PATH), exist_ok=True) + c = sqlite3.connect(DB_PATH, timeout=30) + c.row_factory = sqlite3.Row + return c + + +def init(): + with _lock, _conn() as c: + c.execute("""CREATE TABLE IF NOT EXISTS tasks( + id TEXT PRIMARY KEY, created REAL, updated REAL, + kind TEXT, program TEXT, vid TEXT, status TEXT, + payload TEXT, result TEXT)""") + + +def add_task(tid: str, kind: str, program: str, vid: str, payload: dict): + now = time.time() + with _lock, _conn() as c: + c.execute("INSERT INTO tasks VALUES(?,?,?,?,?,?,?,?,?)", + (tid, now, now, kind, program, vid, "queued", + json.dumps(payload, ensure_ascii=False), "{}")) + + +def update_task(tid: str, status: str, result: dict): + with _lock, _conn() as c: + c.execute("UPDATE tasks SET status=?, result=?, updated=? WHERE id=?", + (status, json.dumps(result, ensure_ascii=False, default=str), time.time(), tid)) + + +def get_task(tid: str): + with _lock, _conn() as c: + r = c.execute("SELECT * FROM tasks WHERE id=?", (tid,)).fetchone() + return _row(r) if r else None + + +def list_tasks(limit: int = 100): + with _lock, _conn() as c: + rows = c.execute("SELECT * FROM tasks ORDER BY created DESC LIMIT ?", (limit,)).fetchall() + return [_row(r) for r in rows] + + +def _row(r): + d = dict(r) + for k in ("payload", "result"): + try: + d[k] = json.loads(d[k] or "{}") + except Exception: + d[k] = {} + return d \ No newline at end of file diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..eff9544 --- /dev/null +++ b/web/index.html @@ -0,0 +1,250 @@ + + + + + +EduForge — Verification Combine + + + + +
+ +
+

Запуск верификации

+
Вставь ссылку SheerID с verificationId — движок сам пройдёт шаги и загрузит документ.
+
+

Цель

+ + +
+
+
+
+
+
+
+

Личность (пусто = сгенерировать)

+
+
+
+
+
+
+
+
+
+
+ +
+
+
+ +
+

Очередь задач

+
Автообновление каждые 4 секунды.
+
+
+ +
IDПрограммаVIDСтатусДеталиВремя
+
+ +
+

Генератор документов

+
Student ID, транскрипт, бейдж учителя, PDF-сертификат, PSU LionPATH.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+ +
+

Transcript Studio

+
288 школ · 8 макетов · 20 стран. Отдельный модуль, рендер в браузере, экспорт PDF.
+ +
+ +
+

Программы SheerID

+
Живые programId проверены запросом к services.sheerid.com.
+
КлючProgram IDНазваниеТипПримечание
+

Мёртвые (404)

+
+ +
+

Настройки

+
+ + +
Токен хранится только в этом браузере (localStorage) и уходит в заголовке X-Admin-Token.
+ +
+

О комбайне

+
+
+
+ + + \ No newline at end of file diff --git a/web/transcript/index.html b/web/transcript/index.html new file mode 100644 index 0000000..854db48 --- /dev/null +++ b/web/transcript/index.html @@ -0,0 +1,7127 @@ + + + + + +EduForge · Document Studio + + + + + +
+
+
+
TS
+
+
Document Studio
+
Official Transcript Generator
+
+
+
+ + + +
+ +
+ + +
+ +
+ + +
+
+
+ + + + +
+ — +
+ + +
+
+
+
+
+
+ +
+
+ + + + +