EduForge: SheerID verification combine — API engine, doc generators, Transcript Studio (288 schools), RU/EN dashboard

This commit is contained in:
EduForge
2026-11-16 16:34:33 +02:00
commit 6f0fe138df
21 changed files with 10245 additions and 0 deletions
+14
View File
@@ -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
+21
View File
@@ -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.
+93
View File
@@ -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
+20
View File
@@ -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"]
+13
View File
@@ -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
+8
View File
@@ -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
View File
+105
View File
@@ -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"}'
)
View File
+958
View File
@@ -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
""")
+170
View File
@@ -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}
+49
View File
@@ -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"},
}
View File
+592
View File
@@ -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}%")
+114
View File
@@ -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}"
+407
View File
@@ -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"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LionPATH - Student Home</title>
<style>
:root {{
--psu-blue: #1E407C; /* Penn State Nittany Navy */
--psu-light-blue: #96BEE6;
--bg-gray: #f4f4f4;
--text-color: #333;
}}
body {{
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif;
background-color: #e0e0e0; /* Browser background */
margin: 0;
padding: 20px;
color: var(--text-color);
display: flex;
justify-content: center;
}}
/* Simulated browser window */
.viewport {{
width: 100%;
max-width: 1100px;
background-color: #fff;
box-shadow: 0 5px 20px rgba(0,0,0,0.15);
min-height: 800px;
display: flex;
flex-direction: column;
}}
/* Top nav bar LionPATH */
.header {{
background-color: var(--psu-blue);
color: white;
padding: 0 20px;
height: 60px;
display: flex;
align-items: center;
justify-content: space-between;
}}
.brand {{
display: flex;
align-items: center;
gap: 15px;
}}
/* PSU Logo Simulate */
.psu-logo {{
font-family: "Georgia", serif;
font-size: 20px;
font-weight: bold;
letter-spacing: 1px;
border-right: 1px solid rgba(255,255,255,0.3);
padding-right: 15px;
}}
.system-name {{
font-size: 18px;
font-weight: 300;
}}
.user-menu {{
font-size: 14px;
display: flex;
align-items: center;
gap: 20px;
}}
.nav-bar {{
background-color: #f8f8f8;
border-bottom: 1px solid #ddd;
padding: 10px 20px;
font-size: 13px;
color: #666;
display: flex;
gap: 20px;
}}
.nav-item {{ cursor: pointer; }}
.nav-item.active {{ color: var(--psu-blue); font-weight: bold; border-bottom: 2px solid var(--psu-blue); padding-bottom: 8px; }}
/* Main content area */
.content {{
padding: 30px;
flex: 1;
}}
.page-header {{
display: flex;
justify-content: space-between;
align-items: flex-end;
margin-bottom: 20px;
border-bottom: 1px solid #eee;
padding-bottom: 10px;
}}
.page-title {{
font-size: 24px;
color: var(--psu-blue);
margin: 0;
}}
.term-selector {{
background: #fff;
border: 1px solid #ccc;
padding: 5px 10px;
border-radius: 4px;
font-size: 14px;
color: #333;
font-weight: bold;
}}
/* Student info card */
.student-card {{
background: #fcfcfc;
border: 1px solid #e0e0e0;
padding: 15px;
margin-bottom: 25px;
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 20px;
font-size: 13px;
}}
.info-label {{ color: #777; font-size: 11px; text-transform: uppercase; margin-bottom: 4px; }}
.info-val {{ font-weight: bold; color: #333; font-size: 14px; }}
.status-badge {{
background-color: #e6fffa; color: #007a5e;
padding: 4px 8px; border-radius: 4px; font-weight: bold; border: 1px solid #b2f5ea;
}}
/* Course schedule */
.schedule-table {{
width: 100%;
border-collapse: collapse;
font-size: 13px;
}}
.schedule-table th {{
text-align: left;
padding: 12px;
background-color: #f0f0f0;
border-bottom: 2px solid #ccc;
color: #555;
}}
.schedule-table td {{
padding: 15px 12px;
border-bottom: 1px solid #eee;
}}
.course-code {{ font-weight: bold; color: var(--psu-blue); }}
.course-title {{ font-weight: 500; }}
/* Print adaptation */
@media print {{
body {{ background: white; padding: 0; }}
.viewport {{ box-shadow: none; max-width: 100%; min-height: auto; }}
.nav-bar {{ display: none; }}
@page {{ margin: 1cm; size: landscape; }}
}}
</style>
</head>
<body>
<div class="viewport">
<div class="header">
<div class="brand">
<div class="psu-logo">PennState</div>
<div class="system-name">LionPATH</div>
</div>
<div class="user-menu">
<span>Welcome, <strong>{name}</strong></span>
<span>|</span>
<span>Sign Out</span>
</div>
</div>
<div class="nav-bar">
<div class="nav-item">Student Home</div>
<div class="nav-item active">My Class Schedule</div>
<div class="nav-item">Academics</div>
<div class="nav-item">Finances</div>
<div class="nav-item">Campus Life</div>
</div>
<div class="content">
<div class="page-header">
<h1 class="page-title">My Class Schedule</h1>
<div class="term-selector">
Term: <strong>Fall 2025</strong> (Aug 25 - Dec 12)
</div>
</div>
<div class="student-card">
<div>
<div class="info-label">Student Name</div>
<div class="info-val">{name}</div>
</div>
<div>
<div class="info-label">PSU ID</div>
<div class="info-val">{psu_id}</div>
</div>
<div>
<div class="info-label">Academic Program</div>
<div class="info-val">{major}</div>
</div>
<div>
<div class="info-label">Enrollment Status</div>
<div class="status-badge">✅ Enrolled</div>
</div>
</div>
<div style="margin-bottom: 10px; font-size: 12px; color: #666; text-align: right;">
Data retrieved: <span>{date}</span>
</div>
<table class="schedule-table">
<thead>
<tr>
<th width="10%">Class Nbr</th>
<th width="15%">Course</th>
<th width="35%">Title</th>
<th width="20%">Days & Times</th>
<th width="10%">Room</th>
<th width="10%">Units</th>
</tr>
</thead>
<tbody>
<tr>
<td>14920</td>
<td class="course-code">CMPSC 465</td>
<td class="course-title">Data Structures and Algorithms</td>
<td>MoWeFr 10:10AM - 11:00AM</td>
<td>Willard 062</td>
<td>3.00</td>
</tr>
<tr>
<td>18233</td>
<td class="course-code">MATH 230</td>
<td class="course-title">Calculus and Vector Analysis</td>
<td>TuTh 1:35PM - 2:50PM</td>
<td>Thomas 102</td>
<td>4.00</td>
</tr>
<tr>
<td>20491</td>
<td class="course-code">CMPSC 473</td>
<td class="course-title">Operating Systems Design</td>
<td>MoWe 2:30PM - 3:45PM</td>
<td>Westgate E201</td>
<td>3.00</td>
</tr>
<tr>
<td>11029</td>
<td class="course-code">ENGL 202C</td>
<td class="course-title">Technical Writing</td>
<td>Fr 1:25PM - 2:15PM</td>
<td>Boucke 304</td>
<td>3.00</td>
</tr>
<tr>
<td>15502</td>
<td class="course-code">STAT 318</td>
<td class="course-title">Elementary Probability</td>
<td>TuTh 9:05AM - 10:20AM</td>
<td>Osmond 112</td>
<td>3.00</td>
</tr>
</tbody>
</table>
<div style="margin-top: 50px; border-top: 1px solid #ddd; padding-top: 10px; font-size: 11px; color: #888; text-align: center;">
&copy; 2025 The Pennsylvania State University. All rights reserved.<br>
LionPATH is the student information system for Penn State.
</div>
</div>
</div>
</body>
</html>
"""
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}")
+75
View File
@@ -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"></span>', f'id="currentDate">{current_date}</span>')
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)
+169
View File
@@ -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")))
+60
View File
@@ -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
+250
View File
@@ -0,0 +1,250 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>EduForge — Verification Combine</title>
<style>
:root{--bg:#0b0f14;--panel:#111823;--panel2:#0e141d;--line:#1e2a3a;--txt:#d7e2ee;--mut:#7d8fa3;
--acc:#37e0a1;--acc2:#3aa0ff;--warn:#ffb454;--err:#ff5d6c;--mono:'JetBrains Mono',ui-monospace,Consolas,monospace}
*{box-sizing:border-box;margin:0;padding:0}
body{background:var(--bg);color:var(--txt);font:14px/1.5 'Segoe UI',system-ui,sans-serif;display:flex;min-height:100vh}
a{color:var(--acc2);text-decoration:none}
aside{width:220px;background:var(--panel2);border-right:1px solid var(--line);padding:18px 12px;position:sticky;top:0;height:100vh;flex-shrink:0}
.logo{font:700 19px var(--mono);color:var(--acc);letter-spacing:.5px;padding:6px 10px 16px}
.logo span{color:var(--mut);font-weight:400}
nav button{display:flex;align-items:center;gap:9px;width:100%;background:none;border:0;color:var(--mut);
padding:10px 12px;border-radius:8px;cursor:pointer;font-size:13.5px;text-align:left;margin-bottom:2px}
nav button:hover{background:#16202e;color:var(--txt)}
nav button.on{background:#152232;color:var(--acc);font-weight:600}
nav .ic{width:17px;text-align:center}
.lang{margin-top:18px;display:flex;gap:6px;padding:0 10px}
.lang button{flex:1;background:#16202e;border:1px solid var(--line);color:var(--mut);border-radius:6px;padding:5px;cursor:pointer;font-size:12px}
.lang button.on{color:var(--acc);border-color:var(--acc)}
main{flex:1;padding:26px 30px;max-width:1060px}
h1{font-size:20px;margin-bottom:4px}
.sub{color:var(--mut);margin-bottom:20px;font-size:13px}
.card{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:18px;margin-bottom:16px}
.card h2{font-size:14px;color:var(--acc);margin-bottom:12px;font-weight:600}
.grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.grid3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px}
label{display:block;font-size:12px;color:var(--mut);margin-bottom:4px}
input,select,textarea{width:100%;background:var(--panel2);border:1px solid var(--line);color:var(--txt);
border-radius:8px;padding:9px 11px;font-size:13px;font-family:inherit}
input:focus,select:focus{outline:none;border-color:var(--acc2)}
.mono{font-family:var(--mono)}
.btn{background:var(--acc);color:#04120c;border:0;border-radius:8px;padding:10px 18px;font-weight:700;
cursor:pointer;font-size:13.5px;margin-top:14px}
.btn:hover{filter:brightness(1.1)}
.btn.sec{background:#1b2836;color:var(--txt);font-weight:500}
.btn:disabled{opacity:.5;cursor:default}
.row{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
.pill{display:inline-block;padding:2px 9px;border-radius:20px;font-size:11.5px;font-weight:600;font-family:var(--mono)}
.p-ok{background:#0f2e22;color:var(--acc)}.p-run{background:#12253a;color:var(--acc2)}
.p-wait{background:#2e2510;color:var(--warn)}.p-err{background:#331419;color:var(--err)}
.p-mut{background:#1a2431;color:var(--mut)}
table{width:100%;border-collapse:collapse;font-size:12.5px}
th{text-align:left;color:var(--mut);font-weight:500;padding:7px 9px;border-bottom:1px solid var(--line)}
td{padding:8px 9px;border-bottom:1px solid #16202e;vertical-align:top}
tr:hover td{background:#131c28}
.hide{display:none}
.note{font-size:12px;color:var(--mut);margin-top:8px}
.docprev{max-width:340px;border:1px solid var(--line);border-radius:8px;margin-top:12px;background:#fff}
.kv{font-family:var(--mono);font-size:12px;color:var(--mut)}
.stat{display:flex;gap:14px;margin-bottom:18px;flex-wrap:wrap}
.stat .box{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:12px 18px;min-width:120px}
.stat .n{font:700 22px var(--mono);color:var(--acc)}
.stat .l{font-size:11.5px;color:var(--mut)}
iframe{width:100%;height:78vh;border:1px solid var(--line);border-radius:12px;background:#fff}
.toast{position:fixed;bottom:22px;right:22px;background:#152232;border:1px solid var(--acc);color:var(--txt);
padding:12px 18px;border-radius:10px;font-size:13px;opacity:0;transition:.3s;pointer-events:none;max-width:380px}
.toast.show{opacity:1}
</style>
</head>
<body>
<aside>
<div class="logo">Edu<span>Forge</span></div>
<nav id="nav">
<button data-t="run" class="on"><span class="ic">▶</span><span data-i="nav_run">Запуск</span></button>
<button data-t="queue"><span class="ic">≡</span><span data-i="nav_queue">Очередь</span></button>
<button data-t="docs"><span class="ic">▤</span><span data-i="nav_docs">Документы</span></button>
<button data-t="studio"><span class="ic">◫</span><span data-i="nav_studio">Transcript Studio</span></button>
<button data-t="programs"><span class="ic">◎</span><span data-i="nav_prog">Программы</span></button>
<button data-t="settings"><span class="ic">⚙</span><span data-i="nav_set">Настройки</span></button>
</nav>
<div class="lang"><button id="lru" class="on">RU</button><button id="len">EN</button></div>
</aside>
<main>
<!-- RUN -->
<section id="t-run">
<h1 data-i="run_h">Запуск верификации</h1>
<div class="sub" data-i="run_sub">Вставь ссылку SheerID с verificationId — движок сам пройдёт шаги и загрузит документ.</div>
<div class="card">
<h2 data-i="run_target">Цель</h2>
<label data-i="run_url">Ссылка верификации или verificationId</label>
<input id="v_url" class="mono" placeholder="https://services.sheerid.com/verify/.../?verificationId=...">
<div class="grid3" style="margin-top:12px">
<div><label data-i="run_prog">Программа</label><select id="v_prog"></select></div>
<div><label data-i="run_school">Школа</label><select id="v_school"></select></div>
<div><label data-i="run_doc">Документ</label><select id="v_doc"></select></div>
</div>
</div>
<div class="card">
<h2 data-i="run_ident">Личность (пусто = сгенерировать)</h2>
<div class="grid">
<div><label data-i="f_first">Имя</label><input id="v_first"></div>
<div><label data-i="f_last">Фамилия</label><input id="v_last"></div>
<div><label>Email</label><input id="v_email" class="mono"></div>
<div><label data-i="f_dob">Дата рождения</label><input id="v_dob" class="mono" placeholder="2002-05-14"></div>
</div>
<div class="grid" style="margin-top:12px">
<div><label data-i="run_proxy">Прокси (опционально)</label><input id="v_proxy" class="mono" placeholder="http://user:pass@host:port"></div>
<div><label>SSO</label><select id="v_sso"><option value="1" data-i="run_skip">Пропускать SSO</option><option value="0" data-i="run_keep">Не пропускать</option></select></div>
</div>
<button class="btn" id="v_go" data-i="run_go">Запустить</button>
<div class="note" id="v_out"></div>
</div>
</section>
<!-- QUEUE -->
<section id="t-queue" class="hide">
<h1 data-i="q_h">Очередь задач</h1>
<div class="sub" data-i="q_sub">Автообновление каждые 4 секунды.</div>
<div class="stat" id="q_stat"></div>
<div class="card"><table><thead><tr>
<th>ID</th><th data-i="q_prog">Программа</th><th>VID</th><th data-i="q_status">Статус</th><th data-i="q_detail">Детали</th><th data-i="q_time">Время</th>
</tr></thead><tbody id="q_body"></tbody></table></div>
</section>
<!-- DOCS -->
<section id="t-docs" class="hide">
<h1 data-i="d_h">Генератор документов</h1>
<div class="sub" data-i="d_sub">Student ID, транскрипт, бейдж учителя, PDF-сертификат, PSU LionPATH.</div>
<div class="card">
<div class="grid3">
<div><label data-i="d_type">Тип</label><select id="d_type"></select></div>
<div><label data-i="f_first">Имя</label><input id="d_first"></div>
<div><label data-i="f_last">Фамилия</label><input id="d_last"></div>
</div>
<div class="grid" style="margin-top:12px">
<div><label data-i="run_school">Школа</label><select id="d_school"></select></div>
<div><label data-i="f_dob">Дата рождения</label><input id="d_dob" class="mono" placeholder="2002-05-14"></div>
</div>
<div class="row"><button class="btn" id="d_go" data-i="d_go">Сгенерировать</button>
<button class="btn sec" id="d_dl" data-i="d_dl" disabled>Скачать</button></div>
<div class="note" id="d_out"></div>
<img id="d_prev" class="docprev hide">
</div>
</section>
<!-- STUDIO -->
<section id="t-studio" class="hide">
<h1>Transcript Studio</h1>
<div class="sub" data-i="s_sub">288 школ · 8 макетов · 20 стран. Отдельный модуль, рендер в браузере, экспорт PDF.</div>
<iframe src="/transcript/" loading="lazy"></iframe>
</section>
<!-- PROGRAMS -->
<section id="t-programs" class="hide">
<h1 data-i="p_h">Программы SheerID</h1>
<div class="sub" data-i="p_sub">Живые programId проверены запросом к services.sheerid.com.</div>
<div class="card"><table><thead><tr><th data-i="p_key">Ключ</th><th>Program ID</th><th data-i="p_title">Название</th><th data-i="p_kind">Тип</th><th data-i="p_note">Примечание</th></tr></thead><tbody id="p_body"></tbody></table></div>
<div class="card"><h2 data-i="p_dead">Мёртвые (404)</h2><div id="p_dead" class="kv"></div></div>
</section>
<!-- SETTINGS -->
<section id="t-settings" class="hide">
<h1 data-i="set_h">Настройки</h1>
<div class="card">
<label data-i="set_token">Admin-токен (если задан EDUFORGE_TOKEN на сервере)</label>
<input id="set_token" class="mono" type="password">
<div class="note" data-i="set_note">Токен хранится только в этом браузере (localStorage) и уходит в заголовке X-Admin-Token.</div>
<button class="btn" id="set_save" data-i="set_save">Сохранить</button>
</div>
<div class="card"><h2 data-i="set_about">О комбайне</h2><div class="kv" id="set_about"></div></div>
</section>
</main>
<div class="toast" id="toast"></div>
<script>
const I={
ru:{nav_run:'Запуск',nav_queue:'Очередь',nav_docs:'Документы',nav_studio:'Transcript Studio',nav_prog:'Программы',nav_set:'Настройки',
run_h:'Запуск верификации',run_sub:'Вставь ссылку SheerID с verificationId — движок сам пройдёт шаги и загрузит документ.',
run_target:'Цель',run_url:'Ссылка верификации или verificationId',run_prog:'Программа',run_school:'Школа',run_doc:'Документ',
run_ident:'Личность (пусто = сгенерировать)',f_first:'Имя',f_last:'Фамилия',f_dob:'Дата рождения',run_proxy:'Прокси (опционально)',
run_skip:'Пропускать SSO',run_keep:'Не пропускать',run_go:'Запустить',q_h:'Очередь задач',q_sub:'Автообновление каждые 4 секунды.',
q_prog:'Программа',q_status:'Статус',q_detail:'Детали',q_time:'Время',d_h:'Генератор документов',
d_sub:'Student ID, транскрипт, бейдж учителя, PDF-сертификат, PSU LionPATH.',d_type:'Тип',d_go:'Сгенерировать',d_dl:'Скачать',
s_sub:'288 школ · 8 макетов · 20 стран. Отдельный модуль, рендер в браузере, экспорт PDF.',
p_h:'Программы SheerID',p_sub:'Живые programId проверены запросом к services.sheerid.com.',p_key:'Ключ',p_title:'Название',p_kind:'Тип',p_note:'Примечание',p_dead:'Мёртвые (404)',
set_h:'Настройки',set_token:'Admin-токен (если задан EDUFORGE_TOKEN на сервере)',set_note:'Токен хранится только в этом браузере (localStorage) и уходит в заголовке X-Admin-Token.',set_save:'Сохранить',set_about:'О комбайне',
started:'Задача создана',err:'Ошибка',gen_ok:'Документ готов',saved:'Сохранено'},
en:{nav_run:'Run',nav_queue:'Queue',nav_docs:'Documents',nav_studio:'Transcript Studio',nav_prog:'Programs',nav_set:'Settings',
run_h:'Run verification',run_sub:'Paste a SheerID link with verificationId — the engine walks the steps and uploads the document.',
run_target:'Target',run_url:'Verification URL or verificationId',run_prog:'Program',run_school:'School',run_doc:'Document',
run_ident:'Identity (blank = auto-generate)',f_first:'First name',f_last:'Last name',f_dob:'Birth date',run_proxy:'Proxy (optional)',
run_skip:'Skip SSO',run_keep:'Keep SSO',run_go:'Run',q_h:'Task queue',q_sub:'Auto-refresh every 4 seconds.',
q_prog:'Program',q_status:'Status',q_detail:'Detail',q_time:'Time',d_h:'Document generator',
d_sub:'Student ID, transcript, teacher badge, PDF certificate, PSU LionPATH.',d_type:'Type',d_go:'Generate',d_dl:'Download',
s_sub:'288 schools · 8 layouts · 20 countries. Standalone module, browser render, PDF export.',
p_h:'SheerID programs',p_sub:'Live programIds verified against services.sheerid.com.',p_key:'Key',p_title:'Title',p_kind:'Kind',p_note:'Note',p_dead:'Dead (404)',
set_h:'Settings',set_token:'Admin token (if EDUFORGE_TOKEN is set on the server)',set_note:'Token stays in this browser (localStorage) and is sent as X-Admin-Token.',set_save:'Save',set_about:'About',
started:'Task created',err:'Error',gen_ok:'Document ready',saved:'Saved'}};
let lang=localStorage.ef_lang||'ru';
const $=s=>document.querySelector(s);
const tok=()=>localStorage.ef_token||'';
const H=()=>({'Content-Type':'application/json','X-Admin-Token':tok()});
function applyLang(){document.querySelectorAll('[data-i]').forEach(e=>{const k=e.dataset.i;if(I[lang][k])e.textContent=I[lang][k];});
$('#lru').classList.toggle('on',lang==='ru');$('#len').classList.toggle('on',lang==='en');}
$('#lru').onclick=()=>{lang='ru';localStorage.ef_lang=lang;applyLang();};
$('#len').onclick=()=>{lang='en';localStorage.ef_lang=lang;applyLang();};
function toast(m){const t=$('#toast');t.textContent=m;t.classList.add('show');setTimeout(()=>t.classList.remove('show'),3200);}
document.querySelectorAll('#nav button').forEach(b=>b.onclick=()=>{
document.querySelectorAll('#nav button').forEach(x=>x.classList.remove('on'));b.classList.add('on');
document.querySelectorAll('main section').forEach(s=>s.classList.add('hide'));$('#t-'+b.dataset.t).classList.remove('hide');
if(b.dataset.t==='queue')loadQueue();if(b.dataset.t==='programs')loadPrograms();});
async function jget(u){const r=await fetch(u,{headers:H()});return r.json();}
async function init(){
const [p,s,d,h]=await Promise.all([jget('/api/programs'),jget('/api/schools'),jget('/api/doc_types'),jget('/health')]);
const po=$('#v_prog');po.innerHTML=Object.entries(p.programs).map(([k,v])=>`<option value="${k}">${k} — ${v.title}</option>`).join('');
const so='<option>'+Object.entries(s.schools).map(([k,v])=>`<option value="${k}">${v.name}</option>`).join('');
$('#v_school').innerHTML=so;$('#d_school').innerHTML=so;
const dt=Object.entries(d.doc_types).filter(([k])=>k!=='transcript_studio').map(([k,v])=>`<option value="${k}">${v.label}</option>`).join('');
$('#v_doc').innerHTML=dt;$('#d_type').innerHTML=dt;
$('#set_about').textContent=`EduForge v${h.programs?'1.0':''} · programs: ${h.programs} · schools: ${h.schools} · engine: curl_cffi + NewRelic headers`;
$('#set_token').value=tok();applyLang();}
$('#v_go').onclick=async()=>{
const body={url:$('#v_url').value.trim(),program:$('#v_prog').value,school_id:$('#v_school').value,doc_type:$('#v_doc').value,
first:$('#v_first').value||null,last:$('#v_last').value||null,email:$('#v_email').value||null,birth_date:$('#v_dob').value||null,
proxy:$('#v_proxy').value||null,skip_sso:$('#v_sso').value==='1'};
$('#v_go').disabled=true;
try{const r=await fetch('/api/verify',{method:'POST',headers:H(),body:JSON.stringify(body)});const j=await r.json();
if(!r.ok)throw new Error(j.detail||r.status);
$('#v_out').innerHTML=`<span class="pill p-ok">${I[lang].started}</span> <span class="mono">${j.task_id}</span> · vid <span class="mono">${j.vid}</span>`;
toast(I[lang].started+': '+j.task_id);}catch(e){$('#v_out').innerHTML=`<span class="pill p-err">${I[lang].err}</span> ${e.message}`;}
$('#v_go').disabled=false;};
const PILL={queued:'p-mut',running:'p-run',generating:'p-run',submitting:'p-run',submitted:'p-ok',verified:'p-ok',failed:'p-err',rejected:'p-err',pending:'p-wait'};
async function loadQueue(){
const j=await jget('/api/tasks');const ts=j.tasks||[];
const cnt={};ts.forEach(t=>cnt[t.status]=(cnt[t.status]||0)+1);
$('#q_stat').innerHTML=['submitted','running','failed','queued'].map(k=>`<div class="box"><div class="n">${cnt[k]||0}</div><div class="l">${k}</div></div>`).join('');
$('#q_body').innerHTML=ts.map(t=>{const det=t.result||{};const d=det.stage||det.status||'';const err=det.detail?(typeof det.detail==='string'?det.detail:JSON.stringify(det.detail)).slice(0,80):'';
return `<tr><td class="mono">${t.id}</td><td>${t.program}</td><td class="mono">${(t.vid||'').slice(0,10)}…</td>
<td><span class="pill ${PILL[t.status]||'p-mut'}">${t.status}</span></td><td class="kv">${d} ${err}</td>
<td class="kv">${new Date(t.created*1000).toLocaleTimeString()}</td></tr>`;}).join('')||'<tr><td colspan=6 class="kv">—</td></tr>';}
setInterval(()=>{if(!$('#t-queue').classList.contains('hide'))loadQueue();},4000);
let lastDoc=null;
$('#d_go').onclick=async()=>{
const body={doc_type:$('#d_type').value,first:$('#d_first').value||null,last:$('#d_last').value||null,school_id:$('#d_school').value,dob:$('#d_dob').value||null};
$('#d_go').disabled=true;$('#d_out').textContent='…';
try{const r=await fetch('/api/generate',{method:'POST',headers:H(),body:JSON.stringify(body)});
if(!r.ok){const j=await r.json();throw new Error(j.detail||r.status);}
const blob=await r.blob();lastDoc={blob,name:r.headers.get('Content-Disposition')?.match(/filename="(.+)"/)?.[1]||'document.png'};
$('#d_out').innerHTML=`<span class="pill p-ok">${I[lang].gen_ok}</span> <span class="kv">${r.headers.get('X-Identity')||''} · ${(blob.size/1024).toFixed(1)} KB</span>`;
$('#d_dl').disabled=false;
if(blob.type.startsWith('image')){$('#d_prev').src=URL.createObjectURL(blob);$('#d_prev').classList.remove('hide');}else $('#d_prev').classList.add('hide');
}catch(e){$('#d_out').innerHTML=`<span class="pill p-err">${I[lang].err}</span> ${e.message}`;}
$('#d_go').disabled=false;};
$('#d_dl').onclick=()=>{if(!lastDoc)return;const a=document.createElement('a');a.href=URL.createObjectURL(lastDoc.blob);a.download=lastDoc.name;a.click();};
async function loadPrograms(){const j=await jget('/api/programs');
$('#p_body').innerHTML=Object.entries(j.programs).map(([k,v])=>`<tr><td class="mono">${k}</td><td class="mono">${v.programId}</td><td>${v.title}</td><td><span class="pill p-ok">${v.kind}</span></td><td class="kv">${v.note||''}</td></tr>`).join('');
$('#p_dead').innerHTML=Object.entries(j.dead).map(([k,v])=>`${k} — ${v}`).join('<br>');}
$('#set_save').onclick=()=>{localStorage.ef_token=$('#set_token').value;toast(I[lang].saved);};
init();
</script>
</body>
</html>
File diff suppressed because it is too large Load Diff