recovered snapshot from suspended aaronjaworski710 (history unavailable)
This commit is contained in:
@@ -0,0 +1,16 @@
|
|||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
.git/
|
||||||
|
.codegraph/
|
||||||
|
frontend/node_modules/
|
||||||
|
frontend/dist/
|
||||||
|
accounts/
|
||||||
|
.browser-profile/
|
||||||
|
.playwright-mcp/
|
||||||
|
.env
|
||||||
|
config.json
|
||||||
|
proxies.txt
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Self-hosting / production — copy to .env (never commit, already in .gitignore)
|
||||||
|
GITHUB_REGISTER_HOST=127.0.0.1
|
||||||
|
GITHUB_REGISTER_PORT=8093
|
||||||
|
GITHUB_REGISTER_USERNAME=admin
|
||||||
|
GITHUB_REGISTER_PASSWORD=change-me-to-a-strong-password
|
||||||
+66
@@ -0,0 +1,66 @@
|
|||||||
|
# === Python ===
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*.egg-info/
|
||||||
|
.eggs/
|
||||||
|
build/
|
||||||
|
dist/
|
||||||
|
.pytest_cache/
|
||||||
|
.mypy_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
.coverage
|
||||||
|
htmlcov/
|
||||||
|
|
||||||
|
# === Virtual env ===
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
env/
|
||||||
|
|
||||||
|
# === Node / frontend ===
|
||||||
|
node_modules/
|
||||||
|
frontend/node_modules/
|
||||||
|
frontend/dist/
|
||||||
|
frontend/.vite/
|
||||||
|
npm-debug.log*
|
||||||
|
|
||||||
|
# === Config (SECRETS — never commit) ===
|
||||||
|
config.json
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
|
||||||
|
# === Account output (SENSITIVE — never commit) ===
|
||||||
|
github_accounts_*.txt
|
||||||
|
github_recovery_codes.txt
|
||||||
|
github-recovery-codes*.txt
|
||||||
|
mail_credentials.txt
|
||||||
|
|
||||||
|
# === Browser profile (trust DataDome, data sensitif) ===
|
||||||
|
.browser-profile/
|
||||||
|
.datadome-trust.json
|
||||||
|
|
||||||
|
# === Playwright / step recordings (may contain personal values) ===
|
||||||
|
.playwright-mcp
|
||||||
|
playwright-report/
|
||||||
|
test-results/
|
||||||
|
blob-report/
|
||||||
|
screenshots/
|
||||||
|
artifacts/
|
||||||
|
recorded_steps.json
|
||||||
|
recorded_steps.py
|
||||||
|
*.trace.zip
|
||||||
|
*.har
|
||||||
|
|
||||||
|
# === Credentials / sertifikat ===
|
||||||
|
*.pem
|
||||||
|
*.key
|
||||||
|
*.p12
|
||||||
|
*.pfx
|
||||||
|
accounts/
|
||||||
|
regkit_codebuddy.*
|
||||||
|
|
||||||
|
# === Log & temp ===
|
||||||
|
*.log
|
||||||
|
*.tmp
|
||||||
|
.DS_Store
|
||||||
|
proxies.txt*
|
||||||
@@ -0,0 +1,483 @@
|
|||||||
|
# Resend — Style Reference
|
||||||
|
> black velvet with violet neon
|
||||||
|
|
||||||
|
**Theme:** dark
|
||||||
|
|
||||||
|
Source measurements are normalized; roles and recommendations are interpreted. Font summary lists are independent, not paired by position. HTML examples are reconstructions, not source components.
|
||||||
|
|
||||||
|
Resend lives in a near-total darkness — pure black canvas, hairline graphite borders, and white-on-black typography that feels like reading text printed on matte glass. The hero is anti-decorative: a single large serif headline at 96px Domaine next to a 3D black cube, with no gradient wash and no marketing illustration. The brand mark is a tight violet (#9281f7) that appears in email-address strings, status icons, and code samples — never on buttons. A monospaced font (Commit Mono) carries the developer identity through every code block, badge, and inline label, making the page read like a terminal wrapped in a luxury interface. Components are sharp-cornered or gently rounded (6px / 16px), low-elevation, and rely on 1px borders rather than shadows to separate layers. Motion is restrained but expressive: fade-and-slide hero text, subtle WebGL rotation on the hero cube, and short 150ms ease-out transitions on hover.
|
||||||
|
|
||||||
|
## Tokens — Colors
|
||||||
|
|
||||||
|
| Name | Value | Token | Role |
|
||||||
|
|------|-------|-------|------|
|
||||||
|
| Void Black | `#000000` | `--color-void-black` | Page background, card surfaces, overlay scrims — the entire canvas |
|
||||||
|
| Graphite Hairline | `#292d30` | `--color-graphite-hairline` | 1px borders on cards, inputs, buttons, code blocks, dividers — defines every layer separation |
|
||||||
|
| White | `#ffffff` | `--color-white` | Primary headings, hero text, button labels, icon fills on dark surfaces |
|
||||||
|
| Bone White | `#f0f0f0` | `--color-bone-white` | Body text, secondary headings, stroke outlines on icons — the primary reading color |
|
||||||
|
| Ash Gray | `#a1a4a5` | `--color-ash-gray` | Muted body text, badge labels, icon strokes — third-tier text and metadata |
|
||||||
|
| Smoke Gray | `#abafb4` | `--color-smoke-gray` | Link color, inactive button text, supporting captions — fourth-tier text |
|
||||||
|
| Iron | `#6e727a` | `--color-iron` | Subtle decorative strokes, disabled states, low-emphasis borders |
|
||||||
|
| Charcoal | `#464a4d` | `--color-charcoal` | Inline code text, muted labels — text that should disappear into the surface |
|
||||||
|
| Iris Violet | `linear-gradient(to right bottom in oklab, rgb(146, 129, 247) 0%, rgb(154, 84, 220) 100%)` | `--color-iris-violet` | Violet text accent for links, tags, and emphasized short phrases; Diagonal violet-to-magenta gradient on icon containers and brand badges |
|
||||||
|
| Iris Violet Glow | `#baa7ff` | `--color-iris-violet-glow` | Violet text accent for links, tags, and emphasized short phrases |
|
||||||
|
| Signal Blue | `#3b9eff` | `--color-signal-blue` | Blue action color for filled buttons, selected navigation states, and focused conversion moments. |
|
||||||
|
| Sky Blue | `#70b8ff` | `--color-sky-blue` | Blue text accent for links, tags, and emphasized short phrases |
|
||||||
|
| Pulse Green | `#3ad389` | `--color-pulse-green` | Green text accent for links, tags, and emphasized short phrases. Use as a supporting accent, not as a status color |
|
||||||
|
| Alarm Red | `#ff9592` | `--color-alarm-red` | Red text accent for links, tags, and emphasized short phrases. Use as a supporting accent, not as a status color |
|
||||||
|
| Crimson | `#ff6465` | `--color-crimson` | Red wash for highlight backgrounds, decorative bands, and soft emphasis behind content. Use as a supporting accent, not as a status color |
|
||||||
|
| Amber | `#ffca16` | `--color-amber` | Yellow text accent for links, tags, and emphasized short phrases. Use as a supporting accent, not as a status color |
|
||||||
|
| Amber Glow | `#ffd60a` | `--color-amber-glow` | Yellow wash for highlight backgrounds, decorative bands, and soft emphasis behind content. Use as a supporting accent, not as a status color |
|
||||||
|
| Surface Gradient | `linear-gradient(rgb(27, 27, 27), rgb(3, 3, 3))` | `--color-surface-gradient` | Subtle card-to-canvas surface lift — used in edge fades and elevated panels |
|
||||||
|
|
||||||
|
## Tokens — Typography
|
||||||
|
|
||||||
|
### Inter — Body copy, UI labels, navigation, buttons, links. The workhorse — appears 1280 times across every non-code surface. · `--font-inter`
|
||||||
|
- **Substitute:** Inter (Google Fonts), Söhne, system-ui
|
||||||
|
- **Weights:** 400, 500, 600
|
||||||
|
- **Sizes:** 12px, 14px, 16px, 18px, 24px
|
||||||
|
- **Line height:** 1.00, 1.33, 1.43, 1.50, 1.60
|
||||||
|
- **Role:** Body copy, UI labels, navigation, buttons, links. The workhorse — appears 1280 times across every non-code surface.
|
||||||
|
|
||||||
|
### Domaine — Hero display type — weight 400 at 96px with -0.01em tracking creates an editorial, almost-printed feel. Only used twice on the entire page for the largest hero statement. · `--font-domaine`
|
||||||
|
- **Substitute:** GT Sectra, Tiempos Headline, Playfair Display
|
||||||
|
- **Weights:** 400
|
||||||
|
- **Sizes:** 77px, 96px
|
||||||
|
- **Line height:** 1.00
|
||||||
|
- **Letter spacing:** -0.01em
|
||||||
|
- **OpenType features:** `"ss01", "ss04", "ss11"`
|
||||||
|
- **Role:** Hero display type — weight 400 at 96px with -0.01em tracking creates an editorial, almost-printed feel. Only used twice on the entire page for the largest hero statement.
|
||||||
|
|
||||||
|
### aBC Favorit — Section headlines and sub-headlines. The 56px weight-400 with -0.05em tracking is the signature — extreme negative tracking on a geometric sans creates a compressed, confident display feel that contrasts the editorial Domaine hero. · `--font-abc-favorit`
|
||||||
|
- **Substitute:** Inter Display, Söhne Breit, GT America
|
||||||
|
- **Weights:** 400, 500
|
||||||
|
- **Sizes:** 14px, 16px, 20px, 56px
|
||||||
|
- **Line height:** 1.00, 1.20, 1.30, 1.50
|
||||||
|
- **Letter spacing:** -0.05em at 56px, +0.025em at 14px
|
||||||
|
- **OpenType features:** `"ss01", "ss04", "ss11"; "ss01", "ss03", "ss04"`
|
||||||
|
- **Role:** Section headlines and sub-headlines. The 56px weight-400 with -0.05em tracking is the signature — extreme negative tracking on a geometric sans creates a compressed, confident display feel that contrasts the editorial Domaine hero.
|
||||||
|
|
||||||
|
### Commit Mono — Code blocks, inline code, terminal-style badges, API labels. Monospaced presence is the developer's identity signal — appears 814 times, rivaling Inter. · `--font-commit-mono`
|
||||||
|
- **Substitute:** JetBrains Mono, Berkeley Mono, IBM Plex Mono
|
||||||
|
- **Weights:** 400
|
||||||
|
- **Sizes:** 12px, 14px, 16px
|
||||||
|
- **Line height:** 1.33, 1.43, 1.50
|
||||||
|
- **Role:** Code blocks, inline code, terminal-style badges, API labels. Monospaced presence is the developer's identity signal — appears 814 times, rivaling Inter.
|
||||||
|
|
||||||
|
### Helvetica — Helvetica — detected in extracted data but not described by AI · `--font-helvetica`
|
||||||
|
- **Weights:** 400, 600, 700
|
||||||
|
- **Sizes:** 14px
|
||||||
|
- **Line height:** 1, 1.71
|
||||||
|
- **Role:** Helvetica — detected in extracted data but not described by AI
|
||||||
|
|
||||||
|
### -apple-system — -apple-system — detected in extracted data but not described by AI · `--font-apple-system`
|
||||||
|
- **Weights:** 400
|
||||||
|
- **Sizes:** 14px
|
||||||
|
- **Line height:** 1.5, 1.55
|
||||||
|
- **OpenType features:** `"liga" 0`
|
||||||
|
- **Role:** -apple-system — detected in extracted data but not described by AI
|
||||||
|
|
||||||
|
### Type Scale
|
||||||
|
|
||||||
|
| Role | Family | Weight | Size | Line Height | Letter Spacing | Token |
|
||||||
|
|------|--------|--------|------|-------------|----------------|-------|
|
||||||
|
| caption | — | — | 12px | 1.33 | 0px | `--text-caption` |
|
||||||
|
| body-sm | — | — | 14px | 1.43 | 0px | `--text-body-sm` |
|
||||||
|
| body | — | — | 16px | 1.5 | 0px | `--text-body` |
|
||||||
|
| subheading | — | — | 20px | 1 | 0px | `--text-subheading` |
|
||||||
|
| heading-sm | — | — | 24px | 1.5 | 0px | `--text-heading-sm` |
|
||||||
|
| heading | — | — | 56px | 1.2 | -2.8px | `--text-heading` |
|
||||||
|
| heading-lg | — | — | 77px | 1 | -0.77px | `--text-heading-lg` |
|
||||||
|
| display | — | — | 96px | 1 | -0.96px | `--text-display` |
|
||||||
|
|
||||||
|
## Tokens — Spacing & Shapes
|
||||||
|
|
||||||
|
**Base unit:** 4px
|
||||||
|
|
||||||
|
**Density:** comfortable
|
||||||
|
|
||||||
|
### Spacing Scale
|
||||||
|
|
||||||
|
| Name | Value | Token |
|
||||||
|
|------|-------|-------|
|
||||||
|
| 4 | 4px | `--spacing-4` |
|
||||||
|
| 8 | 8px | `--spacing-8` |
|
||||||
|
| 12 | 12px | `--spacing-12` |
|
||||||
|
| 16 | 16px | `--spacing-16` |
|
||||||
|
| 20 | 20px | `--spacing-20` |
|
||||||
|
| 24 | 24px | `--spacing-24` |
|
||||||
|
| 28 | 28px | `--spacing-28` |
|
||||||
|
| 32 | 32px | `--spacing-32` |
|
||||||
|
| 40 | 40px | `--spacing-40` |
|
||||||
|
| 48 | 48px | `--spacing-48` |
|
||||||
|
| 64 | 64px | `--spacing-64` |
|
||||||
|
| 80 | 80px | `--spacing-80` |
|
||||||
|
| 96 | 96px | `--spacing-96` |
|
||||||
|
| 104 | 104px | `--spacing-104` |
|
||||||
|
| 144 | 144px | `--spacing-144` |
|
||||||
|
|
||||||
|
### Border Radius
|
||||||
|
|
||||||
|
| Element | Value |
|
||||||
|
|---------|-------|
|
||||||
|
| cards | 16px |
|
||||||
|
| badges | 6px |
|
||||||
|
| inputs | 6px |
|
||||||
|
| buttons | 6px |
|
||||||
|
| large-panels | 24px |
|
||||||
|
|
||||||
|
### Shadows
|
||||||
|
|
||||||
|
| Name | Value | Token |
|
||||||
|
|------|-------|-------|
|
||||||
|
| subtle | `rgba(176, 199, 217, 0.145) 0px 0px 0px 1px` | `--shadow-subtle` |
|
||||||
|
| subtle-2 | `rgb(0, 0, 0) 0px 0px 0px 8px` | `--shadow-subtle-2` |
|
||||||
|
| subtle-3 | `rgba(0, 0, 0, 0.1) 0px 1px 3px 0px, rgba(0, 0, 0, 0.1) 0p...` | `--shadow-subtle-3` |
|
||||||
|
|
||||||
|
### Layout
|
||||||
|
|
||||||
|
- **Page max-width:** 1200px
|
||||||
|
- **Section gap:** 96px
|
||||||
|
- **Card padding:** 32px
|
||||||
|
- **Element gap:** 16px
|
||||||
|
|
||||||
|
## Components
|
||||||
|
|
||||||
|
### Primary Button (Ghost on Black)
|
||||||
|
**Role:** Default CTA — 'Get started', 'Log in'
|
||||||
|
|
||||||
|
Transparent background, 1px border in #292d30, white text (#ffffff), 6px radius, 12px 16px padding. Hover increases border opacity to white. This is the signature button — never filled, never colorful.
|
||||||
|
|
||||||
|
### Nav Link Button
|
||||||
|
**Role:** Top navigation items — 'Features', 'Company', 'Resources'
|
||||||
|
|
||||||
|
Transparent background, no border, text color #f0f0f0 at 14px Inter weight 400, 0px padding. Underline or color shift on hover to #ffffff.
|
||||||
|
|
||||||
|
### Text Link with Chevron
|
||||||
|
**Role:** Inline CTAs — 'Documentation', 'Get started >'
|
||||||
|
|
||||||
|
No background, no border, white or #f0f0f0 text at 16px Inter, trailing chevron icon in same color. Restrained, terminal-like.
|
||||||
|
|
||||||
|
### Hero Announcement Pill
|
||||||
|
**Role:** 'Announcing Resend Forward >' badge above hero headline
|
||||||
|
|
||||||
|
Transparent fill, 1px border in #292d30, #f0f0f0 text at 14px Inter, 9999px (pill) radius, 6px 12px padding. Small chromatic accent chevron.
|
||||||
|
|
||||||
|
### Section Card
|
||||||
|
**Role:** Content cards in feature sections and testimonial grid
|
||||||
|
|
||||||
|
Black background (#000000), 1px border in #292d30, 16px radius, 32px padding, no shadow. Cards rely on the border to separate from the black canvas.
|
||||||
|
|
||||||
|
### Testimonial Card
|
||||||
|
**Role:** Customer quote cards in 'Beyond expectations' section
|
||||||
|
|
||||||
|
Black background, 1px #292d30 border, 16px radius, 24px padding. Contains quoted text at 16px Inter, avatar (32px circle), name at 14px weight 500 in #f0f0f0, role/title in #a1a4a5.
|
||||||
|
|
||||||
|
### Code Block / Terminal Window
|
||||||
|
**Role:** Developer-facing code snippets and API examples
|
||||||
|
|
||||||
|
Black background, 1px #292d30 border, 16px radius, Commit Mono at 12-14px. Syntax highlighting uses #9281f7 for strings/keywords, #3b9eff for filenames, #3ad389 for success values, #ff9592 for errors. Optional traffic-light dots in top-left for terminal aesthetic.
|
||||||
|
|
||||||
|
### Logo Grid
|
||||||
|
**Role:** Customer logos — Warner Bros, Max, Raycast, etc.
|
||||||
|
|
||||||
|
Inline-display logos at their native colors on black canvas, centered in a 4-column grid with 60px row gap. No card wrappers, no labels — just the marks breathing against black.
|
||||||
|
|
||||||
|
### Status Indicator Dot
|
||||||
|
**Role:** Email event status — delivered, opened, clicked, bounced, complained
|
||||||
|
|
||||||
|
2-3px diameter filled dot, no border, paired with label text in Commit Mono. Colors map to semantics: #3ad389 delivered, #70b8ff opened, #baa7ff clicked, #ff9592 bounced, #ffca16 complained.
|
||||||
|
|
||||||
|
### Email Address Badge
|
||||||
|
**Role:** 'from:' addresses in code samples and UI
|
||||||
|
|
||||||
|
No background, Commit Mono at 12-14px, text color #9281f7 (Iris Violet). The violet-on-black makes email identifiers the most readable code element — a deliberate developer-UX choice.
|
||||||
|
|
||||||
|
### Icon Container
|
||||||
|
**Role:** Rounded-square containers for app icons in integrations grid
|
||||||
|
|
||||||
|
32x32 or 48x48 rounded square (16px radius), subtle gradient fill (oklab violet→magenta), white or violet stroke icon inside. Creates the only chromatic surface on the page.
|
||||||
|
|
||||||
|
### 3D Hero Cube
|
||||||
|
**Role:** WebGL-rendered black geometric cube in hero
|
||||||
|
|
||||||
|
Full-opacity black cube with subtle edge highlights in #292d30, rotating slowly. No glow, no color — a sculptural object that anchors the right side of the hero against the black canvas.
|
||||||
|
|
||||||
|
### Footer Link Row
|
||||||
|
**Role:** Minimal footer with two text links
|
||||||
|
|
||||||
|
Two text links ('Privacy', 'Terms') at 14px Inter in #a1a4a5, separated by space, no decorative elements. Footer is intentionally minimal — no logo, no columns.
|
||||||
|
|
||||||
|
## Do's and Don'ts
|
||||||
|
|
||||||
|
### Do
|
||||||
|
- Use pure #000000 as the page canvas — never off-black or tinted dark grays for the background.
|
||||||
|
- Separate all UI layers with 1px borders in #292d30, not shadows. Cards, inputs, code blocks all rely on hairline borders against the black canvas.
|
||||||
|
- Use Commit Mono for any code, email address, or developer-facing string. Keep Inter for prose and UI chrome.
|
||||||
|
- Keep buttons ghost/outlined: transparent fill, 1px border, white text. Never use a filled colorful button as the primary CTA.
|
||||||
|
- Use 6px radius for buttons, badges, inputs. Use 16px radius for cards and code windows. Never mix — the radius scale is two values.
|
||||||
|
- Let Iris Violet (#9281f7) mark code strings and developer identifiers. It is the only brand color and should feel like syntax highlighting, not decoration.
|
||||||
|
- Apply tight -0.05em letter-spacing at 56px display sizes and -0.01em at 96px hero sizes. The compressed tracking is what makes the headlines feel confident.
|
||||||
|
|
||||||
|
### Don't
|
||||||
|
- Don't add gradients, glows, or chromatic washes to the hero or section backgrounds. The canvas is flat black.
|
||||||
|
- Don't use filled accent-color buttons (blue, violet, green) as primary actions. Buttons stay ghost or white-text-on-black.
|
||||||
|
- Don't use multiple border radii on a single surface. Cards are 16px, buttons/badges/inputs are 6px — pick one per component.
|
||||||
|
- Don't introduce colored card backgrounds. Cards sit on black with hairline borders; no #292d30 fills.
|
||||||
|
- Don't use shadows for elevation. The design relies on 1px borders and subtle backdrop blurs, not drop shadows.
|
||||||
|
- Don't pair Iris Violet with large type as a decorative heading color. It belongs to code and developer identifiers only.
|
||||||
|
- Don't break the monochrome-with-one-violet discipline by adding multiple accent hues to UI chrome. The status colors (green, blue, red, amber) are reserved for data/status indicators.
|
||||||
|
|
||||||
|
## Surfaces
|
||||||
|
|
||||||
|
| Level | Name | Value | Purpose |
|
||||||
|
|-------|------|-------|---------|
|
||||||
|
| 0 | Void | `#000000` | Primary page canvas, full-bleed black |
|
||||||
|
| 1 | Graphite | `#292d30` | Hairline borders defining card and input surfaces against the void |
|
||||||
|
| 2 | Surface Lift | `#0b0e14` | Elevated panels and overlay scrims via subtle gradient |
|
||||||
|
| 3 | Backdrop Blur | `#000000f2` | Modal and navigation overlays with blur(25px) |
|
||||||
|
|
||||||
|
## Elevation
|
||||||
|
|
||||||
|
Elevation is achieved through 1px hairline borders (#292d30) against a flat black canvas, never through drop shadows. The only shadow token in active use is a faint 1px ring (rgba(176, 199, 217, 0.145)) on icon containers, used sparingly to suggest a subtle light source rather than depth.
|
||||||
|
|
||||||
|
## Imagery
|
||||||
|
|
||||||
|
Imagery is almost entirely WebGL-rendered 3D objects (black cube in hero, rotating geometric forms) and inline product UI screenshots shown inside dark code windows. No photography, no illustrations, no lifestyle imagery. Logos in the trust bar are inline SVGs at native colors. Icons are 1px-1.5px stroke outlines in #f0f0f0 or #a1a4a5. The visual language is: black canvas, 3D object as hero anchor, dark code windows as product proof, white SVG logos as social proof. Nothing decorative — every visual element is either structural (cube) or demonstrative (code window, logo).
|
||||||
|
|
||||||
|
## Agent Prompt Guide
|
||||||
|
|
||||||
|
Quick Color Reference:
|
||||||
|
- text/heading: #ffffff
|
||||||
|
- text/body: #f0f0f0
|
||||||
|
- text/muted: #a1a4a5
|
||||||
|
- background/canvas: #000000
|
||||||
|
- border/hairline: #292d30
|
||||||
|
- accent/code: #9281f7
|
||||||
|
- primary action: #3b9eff (filled action)
|
||||||
|
|
||||||
|
3-5 Example Component Prompts:
|
||||||
|
|
||||||
|
1. Create a section headline: 'Integrate tonight' at 56px aBCFavorit weight 400, color #ffffff, letter-spacing -2.8px, line-height 1.2. Below it, body copy at 18px Inter weight 400, color #a1a4a5. Section sits on a #000000 canvas with no border.
|
||||||
|
|
||||||
|
2. Create a code terminal window: #000000 background, 1px border in #292d30, 16px radius, padding 24px. Content in Commit Mono at 14px. Email address strings colored #9281f7, keywords colored #f0f0f0, success values colored #3ad389. Optional 3 traffic-light dots (8px circles) in top-left.
|
||||||
|
|
||||||
|
3. Create a navigation bar: transparent background, Resend wordmark logo on left (white), nav items ('Features', 'Company', 'Resources') in Inter 14px weight 400, color #f0f0f0. On the right, a 'Get started' button — transparent fill, 1px border in #292d30, white text, 6px radius, 8px 16px padding. The bar sits on #000000 with no separator.
|
||||||
|
|
||||||
|
4. Create a testimonial card: #000000 background, 1px border in #292d30, 16px radius, 32px padding. Quote text in Inter 16px weight 400, color #f0f0f0. Below: 32px circular avatar, name in Inter 14px weight 500 #f0f0f0, role/title in #a1a4a5. No shadow.
|
||||||
|
|
||||||
|
5. Create a status indicator row: inline pill with a 2px circle dot in #3ad389 followed by 'Delivered' label in Commit Mono 12px, color #a1a4a5. Dot indicates email event status. No background, no border, sits inline within a dark code window.
|
||||||
|
|
||||||
|
## Similar Brands
|
||||||
|
|
||||||
|
- **Linear** — Same black-canvas, hairline-border aesthetic with restrained chromatic accents and sharp typography
|
||||||
|
- **Vercel** — Near-identical pure-black backgrounds with white typography and minimal border-based elevation
|
||||||
|
- **Plaid** — Dark-mode developer-tool identity with monospaced code emphasis and single-accent palette
|
||||||
|
- **Railway** — Black canvas with terminal-style code windows as the primary product showcase
|
||||||
|
- **Stripe (dark mode)** — Editorially confident display type on black with hairline borders and ghost buttons
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
### CSS Custom Properties
|
||||||
|
|
||||||
|
```css
|
||||||
|
:root {
|
||||||
|
/* Colors */
|
||||||
|
--color-void-black: #000000;
|
||||||
|
--color-graphite-hairline: #292d30;
|
||||||
|
--color-white: #ffffff;
|
||||||
|
--color-bone-white: #f0f0f0;
|
||||||
|
--color-ash-gray: #a1a4a5;
|
||||||
|
--color-smoke-gray: #abafb4;
|
||||||
|
--color-iron: #6e727a;
|
||||||
|
--color-charcoal: #464a4d;
|
||||||
|
--color-iris-violet: #9281f7;
|
||||||
|
--gradient-iris-violet: linear-gradient(to right bottom in oklab, rgb(146, 129, 247) 0%, rgb(154, 84, 220) 100%);
|
||||||
|
--color-iris-violet-glow: #baa7ff;
|
||||||
|
--color-signal-blue: #3b9eff;
|
||||||
|
--color-sky-blue: #70b8ff;
|
||||||
|
--color-pulse-green: #3ad389;
|
||||||
|
--color-alarm-red: #ff9592;
|
||||||
|
--color-crimson: #ff6465;
|
||||||
|
--color-amber: #ffca16;
|
||||||
|
--color-amber-glow: #ffd60a;
|
||||||
|
--color-surface-gradient: #0b0e14;
|
||||||
|
--gradient-surface-gradient: linear-gradient(rgb(27, 27, 27), rgb(3, 3, 3));
|
||||||
|
|
||||||
|
/* Typography — Font Families */
|
||||||
|
--font-inter: 'Inter', ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||||
|
--font-domaine: 'Domaine', ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||||
|
--font-abc-favorit: 'aBC Favorit', ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||||
|
--font-commit-mono: 'Commit Mono', ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||||
|
--font-helvetica: 'Helvetica', ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||||
|
--font-apple-system: '-apple-system', ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||||
|
|
||||||
|
/* Typography — Scale */
|
||||||
|
--text-caption: 12px;
|
||||||
|
--leading-caption: 1.33;
|
||||||
|
--tracking-caption: 0px;
|
||||||
|
--text-body-sm: 14px;
|
||||||
|
--leading-body-sm: 1.43;
|
||||||
|
--tracking-body-sm: 0px;
|
||||||
|
--text-body: 16px;
|
||||||
|
--leading-body: 1.5;
|
||||||
|
--tracking-body: 0px;
|
||||||
|
--text-subheading: 20px;
|
||||||
|
--leading-subheading: 1;
|
||||||
|
--tracking-subheading: 0px;
|
||||||
|
--text-heading-sm: 24px;
|
||||||
|
--leading-heading-sm: 1.5;
|
||||||
|
--tracking-heading-sm: 0px;
|
||||||
|
--text-heading: 56px;
|
||||||
|
--leading-heading: 1.2;
|
||||||
|
--tracking-heading: -2.8px;
|
||||||
|
--text-heading-lg: 77px;
|
||||||
|
--leading-heading-lg: 1;
|
||||||
|
--tracking-heading-lg: -0.77px;
|
||||||
|
--text-display: 96px;
|
||||||
|
--leading-display: 1;
|
||||||
|
--tracking-display: -0.96px;
|
||||||
|
|
||||||
|
/* Typography — Weights */
|
||||||
|
--font-weight-regular: 400;
|
||||||
|
--font-weight-medium: 500;
|
||||||
|
--font-weight-semibold: 600;
|
||||||
|
--font-weight-bold: 700;
|
||||||
|
|
||||||
|
/* Spacing */
|
||||||
|
--spacing-unit: 4px;
|
||||||
|
--spacing-4: 4px;
|
||||||
|
--spacing-8: 8px;
|
||||||
|
--spacing-12: 12px;
|
||||||
|
--spacing-16: 16px;
|
||||||
|
--spacing-20: 20px;
|
||||||
|
--spacing-24: 24px;
|
||||||
|
--spacing-28: 28px;
|
||||||
|
--spacing-32: 32px;
|
||||||
|
--spacing-40: 40px;
|
||||||
|
--spacing-48: 48px;
|
||||||
|
--spacing-64: 64px;
|
||||||
|
--spacing-80: 80px;
|
||||||
|
--spacing-96: 96px;
|
||||||
|
--spacing-104: 104px;
|
||||||
|
--spacing-144: 144px;
|
||||||
|
|
||||||
|
/* Layout */
|
||||||
|
--page-max-width: 1200px;
|
||||||
|
--section-gap: 96px;
|
||||||
|
--card-padding: 32px;
|
||||||
|
--element-gap: 16px;
|
||||||
|
|
||||||
|
/* Border Radius */
|
||||||
|
--radius-md: 6px;
|
||||||
|
--radius-lg: 10px;
|
||||||
|
--radius-2xl: 16px;
|
||||||
|
--radius-3xl: 24px;
|
||||||
|
|
||||||
|
/* Named Radii */
|
||||||
|
--radius-cards: 16px;
|
||||||
|
--radius-badges: 6px;
|
||||||
|
--radius-inputs: 6px;
|
||||||
|
--radius-buttons: 6px;
|
||||||
|
--radius-large-panels: 24px;
|
||||||
|
|
||||||
|
/* Shadows */
|
||||||
|
--shadow-subtle: rgba(176, 199, 217, 0.145) 0px 0px 0px 1px;
|
||||||
|
--shadow-subtle-2: rgb(0, 0, 0) 0px 0px 0px 8px;
|
||||||
|
--shadow-subtle-3: rgba(0, 0, 0, 0.1) 0px 1px 3px 0px, rgba(0, 0, 0, 0.1) 0px 1px 2px -1px;
|
||||||
|
|
||||||
|
/* Surfaces */
|
||||||
|
--surface-void: #000000;
|
||||||
|
--surface-graphite: #292d30;
|
||||||
|
--surface-surface-lift: #0b0e14;
|
||||||
|
--surface-backdrop-blur: #000000f2;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Tailwind v4
|
||||||
|
|
||||||
|
```css
|
||||||
|
@theme {
|
||||||
|
/* Colors */
|
||||||
|
--color-void-black: #000000;
|
||||||
|
--color-graphite-hairline: #292d30;
|
||||||
|
--color-white: #ffffff;
|
||||||
|
--color-bone-white: #f0f0f0;
|
||||||
|
--color-ash-gray: #a1a4a5;
|
||||||
|
--color-smoke-gray: #abafb4;
|
||||||
|
--color-iron: #6e727a;
|
||||||
|
--color-charcoal: #464a4d;
|
||||||
|
--color-iris-violet: #9281f7;
|
||||||
|
--color-iris-violet-glow: #baa7ff;
|
||||||
|
--color-signal-blue: #3b9eff;
|
||||||
|
--color-sky-blue: #70b8ff;
|
||||||
|
--color-pulse-green: #3ad389;
|
||||||
|
--color-alarm-red: #ff9592;
|
||||||
|
--color-crimson: #ff6465;
|
||||||
|
--color-amber: #ffca16;
|
||||||
|
--color-amber-glow: #ffd60a;
|
||||||
|
--color-surface-gradient: #0b0e14;
|
||||||
|
|
||||||
|
/* Typography */
|
||||||
|
--font-inter: 'Inter', ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||||
|
--font-domaine: 'Domaine', ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||||
|
--font-abc-favorit: 'aBC Favorit', ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||||
|
--font-commit-mono: 'Commit Mono', ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||||
|
--font-helvetica: 'Helvetica', ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||||
|
--font-apple-system: '-apple-system', ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||||
|
|
||||||
|
/* Typography — Scale */
|
||||||
|
--text-caption: 12px;
|
||||||
|
--leading-caption: 1.33;
|
||||||
|
--tracking-caption: 0px;
|
||||||
|
--text-body-sm: 14px;
|
||||||
|
--leading-body-sm: 1.43;
|
||||||
|
--tracking-body-sm: 0px;
|
||||||
|
--text-body: 16px;
|
||||||
|
--leading-body: 1.5;
|
||||||
|
--tracking-body: 0px;
|
||||||
|
--text-subheading: 20px;
|
||||||
|
--leading-subheading: 1;
|
||||||
|
--tracking-subheading: 0px;
|
||||||
|
--text-heading-sm: 24px;
|
||||||
|
--leading-heading-sm: 1.5;
|
||||||
|
--tracking-heading-sm: 0px;
|
||||||
|
--text-heading: 56px;
|
||||||
|
--leading-heading: 1.2;
|
||||||
|
--tracking-heading: -2.8px;
|
||||||
|
--text-heading-lg: 77px;
|
||||||
|
--leading-heading-lg: 1;
|
||||||
|
--tracking-heading-lg: -0.77px;
|
||||||
|
--text-display: 96px;
|
||||||
|
--leading-display: 1;
|
||||||
|
--tracking-display: -0.96px;
|
||||||
|
|
||||||
|
/* Spacing */
|
||||||
|
--spacing-4: 4px;
|
||||||
|
--spacing-8: 8px;
|
||||||
|
--spacing-12: 12px;
|
||||||
|
--spacing-16: 16px;
|
||||||
|
--spacing-20: 20px;
|
||||||
|
--spacing-24: 24px;
|
||||||
|
--spacing-28: 28px;
|
||||||
|
--spacing-32: 32px;
|
||||||
|
--spacing-40: 40px;
|
||||||
|
--spacing-48: 48px;
|
||||||
|
--spacing-64: 64px;
|
||||||
|
--spacing-80: 80px;
|
||||||
|
--spacing-96: 96px;
|
||||||
|
--spacing-104: 104px;
|
||||||
|
--spacing-144: 144px;
|
||||||
|
|
||||||
|
/* Border Radius */
|
||||||
|
--radius-md: 6px;
|
||||||
|
--radius-lg: 10px;
|
||||||
|
--radius-2xl: 16px;
|
||||||
|
--radius-3xl: 24px;
|
||||||
|
|
||||||
|
/* Shadows */
|
||||||
|
--shadow-subtle: rgba(176, 199, 217, 0.145) 0px 0px 0px 1px;
|
||||||
|
--shadow-subtle-2: rgb(0, 0, 0) 0px 0px 0px 8px;
|
||||||
|
--shadow-subtle-3: rgba(0, 0, 0, 0.1) 0px 1px 3px 0px, rgba(0, 0, 0, 0.1) 0px 1px 2px -1px;
|
||||||
|
}
|
||||||
|
```
|
||||||
+44
@@ -0,0 +1,44 @@
|
|||||||
|
# ---------- stage 1: build frontend (alpine) ----------
|
||||||
|
FROM node:20-alpine AS frontend
|
||||||
|
WORKDIR /build
|
||||||
|
COPY frontend/package*.json ./
|
||||||
|
RUN npm ci --no-audit --no-fund
|
||||||
|
COPY frontend/ ./
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# ---------- stage 2: runtime (debian slim: glibc needed for Firefox/Camoufox) ----------
|
||||||
|
FROM python:3.12-slim-bookworm AS runtime
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
PYTHONUNBUFFERED=1 \
|
||||||
|
PIP_NO_CACHE_DIR=1 \
|
||||||
|
GITHUB_REGISTER_HOST=0.0.0.0 \
|
||||||
|
GITHUB_REGISTER_PORT=8093
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Deps Firefox headful/headless + virtual display + healthcheck.
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
ca-certificates curl xvfb \
|
||||||
|
libgtk-3-0 libdbus-glib-1-2 libxt6 libasound2 \
|
||||||
|
libnss3 libxss1 libxrandr2 libxcomposite1 libxdamage1 libxfixes3 \
|
||||||
|
libpango-1.0-0 libcairo2 libatk1.0-0 libatk-bridge2.0-0 \
|
||||||
|
libcups2 libdrm2 libxkbcommon0 libgbm1 fonts-liberation \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY requirements.txt ./
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
# Wajib sukses: unduh browser Camoufox sekali saat build (bukan tiap start).
|
||||||
|
RUN python -m camoufox fetch
|
||||||
|
|
||||||
|
COPY github_register/ ./github_register/
|
||||||
|
COPY web/ ./web/
|
||||||
|
COPY main.py proxy_rotator.py config.example.json ./
|
||||||
|
|
||||||
|
COPY --from=frontend /build/dist ./frontend/dist
|
||||||
|
|
||||||
|
EXPOSE 8093
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --retries=3 --start-period=20s \
|
||||||
|
CMD curl -fsS http://127.0.0.1:8093/health || exit 1
|
||||||
|
|
||||||
|
# config.json is mounted from the host (see compose); fall back to the example if forgotten.
|
||||||
|
CMD ["sh", "-c", "test -f config.json || cp config.example.json config.json; exec python -m web.server"]
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 mhiqrambg
|
||||||
|
|
||||||
|
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.
|
||||||
@@ -0,0 +1,475 @@
|
|||||||
|
# GH-RegKit Prime
|
||||||
|
|
||||||
|
Full-stack GitHub account autoreg farm: **Camoufox anti-detect browser + free
|
||||||
|
mail.cx mailboxes + FREE multi-LLM Arkose FunCaptcha solver + proxy pool
|
||||||
|
rotator + web dashboard**. Runs at $0 per account.
|
||||||
|
|
||||||
|
> Telegram-канал: [@alstack](https://t.me/alstack) — апдейты, новые тулзы, разборы.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
| Feature | **Prime** |
|
||||||
|
|---|---|
|
||||||
|
| Signup flow | single-page form | **multi-step wizard** (email → Continue → password → Continue → username → Create account) |
|
||||||
|
| Arkose FunCaptcha | none | **multi-model LLM voting solver** — sequence / rotate / character / wires |
|
||||||
|
| Captcha cost | — | **$0** — qwen3-vl-flash + qwen-vl-max + qwen-vl-plus vote in parallel (~1-3 s each) via any OpenAI-compatible vision gateway |
|
||||||
|
| Dashboard | config/jobs/logs/accounts/TOTP | same + captcha toggles (`solve_captcha`, `captcha_max_rounds`) + `create_pat` |
|
||||||
|
| Warm-up | none | **homepage dwell + JS-scroll warm-up** — fixes `suspended` accounts |
|
||||||
|
| PAT farming | none | **stage 6: classic PAT** (repo+workflow scopes) appended to the account row |
|
||||||
|
| Knowledge base | — | [`docs/AUTOREG-KNOWLEDGE.md`](docs/AUTOREG-KNOWLEDGE.md) — every field-verified fact about GitHub autoreg |
|
||||||
|
|
||||||
|
### How the free captcha solver works
|
||||||
|
|
||||||
|
1. After **Create account**, Arkose FunCaptcha appears in an `octocaptcha.com`
|
||||||
|
iframe (~16 s PoW, then "Visual puzzle").
|
||||||
|
2. Solver clicks Visual puzzle, detects the variant, screenshots reference +
|
||||||
|
all candidates, stitches a numbered grid, enhances with PIL.
|
||||||
|
3. Grid + variant prompt go to 3+ vision models **in parallel** (55 s
|
||||||
|
deadline); each answers `ANSWER=<n>`; majority wins.
|
||||||
|
4. Navigates to the winning candidate → Submit → repeats rounds until
|
||||||
|
octocaptcha disappears (= passed). Annotated `REVIEW_rN.png` per round.
|
||||||
|
|
||||||
|
### Vision gateway (free default)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
set VOTE_BASE=http://127.0.0.1:16432/v1 # any OpenAI-compatible vision gateway
|
||||||
|
set VOTE_KEY=***
|
||||||
|
set VOTE_MODELS=qwen3-vl-flash,qwen-vl-max,qwen-vl-plus
|
||||||
|
```
|
||||||
|
|
||||||
|
Works with OpenRouter, Aurora, one-api/new-api, LiteLLM — anything accepting
|
||||||
|
`image_url` content parts.
|
||||||
|
|
||||||
|
### Pitfalls (field-learned)
|
||||||
|
|
||||||
|
- Headful by default — headless is a DataDome/Picasso tell.
|
||||||
|
- One sticky exit IP per account; mid-session IP rotation flags DataDome.
|
||||||
|
- `character` variant on round 0 → `SKIP_VARIANT`, window reloads for a new
|
||||||
|
challenge (models can't reach consensus on it).
|
||||||
|
- Accounts created WITHOUT passing octocaptcha are born-locked. Never
|
||||||
|
force-submit a disabled Create account button.
|
||||||
|
- GitHub secondary rate limits last hours — stop, don't hammer.
|
||||||
|
- Windows: run with `PYTHONPATH=""` if another env pollutes imports.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# GitHub Register
|
||||||
|
|
||||||
|
A GitHub account registration toolkit that uses Camoufox for browser automation
|
||||||
|
and mail.cx (free, default), [Litensi](https://litensi.id) (paid), [temp.tf](https://temp.tf)
|
||||||
|
(free gmail/outlook/hotmail alias pool, no keys), or your own Gmail / Outlook
|
||||||
|
mailbox (IMAP +alias, unlimited addresses) for verification mailboxes. It can be run from the CLI, through a local web
|
||||||
|
console, or as a Docker service behind an nginx reverse proxy.
|
||||||
|
|
||||||
|
> Use this only for accounts and workflows you are authorized to manage.
|
||||||
|
> Automated account registration may violate GitHub's Terms of Service and can
|
||||||
|
> result in account or IP restrictions.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Creates a mailbox, password, and username for GitHub signup. Mail providers:
|
||||||
|
mail.cx (free), temp.tf (free, shared gmail/outlook/hotmail alias pool, no
|
||||||
|
keys needed), Litensi (paid), Gmail or Outlook via IMAP — one real mailbox,
|
||||||
|
unlimited `base+random@domain` aliases, App Password auth.
|
||||||
|
- Verifies the eight-digit GitHub launch code from the mailbox.
|
||||||
|
- Logs in again when a newly verified account is redirected to `/login`.
|
||||||
|
- Optionally creates a first repository, enables TOTP 2FA, and stores recovery
|
||||||
|
codes per account.
|
||||||
|
- Optionally sets a profile status and completes profile fields after 2FA.
|
||||||
|
- Provides a web console for configuration, job control, live logs, account
|
||||||
|
export, TOTP generation, and recovery-code viewing.
|
||||||
|
- Works on desktop and mobile: the console reflows to a bottom navigation bar
|
||||||
|
and a drawer on phones.
|
||||||
|
- Organizes accounts into groups, merges account files into one, and exports
|
||||||
|
accounts as TXT, CSV, or JSON.
|
||||||
|
- Reorders a Litensi mailbox from the console to fetch a fresh code, capped at
|
||||||
|
two minutes with a manual stop.
|
||||||
|
- Protects the console with username + password auth (rate-limited,
|
||||||
|
server-side sessions) for self-hosting.
|
||||||
|
|
||||||
|
<img src="docs/dashboard_status.png" alt="Web console — Status page with live streaming log" width="880">
|
||||||
|
|
||||||
|
<img src="docs/dashboard_config_gmail.png" alt="Web console — mail provider config with Gmail +alias" width="880">
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
- Python 3.11 or newer.
|
||||||
|
- Node.js 18 or newer, only to rebuild the frontend.
|
||||||
|
- A mailbox provider: mail.cx works out of the box (free, default). For the
|
||||||
|
Litensi provider, a Litensi account with API credentials and a balance. For
|
||||||
|
Gmail/Outlook providers: an account with IMAP enabled and an App Password
|
||||||
|
(Google: 2FA on → App Passwords; Outlook: alias/plus-addressing enabled).
|
||||||
|
- Internet access. A residential proxy may be needed depending on your network.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone <repository-url> github-regkit
|
||||||
|
cd github-regkit
|
||||||
|
|
||||||
|
python3 -m venv .venv
|
||||||
|
source .venv/bin/activate
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
# Download Camoufox once.
|
||||||
|
python -m camoufox fetch
|
||||||
|
|
||||||
|
# Create local configuration.
|
||||||
|
cp config.example.json config.json
|
||||||
|
```
|
||||||
|
|
||||||
|
On Windows PowerShell:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv\Scripts\Activate.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
### Linux (Ubuntu/Debian)
|
||||||
|
|
||||||
|
Headful mode (`headless: false`) needs a display plus the Firefox system
|
||||||
|
libraries. On a desktop these are usually already installed; on a minimal
|
||||||
|
server install them and run inside a virtual display:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Ubuntu 22.04
|
||||||
|
sudo apt update
|
||||||
|
sudo apt install -y libgtk-3-0 libdbus-glib-1-2 libxt6 libasound2 xvfb
|
||||||
|
|
||||||
|
# Ubuntu 24.04 uses libasound2t64 instead of libasound2
|
||||||
|
sudo apt install -y libgtk-3-0 libdbus-glib-1-2 libxt6 libasound2t64 xvfb
|
||||||
|
|
||||||
|
# headless VPS — wrap headful runs with a virtual display
|
||||||
|
xvfb-run -a python main.py --count 1
|
||||||
|
```
|
||||||
|
|
||||||
|
For unattended servers, `headless: true` (or `python main.py --headless`)
|
||||||
|
works without a display, though it is slightly more likely to be flagged by
|
||||||
|
DataDome.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
Set your local values in `config.json`. This file must never be committed.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"mail_provider": "mailcx",
|
||||||
|
"mailcx_domain": "",
|
||||||
|
"litensi_api_id": "1234",
|
||||||
|
"litensi_api_key": "your-api-key",
|
||||||
|
"litensi_site": "github.com",
|
||||||
|
"litensi_zone": "",
|
||||||
|
"imap_user": "yourbox@gmail.com",
|
||||||
|
"imap_password": "your-app-password",
|
||||||
|
"imap_host": "",
|
||||||
|
"imap_port": 993,
|
||||||
|
"imap_alias_domain": "",
|
||||||
|
"temptf_providers": "gmail.com,outlook.com,hotmail.com,high.edu.pl",
|
||||||
|
"temptf_dot": true,
|
||||||
|
"temptf_plus": true,
|
||||||
|
"register_count": 1,
|
||||||
|
"proxy": "",
|
||||||
|
"proxy_file": "",
|
||||||
|
"headless": false,
|
||||||
|
"delay_sec": 5.0,
|
||||||
|
"max_username_tries": 6,
|
||||||
|
"otp_timeout_sec": 240,
|
||||||
|
"browser_profile_dir": ".browser-profile",
|
||||||
|
"fresh_profile": true,
|
||||||
|
"proxy_hard_block_retries": 2,
|
||||||
|
"proxy_rate_limit_retries": 2,
|
||||||
|
"create_repo": true,
|
||||||
|
"repo_name": "hello",
|
||||||
|
"enable_2fa": true,
|
||||||
|
"set_profile_status": true,
|
||||||
|
"profile_status": "On vacation",
|
||||||
|
"complete_profile": true,
|
||||||
|
"profile_name": "",
|
||||||
|
"profile_bio": "",
|
||||||
|
"profile_location": ""
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field | Description |
|
||||||
|
| --- | --- |
|
||||||
|
| `mail_provider` | Mail backend: `mailcx` (free, default) or `litensi` (paid, more reliable). |
|
||||||
|
| `mailcx_domain` | Mail.cx domain. Leave blank to auto-pick from available domains. |
|
||||||
|
| `litensi_api_id` / `litensi_api_key` | Litensi API credentials (used when `mail_provider` is `litensi`). |
|
||||||
|
| `litensi_site` | Sender domain in Litensi, for example `github.com`. |
|
||||||
|
| `litensi_zone` | Mailbox zone. Leave blank to choose the cheapest in-stock zone. |
|
||||||
|
| `register_count` | Accounts to process in one job. |
|
||||||
|
| `proxy` | Optional single proxy in `http://user:pass@host:port` format. |
|
||||||
|
| `proxy_file` | Optional proxy pool file in the project root (one `scheme://user:pass@host:port` per line). Each account picks a random proxy; also settable via the web console upload. Takes precedence over `proxy`. |
|
||||||
|
| `headless` | Runs without a browser window. `false` is easier to observe and often more stable. |
|
||||||
|
| `delay_sec` | Delay between accounts. |
|
||||||
|
| `max_username_tries` | Username conflict retry limit. |
|
||||||
|
| `otp_timeout_sec` | Maximum wait time for the verification email. |
|
||||||
|
| `browser_profile_dir` | Persistent browser profile directory (trust cookies are carried separately, so fresh profiles still pass DataDome). |
|
||||||
|
| `fresh_profile` | Uses a fresh browser profile for each account while carrying trusted cookies separately. |
|
||||||
|
| `create_repo` / `repo_name` | Enables and names the first repository. |
|
||||||
|
| `enable_2fa` | Enables TOTP 2FA and captures recovery codes. |
|
||||||
|
| `set_profile_status` / `profile_status` | Enables and sets a post-2FA profile status. |
|
||||||
|
| `complete_profile` | Enables post-2FA profile completion. |
|
||||||
|
| `profile_name`, `profile_bio`, `profile_location` | Custom profile values. Blank fields use Random User or ZenQuotes data. |
|
||||||
|
|
||||||
|
## Running
|
||||||
|
|
||||||
|
### Web console
|
||||||
|
|
||||||
|
Build the UI after frontend changes:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd frontend
|
||||||
|
npm install
|
||||||
|
npm run build
|
||||||
|
cd ..
|
||||||
|
```
|
||||||
|
|
||||||
|
Start the local server:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
source .venv/bin/activate
|
||||||
|
python -m web.server
|
||||||
|
```
|
||||||
|
|
||||||
|
Open <http://127.0.0.1:8093>.
|
||||||
|
|
||||||
|
- **Status**: start or stop jobs and inspect progress.
|
||||||
|
- **Live Log**: review events in real time.
|
||||||
|
- **Config**: edit local settings, check Litensi zones (with a zone search),
|
||||||
|
and check mail.cx domains.
|
||||||
|
- **Accounts**: copy or export accounts (TXT / CSV / JSON), generate TOTP
|
||||||
|
codes, view recovery codes, resend a Litensi mailbox code, merge one account
|
||||||
|
file into another, and organize accounts into groups. Each row has an actions
|
||||||
|
menu for group, copy, 2FA, recovery, resend, and delete.
|
||||||
|
|
||||||
|
The console is responsive: the sidebar collapses to an icon rail on narrow
|
||||||
|
laptops, and on phones it switches to a top bar, a bottom navigation bar, and a
|
||||||
|
slide-in drawer, with account rows reflowed into cards.
|
||||||
|
|
||||||
|
### Resend mailbox code
|
||||||
|
|
||||||
|
**Accounts → row actions → Resend mailbox code** reorders the same Litensi
|
||||||
|
mailbox and polls its status until a new GitHub code arrives or two minutes
|
||||||
|
pass. It stops automatically at the cap, and the dialog has a Stop button for
|
||||||
|
an early abort. Reorder needs only the API credentials from `config.json` and
|
||||||
|
the email stored in the accounts file, so no extra metadata is kept. The
|
||||||
|
provider validates ownership of the email, so an address that was not ordered
|
||||||
|
on this Litensi account fails with `ACTIVATION DOES NOT EXIST`.
|
||||||
|
|
||||||
|
Protect the web console with username + password (like n8n/WAHA) for
|
||||||
|
self-hosting/production. Copy `.env.example` to `.env` and fill it in
|
||||||
|
(`.env` is git-ignored; server auto-loads it, no extra dependency):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
python -m web.server
|
||||||
|
```
|
||||||
|
|
||||||
|
```dotenv
|
||||||
|
GITHUB_REGISTER_HOST=127.0.0.1
|
||||||
|
GITHUB_REGISTER_PORT=8093
|
||||||
|
GITHUB_REGISTER_USERNAME=admin
|
||||||
|
GITHUB_REGISTER_PASSWORD=use-a-strong-password
|
||||||
|
```
|
||||||
|
|
||||||
|
Legacy single-password mode still works (`GITHUB_REGISTER_ACCESS_PASSWORD`),
|
||||||
|
but username+password is preferred. When auth is enabled, the API docs page
|
||||||
|
is disabled and every API route requires login. Login attempts are rate-limited
|
||||||
|
per IP (10 failures/60s → HTTP 429), oversized login bodies are rejected
|
||||||
|
(413), credential comparison is timing-safe, security headers are set
|
||||||
|
(`nosniff`, `DENY` framing, `no-referrer`, `no-store` on APIs),
|
||||||
|
and Sign out invalidates the server-side session.
|
||||||
|
The server binds to `127.0.0.1` by default — only bind `0.0.0.0` behind a trusted reverse proxy with HTTPS.
|
||||||
|
|
||||||
|
To open the console from another device on the same network (phone, tablet),
|
||||||
|
set `GITHUB_REGISTER_HOST=0.0.0.0` in `.env`, restart the server, then browse to
|
||||||
|
`http://<your-lan-ip>:8093` from the other device. Always set a strong
|
||||||
|
`GITHUB_REGISTER_USERNAME`/`GITHUB_REGISTER_PASSWORD` first: `config.json` holds
|
||||||
|
real API keys and proxy credentials, so an unauthenticated `0.0.0.0` bind
|
||||||
|
exposes them to everyone on that network. Use this only on a trusted private
|
||||||
|
network, never on public Wi-Fi.
|
||||||
|
|
||||||
|
### Docker
|
||||||
|
|
||||||
|
Multi-stage image: `node:20-alpine` (frontend build) + `python:3.12-slim`
|
||||||
|
(runtime, includes Camoufox Firefox + `xvfb` for headful mode):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.example .env # set a strong GITHUB_REGISTER_PASSWORD
|
||||||
|
cp config.example.json config.json
|
||||||
|
touch proxies.txt .datadome-trust.json github_recovery_codes.txt
|
||||||
|
docker compose up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
Open <http://localhost:8093> for a quick local check. (The compose file in
|
||||||
|
this repo does not publish ports — production traffic goes through nginx,
|
||||||
|
see below; add a `ports:` entry if you need direct local access.)
|
||||||
|
|
||||||
|
Compose overrides `GITHUB_REGISTER_HOST=0.0.0.0` inside the container.
|
||||||
|
All files below persist on the host via bind-mount
|
||||||
|
(do not delete): `config.json`, `accounts/` (`github_accounts_*.txt`,
|
||||||
|
`recovery/`, `groups.json`), `.browser-profile/`, `proxies.txt`,
|
||||||
|
`.datadome-trust.json` (trust cookie — losing it means DataDome 403s from scratch),
|
||||||
|
`github_recovery_codes.txt`. Not persistent, which is fine: web login sessions
|
||||||
|
(in memory — log in again). For display-less VPS, set `"headless": true` in
|
||||||
|
`config.json` (cheaper, slightly easier for DataDome to flag). A DataDome
|
||||||
|
challenge cannot be solved without a visible window, so headless runs fail fast
|
||||||
|
instead of waiting for a manual click; use a residential proxy for headless.
|
||||||
|
|
||||||
|
### VPS + nginx reverse proxy (one docker network)
|
||||||
|
|
||||||
|
Compose already joins the external `nginx-network` and does **not** publish
|
||||||
|
ports — public access only via nginx. Make sure the network exists:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker network ls | grep nginx-network || docker network create nginx-network
|
||||||
|
docker compose up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
Example server block in nginx (same network, TLS via certbot):
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
server_name regkit.example.com;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://app:8093;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
# SSE live-log: no buffering + no quick timeouts
|
||||||
|
proxy_buffering off;
|
||||||
|
proxy_read_timeout 86400s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`GITHUB_REGISTER_TRUST_PROXY=1` (already in compose) makes rate-limit read the
|
||||||
|
real IP from `X-Forwarded-For`. Do not enable it when the container is exposed
|
||||||
|
directly without a proxy.
|
||||||
|
|
||||||
|
### CLI
|
||||||
|
|
||||||
|
```bash
|
||||||
|
source .venv/bin/activate
|
||||||
|
python main.py
|
||||||
|
python main.py --count 3
|
||||||
|
python main.py --proxy http://user:pass@host:port
|
||||||
|
python main.py --headless
|
||||||
|
python main.py --config config.local.json --count 1
|
||||||
|
```
|
||||||
|
|
||||||
|
Press `Ctrl+C` to stop the CLI or server. A `KeyboardInterrupt` or
|
||||||
|
`asyncio.CancelledError` during Uvicorn shutdown is expected after interruption.
|
||||||
|
|
||||||
|
## Registration Flow
|
||||||
|
|
||||||
|
1. Open the signup page and fight through DataDome until the form is ready.
|
||||||
|
2. Only then order a mailbox with the configured provider (mail.cx is
|
||||||
|
implicit and free; Litensi orders a zone, auto-picking the cheapest
|
||||||
|
in-stock zone when `litensi_zone` is blank). Ordering late avoids burning
|
||||||
|
balance/expiry while DataDome eats time; a fatal provider failure (empty
|
||||||
|
balance, bad key, out of stock, IP not allowed) aborts the job immediately.
|
||||||
|
A single mailbox that never receives the GitHub code within
|
||||||
|
`otp_timeout_sec` is only a per-account failure — that account is counted
|
||||||
|
as FAIL and the batch continues with the next one.
|
||||||
|
3. Open GitHub signup and fill email, password, and a username based on the
|
||||||
|
mailbox local part.
|
||||||
|
4. Submit the form. If an overlay intercepts pointer clicks, the runner falls
|
||||||
|
back to a DOM click. A disabled form is refreshed and filled with the same
|
||||||
|
data before switching browser sessions.
|
||||||
|
5. Poll the mailbox and enter the GitHub launch code.
|
||||||
|
6. Sign in again if GitHub redirects the new account to login.
|
||||||
|
7. Create the first repository when enabled.
|
||||||
|
8. Enable TOTP 2FA, capture recovery codes, and persist them per account.
|
||||||
|
9. Optionally set profile status, then complete profile name, bio, and location.
|
||||||
|
|
||||||
|
Post-signup stage failures do not discard an account that was already verified.
|
||||||
|
The reason is written to Live Log.
|
||||||
|
|
||||||
|
## Account Output
|
||||||
|
|
||||||
|
```text
|
||||||
|
accounts/
|
||||||
|
github_accounts_<timestamp>.txt
|
||||||
|
recovery/
|
||||||
|
<email-hash>.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
Each account file contains one line per account:
|
||||||
|
|
||||||
|
```text
|
||||||
|
email----password----username----totp_secret----has_recovery
|
||||||
|
```
|
||||||
|
|
||||||
|
Recovery codes are stored separately under `accounts/recovery/`. The Accounts
|
||||||
|
page can reveal and copy them with the **Recovery** action.
|
||||||
|
|
||||||
|
Example account output:
|
||||||
|
|
||||||
|
```text
|
||||||
|
user@example.com----example-password----example-user----EXAMPLETOTPSECRET000
|
||||||
|
```
|
||||||
|
|
||||||
|
Generate a TOTP code manually from the fourth field:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -c "import pyotp; print(pyotp.TOTP('EXAMPLETOTPSECRET000').now())"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Recording a Manual Flow
|
||||||
|
|
||||||
|
`record_camoufox.py` opens Camoufox and records clicks, inputs, and navigation.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
.venv/bin/python record_camoufox.py
|
||||||
|
.venv/bin/python record_camoufox.py --url https://github.com/login
|
||||||
|
```
|
||||||
|
|
||||||
|
Its output can contain email addresses, session URLs, and selectors. Treat
|
||||||
|
`recorded_steps.json` as sensitive local data.
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
| Problem | Action |
|
||||||
|
| --- | --- |
|
||||||
|
| `BAD SITE` | Use a complete domain such as `github.com` for `litensi_site`. |
|
||||||
|
| No zone or stock | Use **Check Zone**, choose an in-stock zone, or leave it blank for automatic selection. |
|
||||||
|
| No verification email | Check Litensi balance and allow the mailbox reorder retry. |
|
||||||
|
| Proxy `405/407` on CONNECT | Scheme/port/auth mismatch in `proxies.txt` (e.g. SOCKS endpoint declared as `http`). Verify with `curl -x <proxy> https://api.ipify.org`. |
|
||||||
|
| VPS runs old code | The image is stale — `git pull` then `docker compose up -d --build` on the VPS. |
|
||||||
|
| `config.json`/`proxies.txt` became directories | They did not exist before `up`, so docker created folders. `rm -rf` them, create real files (`cp`/`touch`), then `up` again. |
|
||||||
|
| VPS IP port 80/443 unreachable | Nothing listening or firewall closed: check `docker ps`, `curl http://127.0.0.1:80` on the host, `ufw status`, and the cloud security group. The app itself exposes no ports — traffic must flow through nginx. |
|
||||||
|
| Console returns 403 errors after redeploy | Stale token: sessions live in server memory and die on restart, while the browser keeps the old token. Reload the page — the UI now detects this and returns to the login screen automatically. Just log in again. |
|
||||||
|
| DataDome hard block or signup 403 | Change IP/proxy, disable VPN/WARP, then retry after a delay. |
|
||||||
|
| Create account or repository will not click | Review Live Log. Native clicks fall back to DOM clicks when an overlay intercepts them. |
|
||||||
|
| Web UI does not reflect frontend changes | Run `npm run build`, then restart `python -m web.server`. |
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
- Never commit `.env`, `config.json`, `proxies.txt`, `accounts/`,
|
||||||
|
`.browser-profile/`, `.datadome-trust.json`, `github_recovery_codes.txt`,
|
||||||
|
recovery codes, or browser recordings.
|
||||||
|
- Account files contain full credentials, including password and TOTP secret.
|
||||||
|
- Recovery codes grant account recovery and should be stored securely.
|
||||||
|
- Web console auth: username + password from `.env`, 10 failed logins/60s
|
||||||
|
per IP → HTTP 429, sessions are server-side and die on Sign out.
|
||||||
|
Only expose via HTTPS reverse proxy; never enable `TRUST_PROXY` without one.
|
||||||
|
- Before pushing, inspect `git status --short` and `git diff --cached`.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Released under the [MIT License](LICENSE).
|
||||||
|
|
||||||
|
## Proof (2026-10-10)
|
||||||
|
|
||||||
|
- **50 accounts** in the daily bank, **5 full gmail cycles** (2FA TOTP + 16 recovery codes + PAT `ghp_...` + filled profile)
|
||||||
|
- Provider: Gmail +alias via IMAP (`baradok609+<rand>@gmail.com`) — one mailbox, unlimited addresses
|
||||||
|
- Launch code read live from IMAP: `verification code: 58423445` → typed into 8 boxes → `logged_in cookie confirmed`
|
||||||
|
- Dead-proxy fast-rotate: timeout/`<unknown error>` → proxy disabled after 2 navigations (was burning 5 min/account)
|
||||||
|
- Repo stage: React native-setter + direct-visit probe (fixed `creation not confirmed`)
|
||||||
|
- Profile stage: lazy react-partial render → scroll + 3-try retry (fixed `Edit profile button not found`)
|
||||||
+378
@@ -0,0 +1,378 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""backfill_pat.py — recover PAT for saved accounts missing it.
|
||||||
|
|
||||||
|
Per account in accounts/BACKFILL_QUEUE.txt:
|
||||||
|
1. github.com/password_reset -> request reset email
|
||||||
|
2. Gmail IMAP (donor, alias) -> extract reset link
|
||||||
|
3. set new password -> usually auto-login
|
||||||
|
4. login fallback + TOTP 2FA (if secret known)
|
||||||
|
5. /settings/tokens/new -> sudo gate -> note -> repo+workflow -> Generate
|
||||||
|
6. append full line to accounts/BACKFILL_RESULTS.txt, drop from queue
|
||||||
|
|
||||||
|
Secrets are read at runtime from config.json / accounts files / batch log.
|
||||||
|
Usage: python backfill_pat.py [only-suffix ...]
|
||||||
|
"""
|
||||||
|
import hashlib
|
||||||
|
import imaplib
|
||||||
|
import email as emaillib
|
||||||
|
import json
|
||||||
|
import random
|
||||||
|
import re
|
||||||
|
import string
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pyotp
|
||||||
|
from camoufox.sync_api import Camoufox
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
cfg = json.loads((ROOT / "config.json").read_text(encoding="utf-8"))
|
||||||
|
RESULTS = ROOT / "accounts" / "BACKFILL_RESULTS.txt"
|
||||||
|
QUEUE = ROOT / "accounts" / "BACKFILL_QUEUE.txt"
|
||||||
|
RECOVERY_DIR = ROOT / "accounts" / "recovery"
|
||||||
|
|
||||||
|
|
||||||
|
def log(m):
|
||||||
|
print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
def gen_pass():
|
||||||
|
alpha = string.ascii_letters + string.digits
|
||||||
|
return "Bx9!" + "".join(random.choice(alpha) for _ in range(14)) + "q2"
|
||||||
|
|
||||||
|
|
||||||
|
def collect_accounts(only=None):
|
||||||
|
accs = []
|
||||||
|
known = {}
|
||||||
|
for f in sorted((ROOT / "accounts").glob("github_accounts_*.txt")):
|
||||||
|
for ln in f.read_text(encoding="utf-8", errors="ignore").splitlines():
|
||||||
|
p = ln.strip().split("----")
|
||||||
|
if len(p) >= 3 and p[0]:
|
||||||
|
known[p[0].strip().lower()] = (p[2].strip(), p[3].strip() if len(p) > 3 else "")
|
||||||
|
# g7xdk89or9 was never saved — recover username+totp from batch B log slice
|
||||||
|
g7 = None
|
||||||
|
try:
|
||||||
|
lb = (ROOT / "batch_b_1012.log").read_text(encoding="utf-8", errors="ignore")
|
||||||
|
i = lb.find("g7xdk89or9@gmail.com")
|
||||||
|
if i >= 0:
|
||||||
|
j = lb.find("--- account", i)
|
||||||
|
sl = lb[i:j if j > i else i + 40000]
|
||||||
|
mt = re.search(r"TOTP secret captured: ([A-Z2-7]{16})", sl)
|
||||||
|
g7 = ("baradok609g7xdk89or9", mt.group(1) if mt else "")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
for ln in QUEUE.read_text(encoding="utf-8").splitlines():
|
||||||
|
em = ln.strip().split("|")[0].strip()
|
||||||
|
if not em or "@" not in em:
|
||||||
|
continue
|
||||||
|
if only and not any(s in em for s in only):
|
||||||
|
continue
|
||||||
|
if em.lower() in known:
|
||||||
|
u, t = known[em.lower()]
|
||||||
|
elif g7 and "g7xdk89or9" in em.lower():
|
||||||
|
u, t = g7
|
||||||
|
else:
|
||||||
|
u = em.split("+")[0].split("@")[0] + re.sub(r"[^a-z0-9]", "", em.split("+")[1].split("@")[0])
|
||||||
|
t = ""
|
||||||
|
accs.append({"email": em, "username": u, "totp": t})
|
||||||
|
return accs
|
||||||
|
|
||||||
|
|
||||||
|
def imap_reset_link(email_addr, timeout=240):
|
||||||
|
suffix = email_addr.split("+")[1].split("@")[0].lower()
|
||||||
|
end = time.time() + timeout
|
||||||
|
while time.time() < end:
|
||||||
|
try:
|
||||||
|
M = imaplib.IMAP4_SSL(cfg["imap_host"], int(cfg["imap_port"]))
|
||||||
|
M.login(cfg["imap_user"], cfg["imap_password"])
|
||||||
|
M.select("INBOX")
|
||||||
|
for crit in (f'TO "{suffix}"', "UNSEEN", 'SINCE "12-Oct-2026"'):
|
||||||
|
typ, data = M.search(None, crit)
|
||||||
|
ids = (data[0].split() or [])[-80:]
|
||||||
|
for i in reversed(ids):
|
||||||
|
try:
|
||||||
|
typ, md = M.fetch(i, "(BODY.PEEK[])")
|
||||||
|
msg = emaillib.message_from_bytes(md[0][1])
|
||||||
|
to = (msg.get("To") or "").lower()
|
||||||
|
subj = (msg.get("Subject") or "").lower()
|
||||||
|
if suffix not in to:
|
||||||
|
continue
|
||||||
|
if "password" not in subj and "reset" not in subj:
|
||||||
|
continue
|
||||||
|
body = ""
|
||||||
|
if msg.is_multipart():
|
||||||
|
for part in msg.walk():
|
||||||
|
if part.get_content_type() == "text/html":
|
||||||
|
body = part.get_payload(decode=True).decode("utf-8", "ignore")
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
body = msg.get_payload(decode=True).decode("utf-8", "ignore")
|
||||||
|
m = re.search(r"https://github\.com/[^\"'\s<>]*password[^\"'\s<>]*", body)
|
||||||
|
if m:
|
||||||
|
link = m.group(0).replace("&", "&").rstrip(".")
|
||||||
|
M.logout()
|
||||||
|
return link
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
M.logout()
|
||||||
|
except Exception as e:
|
||||||
|
log(f"imap err: {type(e).__name__} {e}")
|
||||||
|
time.sleep(10)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _fill_first(page, selectors, value):
|
||||||
|
for s in selectors:
|
||||||
|
try:
|
||||||
|
loc = page.locator(s).first
|
||||||
|
if loc.count() and loc.is_visible():
|
||||||
|
loc.fill(value)
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _click(page, selectors):
|
||||||
|
for s in selectors:
|
||||||
|
try:
|
||||||
|
loc = page.locator(s).first
|
||||||
|
if loc.count() and loc.is_visible():
|
||||||
|
loc.click(timeout=8000)
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
try:
|
||||||
|
page.evaluate(
|
||||||
|
"(sel) => { const e = document.querySelector(sel); if (e) e.click(); }", s)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _ensure_login(page, acc, newpass):
|
||||||
|
page.goto("https://github.com/settings/profile", wait_until="domcontentloaded", timeout=60000)
|
||||||
|
time.sleep(3)
|
||||||
|
if "/login" not in page.url:
|
||||||
|
return True
|
||||||
|
log("login form fallback")
|
||||||
|
_fill_first(page, ["#login_field", "input[name='login']"], acc["username"])
|
||||||
|
_fill_first(page, ["#password", "input[name='password']"], newpass)
|
||||||
|
_click(page, ["input[type='submit']", "button[type='submit']"])
|
||||||
|
time.sleep(6)
|
||||||
|
if re.search(r"two-factor|otp|authenticator", page.content().lower()):
|
||||||
|
if not acc["totp"]:
|
||||||
|
log("2FA required but no TOTP secret — abort")
|
||||||
|
return False
|
||||||
|
code = pyotp.TOTP(acc["totp"]).now()
|
||||||
|
log(f"2FA code submitted")
|
||||||
|
_fill_first(page, ["#otp", "input[name='otp']", "input[autocomplete='one-time-code']",
|
||||||
|
"#app_totp"], code)
|
||||||
|
_click(page, ["button[type='submit']", "input[type='submit']"])
|
||||||
|
time.sleep(6)
|
||||||
|
page.goto("https://github.com/settings/profile", wait_until="domcontentloaded", timeout=60000)
|
||||||
|
return "/login" not in page.url
|
||||||
|
|
||||||
|
|
||||||
|
def _create_pat(page, newpass):
|
||||||
|
page.goto("https://github.com/settings/tokens/new", wait_until="domcontentloaded", timeout=60000)
|
||||||
|
time.sleep(3)
|
||||||
|
# sudo gate
|
||||||
|
if page.locator("#sudo_password, input[name='sudo_password']").count():
|
||||||
|
log("sudo gate -> new password")
|
||||||
|
_fill_first(page, ["#sudo_password", "input[name='sudo_password']"], newpass)
|
||||||
|
_click(page, ["button[type='submit']", "input[type='submit']"])
|
||||||
|
time.sleep(5)
|
||||||
|
_fill_first(page, ["#oauth_access_description", "textarea#oauth_access_description"], "ci")
|
||||||
|
page.evaluate("""() => {
|
||||||
|
for (const v of ['repo','workflow']) {
|
||||||
|
const cb = document.querySelector(`input[type=checkbox][value='${v}']`);
|
||||||
|
if (cb && !cb.checked) { cb.click(); }
|
||||||
|
}
|
||||||
|
}""")
|
||||||
|
time.sleep(1)
|
||||||
|
_click(page, ["button:has-text('Generate token')", "input[value='Generate token']",
|
||||||
|
"input[name='commit']", "button[type='submit']"])
|
||||||
|
time.sleep(6)
|
||||||
|
m = re.search(r"ghp_[A-Za-z0-9]{36}", page.inner_text("body"))
|
||||||
|
if not m:
|
||||||
|
m = re.search(r"ghp_[A-Za-z0-9]{36}", page.content())
|
||||||
|
if not m:
|
||||||
|
time.sleep(6)
|
||||||
|
m = re.search(r"ghp_[A-Za-z0-9]{36}", page.content())
|
||||||
|
return m.group(0) if m else ""
|
||||||
|
|
||||||
|
|
||||||
|
def backfill_one(acc, proxies):
|
||||||
|
em = acc["email"]
|
||||||
|
newpass = gen_pass()
|
||||||
|
for attempt in range(3):
|
||||||
|
px = random.choice(proxies)
|
||||||
|
log(f"--- {em} (try {attempt+1}, proxy {px.split('@')[-1]}) ---")
|
||||||
|
try:
|
||||||
|
with Camoufox(headless=True, proxy={"server": px}) as browser:
|
||||||
|
page = browser.new_page()
|
||||||
|
page.set_default_timeout(45000)
|
||||||
|
# 1) request reset
|
||||||
|
page.goto("https://github.com/password_reset", wait_until="domcontentloaded", timeout=60000)
|
||||||
|
# fail fast on block pages (free proxies are often flagged)
|
||||||
|
try:
|
||||||
|
_bt = page.inner_text("body", timeout=4000).lower()
|
||||||
|
except Exception:
|
||||||
|
_bt = ""
|
||||||
|
if not _bt.strip():
|
||||||
|
try:
|
||||||
|
_bt = page.content().lower()
|
||||||
|
except Exception:
|
||||||
|
_bt = ""
|
||||||
|
if ("access is temporarily restricted" in _bt or "unusual activity" in _bt
|
||||||
|
or "enable js" in _bt or "slide right to secure" in _bt):
|
||||||
|
raise RuntimeError("block page on /password_reset — flagged proxy")
|
||||||
|
sel = None
|
||||||
|
for s in ("#login_field", "input[name='user[email]']",
|
||||||
|
"input[type='email']", "input[type='text']"):
|
||||||
|
try:
|
||||||
|
page.wait_for_selector(s, state="visible", timeout=12000)
|
||||||
|
sel = s
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
if not sel:
|
||||||
|
raise RuntimeError("reset form not found")
|
||||||
|
page.locator(sel).first.fill(em)
|
||||||
|
filled = True
|
||||||
|
if not filled:
|
||||||
|
raise RuntimeError("reset form not found")
|
||||||
|
_click(page, ["button[type='submit']", "input[type='submit']"])
|
||||||
|
time.sleep(5)
|
||||||
|
# 2) link from IMAP
|
||||||
|
link = imap_reset_link(em)
|
||||||
|
if not link:
|
||||||
|
raise RuntimeError("no reset email in IMAP")
|
||||||
|
log("reset link received")
|
||||||
|
# 3) set new password (proper waits — slow proxies render late)
|
||||||
|
page.goto(link, wait_until="domcontentloaded", timeout=60000)
|
||||||
|
# 3a) 2FA gate on reset link (accounts have TOTP enabled)
|
||||||
|
try:
|
||||||
|
otp_box = page.wait_for_selector("input[name='app_otp'], #otp", state="visible", timeout=8000)
|
||||||
|
except Exception:
|
||||||
|
otp_box = None
|
||||||
|
if otp_box:
|
||||||
|
code = ""
|
||||||
|
if acc.get("totp"):
|
||||||
|
try:
|
||||||
|
import pyotp
|
||||||
|
code = pyotp.TOTP(acc["totp"].replace(" ", "")).now()
|
||||||
|
except Exception:
|
||||||
|
code = ""
|
||||||
|
if not code:
|
||||||
|
try:
|
||||||
|
key = hashlib.sha256(em.strip().lower().encode()).hexdigest()
|
||||||
|
rf = RECOVERY_DIR / f"{key}.txt"
|
||||||
|
if rf.exists():
|
||||||
|
for tok in rf.read_text().split():
|
||||||
|
if tok.count("-") == 1 and len(tok) == 11:
|
||||||
|
code = tok
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if not code:
|
||||||
|
raise RuntimeError("2FA gate on reset link but no TOTP/recovery code")
|
||||||
|
log(f"reset link 2FA gate — filling {'TOTP' if len(code) == 6 else 'recovery code'}")
|
||||||
|
otp_box.fill(code)
|
||||||
|
try:
|
||||||
|
page.wait_for_function(
|
||||||
|
"() => !document.querySelector(\"input[name='app_otp']\")",
|
||||||
|
timeout=20000)
|
||||||
|
except Exception:
|
||||||
|
_click(page, ["button[type='submit']", "input[type='submit']"])
|
||||||
|
time.sleep(6)
|
||||||
|
psel = None
|
||||||
|
for s in ("#password", "input[name='user[password]']",
|
||||||
|
"input[type='password']"):
|
||||||
|
try:
|
||||||
|
page.wait_for_selector(s, state="visible", timeout=15000)
|
||||||
|
psel = s
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
if not psel:
|
||||||
|
try:
|
||||||
|
_bt2 = page.inner_text("body", timeout=4000).lower()
|
||||||
|
except Exception:
|
||||||
|
_bt2 = ""
|
||||||
|
if not _bt2.strip():
|
||||||
|
try:
|
||||||
|
_bt2 = page.content().lower()
|
||||||
|
except Exception:
|
||||||
|
_bt2 = ""
|
||||||
|
if ("access is temporarily restricted" in _bt2
|
||||||
|
or "slide right to secure" in _bt2 or "enable js" in _bt2
|
||||||
|
or "security risk" in _bt2 or "aboutneterror" in _bt2
|
||||||
|
or "certerror" in _bt2):
|
||||||
|
raise RuntimeError("block/TLS-error page on reset link — bad proxy")
|
||||||
|
try:
|
||||||
|
import time as _t
|
||||||
|
dbg = ROOT / "accounts" / f"bf_debug_{int(_t.time())}.html"
|
||||||
|
dbg.write_text(page.content(), encoding="utf-8", errors="ignore")
|
||||||
|
log(f"reset-page debug dump: {dbg.name} (url={page.url})")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
raise RuntimeError("reset form fields not found")
|
||||||
|
page.locator(psel).first.fill(newpass)
|
||||||
|
_fill_first(page, ["#password_confirmation", "input[name='user[password_confirmation]']"], newpass)
|
||||||
|
_click(page, ["button[type='submit']", "input[type='submit']"])
|
||||||
|
time.sleep(8)
|
||||||
|
# 4) ensure logged in
|
||||||
|
if not _ensure_login(page, acc, newpass):
|
||||||
|
raise RuntimeError("login failed")
|
||||||
|
log("logged in")
|
||||||
|
# 5) PAT
|
||||||
|
pat = _create_pat(page, newpass)
|
||||||
|
if not pat:
|
||||||
|
raise RuntimeError("PAT not created")
|
||||||
|
log(f"PAT recovered: ghp_...{pat[-4:]}")
|
||||||
|
# 6) persist
|
||||||
|
rec = ""
|
||||||
|
try:
|
||||||
|
key = hashlib.sha256(em.strip().lower().encode()).hexdigest()
|
||||||
|
rf = RECOVERY_DIR / f"{key}.txt"
|
||||||
|
if rf.exists():
|
||||||
|
rec = " ".join(rf.read_text().split())
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
line = f"{em}----{newpass}----{acc['username']}----{acc['totp']}----{rec}----{pat}"
|
||||||
|
with RESULTS.open("a", encoding="utf-8") as fh:
|
||||||
|
fh.write(line + "\n")
|
||||||
|
qlines = [l for l in QUEUE.read_text(encoding="utf-8").splitlines()
|
||||||
|
if em.lower() not in l.lower()]
|
||||||
|
QUEUE.write_text("\n".join(qlines) + ("\n" if qlines else ""), encoding="utf-8")
|
||||||
|
log(f"SAVED + dequeued: {em}")
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
log(f"attempt failed: {type(e).__name__}: {e}")
|
||||||
|
time.sleep(10)
|
||||||
|
log(f"GIVE UP: {em}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
only = sys.argv[1:] or None
|
||||||
|
accs = collect_accounts(only)
|
||||||
|
log(f"queue: {len(accs)} accounts: {[a['email'].split('+')[1].split('@')[0] for a in accs]}")
|
||||||
|
proxies = [l.strip() for l in (ROOT / "proxies.txt").read_text().splitlines()
|
||||||
|
if l.strip() and not l.lstrip().startswith("#") and l.strip().startswith("http")]
|
||||||
|
proxies_b = [l.strip() for l in (ROOT / "proxies_b.txt").read_text().splitlines()
|
||||||
|
if l.strip() and not l.lstrip().startswith("#") and l.strip().startswith("http")]
|
||||||
|
allp = list(set(proxies + proxies_b)) or proxies
|
||||||
|
ok = 0
|
||||||
|
for acc in accs:
|
||||||
|
if backfill_one(acc, allp):
|
||||||
|
ok += 1
|
||||||
|
time.sleep(random.uniform(20, 40))
|
||||||
|
log(f"BACKFILL DONE: {ok}/{len(accs)} recovered")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
{
|
||||||
|
"mail_provider": "mailcx",
|
||||||
|
"mailcx_domain": "",
|
||||||
|
"litensi_api_id": "",
|
||||||
|
"litensi_api_key": "",
|
||||||
|
"litensi_site": "github.com",
|
||||||
|
"litensi_zone": "",
|
||||||
|
"imap_user": "",
|
||||||
|
"imap_password": "",
|
||||||
|
"imap_host": "",
|
||||||
|
"imap_port": 993,
|
||||||
|
"imap_alias_domain": "",
|
||||||
|
"temptf_providers": "gmail.com,outlook.com,hotmail.com,high.edu.pl",
|
||||||
|
"temptf_dot": true,
|
||||||
|
"temptf_plus": true,
|
||||||
|
"register_count": 1,
|
||||||
|
"proxy": "",
|
||||||
|
"proxy_file": "",
|
||||||
|
"headless": false,
|
||||||
|
"delay_sec": 5.0,
|
||||||
|
"max_username_tries": 6,
|
||||||
|
"otp_timeout_sec": 240,
|
||||||
|
"browser_profile_dir": ".browser-profile",
|
||||||
|
"fresh_profile": true,
|
||||||
|
"proxy_hard_block_retries": 2,
|
||||||
|
"proxy_rate_limit_retries": 2,
|
||||||
|
"create_repo": true,
|
||||||
|
"repo_name": "hello",
|
||||||
|
"enable_2fa": true,
|
||||||
|
"set_profile_status": true,
|
||||||
|
"profile_status": "On vacation",
|
||||||
|
"complete_profile": true,
|
||||||
|
"profile_name": "",
|
||||||
|
"profile_bio": "",
|
||||||
|
"profile_location": ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
name: github-regkit
|
||||||
|
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
build: .
|
||||||
|
image: gh-regkit-prime:latest
|
||||||
|
container_name: github-regkit
|
||||||
|
restart: unless-stopped
|
||||||
|
# .env is read first, then environment below overrides (HOST must be 0.0.0.0 in container).
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
environment:
|
||||||
|
GITHUB_REGISTER_HOST: 0.0.0.0
|
||||||
|
GITHUB_REGISTER_PORT: 8093
|
||||||
|
# Nginx fills X-Forwarded-For; required so rate-limit sees the real IP,
|
||||||
|
# not the nginx container IP. Only enable behind a trusted proxy.
|
||||||
|
GITHUB_REGISTER_TRUST_PROXY: 1
|
||||||
|
# Internal only — public access ONLY via nginx on the same network.
|
||||||
|
expose:
|
||||||
|
- "8093"
|
||||||
|
volumes:
|
||||||
|
# Must exist on the host BEFORE up (otherwise docker creates directories):
|
||||||
|
# cp config.example.json config.json && touch proxies.txt .datadome-trust.json github_recovery_codes.txt
|
||||||
|
- ./config.json:/app/config.json
|
||||||
|
- ./accounts:/app/accounts
|
||||||
|
- ./.browser-profile:/app/.browser-profile
|
||||||
|
- ./proxies.txt:/app/proxies.txt
|
||||||
|
# DataDome trust cookie + recovery code backup — losing them = 403s from scratch
|
||||||
|
- ./.datadome-trust.json:/app/.datadome-trust.json
|
||||||
|
- ./github_recovery_codes.txt:/app/github_recovery_codes.txt
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "curl", "-fsS", "http://127.0.0.1:8093/health"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
start_period: 20s
|
||||||
|
networks:
|
||||||
|
- nginx-network
|
||||||
|
|
||||||
|
networks:
|
||||||
|
nginx-network:
|
||||||
|
external: true
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
# GitHub Autoreg — собранная база знаний
|
||||||
|
|
||||||
|
Все проверенные факты из наших прогонов. Дата актуальности: 2026-10-09.
|
||||||
|
Канал: [@alstack](https://t.me/alstack).
|
||||||
|
|
||||||
|
## 1. Флоу signup (живой, октябрь 2026)
|
||||||
|
|
||||||
|
- GitHub перевёл signup на **multi-step wizard**: email -> Continue -> password
|
||||||
|
-> Continue -> username -> Create account. Одностраничная форма мертва.
|
||||||
|
- Вход: https://github.com/?utm_source=google (ref-параметр снижает подозрительность).
|
||||||
|
- После Create account может появиться **Arkose FunCaptcha** (octocaptcha.com iframe):
|
||||||
|
~16с PoW, потом "Visual puzzle". Варианты: sequence / rotate / character / wires.
|
||||||
|
- Email-верификация: письмо mail.cx приходит за 5-30с; код 8 цифр.
|
||||||
|
- После верификации — авто-логин, проверка cookie `logged_in`.
|
||||||
|
|
||||||
|
## 2. Анти-детект и прогрев (лечит suspended)
|
||||||
|
|
||||||
|
- **Camoufox** (Firefox anti-detect) — единственный стабильный движок.
|
||||||
|
Chromium/patchright ловят DataDome быстрее.
|
||||||
|
- **Прогрев обязателен**: dwell 4-7с на главной + JS-скроллы + пауза 6-10с
|
||||||
|
на /signup перед формой. Без прогрева акки часто `suspended` на home IP.
|
||||||
|
- **ВАЖНО**: `page.mouse.move()` в Playwright НЕ имеет таймаута — на
|
||||||
|
недогруженной странице висит вечно. Только JS `window.scrollBy` +
|
||||||
|
`set_default_timeout`.
|
||||||
|
- DataDome trust cookie сохраняется между прогонами (`.datadome-trust.json`),
|
||||||
|
клонируется в fresh-профиль.
|
||||||
|
- fresh_profile=True: новый браузер без кэша на каждый акк.
|
||||||
|
|
||||||
|
## 3. Captcha: multi-LLM voting ($0)
|
||||||
|
|
||||||
|
- Multi-LLM voting solver (собственная реализация).
|
||||||
|
- Кандидаты склеиваются в пронумерованную сетку, PIL-энханс, уходят
|
||||||
|
параллельно в vision-модели; большинство побеждает; `ANSWER=<n>`.
|
||||||
|
- Бесплатные voter'ы через локальный OpenAI-совместимый гейтвей
|
||||||
|
(dashscope-proxy 127.0.0.1:16432): qwen3-vl-flash (подтверждён: COLOR=red
|
||||||
|
за 2.0с), qwen-vl-max, qwen-vl-plus.
|
||||||
|
- Review-скриншоты REVIEW_rN.png: красная рамка = финальный голос,
|
||||||
|
цветные = голоса моделей.
|
||||||
|
- wag-captcha sidecar (:8877) — для DataDome, НЕ для Arkose.
|
||||||
|
- CapSolver DataDomeSliderTask работает, но платно; баланс был $0.
|
||||||
|
|
||||||
|
## 4. Почта
|
||||||
|
|
||||||
|
- **mail.cx** — бесплатно, без регистрации: домены uqu.me, ddker.com, 9k3r.com.
|
||||||
|
- IMAP/SMTP не нужны — REST API (создание inbox, чтение сообщений).
|
||||||
|
- Gmail +alias канонизируется GitHub'ом — не годится для масс-рега.
|
||||||
|
- t-online.de 17k ящиков — все уже зарегистрированы на GitHub.
|
||||||
|
- 1secmail мёртв. tempmail.lol v2: токен в query (?token=).
|
||||||
|
|
||||||
|
## 5. Прокси
|
||||||
|
|
||||||
|
- Бесплатные пулы (ProxyScrape/TheSpeedX и 60+ источников через ProxyGrab) —
|
||||||
|
выход ~50-90 живых на github.com из тысяч. Тест: GET /login через прокси.
|
||||||
|
- Free-прокси медленные: goto может падать по таймауту -> sticky-ротация
|
||||||
|
(proxy_hard_block_retries=3, proxy_rate_limit_retries=2).
|
||||||
|
- Home IP (без прокси) -> акк регистрируется, но почти всегда `suspended`.
|
||||||
|
- ZTE 4G модем (192.168.0.4:8080-8091) — ротация IP через web API модема
|
||||||
|
(DISCONNECT_NETWORK/CONNECT_NETWORK), lifecell Ukraine.
|
||||||
|
- Прокси-пулы парсить `line.split()[0]` (формат "http://ip:port ip").
|
||||||
|
|
||||||
|
## 6. Post-signup стадии (enrich)
|
||||||
|
|
||||||
|
- Stage 4: create first repository (делает акк "живым").
|
||||||
|
- Stage 5: TOTP 2FA — Settings -> Password and authentication ->
|
||||||
|
Authenticator app -> "setup key" -> secret -> pyotp -> recovery codes.
|
||||||
|
- Stage 6: classic PAT —
|
||||||
|
/settings/tokens/new -> sudo password -> note -> scopes repo+workflow ->
|
||||||
|
Generate token -> токен показывается ОДИН раз, читать regex ghp_[A-Za-z0-9]{36}.
|
||||||
|
- Profile completion: avatar/status/bio — генератор персон.
|
||||||
|
|
||||||
|
## 7. Формат выхлопа
|
||||||
|
|
||||||
|
`email----password----username----totp_secret----has_recovery----pat`
|
||||||
|
|
||||||
|
Recovery-коды отдельно: accounts/recovery/<email-hash>.txt
|
||||||
|
|
||||||
|
## 8. Windows-питфолы
|
||||||
|
|
||||||
|
- Camoufox в потоке uvicorn -> `[Errno 22] Invalid argument`. Только subprocess.
|
||||||
|
- PYTHONPATH="" обязателен (Hermes venv контаминирует).
|
||||||
|
- Python 3.11 (не 3.14 — greenlet несовместим).
|
||||||
|
- write_file маскирует секреты -> ключи читать из файла в рантайме.
|
||||||
|
- git-remote-https мёртв на машине -> пуш через Git Data API
|
||||||
|
(blob -> tree -> commit -> ref update); пустая репа требует init через
|
||||||
|
Contents API первым файлом.
|
||||||
|
|
||||||
|
## 8b. Username-цикл (баг, найден 09.10)
|
||||||
|
|
||||||
|
- Короткие базы (t76x) + последовательные суффиксы (name2/name3) тоже заняты —
|
||||||
|
GitHub сжирает все page-reloads на "Username X is not available".
|
||||||
|
- Фикс 1: retry со СЛУЧАЙНЫМ суффиксом 100-9999, не +1.
|
||||||
|
- Фикс 2: при SESSION switch брать НОВЫЙ mailbox (mail.cx бесплатен) —
|
||||||
|
новый email = новая база username. Только для provider=mailcx.
|
||||||
|
|
||||||
|
## 9. Статистика наших прогонов
|
||||||
|
|
||||||
|
- 2026-10-09: smoke через прокси: verified+logged_in ~2мин/акк.
|
||||||
|
- Масс-батч 25: в работе, промежуточно 4+ OK.
|
||||||
|
- suspended без прокси/proxy: uur5221b8slxlc@9k3r.com (home IP).
|
||||||
|
- GitHub checkup-страница: "More options" -> "tomorrow" dismisses.
|
||||||
|
- 2FA input: input[name=app_otp]; "context destroyed" после Verify = успех.
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 77 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 83 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 56 KiB |
@@ -0,0 +1,138 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||||
|
<meta name="theme-color" content="#000000" />
|
||||||
|
<title>GitHub Register</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||||
|
<link
|
||||||
|
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap"
|
||||||
|
rel="stylesheet"
|
||||||
|
/>
|
||||||
|
<style>
|
||||||
|
/* Tokens mirror DESIGN.md (Resend style reference): void-black canvas,
|
||||||
|
hairline borders for layer separation, one blue action, violet for code. */
|
||||||
|
:root {
|
||||||
|
--color-void-black: #000000;
|
||||||
|
--color-graphite-hairline: #292d30;
|
||||||
|
--color-white: #ffffff;
|
||||||
|
--color-bone-white: #f0f0f0;
|
||||||
|
--color-ash-gray: #a1a4a5;
|
||||||
|
--color-smoke-gray: #abafb4;
|
||||||
|
--color-iron: #6e727a;
|
||||||
|
--color-charcoal: #464a4d;
|
||||||
|
--color-iris-violet: #9281f7;
|
||||||
|
--color-iris-violet-glow: #baa7ff;
|
||||||
|
--color-signal-blue: #3b9eff;
|
||||||
|
--color-sky-blue: #70b8ff;
|
||||||
|
--color-pulse-green: #3ad389;
|
||||||
|
--color-alarm-red: #ff9592;
|
||||||
|
--color-crimson: #ff6465;
|
||||||
|
--color-amber: #ffca16;
|
||||||
|
|
||||||
|
/* Surfaces */
|
||||||
|
--bg-primary: var(--color-void-black);
|
||||||
|
--bg-secondary: var(--color-void-black);
|
||||||
|
--bg-card: var(--color-void-black);
|
||||||
|
--bg-card-hover: #0e1013;
|
||||||
|
--bg-input: #000000;
|
||||||
|
--border: var(--color-graphite-hairline);
|
||||||
|
--border-strong: var(--color-iron);
|
||||||
|
|
||||||
|
/* Text */
|
||||||
|
--text-primary: var(--color-white);
|
||||||
|
--text-secondary: var(--color-bone-white);
|
||||||
|
--text-muted: var(--color-ash-gray);
|
||||||
|
--text-disabled: var(--color-iron);
|
||||||
|
|
||||||
|
/* One blue action, violet reserved for code identifiers */
|
||||||
|
--accent: var(--color-signal-blue);
|
||||||
|
--accent-rgb: 59, 158, 255;
|
||||||
|
--accent-strong: var(--color-sky-blue);
|
||||||
|
--accent-text: var(--color-sky-blue);
|
||||||
|
--accent-soft: rgba(59, 158, 255, 0.14);
|
||||||
|
--code-ident: var(--color-iris-violet);
|
||||||
|
|
||||||
|
/* Data / status only, never UI chrome */
|
||||||
|
--success: var(--color-pulse-green);
|
||||||
|
--success-rgb: 58, 211, 137;
|
||||||
|
--danger: var(--color-alarm-red);
|
||||||
|
--danger-rgb: 255, 149, 146;
|
||||||
|
--danger-strong: var(--color-crimson);
|
||||||
|
--warning: var(--color-amber);
|
||||||
|
|
||||||
|
/* Legacy aliases still referenced by panel inline styles */
|
||||||
|
--bg: var(--bg-primary);
|
||||||
|
--bg-raise: var(--bg-card);
|
||||||
|
--text: var(--text-secondary);
|
||||||
|
--ink: var(--text-primary);
|
||||||
|
--muted: var(--text-muted);
|
||||||
|
--ok: var(--success);
|
||||||
|
--ok-rgb: var(--success-rgb);
|
||||||
|
--glass-border: var(--border);
|
||||||
|
--glass: var(--bg-card);
|
||||||
|
--glass-strong: var(--bg-card-hover);
|
||||||
|
--ring: 0 0 0 3px rgba(59, 158, 255, 0.28);
|
||||||
|
|
||||||
|
/* Two-value radius scale: 6px controls, 16px cards, 24px panels */
|
||||||
|
--radius-control: 6px;
|
||||||
|
--radius-card: 16px;
|
||||||
|
--radius-panel: 24px;
|
||||||
|
|
||||||
|
--font-inter: 'Inter', ui-sans-serif, system-ui, -apple-system,
|
||||||
|
BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||||
|
--font-mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo,
|
||||||
|
Monaco, Consolas, monospace;
|
||||||
|
|
||||||
|
--page-max-width: 1200px;
|
||||||
|
--bottom-nav-height: 60px;
|
||||||
|
}
|
||||||
|
|
||||||
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
|
||||||
|
html { -webkit-text-size-adjust: 100%; }
|
||||||
|
|
||||||
|
html, body, #root { height: 100%; }
|
||||||
|
|
||||||
|
body {
|
||||||
|
background: var(--bg-primary);
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-family: var(--font-inter);
|
||||||
|
font-size: 16px;
|
||||||
|
line-height: 1.5;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Mobile scrolls the document; desktop scrolls inside .app-main. */
|
||||||
|
@media (max-width: 820px) {
|
||||||
|
body { overflow: auto; }
|
||||||
|
html, body, #root { height: auto; min-height: 100%; }
|
||||||
|
}
|
||||||
|
|
||||||
|
::selection { background: rgba(59, 158, 255, 0.30); }
|
||||||
|
|
||||||
|
::-webkit-scrollbar { width: 8px; height: 8px; }
|
||||||
|
::-webkit-scrollbar-thumb { background: var(--color-graphite-hairline); border-radius: 4px; }
|
||||||
|
::-webkit-scrollbar-thumb:hover { background: var(--color-iron); }
|
||||||
|
::-webkit-scrollbar-track { background: transparent; }
|
||||||
|
|
||||||
|
code, pre, kbd, samp { font-family: var(--font-mono); }
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
*, *::before, *::after {
|
||||||
|
animation-duration: 0.01ms !important;
|
||||||
|
animation-iteration-count: 1 !important;
|
||||||
|
transition-duration: 0.01ms !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.jsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Generated
+1738
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"name": "github-regkit-frontend",
|
||||||
|
"private": true,
|
||||||
|
"version": "1.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build",
|
||||||
|
"preview": "vite preview",
|
||||||
|
"verify:ui": "node verify-ui.cjs",
|
||||||
|
"verify:clicks": "node verify-clicks.cjs"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"lucide-react": "^1.33.0",
|
||||||
|
"react": "^18.3.1",
|
||||||
|
"react-dom": "^18.3.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@vitejs/plugin-react": "^4.3.4",
|
||||||
|
"playwright": "^1.63.0",
|
||||||
|
"vite": "^5.4.11"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,481 @@
|
|||||||
|
import React, { useEffect, useState } from "react";
|
||||||
|
import {
|
||||||
|
Activity,
|
||||||
|
Boxes,
|
||||||
|
ExternalLink,
|
||||||
|
FolderGit2,
|
||||||
|
Heart,
|
||||||
|
LogOut,
|
||||||
|
Menu,
|
||||||
|
Octagon,
|
||||||
|
PanelLeftClose,
|
||||||
|
PanelLeftOpen,
|
||||||
|
Plus,
|
||||||
|
Settings,
|
||||||
|
ShieldCheck,
|
||||||
|
X,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { api, getToken, setToken } from "./api.js";
|
||||||
|
import StatusPanel from "./components/StatusPanel.jsx";
|
||||||
|
import ConfigPanel from "./components/ConfigPanel.jsx";
|
||||||
|
import AccountsPanel from "./components/AccountsPanel.jsx";
|
||||||
|
import {
|
||||||
|
Badge,
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
Dialog,
|
||||||
|
Input,
|
||||||
|
Spinner,
|
||||||
|
} from "./components/ui.jsx";
|
||||||
|
|
||||||
|
const NAV = [
|
||||||
|
{ id: "status", label: "Status", icon: Activity },
|
||||||
|
{ id: "config", label: "Config", icon: Settings },
|
||||||
|
{ id: "accounts", label: "Accounts", icon: Boxes },
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function App() {
|
||||||
|
const [auth, setAuth] = useState(null);
|
||||||
|
const [tab, setTab] = useState("status");
|
||||||
|
const [username, setUsername] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [running, setRunning] = useState(false);
|
||||||
|
const [sidebarOpen, setSidebarOpen] = useState(true);
|
||||||
|
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||||
|
const [group, setGroup] = useState("");
|
||||||
|
const [groups, setGroups] = useState([]);
|
||||||
|
const [groupCreateOpen, setGroupCreateOpen] = useState(false);
|
||||||
|
const [newGroupName, setNewGroupName] = useState("");
|
||||||
|
const [groupBusy, setGroupBusy] = useState(false);
|
||||||
|
const [groupDelete, setGroupDelete] = useState(null); // group name | null
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
api
|
||||||
|
.get("/api/config")
|
||||||
|
.then((d) => setAuth({ needs: d.needs_auth }))
|
||||||
|
.catch(() => setAuth({ needs: true }));
|
||||||
|
}, []);
|
||||||
|
useEffect(() => {
|
||||||
|
if (auth?.needs && !getToken()) return undefined;
|
||||||
|
const timer = setInterval(
|
||||||
|
() =>
|
||||||
|
api
|
||||||
|
.get("/api/status")
|
||||||
|
.then((d) => setRunning(!!d.running))
|
||||||
|
.catch(() => {}),
|
||||||
|
2500,
|
||||||
|
);
|
||||||
|
return () => clearInterval(timer);
|
||||||
|
}, [auth]);
|
||||||
|
|
||||||
|
function loadGroups() {
|
||||||
|
api
|
||||||
|
.get("/api/groups")
|
||||||
|
.then((d) => setGroups(d.groups || []))
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
|
useEffect(() => {
|
||||||
|
if (auth === null) return undefined;
|
||||||
|
if (auth.needs && !getToken()) return undefined;
|
||||||
|
loadGroups();
|
||||||
|
const t = setInterval(loadGroups, 10000);
|
||||||
|
return () => clearInterval(t);
|
||||||
|
}, [auth]);
|
||||||
|
|
||||||
|
function selectGroup(name) {
|
||||||
|
setGroup(name);
|
||||||
|
setTab("accounts");
|
||||||
|
setDrawerOpen(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Drawer is a mobile-only surface: close on Escape and when returning to desktop.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!drawerOpen) return undefined;
|
||||||
|
const onKeyDown = (e) => e.key === "Escape" && setDrawerOpen(false);
|
||||||
|
const onResize = () => {
|
||||||
|
if (window.innerWidth > 820) setDrawerOpen(false);
|
||||||
|
};
|
||||||
|
document.addEventListener("keydown", onKeyDown);
|
||||||
|
window.addEventListener("resize", onResize);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener("keydown", onKeyDown);
|
||||||
|
window.removeEventListener("resize", onResize);
|
||||||
|
};
|
||||||
|
}, [drawerOpen]);
|
||||||
|
|
||||||
|
async function doCreateGroup() {
|
||||||
|
const name = newGroupName.trim();
|
||||||
|
if (!name || groupBusy) return;
|
||||||
|
setGroupBusy(true);
|
||||||
|
try {
|
||||||
|
await api.post("/api/groups", { name });
|
||||||
|
setGroupCreateOpen(false);
|
||||||
|
setNewGroupName("");
|
||||||
|
setGroup(name);
|
||||||
|
setTab("accounts");
|
||||||
|
loadGroups();
|
||||||
|
} catch (e) {
|
||||||
|
alert(`Failed to create group: ${e.message}`);
|
||||||
|
} finally {
|
||||||
|
setGroupBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doDeleteGroup() {
|
||||||
|
const name = groupDelete;
|
||||||
|
if (!name || groupBusy) return;
|
||||||
|
setGroupBusy(true);
|
||||||
|
try {
|
||||||
|
await api.del(`/api/groups?name=${encodeURIComponent(name)}`);
|
||||||
|
if (group === name) setGroup("");
|
||||||
|
loadGroups();
|
||||||
|
} catch (e) {
|
||||||
|
alert(`Failed to delete group: ${e.message}`);
|
||||||
|
} finally {
|
||||||
|
setGroupBusy(false);
|
||||||
|
setGroupDelete(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doLogin() {
|
||||||
|
try {
|
||||||
|
const data = await api.post("/api/auth", { username, password });
|
||||||
|
setToken(data.token);
|
||||||
|
setAuth({ needs: data.needs_auth });
|
||||||
|
setUsername("");
|
||||||
|
setPassword("");
|
||||||
|
} catch (error) {
|
||||||
|
alert(`Login failed: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (auth === null)
|
||||||
|
return (
|
||||||
|
<main className="app-loading">
|
||||||
|
<Spinner />
|
||||||
|
<span>Loading application</span>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
if (auth.needs && !getToken())
|
||||||
|
return (
|
||||||
|
<main className="app-login">
|
||||||
|
<Card className="app-login-card">
|
||||||
|
<div className="app-login-mark">
|
||||||
|
<ShieldCheck size={26} />
|
||||||
|
</div>
|
||||||
|
<h1>GitHub Register</h1>
|
||||||
|
<p>Enter your username and password to open the console.</p>
|
||||||
|
<Input
|
||||||
|
type="text"
|
||||||
|
placeholder="Username"
|
||||||
|
autoComplete="username"
|
||||||
|
value={username}
|
||||||
|
onChange={(e) => setUsername(e.target.value)}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && doLogin()}
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
type="password"
|
||||||
|
placeholder="Password"
|
||||||
|
autoComplete="current-password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && doLogin()}
|
||||||
|
/>
|
||||||
|
<Button variant="primary" size="lg" onClick={doLogin}>
|
||||||
|
Sign in
|
||||||
|
</Button>
|
||||||
|
</Card>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
|
||||||
|
const ActivePanel = {
|
||||||
|
status: StatusPanel,
|
||||||
|
config: ConfigPanel,
|
||||||
|
accounts: AccountsPanel,
|
||||||
|
}[tab];
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`${sidebarOpen ? "app-shell" : "app-shell app-shell-collapsed"}${drawerOpen ? " app-drawer-open" : ""}`}
|
||||||
|
>
|
||||||
|
{/* Mobile top bar: brand + job status + labeled menu (not a bare hamburger). */}
|
||||||
|
<header className="app-topbar">
|
||||||
|
<div className="app-topbar-brand">
|
||||||
|
<div className="app-brand-icon">
|
||||||
|
<Octagon size={18} />
|
||||||
|
</div>
|
||||||
|
<strong>GitHub Register</strong>
|
||||||
|
</div>
|
||||||
|
<div className="app-topbar-right">
|
||||||
|
<Badge tone={running ? "success" : "muted"}>
|
||||||
|
{running && <span className="pulse-dot" />}
|
||||||
|
{running ? "Running" : "Idle"}
|
||||||
|
</Badge>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="app-menu-btn"
|
||||||
|
onClick={() => setDrawerOpen(true)}
|
||||||
|
aria-label="Open menu"
|
||||||
|
aria-expanded={drawerOpen}
|
||||||
|
>
|
||||||
|
<Menu size={17} />
|
||||||
|
<span>Menu</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<div
|
||||||
|
className="app-drawer-scrim"
|
||||||
|
onClick={() => setDrawerOpen(false)}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
<aside
|
||||||
|
className={
|
||||||
|
sidebarOpen ? "app-sidebar" : "app-sidebar app-sidebar-collapsed"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="app-sidebar-top">
|
||||||
|
<div className="app-brand">
|
||||||
|
<div className="app-brand-icon">
|
||||||
|
<Octagon size={20} />
|
||||||
|
</div>
|
||||||
|
<div className="app-brand-copy">
|
||||||
|
<strong>GitHub Register</strong>
|
||||||
|
<a
|
||||||
|
className="app-brand-link"
|
||||||
|
href="https://t.me/alstack"
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
>
|
||||||
|
@alstack
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="app-drawer-close"
|
||||||
|
onClick={() => setDrawerOpen(false)}
|
||||||
|
aria-label="Close menu"
|
||||||
|
>
|
||||||
|
<X size={18} />
|
||||||
|
</button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="app-sidebar-toggle"
|
||||||
|
onClick={() => setSidebarOpen((open) => !open)}
|
||||||
|
aria-label={sidebarOpen ? "Collapse sidebar" : "Expand sidebar"}
|
||||||
|
title={sidebarOpen ? "Collapse sidebar" : "Expand sidebar"}
|
||||||
|
>
|
||||||
|
{sidebarOpen ? (
|
||||||
|
<PanelLeftClose size={17} />
|
||||||
|
) : (
|
||||||
|
<PanelLeftOpen size={17} />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<nav className="app-nav">
|
||||||
|
{NAV.map(({ id, label, icon: Icon }) => (
|
||||||
|
<button
|
||||||
|
key={id}
|
||||||
|
className={tab === id ? "app-nav-item active" : "app-nav-item"}
|
||||||
|
onClick={() => {
|
||||||
|
setTab(id);
|
||||||
|
setDrawerOpen(false);
|
||||||
|
if (id === "accounts") setGroup("");
|
||||||
|
}}
|
||||||
|
title={label}
|
||||||
|
>
|
||||||
|
<Icon size={17} />
|
||||||
|
<span>{label}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
<div className="app-nav-groups">
|
||||||
|
<div className="app-nav-label">
|
||||||
|
<span>Groups</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="app-nav-add"
|
||||||
|
onClick={() => {
|
||||||
|
setNewGroupName("");
|
||||||
|
setGroupCreateOpen(true);
|
||||||
|
}}
|
||||||
|
title="New group"
|
||||||
|
aria-label="New group"
|
||||||
|
>
|
||||||
|
<Plus size={14} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{groups.map((g) => (
|
||||||
|
<div key={g.name} className="app-group-row">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={
|
||||||
|
tab === "accounts" && group === g.name
|
||||||
|
? "app-nav-item active"
|
||||||
|
: "app-nav-item"
|
||||||
|
}
|
||||||
|
onClick={() => selectGroup(g.name)}
|
||||||
|
title={`${g.name} · ${g.count} accounts`}
|
||||||
|
>
|
||||||
|
<FolderGit2 size={16} />
|
||||||
|
<span className="app-group-name">{g.name}</span>
|
||||||
|
<span className="app-group-count">{g.count}</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="app-group-del"
|
||||||
|
onClick={() => setGroupDelete(g.name)}
|
||||||
|
title={`Delete group ${g.name}`}
|
||||||
|
aria-label={`Delete group ${g.name}`}
|
||||||
|
>
|
||||||
|
<X size={12} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{groups.length === 0 && (
|
||||||
|
<div className="app-nav-empty">No groups yet</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
<div className="app-sidebar-footer">
|
||||||
|
<Badge tone={running ? "success" : "muted"}>
|
||||||
|
{running && <span className="pulse-dot" />}
|
||||||
|
{running ? "Job running" : "Idle"}
|
||||||
|
</Badge>
|
||||||
|
{auth.needs && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={async () => {
|
||||||
|
try {
|
||||||
|
await api.post("/api/logout", {});
|
||||||
|
} catch {
|
||||||
|
/* expired token = already logged out, just clear local state */
|
||||||
|
}
|
||||||
|
setToken("");
|
||||||
|
window.location.reload();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<LogOut size={14} /> <span>Sign out</span>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<a
|
||||||
|
className="app-support"
|
||||||
|
href="https://t.me/alstack"
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
title="@alstack"
|
||||||
|
>
|
||||||
|
<Heart size={12} />
|
||||||
|
<span>Telegram</span>
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
className="app-credit"
|
||||||
|
href="https://github.com/gbonnet65923/gh-regkit-prime"
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
title="gbonnet65923/gh-regkit-prime"
|
||||||
|
>
|
||||||
|
<ExternalLink size={12} />
|
||||||
|
<span>gh-regkit-prime</span>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
<main className="app-main" key={tab}>
|
||||||
|
<ActivePanel
|
||||||
|
onGotoAccounts={() => {
|
||||||
|
setTab("accounts");
|
||||||
|
setGroup("");
|
||||||
|
}}
|
||||||
|
onGotoStatus={() => {
|
||||||
|
setTab("status");
|
||||||
|
}}
|
||||||
|
group={group}
|
||||||
|
onClearGroup={() => setGroup("")}
|
||||||
|
onGroupsChanged={loadGroups}
|
||||||
|
/>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
{/* Mobile bottom nav: the three primary destinations, one thumb away. */}
|
||||||
|
<nav className="app-bottomnav" aria-label="Primary">
|
||||||
|
{NAV.map(({ id, label, icon: Icon }) => (
|
||||||
|
<button
|
||||||
|
key={id}
|
||||||
|
type="button"
|
||||||
|
className={
|
||||||
|
tab === id
|
||||||
|
? "app-bottomnav-item active"
|
||||||
|
: "app-bottomnav-item"
|
||||||
|
}
|
||||||
|
onClick={() => {
|
||||||
|
setTab(id);
|
||||||
|
if (id === "accounts") setGroup("");
|
||||||
|
}}
|
||||||
|
aria-current={tab === id ? "page" : undefined}
|
||||||
|
>
|
||||||
|
<Icon size={19} />
|
||||||
|
<span>{label}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<Dialog
|
||||||
|
open={groupCreateOpen}
|
||||||
|
onClose={() => !groupBusy && setGroupCreateOpen(false)}
|
||||||
|
title="New group"
|
||||||
|
footer={
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
onClick={() => setGroupCreateOpen(false)}
|
||||||
|
disabled={groupBusy}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
onClick={doCreateGroup}
|
||||||
|
disabled={groupBusy || !newGroupName.trim()}
|
||||||
|
>
|
||||||
|
<Plus size={15} /> Create
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div style={{ display: "grid", gap: 10 }}>
|
||||||
|
<Input
|
||||||
|
autoFocus
|
||||||
|
value={newGroupName}
|
||||||
|
onChange={(e) => setNewGroupName(e.target.value)}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && doCreateGroup()}
|
||||||
|
placeholder="Group name, e.g. Github"
|
||||||
|
disabled={groupBusy}
|
||||||
|
/>
|
||||||
|
<div style={{ fontSize: 12, color: "var(--text-muted)" }}>
|
||||||
|
Only letters, digits, <code>-</code>, <code>_</code>, and{" "}
|
||||||
|
<code>.</code> (maks 60 karakter).
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
<Dialog
|
||||||
|
open={!!groupDelete}
|
||||||
|
onClose={() => setGroupDelete(null)}
|
||||||
|
title="Delete this group?"
|
||||||
|
footer={
|
||||||
|
<>
|
||||||
|
<Button onClick={() => setGroupDelete(null)}>Cancel</Button>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
onClick={doDeleteGroup}
|
||||||
|
disabled={groupBusy}
|
||||||
|
>
|
||||||
|
<X size={15} /> Delete
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Group <strong>{groupDelete}</strong> will be deleted. Accounts inside
|
||||||
|
are kept, only removed from the group.
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
const TOKEN_KEY = 'github-regkit-token'
|
||||||
|
|
||||||
|
export function getToken() {
|
||||||
|
return localStorage.getItem(TOKEN_KEY) || ''
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setToken(token) {
|
||||||
|
if (token) localStorage.setItem(TOKEN_KEY, token)
|
||||||
|
else localStorage.removeItem(TOKEN_KEY)
|
||||||
|
}
|
||||||
|
|
||||||
|
let _reloading = false
|
||||||
|
function authFailed(url) {
|
||||||
|
// Login/logout endpoints report credential errors themselves. Anything
|
||||||
|
// else with 401/403 means the stored token is dead (e.g. server restarted
|
||||||
|
// and wiped in-memory sessions): drop it and force a fresh login.
|
||||||
|
// No stored token + 401/403 is just the logged-out probe (e.g. the initial
|
||||||
|
// /api/config check) never reload or the login screen loops forever.
|
||||||
|
if (url.includes('/api/auth') || url.includes('/api/logout')) return false
|
||||||
|
if (!getToken()) return false
|
||||||
|
setToken('')
|
||||||
|
if (!_reloading) {
|
||||||
|
_reloading = true
|
||||||
|
window.location.reload()
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function request(method, url, body) {
|
||||||
|
const headers = { 'Content-Type': 'application/json' }
|
||||||
|
const token = getToken()
|
||||||
|
if (token) headers['X-Access-Key'] = token
|
||||||
|
const resp = await fetch(url, {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
|
})
|
||||||
|
if (resp.status === 401 || resp.status === 403) {
|
||||||
|
if (authFailed(url)) throw new Error('Session expired. Please log in again.')
|
||||||
|
throw new Error('unauthorized')
|
||||||
|
}
|
||||||
|
const data = await resp.json().catch(() => ({}))
|
||||||
|
if (!resp.ok || data.ok === false) {
|
||||||
|
throw new Error(data.detail || data.message || `HTTP ${resp.status}`)
|
||||||
|
}
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
async function uploadFile(url, file) {
|
||||||
|
const headers = { 'Content-Type': 'text/plain' }
|
||||||
|
const token = getToken()
|
||||||
|
if (token) headers['X-Access-Key'] = token
|
||||||
|
const resp = await fetch(url, { method: 'POST', headers, body: file })
|
||||||
|
if (resp.status === 401 || resp.status === 403) {
|
||||||
|
if (authFailed(url)) throw new Error('Session expired. Please log in again.')
|
||||||
|
throw new Error('unauthorized')
|
||||||
|
}
|
||||||
|
const data = await resp.json().catch(() => ({}))
|
||||||
|
if (!resp.ok || data.ok === false) throw new Error(data.detail || data.message || `HTTP ${resp.status}`)
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
export const api = {
|
||||||
|
get: (url) => request('GET', url),
|
||||||
|
post: (url, body) => request('POST', url, body),
|
||||||
|
put: (url, body) => request('PUT', url, body),
|
||||||
|
del: (url, body) => request('DELETE', url, body),
|
||||||
|
upload: uploadFile,
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function subscribeLogs(after, onLine) {
|
||||||
|
const token = getToken()
|
||||||
|
const headers = {}
|
||||||
|
if (token) headers['X-Access-Key'] = token
|
||||||
|
const resp = await fetch('/api/logs?after=' + after, { headers })
|
||||||
|
if (!resp.ok) {
|
||||||
|
if (resp.status === 401 || resp.status === 403) authFailed('/api/logs')
|
||||||
|
throw new Error('log stream failed')
|
||||||
|
}
|
||||||
|
const reader = resp.body.getReader()
|
||||||
|
const decoder = new TextDecoder()
|
||||||
|
let buf = ''
|
||||||
|
let closed = false
|
||||||
|
|
||||||
|
const read = async () => {
|
||||||
|
while (!closed) {
|
||||||
|
const { done, value } = await reader.read()
|
||||||
|
if (done) break
|
||||||
|
buf += decoder.decode(value, { stream: true })
|
||||||
|
let idx
|
||||||
|
while ((idx = buf.indexOf('\n\n')) !== -1) {
|
||||||
|
const chunk = buf.slice(0, idx)
|
||||||
|
buf = buf.slice(idx + 2)
|
||||||
|
for (const line of chunk.split('\n')) {
|
||||||
|
if (line.startsWith('data: ')) onLine(line.slice(6))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
read().catch(() => {})
|
||||||
|
return () => {
|
||||||
|
closed = true
|
||||||
|
reader.cancel().catch(() => {})
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,35 @@
|
|||||||
|
import React, { useEffect, useRef, useState } from 'react'
|
||||||
|
import { ListEnd, Radio, Trash2 } from 'lucide-react'
|
||||||
|
import { api, subscribeLogs } from '../api.js'
|
||||||
|
import { Badge, Button, Card, EmptyState } from './ui.jsx'
|
||||||
|
|
||||||
|
export default function LogViewer() {
|
||||||
|
const [lines, setLines] = useState([])
|
||||||
|
const [follow, setFollow] = useState(true)
|
||||||
|
const [live, setLive] = useState(false)
|
||||||
|
const [loadError, setLoadError] = useState('')
|
||||||
|
const boxRef = useRef(null)
|
||||||
|
useEffect(() => {
|
||||||
|
let closed = false; let unsubscribe = () => {}
|
||||||
|
api.get('/api/logs/snapshot?limit=500').then((data) => {
|
||||||
|
if (closed) return
|
||||||
|
setLines(data.lines || []); setLive(true)
|
||||||
|
setLoadError('')
|
||||||
|
subscribeLogs(data.seq || 0, (line) => !closed && setLines((prev) => [...prev.slice(-1499), line])).then((unsub) => { if (!closed) unsubscribe = unsub }).catch(() => {})
|
||||||
|
}).catch((error) => {
|
||||||
|
if (!closed) setLoadError(error.message || 'Logs could not be loaded')
|
||||||
|
})
|
||||||
|
return () => { closed = true; unsubscribe(); setLive(false) }
|
||||||
|
}, [])
|
||||||
|
useEffect(() => {
|
||||||
|
const el = boxRef.current
|
||||||
|
if (!follow || !el) return
|
||||||
|
// Keep the newest event visible while the stream is active.
|
||||||
|
el.scrollTop = el.scrollHeight
|
||||||
|
}, [lines, follow])
|
||||||
|
const color = (line) => line.includes('[+]') ? 'success' : line.includes('[-]') || line.includes('[!]') ? 'danger' : line.includes('[*]') ? 'accent' : ''
|
||||||
|
return <div className="log-layout">
|
||||||
|
<Card className="log-toolbar"><div className="log-toolbar-group"><Badge tone={live ? 'success' : 'muted'}><Radio size={12} />{live ? 'Streaming' : 'Connecting'}</Badge><span>{lines.length} lines</span></div><div className="log-toolbar-group"><label className="log-follow"><input type="checkbox" checked={follow} onChange={(e) => setFollow(e.target.checked)} /> Auto-scroll</label><Button size="sm" onClick={() => setLines([])}><Trash2 size={14} /> Clear</Button></div></Card>
|
||||||
|
<Card className="log-terminal" ref={boxRef}>{loadError ? <div className="panel-state panel-state-error"><strong>Unable to load logs</strong><span>{loadError}</span><Button onClick={() => window.location.reload()}>Retry</Button></div> : lines.length === 0 ? <EmptyState icon={ListEnd} title="No logs yet" description="Start a job from the Status page to view events in real time." /> : lines.map((line, index) => <div key={index} className={`log-line ${color(line)}`}>{line}</div>)}</Card>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
@@ -0,0 +1,434 @@
|
|||||||
|
import React, {
|
||||||
|
useCallback,
|
||||||
|
useEffect,
|
||||||
|
useMemo,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
} from "react";
|
||||||
|
import {
|
||||||
|
AlertTriangle,
|
||||||
|
CheckCircle2,
|
||||||
|
Clock3,
|
||||||
|
FileText,
|
||||||
|
ListChecks,
|
||||||
|
Play,
|
||||||
|
Square,
|
||||||
|
Target,
|
||||||
|
XCircle,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { api } from "../api.js";
|
||||||
|
import { Badge, Button, Card, Input, Spinner } from "./ui.jsx";
|
||||||
|
import LogViewer from "./LogViewer.jsx";
|
||||||
|
|
||||||
|
const fmtTime = (ts) =>
|
||||||
|
ts ? new Date(ts * 1000).toLocaleTimeString("en-US", { hour12: false }) : "-";
|
||||||
|
|
||||||
|
const fmtDuration = (sec) => {
|
||||||
|
if (!Number.isFinite(sec) || sec < 0) return "-";
|
||||||
|
const s = Math.floor(sec);
|
||||||
|
const h = Math.floor(s / 3600);
|
||||||
|
const m = Math.floor((s % 3600) / 60);
|
||||||
|
const r = s % 60;
|
||||||
|
const pad = (n) => String(n).padStart(2, "0");
|
||||||
|
return h > 0 ? `${pad(h)}.${pad(m)}.${pad(r)}` : `${pad(m)}.${pad(r)}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function StatusPanel({ onGotoAccounts }) {
|
||||||
|
const [state, setState] = useState(null);
|
||||||
|
const [count, setCount] = useState(1);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [loadError, setLoadError] = useState("");
|
||||||
|
const [now, setNow] = useState(Date.now());
|
||||||
|
const timer = useRef(null);
|
||||||
|
const tickTimer = useRef(null);
|
||||||
|
|
||||||
|
const refresh = useCallback(() => {
|
||||||
|
api
|
||||||
|
.get("/api/status")
|
||||||
|
.then((data) => {
|
||||||
|
setState(data);
|
||||||
|
setLoadError("");
|
||||||
|
})
|
||||||
|
.catch((error) => setLoadError(error.message || "Status could not be loaded"));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
refresh();
|
||||||
|
timer.current = setInterval(refresh, 1500);
|
||||||
|
tickTimer.current = setInterval(() => setNow(Date.now()), 1000);
|
||||||
|
return () => {
|
||||||
|
clearInterval(timer.current);
|
||||||
|
clearInterval(tickTimer.current);
|
||||||
|
};
|
||||||
|
}, [refresh]);
|
||||||
|
|
||||||
|
const running = !!state?.running;
|
||||||
|
const target = state?.target ?? 0;
|
||||||
|
const success = state?.success ?? 0;
|
||||||
|
const failed = state?.fail ?? 0;
|
||||||
|
const done = success + failed;
|
||||||
|
|
||||||
|
// progress: only meaningful when target > 0
|
||||||
|
const progress =
|
||||||
|
target > 0 ? Math.min(100, Math.round((done / target) * 100)) : 0;
|
||||||
|
|
||||||
|
// elapsed live counter
|
||||||
|
const elapsedSec = useMemo(() => {
|
||||||
|
if (!state?.started_at) return 0;
|
||||||
|
const end = state?.finished_at ? state.finished_at * 1000 : now;
|
||||||
|
return Math.max(0, (end - state.started_at * 1000) / 1000);
|
||||||
|
}, [state?.started_at, state?.finished_at, now]);
|
||||||
|
|
||||||
|
// status label + tone
|
||||||
|
const statusInfo = useMemo(() => {
|
||||||
|
if (running)
|
||||||
|
return { label: "Running", tone: "ok", title: "Creating accounts" };
|
||||||
|
if (state?.error)
|
||||||
|
return { label: "Error", tone: "bad", title: "Job failed" };
|
||||||
|
if (state?.finished_at) {
|
||||||
|
if (target > 0 && done >= target && failed === 0)
|
||||||
|
return {
|
||||||
|
label: "Completed",
|
||||||
|
tone: "ok",
|
||||||
|
title: "All accounts were created",
|
||||||
|
};
|
||||||
|
if (target > 0 && done < target)
|
||||||
|
return {
|
||||||
|
label: "Stopped",
|
||||||
|
tone: "muted",
|
||||||
|
title: "Job stopped before completion",
|
||||||
|
};
|
||||||
|
if (failed > 0 && success === 0)
|
||||||
|
return {
|
||||||
|
label: "All failed",
|
||||||
|
tone: "bad",
|
||||||
|
title: "No accounts were created",
|
||||||
|
};
|
||||||
|
return { label: "Completed", tone: "ok", title: "Job completed" };
|
||||||
|
}
|
||||||
|
return { label: "Ready", tone: "muted", title: "Ready to register" };
|
||||||
|
}, [
|
||||||
|
running,
|
||||||
|
state?.error,
|
||||||
|
state?.finished_at,
|
||||||
|
target,
|
||||||
|
done,
|
||||||
|
failed,
|
||||||
|
success,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const progressTone = statusInfo.tone;
|
||||||
|
|
||||||
|
async function start() {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await api.post("/api/start", { count });
|
||||||
|
refresh();
|
||||||
|
} catch (e) {
|
||||||
|
alert(e.message);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function stop() {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await api.post("/api/stop");
|
||||||
|
refresh();
|
||||||
|
} catch (e) {
|
||||||
|
alert(e.message);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={styles.wrap}>
|
||||||
|
{/* hero */}
|
||||||
|
<Card style={styles.hero}>
|
||||||
|
<div style={styles.heroText}>
|
||||||
|
<div style={styles.eyebrow}>GITHUB ACCOUNT REGISTRATION</div>
|
||||||
|
<h1 style={styles.heroTitle}>{statusInfo.title}</h1>
|
||||||
|
</div>
|
||||||
|
<Badge
|
||||||
|
tone={
|
||||||
|
statusInfo.tone === "ok"
|
||||||
|
? "success"
|
||||||
|
: statusInfo.tone === "bad"
|
||||||
|
? "danger"
|
||||||
|
: "muted"
|
||||||
|
}
|
||||||
|
className="status-hero-badge"
|
||||||
|
>
|
||||||
|
{running && <span className="pulse-dot" />}
|
||||||
|
{statusInfo.label}
|
||||||
|
</Badge>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Metrics share one surface with hairline dividers so they read as a
|
||||||
|
single summary, not six separate boxes. */}
|
||||||
|
<Card style={styles.metricsCard}>
|
||||||
|
<div className="status-metrics">
|
||||||
|
<Stat label="Target" value={target} icon={Target} />
|
||||||
|
<Stat label="Success" value={success} tone="ok" icon={CheckCircle2} />
|
||||||
|
<Stat label="Failed" value={failed} tone="bad" icon={XCircle} />
|
||||||
|
<Stat
|
||||||
|
label="Progress"
|
||||||
|
value={target > 0 ? `${done}/${target}` : "-"}
|
||||||
|
hint={target > 0 ? `${progress}%` : null}
|
||||||
|
icon={ListChecks}
|
||||||
|
/>
|
||||||
|
<Stat
|
||||||
|
label="Started"
|
||||||
|
value={fmtTime(state?.started_at)}
|
||||||
|
icon={Play}
|
||||||
|
small
|
||||||
|
/>
|
||||||
|
<Stat
|
||||||
|
label={running ? "Elapsed" : "Duration"}
|
||||||
|
value={fmtDuration(elapsedSec)}
|
||||||
|
icon={running ? Clock3 : Square}
|
||||||
|
small
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Show progress only after the server has a target. */}
|
||||||
|
{target > 0 && (
|
||||||
|
<Card style={styles.progressCard}>
|
||||||
|
<div style={styles.progressHead}>
|
||||||
|
<span style={{ color: "var(--muted)", fontWeight: 600 }}>
|
||||||
|
Progress
|
||||||
|
</span>
|
||||||
|
<span style={{ fontWeight: 700 }}>
|
||||||
|
{done} / {target}{" "}
|
||||||
|
<span style={{ color: "var(--muted)", fontWeight: 500 }}>
|
||||||
|
({progress}%)
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div style={styles.progressTrack}>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
...styles.progressFill,
|
||||||
|
width: `${progress}%`,
|
||||||
|
background: progressFillColor(progressTone, running),
|
||||||
|
boxShadow: progressGlow(progressTone),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{(success > 0 || failed > 0) && (
|
||||||
|
<div style={styles.progressLegend}>
|
||||||
|
<span style={{ color: "var(--ok)" }}>● {success} success</span>
|
||||||
|
<span style={{ color: "var(--danger)" }}>● {failed} failed</span>
|
||||||
|
{running && target - done > 0 && (
|
||||||
|
<span style={{ color: "var(--muted)" }}>
|
||||||
|
● {target - done} pending
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{state?.error && (
|
||||||
|
<Card style={styles.errorCard}>
|
||||||
|
<span
|
||||||
|
style={{ color: "var(--danger)", fontSize: 13, fontWeight: 600 }}
|
||||||
|
>
|
||||||
|
<AlertTriangle
|
||||||
|
size={15}
|
||||||
|
style={{ verticalAlign: "text-bottom", marginRight: 6 }}
|
||||||
|
/>
|
||||||
|
{state.error}
|
||||||
|
</span>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* controls: one grouped surface, one clear action area */}
|
||||||
|
<Card className="status-controls">
|
||||||
|
<div className="status-control-block">
|
||||||
|
<span className="status-control-label">Account count</span>
|
||||||
|
<div className="status-stepper">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="status-stepper-btn"
|
||||||
|
onClick={() => setCount((c) => Math.max(1, c - 1))}
|
||||||
|
disabled={running || count <= 1}
|
||||||
|
aria-label="Decrease count"
|
||||||
|
>
|
||||||
|
−
|
||||||
|
</button>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
min="1"
|
||||||
|
max="1000"
|
||||||
|
value={count}
|
||||||
|
className="status-count-input"
|
||||||
|
onChange={(e) =>
|
||||||
|
setCount(
|
||||||
|
Math.max(1, Math.min(1000, Number(e.target.value) || 1)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
disabled={running}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="status-stepper-btn"
|
||||||
|
onClick={() => setCount((c) => Math.min(1000, c + 1))}
|
||||||
|
disabled={running || count >= 1000}
|
||||||
|
aria-label="Increase count"
|
||||||
|
>
|
||||||
|
+
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="status-actions">
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
className="status-action-primary"
|
||||||
|
onClick={start}
|
||||||
|
disabled={running || busy}
|
||||||
|
>
|
||||||
|
<Play size={16} /> Start
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
className="status-action-stop"
|
||||||
|
onClick={stop}
|
||||||
|
disabled={!running || busy}
|
||||||
|
>
|
||||||
|
<Square size={15} /> Stop
|
||||||
|
</Button>
|
||||||
|
<Button className="status-action-nav" onClick={onGotoAccounts}>
|
||||||
|
<FileText size={16} /> Accounts
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{state === null && !loadError && (
|
||||||
|
<Card className="status-state-card">
|
||||||
|
<Spinner />
|
||||||
|
<span>Loading job status</span>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
{loadError && (
|
||||||
|
<Card className="status-state-card status-state-error">
|
||||||
|
<strong>Unable to load job status</strong>
|
||||||
|
<span>{loadError}</span>
|
||||||
|
<Button onClick={refresh}>Retry</Button>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<LogViewer />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Stat({ label, value, tone, small, icon: Icon, hint }) {
|
||||||
|
const color =
|
||||||
|
tone === "ok"
|
||||||
|
? "var(--ok)"
|
||||||
|
: tone === "bad"
|
||||||
|
? "var(--danger)"
|
||||||
|
: "var(--text)";
|
||||||
|
return (
|
||||||
|
<div className="status-stat">
|
||||||
|
<div className="status-stat-head">
|
||||||
|
<Icon size={14} className="status-stat-icon" style={{ color }} />
|
||||||
|
<span className="status-stat-label">{label}</span>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className={small ? "status-stat-value is-small" : "status-stat-value"}
|
||||||
|
style={{ color }}
|
||||||
|
>
|
||||||
|
{value}
|
||||||
|
</div>
|
||||||
|
{hint && <div className="status-stat-hint">{hint}</div>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// helper: progress bar gradient depending on state
|
||||||
|
function progressFillColor(tone, running) {
|
||||||
|
if (tone === "bad") return "var(--danger)";
|
||||||
|
if (tone === "muted" && !running) return "var(--border-strong)";
|
||||||
|
return "var(--accent)";
|
||||||
|
}
|
||||||
|
function progressGlow(tone) {
|
||||||
|
return "none";
|
||||||
|
}
|
||||||
|
|
||||||
|
const styles = {
|
||||||
|
wrap: {
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
gap: 14,
|
||||||
|
maxWidth: 980,
|
||||||
|
width: "100%",
|
||||||
|
margin: "0 auto",
|
||||||
|
},
|
||||||
|
hero: {
|
||||||
|
padding: "clamp(18px, 3vw, 26px)",
|
||||||
|
display: "flex",
|
||||||
|
gap: 16,
|
||||||
|
alignItems: "flex-start",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
flexWrap: "wrap",
|
||||||
|
background:
|
||||||
|
"var(--bg-card)",
|
||||||
|
},
|
||||||
|
heroText: { flex: "1 1 260px", minWidth: 0 },
|
||||||
|
eyebrow: {
|
||||||
|
fontSize: 11.5,
|
||||||
|
color: "var(--muted)",
|
||||||
|
fontWeight: 700,
|
||||||
|
letterSpacing: 0.6,
|
||||||
|
marginBottom: 6,
|
||||||
|
},
|
||||||
|
heroTitle: {
|
||||||
|
fontSize: "clamp(20px, 4.5vw, 26px)",
|
||||||
|
fontWeight: 800,
|
||||||
|
letterSpacing: -0.4,
|
||||||
|
lineHeight: 1.2,
|
||||||
|
color: "var(--text-primary)",
|
||||||
|
},
|
||||||
|
|
||||||
|
metricsCard: { padding: 0, overflow: "hidden" },
|
||||||
|
progressCard: { padding: "16px 20px" },
|
||||||
|
progressHead: {
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
alignItems: "baseline",
|
||||||
|
fontSize: 12.5,
|
||||||
|
marginBottom: 10,
|
||||||
|
flexWrap: "wrap",
|
||||||
|
gap: 8,
|
||||||
|
},
|
||||||
|
progressTrack: {
|
||||||
|
height: 10,
|
||||||
|
borderRadius: 4,
|
||||||
|
background: "var(--bg-input)",
|
||||||
|
overflow: "hidden",
|
||||||
|
},
|
||||||
|
progressFill: {
|
||||||
|
height: "100%",
|
||||||
|
borderRadius: 4,
|
||||||
|
transition: "width 0.5s cubic-bezier(0.4, 0, 0.2, 1), background 0.3s",
|
||||||
|
},
|
||||||
|
progressLegend: {
|
||||||
|
display: "flex",
|
||||||
|
gap: 14,
|
||||||
|
flexWrap: "wrap",
|
||||||
|
marginTop: 10,
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: 600,
|
||||||
|
},
|
||||||
|
|
||||||
|
errorCard: {
|
||||||
|
padding: "14px 18px",
|
||||||
|
borderColor: "rgba(var(--danger-rgb),0.4)",
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import React, { useEffect, useRef } from 'react'
|
||||||
|
|
||||||
|
const cx = (...classes) => classes.filter(Boolean).join(' ')
|
||||||
|
|
||||||
|
export const Card = React.forwardRef(function Card({ className, children, ...props }, ref) {
|
||||||
|
return <section ref={ref} className={cx('ui-card', className)} {...props}>{children}</section>
|
||||||
|
})
|
||||||
|
|
||||||
|
export function Button({ className, variant = 'outline', size = 'default', children, ...props }) {
|
||||||
|
return (
|
||||||
|
<button className={cx('ui-button', `ui-button-${variant}`, `ui-button-${size}`, className)} {...props}>
|
||||||
|
{children}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Input({ className, ...props }) {
|
||||||
|
return <input className={cx('ui-input', className)} {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Badge({ tone = 'muted', children, className }) {
|
||||||
|
return <span className={cx('ui-badge', `ui-badge-${tone}`, className)}>{children}</span>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Dialog({ open, onClose, title, children, footer }) {
|
||||||
|
const dialogRef = useRef(null)
|
||||||
|
const onCloseRef = useRef(onClose)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
onCloseRef.current = onClose
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return undefined
|
||||||
|
if (document.activeElement === document.body) dialogRef.current?.focus()
|
||||||
|
const onKeyDown = (event) => {
|
||||||
|
if (event.key === 'Escape') onCloseRef.current()
|
||||||
|
}
|
||||||
|
document.addEventListener('keydown', onKeyDown)
|
||||||
|
return () => document.removeEventListener('keydown', onKeyDown)
|
||||||
|
}, [open])
|
||||||
|
|
||||||
|
if (!open) return null
|
||||||
|
return (
|
||||||
|
<div className="ui-dialog-backdrop" role="presentation" onMouseDown={onClose}>
|
||||||
|
<section ref={dialogRef} tabIndex="-1" className="ui-dialog" role="dialog" aria-modal="true" aria-label={title} onMouseDown={(e) => e.stopPropagation()}>
|
||||||
|
{title && <header className="ui-dialog-header"><h2>{title}</h2><button type="button" className="ui-dialog-close" onClick={onClose} aria-label="Close dialog">×</button></header>}
|
||||||
|
<div className="ui-dialog-body">{children}</div>
|
||||||
|
{footer && <footer className="ui-dialog-footer">{footer}</footer>}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Spinner({ className }) {
|
||||||
|
return <span className={cx('ui-spinner', className)} aria-label="Loading" />
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EmptyState({ icon: Icon, title, description, action }) {
|
||||||
|
return (
|
||||||
|
<div className="ui-empty-state">
|
||||||
|
{Icon && <Icon size={28} strokeWidth={1.7} />}
|
||||||
|
<strong>{title}</strong>
|
||||||
|
{description && <p>{description}</p>}
|
||||||
|
{action}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
/* Shared styles for the zone modal and account notifications. */
|
||||||
|
|
||||||
|
.glass {
|
||||||
|
background: var(--bg-card);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius-card);
|
||||||
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.glass-strong { background: var(--bg-card-hover); }
|
||||||
|
|
||||||
|
.glass-btn {
|
||||||
|
display: inline-flex; align-items: center; justify-content: center; gap: 8px;
|
||||||
|
min-height: 44px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
background: transparent;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
border-radius: var(--radius-control);
|
||||||
|
padding: 9px 16px;
|
||||||
|
font-family: inherit; font-size: 13px; font-weight: 500;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: border-color 150ms ease-out, background 150ms ease-out, color 150ms ease-out;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
.glass-btn:hover:not(:disabled) {
|
||||||
|
border-color: var(--color-smoke-gray);
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
.glass-btn:disabled { opacity: 0.42; cursor: not-allowed; }
|
||||||
|
.glass-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||||
|
|
||||||
|
.glass-btn.primary {
|
||||||
|
background: var(--accent);
|
||||||
|
border-color: transparent;
|
||||||
|
color: var(--color-void-black);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.glass-btn.primary:hover:not(:disabled) { background: var(--accent-strong); }
|
||||||
|
|
||||||
|
.glass-btn.danger {
|
||||||
|
border-color: rgba(var(--danger-rgb), 0.40);
|
||||||
|
color: var(--danger);
|
||||||
|
}
|
||||||
|
.glass-btn.danger:hover:not(:disabled) {
|
||||||
|
background: rgba(var(--danger-rgb), 0.12);
|
||||||
|
border-color: rgba(var(--danger-rgb), 0.60);
|
||||||
|
}
|
||||||
|
|
||||||
|
.glass-input {
|
||||||
|
width: 100%;
|
||||||
|
min-height: 44px;
|
||||||
|
background: var(--bg-input);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
color: var(--text-primary);
|
||||||
|
border-radius: var(--radius-control);
|
||||||
|
padding: 10px 14px;
|
||||||
|
font-family: inherit; font-size: 13.5px;
|
||||||
|
transition: border-color 150ms ease-out, box-shadow 150ms ease-out;
|
||||||
|
}
|
||||||
|
.glass-input:focus {
|
||||||
|
border-color: rgba(var(--accent-rgb), 0.70);
|
||||||
|
box-shadow: var(--ring);
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
.glass-input::placeholder { color: var(--text-muted); }
|
||||||
|
|
||||||
|
.glass-input.number {
|
||||||
|
width: 86px; text-align: center;
|
||||||
|
-moz-appearance: textfield;
|
||||||
|
}
|
||||||
|
.glass-input.number::-webkit-inner-spin-button { display: none; }
|
||||||
|
|
||||||
|
.glass-segmented {
|
||||||
|
display: inline-flex; gap: 4px; padding: 4px;
|
||||||
|
background: var(--bg-input);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius-control);
|
||||||
|
}
|
||||||
|
.glass-segmented button {
|
||||||
|
border: none; background: transparent; color: var(--text-muted);
|
||||||
|
font-family: inherit; font-size: 13px; font-weight: 500;
|
||||||
|
min-height: 36px;
|
||||||
|
padding: 8px 16px; border-radius: var(--radius-control); cursor: pointer;
|
||||||
|
transition: background 150ms ease-out, color 150ms ease-out;
|
||||||
|
display: inline-flex; align-items: center; gap: 7px;
|
||||||
|
}
|
||||||
|
.glass-segmented button.active {
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.badge {
|
||||||
|
display: inline-flex; align-items: center; gap: 6px;
|
||||||
|
font-size: 11px; font-weight: 600;
|
||||||
|
padding: 5px 11px; border-radius: var(--radius-control);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.badge.ok { color: var(--success); border-color: rgba(var(--success-rgb), 0.35); }
|
||||||
|
.badge.bad { color: var(--danger); border-color: rgba(var(--danger-rgb), 0.40); }
|
||||||
|
.badge.accent { color: var(--accent-text); border-color: rgba(var(--accent-rgb), 0.35); }
|
||||||
|
.badge.muted { color: var(--text-muted); }
|
||||||
|
|
||||||
|
.pulse-dot {
|
||||||
|
width: 8px; height: 8px; border-radius: 50%;
|
||||||
|
background: var(--success);
|
||||||
|
animation: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.fade-in { animation: fadeIn 0.25s ease-out; }
|
||||||
|
|
||||||
|
.toast {
|
||||||
|
position: fixed; bottom: 28px; left: 50%; transform: translateX(-50%);
|
||||||
|
z-index: 999; padding: 12px 22px;
|
||||||
|
max-width: calc(100vw - 32px);
|
||||||
|
color: var(--text-primary);
|
||||||
|
animation: toastIn 0.22s ease-out;
|
||||||
|
}
|
||||||
|
@keyframes toastIn { from { opacity: 0; transform: translate(-50%, 12px); } to { opacity: 1; transform: translate(-50%, 0); } }
|
||||||
|
|
||||||
|
/* Keep toasts above the mobile bottom nav. */
|
||||||
|
@media (max-width: 820px) {
|
||||||
|
.toast { bottom: calc(var(--bottom-nav-height) + 16px + env(safe-area-inset-bottom)); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import React from 'react'
|
||||||
|
import ReactDOM from 'react-dom/client'
|
||||||
|
import App from './App.jsx'
|
||||||
|
import './glass.css'
|
||||||
|
import './ui.css'
|
||||||
|
|
||||||
|
ReactDOM.createRoot(document.getElementById('root')).render(
|
||||||
|
<React.StrictMode>
|
||||||
|
<App />
|
||||||
|
</React.StrictMode>,
|
||||||
|
)
|
||||||
+1051
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,153 @@
|
|||||||
|
const { chromium } = require('playwright')
|
||||||
|
const BASE = process.env.BASE || 'http://127.0.0.1:8093'
|
||||||
|
|
||||||
|
const log = []
|
||||||
|
const step = (ok, msg) => { log.push(`${ok ? 'PASS' : 'FAIL'} ${msg}`); return ok }
|
||||||
|
|
||||||
|
async function clickTab(page, label) {
|
||||||
|
await page.evaluate((lbl) => {
|
||||||
|
const nodes = [...document.querySelectorAll('.app-bottomnav-item, .app-nav-item')]
|
||||||
|
for (const el of nodes) { const r = el.getBoundingClientRect(); if ((el.textContent || '').trim() === lbl && r.width > 0 && r.left >= -1 && r.right <= window.innerWidth + 1) { el.click(); return } }
|
||||||
|
}, label)
|
||||||
|
await page.waitForTimeout(500)
|
||||||
|
}
|
||||||
|
|
||||||
|
;(async () => {
|
||||||
|
const browser = await chromium.launch()
|
||||||
|
const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } })
|
||||||
|
const page = await ctx.newPage()
|
||||||
|
const errs = []
|
||||||
|
page.on('console', (m) => m.type() === 'error' && errs.push(m.text()))
|
||||||
|
page.on('pageerror', (e) => errs.push('pageerror: ' + e.message))
|
||||||
|
|
||||||
|
await page.goto(BASE, { waitUntil: 'domcontentloaded' })
|
||||||
|
await page.waitForTimeout(900)
|
||||||
|
|
||||||
|
// 1. Status tab: count stepper +/-, Start/Stop buttons exist and are wired.
|
||||||
|
step(await page.locator('.status-stepper-btn').first().isVisible(), 'Status: count stepper visible')
|
||||||
|
const before = await page.locator('.status-count-input').inputValue()
|
||||||
|
await page.locator('.status-stepper-btn').last().click()
|
||||||
|
await page.waitForTimeout(150)
|
||||||
|
const after = await page.locator('.status-count-input').inputValue()
|
||||||
|
step(Number(after) === Number(before) + 1, `Status: "+" increments count (${before} -> ${after})`)
|
||||||
|
await page.locator('.status-stepper-btn').first().click()
|
||||||
|
await page.waitForTimeout(150)
|
||||||
|
step((await page.locator('.status-count-input').inputValue()) === before, 'Status: "-" decrements count')
|
||||||
|
|
||||||
|
// 2. Log terminal: Clear button empties lines.
|
||||||
|
const linesBefore = await page.locator('.log-line').count()
|
||||||
|
await page.locator('.log-toolbar .ui-button').click()
|
||||||
|
await page.waitForTimeout(300)
|
||||||
|
const linesAfter = await page.locator('.log-line').count()
|
||||||
|
step(linesAfter === 0, `Log: Clear empties terminal (${linesBefore} -> ${linesAfter})`)
|
||||||
|
step(await page.locator('.log-terminal .ui-empty-state').isVisible(), 'Log: empty state shown after clear')
|
||||||
|
|
||||||
|
// 3. Auto-scroll checkbox toggles.
|
||||||
|
await page.locator('.log-follow input[type=checkbox]').click()
|
||||||
|
await page.waitForTimeout(100)
|
||||||
|
step(!(await page.locator('.log-follow input[type=checkbox]').isChecked()), 'Log: auto-scroll checkbox toggles')
|
||||||
|
|
||||||
|
// 4. Accounts tab.
|
||||||
|
await clickTab(page, 'Accounts')
|
||||||
|
step(await page.locator('.accounts-head').isVisible(), 'Accounts: header renders')
|
||||||
|
const exportBtn = page.locator('.export-wrap .ui-button')
|
||||||
|
step(await exportBtn.isVisible(), 'Accounts: Export button visible')
|
||||||
|
await exportBtn.click()
|
||||||
|
await page.waitForTimeout(250)
|
||||||
|
step(await page.locator('.action-menu-inline').isVisible(), 'Accounts: Export menu opens')
|
||||||
|
await page.keyboard.press('Escape')
|
||||||
|
await page.waitForTimeout(200)
|
||||||
|
step(!(await page.locator('.action-menu-inline').isVisible()), 'Accounts: Export menu closes on Escape')
|
||||||
|
|
||||||
|
// 5. Config tab: provider radios switch fields.
|
||||||
|
await clickTab(page, 'Config')
|
||||||
|
step(await page.locator('.cfg-columns').isVisible(), 'Config: layout renders')
|
||||||
|
const litensi = page.locator('label:has-text("Litensi")').first()
|
||||||
|
await litensi.click()
|
||||||
|
await page.waitForTimeout(300)
|
||||||
|
step(await page.locator('text=Litensi API ID').isVisible(), 'Config: switching to Litensi shows its fields')
|
||||||
|
await page.locator('label:has-text("Mail.cx")').first().click()
|
||||||
|
await page.waitForTimeout(300)
|
||||||
|
step(await page.locator('text=Mail.cx Domain').first().isVisible(), 'Config: switching back to Mail.cx shows its fields')
|
||||||
|
|
||||||
|
// 6. Zones modal (uses the design-system modal) opens + closes.
|
||||||
|
await page.locator('label:has-text("Litensi")').first().click()
|
||||||
|
await page.waitForTimeout(250)
|
||||||
|
const zonesBtn = page.locator('button:has-text("Zones")').first()
|
||||||
|
if (await zonesBtn.isVisible()) {
|
||||||
|
await zonesBtn.click()
|
||||||
|
await page.waitForTimeout(1200)
|
||||||
|
const modalOpen = await page.locator('.glass').first().isVisible()
|
||||||
|
step(modalOpen, 'Config: Zones modal opens')
|
||||||
|
if (modalOpen) {
|
||||||
|
await page.locator('.glass button:has-text("Close")').click()
|
||||||
|
await page.waitForTimeout(300)
|
||||||
|
step(!(await page.locator('.glass').first().isVisible()), 'Config: Zones modal closes')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 7. New group dialog: open, type, cancel.
|
||||||
|
await page.locator('.app-nav-add').click()
|
||||||
|
await page.waitForTimeout(300)
|
||||||
|
step(await page.locator('.ui-dialog').isVisible(), 'Group: New group dialog opens')
|
||||||
|
await page.locator('.ui-dialog input').fill('TestGroup')
|
||||||
|
await page.waitForTimeout(100)
|
||||||
|
await page.keyboard.press('Escape')
|
||||||
|
await page.waitForTimeout(300)
|
||||||
|
step(!(await page.locator('.ui-dialog').isVisible()), 'Group: dialog closes on Escape')
|
||||||
|
|
||||||
|
// 8. Sidebar collapse toggle (desktop).
|
||||||
|
await page.locator('.app-sidebar-toggle').click()
|
||||||
|
await page.waitForTimeout(300)
|
||||||
|
const collapsed = await page.locator('.app-shell-collapsed').count()
|
||||||
|
step(collapsed > 0, 'Sidebar: collapse toggle works')
|
||||||
|
await page.locator('.app-sidebar-toggle').click()
|
||||||
|
await page.waitForTimeout(300)
|
||||||
|
|
||||||
|
// 9. Keyboard: Tab reaches a focusable control with visible focus.
|
||||||
|
await page.keyboard.press('Tab')
|
||||||
|
const focused = await page.evaluate(() => document.activeElement?.tagName)
|
||||||
|
step(['BUTTON', 'A', 'INPUT'].includes(focused), `Keyboard: Tab focuses a control (${focused})`)
|
||||||
|
|
||||||
|
await ctx.close()
|
||||||
|
|
||||||
|
// Mobile pass: drawer open/close, bottom nav switches.
|
||||||
|
const mctx = await browser.newContext({ viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true })
|
||||||
|
const mp = await mctx.newPage()
|
||||||
|
mp.on('console', (m) => m.type() === 'error' && errs.push('[mobile] ' + m.text()))
|
||||||
|
mp.on('pageerror', (e) => errs.push('[mobile] pageerror: ' + e.message))
|
||||||
|
await mp.goto(BASE, { waitUntil: 'domcontentloaded' })
|
||||||
|
await mp.waitForTimeout(900)
|
||||||
|
|
||||||
|
await mp.locator('.app-menu-btn').click()
|
||||||
|
await mp.waitForTimeout(350)
|
||||||
|
step(await mp.locator('.app-sidebar').isVisible(), 'Mobile: Menu opens drawer')
|
||||||
|
await mp.locator('.app-drawer-scrim').click({ position: { x: 380, y: 400 } })
|
||||||
|
await mp.waitForTimeout(350)
|
||||||
|
const drawerGone = await mp.locator('.app-sidebar').evaluate((el) => el.getBoundingClientRect().right <= 0)
|
||||||
|
step(drawerGone, 'Mobile: scrim click closes drawer')
|
||||||
|
await clickTab(mp, 'Accounts')
|
||||||
|
step(await mp.locator('.accounts-head').isVisible(), 'Mobile: bottom nav switches to Accounts')
|
||||||
|
await clickTab(mp, 'Status')
|
||||||
|
step(await mp.locator('.status-metrics').isVisible(), 'Mobile: bottom nav switches back to Status')
|
||||||
|
|
||||||
|
// Bottom nav must be fixed and content must clear it.
|
||||||
|
const clear = await mp.evaluate(() => {
|
||||||
|
const nav = document.querySelector('.app-bottomnav')
|
||||||
|
const main = document.querySelector('.app-main')
|
||||||
|
const navR = nav.getBoundingClientRect()
|
||||||
|
const pad = parseFloat(getComputedStyle(main).paddingBottom)
|
||||||
|
return { navTop: Math.round(navR.top), viewportH: window.innerHeight, pad: Math.round(pad), navH: Math.round(navR.height) }
|
||||||
|
})
|
||||||
|
step(clear.pad >= clear.navH, `Mobile: content padding (${clear.pad}) >= bottom nav height (${clear.navH})`)
|
||||||
|
await mctx.close()
|
||||||
|
await browser.close()
|
||||||
|
|
||||||
|
console.log('=== CLICK-THROUGH ===')
|
||||||
|
log.forEach((l) => console.log(' ' + l))
|
||||||
|
console.log('\n=== CONSOLE ERRORS ===')
|
||||||
|
console.log(errs.length ? errs.join('\n') : '(none)')
|
||||||
|
const fails = log.filter((l) => l.startsWith('FAIL')).length
|
||||||
|
console.log(`\nFailures: ${fails}, console errors: ${errs.length}`)
|
||||||
|
process.exit(fails || errs.length ? 1 : 0)
|
||||||
|
})().catch((e) => { console.error('FATAL', e); process.exit(1) })
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* UI verification for the GitHub Register console.
|
||||||
|
*
|
||||||
|
* Checks the redesign against the hard requirements it must hold at every
|
||||||
|
* screen width: no horizontal overflow, no clipped controls, 44px tap targets,
|
||||||
|
* WCAG AA text contrast, and working navigation / dialogs.
|
||||||
|
*
|
||||||
|
* Usage: node verify-ui.cjs [baseUrl]
|
||||||
|
* Requires a running server (default http://127.0.0.1:8093) serving the build.
|
||||||
|
*/
|
||||||
|
const { chromium } = require('playwright')
|
||||||
|
|
||||||
|
const BASE = process.argv[2] || process.env.BASE || 'http://127.0.0.1:8093'
|
||||||
|
const log = []
|
||||||
|
const step = (ok, msg) => { log.push(`${ok ? 'PASS' : 'FAIL'} ${msg}`); return ok }
|
||||||
|
|
||||||
|
// ---- WCAG contrast helpers ----
|
||||||
|
const lum = ([r, g, b]) => {
|
||||||
|
const a = [r, g, b].map((v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4) })
|
||||||
|
return 0.2126 * a[0] + 0.7152 * a[1] + 0.0722 * a[2]
|
||||||
|
}
|
||||||
|
const contrast = (f, b) => { const L1 = lum(f), L2 = lum(b); const [hi, lo] = L1 > L2 ? [L1, L2] : [L2, L1]; return (hi + 0.05) / (lo + 0.05) }
|
||||||
|
const rgba = (s) => { const m = s.match(/rgba?\(([^)]+)\)/); if (!m) return null; const p = m[1].split(',').map(Number); return [p[0], p[1], p[2], p[3] === undefined ? 1 : p[3]] }
|
||||||
|
|
||||||
|
const clickTab = (page, label) => page.evaluate((lbl) => {
|
||||||
|
const nodes = [...document.querySelectorAll('.app-bottomnav-item, .app-nav-item')]
|
||||||
|
for (const el of nodes) {
|
||||||
|
const r = el.getBoundingClientRect()
|
||||||
|
if ((el.textContent || '').trim() === lbl && r.width > 0 && r.left >= -1 && r.right <= window.innerWidth + 1) { el.click(); return true }
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}, label)
|
||||||
|
|
||||||
|
// Page-level overflow, ignoring the intentionally off-canvas mobile drawer.
|
||||||
|
const pageOverflow = (page) => page.evaluate(() => {
|
||||||
|
const de = document.documentElement
|
||||||
|
return de.scrollWidth > de.clientWidth + 1 ? { s: de.scrollWidth, c: de.clientWidth } : null
|
||||||
|
})
|
||||||
|
|
||||||
|
async function auditWidth(browser, width, height) {
|
||||||
|
const ctx = await browser.newContext({ viewport: { width, height }, hasTouch: width <= 820, isMobile: width <= 820 })
|
||||||
|
const page = await ctx.newPage()
|
||||||
|
const errs = []
|
||||||
|
page.on('pageerror', (e) => errs.push(e.message))
|
||||||
|
await page.goto(BASE, { waitUntil: 'domcontentloaded' })
|
||||||
|
await page.waitForTimeout(700)
|
||||||
|
|
||||||
|
const results = {}
|
||||||
|
for (const tab of ['Status', 'Config', 'Accounts']) {
|
||||||
|
await clickTab(page, tab)
|
||||||
|
await page.waitForTimeout(600)
|
||||||
|
results[tab] = {
|
||||||
|
overflow: await pageOverflow(page),
|
||||||
|
clipped: await page.evaluate(() => {
|
||||||
|
const vw = window.innerWidth
|
||||||
|
const drawer = document.querySelector('.app-sidebar')
|
||||||
|
const open = !!document.querySelector('.app-drawer-open')
|
||||||
|
const inScroller = (el) => {
|
||||||
|
let a = el.parentElement
|
||||||
|
while (a) {
|
||||||
|
const ox = getComputedStyle(a).overflowX
|
||||||
|
if (ox === 'auto' || ox === 'scroll') return true
|
||||||
|
a = a.parentElement
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
const out = []
|
||||||
|
document.querySelectorAll('button, a[href], input, select').forEach((el) => {
|
||||||
|
const r = el.getBoundingClientRect()
|
||||||
|
const s = getComputedStyle(el)
|
||||||
|
if (s.display === 'none' || s.visibility === 'hidden' || r.width === 0 || r.height === 0) return
|
||||||
|
if (!open && drawer && drawer.contains(el)) return
|
||||||
|
// A contained horizontal scroll region (e.g. the accounts table) is
|
||||||
|
// the sanctioned way to keep a wide table usable; its children may
|
||||||
|
// legitimately extend past the viewport.
|
||||||
|
if (inScroller(el)) return
|
||||||
|
if (r.right > vw + 1 || r.left < -1) out.push(String(el.className).slice(0, 40))
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
}),
|
||||||
|
smallTargets: await page.evaluate(() => {
|
||||||
|
const out = []
|
||||||
|
const afterArea = (el) => {
|
||||||
|
// Buttons may expand their hit area with an ::after overlay.
|
||||||
|
const a = getComputedStyle(el, '::after')
|
||||||
|
if (a && a.content && a.content !== 'none' && a.position === 'absolute') {
|
||||||
|
const inset = parseFloat(a.top)
|
||||||
|
if (Number.isFinite(inset)) return inset < 0 ? -inset * 2 : 0
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
document.querySelectorAll('button, a[href], input:not([type=hidden]), select, [role=menuitem]').forEach((el) => {
|
||||||
|
const r = el.getBoundingClientRect()
|
||||||
|
const s = getComputedStyle(el)
|
||||||
|
if (s.display === 'none' || s.visibility === 'hidden' || r.width === 0 || r.height === 0) return
|
||||||
|
if (el.tagName === 'A' && s.display.includes('inline') && !s.display.includes('flex')) return
|
||||||
|
const label = el.closest('label')
|
||||||
|
const grow = afterArea(el)
|
||||||
|
const effH = Math.max(r.height + grow, label ? label.getBoundingClientRect().height : 0)
|
||||||
|
const effW = Math.max(r.width + grow, label ? label.getBoundingClientRect().width : 0)
|
||||||
|
if (effH < 44 || effW < 24) out.push({ cls: String(el.className).slice(0, 40), h: Math.round(effH), w: Math.round(effW) })
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
}),
|
||||||
|
contrastFails: await page.evaluate(() => {
|
||||||
|
const out = []
|
||||||
|
const w = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT)
|
||||||
|
let n
|
||||||
|
while ((n = w.nextNode())) {
|
||||||
|
const t = n.textContent.trim(); if (!t) continue
|
||||||
|
const el = n.parentElement; if (!el) continue
|
||||||
|
const r = el.getBoundingClientRect(); if (!r.width || !r.height) continue
|
||||||
|
const s = getComputedStyle(el); if (s.visibility === 'hidden' || s.display === 'none') continue
|
||||||
|
let bgEl = el, bg = 'rgba(0, 0, 0, 0)'
|
||||||
|
while (bgEl && (bg === 'rgba(0, 0, 0, 0)' || bg === 'transparent')) { bg = getComputedStyle(bgEl).backgroundColor; bgEl = bgEl.parentElement }
|
||||||
|
out.push({ t: t.slice(0, 24), fg: s.color, bg, size: parseFloat(s.fontSize), weight: s.fontWeight })
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await ctx.close()
|
||||||
|
return { results, errs }
|
||||||
|
}
|
||||||
|
|
||||||
|
;(async () => {
|
||||||
|
const browser = await chromium.launch()
|
||||||
|
|
||||||
|
// 1. Overflow + clipped + tap targets across the full width range.
|
||||||
|
const widths = [320, 390, 560, 760, 820, 900, 1024, 1100, 1440, 1920]
|
||||||
|
let overflowBad = 0, clipBad = 0, targetBad = 0
|
||||||
|
for (const w of widths) {
|
||||||
|
const { results } = await auditWidth(browser, w, 900)
|
||||||
|
for (const [tab, r] of Object.entries(results)) {
|
||||||
|
if (r.overflow) { overflowBad++; log.push(`FAIL ${w}/${tab} horizontal overflow ${r.overflow.s}>${r.overflow.c}`) }
|
||||||
|
if (r.clipped.length) { clipBad++; log.push(`FAIL ${w}/${tab} clipped: ${r.clipped.join(', ')}`) }
|
||||||
|
if (r.smallTargets.length) { targetBad++; log.push(`FAIL ${w}/${tab} small targets: ${JSON.stringify(r.smallTargets)}`) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
step(overflowBad === 0, `no horizontal overflow at any width (${widths.length} widths x 3 tabs)`)
|
||||||
|
step(clipBad === 0, 'no control clipped off-screen at any width')
|
||||||
|
step(targetBad === 0, 'all interactive targets >= 44px (labels counted for checkboxes)')
|
||||||
|
|
||||||
|
// 2. Contrast on desktop and mobile.
|
||||||
|
let contrastBad = 0
|
||||||
|
for (const [w, h] of [[1440, 900], [390, 844]]) {
|
||||||
|
const { results } = await auditWidth(browser, w, h)
|
||||||
|
const seen = new Set()
|
||||||
|
for (const [tab, r] of Object.entries(results)) {
|
||||||
|
for (const c of r.contrastFails) {
|
||||||
|
const fg = rgba(c.fg), bg = rgba(c.bg)
|
||||||
|
if (!fg || !bg || bg[3] < 1) continue
|
||||||
|
const key = `${c.fg}|${c.bg}|${Math.round(c.size)}`
|
||||||
|
if (seen.has(key)) continue
|
||||||
|
seen.add(key)
|
||||||
|
const large = c.size >= 18 || (c.size >= 14 && Number(c.weight) >= 700)
|
||||||
|
const ratio = contrast(fg, bg)
|
||||||
|
if (ratio < (large ? 3.0 : 4.5)) { contrastBad++; log.push(`FAIL ${w}/${tab} contrast "${c.t}" ${ratio.toFixed(2)}:1`) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
step(contrastBad === 0, 'all text meets WCAG AA contrast (desktop + mobile)')
|
||||||
|
|
||||||
|
// 3. Mobile navigation + drawer behaviour.
|
||||||
|
const mctx = await browser.newContext({ viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true })
|
||||||
|
const mp = await mctx.newPage()
|
||||||
|
const merrs = []
|
||||||
|
mp.on('pageerror', (e) => merrs.push(e.message))
|
||||||
|
await mp.goto(BASE, { waitUntil: 'domcontentloaded' })
|
||||||
|
await mp.waitForTimeout(800)
|
||||||
|
await mp.locator('.app-menu-btn').click()
|
||||||
|
await mp.waitForTimeout(350)
|
||||||
|
step(await mp.locator('.app-sidebar').isVisible(), 'mobile: Menu opens the drawer')
|
||||||
|
await mp.locator('.app-drawer-scrim').click({ position: { x: 380, y: 400 } })
|
||||||
|
await mp.waitForTimeout(350)
|
||||||
|
step(await mp.locator('.app-sidebar').evaluate((el) => el.getBoundingClientRect().right <= 0), 'mobile: scrim closes the drawer')
|
||||||
|
await clickTab(mp, 'Accounts')
|
||||||
|
await mp.waitForTimeout(500)
|
||||||
|
step(await mp.locator('.accounts-head').isVisible(), 'mobile: bottom nav switches panels')
|
||||||
|
const pad = await mp.evaluate(() => {
|
||||||
|
const main = document.querySelector('.app-main')
|
||||||
|
const nav = document.querySelector('.app-bottomnav').getBoundingClientRect()
|
||||||
|
return { pad: parseFloat(getComputedStyle(main).paddingBottom), navH: nav.height }
|
||||||
|
})
|
||||||
|
step(pad.pad >= pad.navH, `mobile: content clears the bottom nav (${Math.round(pad.pad)} >= ${Math.round(pad.navH)})`)
|
||||||
|
await mctx.close()
|
||||||
|
|
||||||
|
await browser.close()
|
||||||
|
|
||||||
|
console.log('=== UI VERIFICATION ===')
|
||||||
|
log.forEach((l) => console.log(' ' + l))
|
||||||
|
const fails = log.filter((l) => l.startsWith('FAIL')).length
|
||||||
|
console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : fails + ' FAILURE(S)'}`)
|
||||||
|
process.exit(fails ? 1 : 0)
|
||||||
|
})().catch((e) => { console.error('FATAL', e); process.exit(1) })
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import react from '@vitejs/plugin-react'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
server: {
|
||||||
|
port: 5173,
|
||||||
|
proxy: {
|
||||||
|
'/api': 'http://127.0.0.1:8093',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
"""Automated GitHub sign-up toolkit (Camoufox + Litensi mail)."""
|
||||||
|
|
||||||
|
from .config import Config, load_config
|
||||||
|
from .runner import register_one, run_job
|
||||||
|
|
||||||
|
__all__ = ["Config", "load_config", "register_one", "run_job"]
|
||||||
@@ -0,0 +1,814 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
common/agent_captcha.py — 视觉 LLM 验证码求解器(agent-captcha)
|
||||||
|
|
||||||
|
思路:截图验证码挑战 -> 发给 vision LLM(OpenRouter)-> LLM 读题+看图给出结构化答案
|
||||||
|
-> 调用方据答案驱动 UI(点箭头/选图/Submit)。
|
||||||
|
|
||||||
|
比打码平台鲁棒:LLM 能读懂任意题型变体,不依赖某平台是否支持该 service。
|
||||||
|
模型:优先 PRIMARY,429/失败则按 FALLBACKS 降级;OpenRouter key 可多个轮换抗限流。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
if sys.platform == "win32":
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8")
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
# 网关/key 全部从 config(.env)读取,不在代码里留明文。见 .env.example。
|
||||||
|
import os as _os
|
||||||
|
import sys as _sys2
|
||||||
|
_sys2.path.insert(0, _os.path.dirname(_os.path.dirname(_os.path.abspath(__file__))))
|
||||||
|
try:
|
||||||
|
import config as _cfg
|
||||||
|
except Exception:
|
||||||
|
_cfg = None
|
||||||
|
|
||||||
|
|
||||||
|
def _c(name, default=""):
|
||||||
|
"""优先环境变量,其次 config.<name>,再 default。"""
|
||||||
|
v = os.environ.get(name)
|
||||||
|
if v:
|
||||||
|
return v
|
||||||
|
if _cfg is not None:
|
||||||
|
v = getattr(_cfg, name, "")
|
||||||
|
if v:
|
||||||
|
return v
|
||||||
|
return default
|
||||||
|
|
||||||
|
|
||||||
|
# 主视觉网关(gpt-5.x)。模型可用 VISION_MODEL 覆盖。
|
||||||
|
VISION_API_BASE = _c("VISION_API_BASE")
|
||||||
|
VISION_API_KEY = _c("VISION_API_KEY")
|
||||||
|
PRIMARY_MODEL = _c("VISION_MODEL", "gpt-5.5")
|
||||||
|
FALLBACK_MODELS = [
|
||||||
|
"gpt-5.4-mini",
|
||||||
|
]
|
||||||
|
# gemma 免费兜底文本网关
|
||||||
|
GEMMA_API_BASE = _c("GEMMA_API_BASE")
|
||||||
|
GEMMA_API_KEY = _c("GEMMA_API_KEY")
|
||||||
|
|
||||||
|
# 模型有时把验证码当"不可协助"拒答;命中这些词就判定为拒答、换下一个 model/key。
|
||||||
|
_REFUSAL_MARKERS = (
|
||||||
|
"cannot fulfill", "can't fulfill", "cannot assist", "can't assist",
|
||||||
|
"i am unable", "i'm unable", "safety guidelines", "harmless ai",
|
||||||
|
"not able to help", "cannot help with that",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _looks_like_refusal(text):
|
||||||
|
if not text:
|
||||||
|
return True
|
||||||
|
t = text.lower()
|
||||||
|
return any(m in t for m in _REFUSAL_MARKERS)
|
||||||
|
|
||||||
|
|
||||||
|
def _load_keys():
|
||||||
|
"""LLM key:默认 VISION_API_KEY(gpt-5 网关)。gemma 兜底 key 也加进来。
|
||||||
|
sk-or- 的 OpenRouter key(若设了 OPENROUTER_KEYS)追加到最后。"""
|
||||||
|
keys = []
|
||||||
|
if VISION_API_KEY:
|
||||||
|
keys.append(VISION_API_KEY)
|
||||||
|
if GEMMA_API_KEY and GEMMA_API_KEY not in keys:
|
||||||
|
keys.append(GEMMA_API_KEY)
|
||||||
|
env = os.environ.get("OPENROUTER_KEYS") or os.environ.get("OPENROUTER_KEY") or ""
|
||||||
|
for k in env.replace("\n", ",").split(","):
|
||||||
|
k = k.strip()
|
||||||
|
if k.startswith("sk-or-") and k not in keys:
|
||||||
|
keys.append(k)
|
||||||
|
return keys
|
||||||
|
|
||||||
|
|
||||||
|
def _endpoint_for_key(key):
|
||||||
|
"""key 决定走哪个网关:sk-or- 走 OpenRouter,sk-Gso 走 gemma 网关,其余走主网关。"""
|
||||||
|
if key.startswith("sk-or-"):
|
||||||
|
return "https://openrouter.ai/api/v1/chat/completions"
|
||||||
|
if key == GEMMA_API_KEY:
|
||||||
|
return f"{GEMMA_API_BASE.rstrip('/')}/v1/chat/completions"
|
||||||
|
return f"{VISION_API_BASE.rstrip('/')}/v1/chat/completions"
|
||||||
|
|
||||||
|
|
||||||
|
def _model_for_key(key, model):
|
||||||
|
"""gemma 兜底网关只有 gemma 模型可用;gpt-5 模型名在那边无效,自动换成 gemma。"""
|
||||||
|
if key == GEMMA_API_KEY and model.startswith("gpt-"):
|
||||||
|
return "google/gemma-4-31b-it:free"
|
||||||
|
if key.startswith("sk-or-") and model.startswith("gpt-"):
|
||||||
|
return "nvidia/nemotron-nano-12b-v2-vl:free"
|
||||||
|
return model
|
||||||
|
|
||||||
|
|
||||||
|
def ask_vision(prompt, image_b64, models=None, keys=None, max_tokens=300, temperature=0.0):
|
||||||
|
"""把 prompt + 图片发给 vision LLM,返回文本答案或 None。
|
||||||
|
按 models 降级、按 keys 轮换;429/5xx 自动换下一个组合。
|
||||||
|
key 决定网关:默认 tiantianai key -> VISION_API_BASE;sk-or- -> OpenRouter。"""
|
||||||
|
models = models or ([PRIMARY_MODEL] + FALLBACK_MODELS)
|
||||||
|
keys = keys or _load_keys()
|
||||||
|
if not keys:
|
||||||
|
print(" [vision] 无可用 key")
|
||||||
|
return None
|
||||||
|
payload_msg = [{
|
||||||
|
"role": "user",
|
||||||
|
"content": [
|
||||||
|
{"type": "text", "text": prompt},
|
||||||
|
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_b64}"}},
|
||||||
|
],
|
||||||
|
}]
|
||||||
|
for model in models:
|
||||||
|
for ki, key in enumerate(keys):
|
||||||
|
real_model = _model_for_key(key, model)
|
||||||
|
try:
|
||||||
|
r = requests.post(
|
||||||
|
_endpoint_for_key(key),
|
||||||
|
headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
|
||||||
|
json={"model": real_model, "messages": payload_msg,
|
||||||
|
"max_tokens": max_tokens, "temperature": temperature},
|
||||||
|
timeout=120,
|
||||||
|
)
|
||||||
|
if r.status_code == 200:
|
||||||
|
txt = r.json()["choices"][0]["message"]["content"]
|
||||||
|
if _looks_like_refusal(txt):
|
||||||
|
print(f" [vision] {real_model} key#{ki} refused, trying next")
|
||||||
|
continue
|
||||||
|
print(f" [vision] {real_model} key#{ki} OK")
|
||||||
|
return txt
|
||||||
|
if r.status_code in (404, 429, 500, 502, 503):
|
||||||
|
continue # 模型不支持图/限流/上游错,换 key 或下一个 model
|
||||||
|
print(f" [vision] {real_model} key#{ki} -> {r.status_code} {r.text[:80]}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f" [vision] {real_model} key#{ki} err: {str(e)[:60]}")
|
||||||
|
continue
|
||||||
|
print(" [vision] 所有 model/key 都失败")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# 多模型投票池:(网关base, key, 模型)。盲区不同,多数表决互相纠错。
|
||||||
|
# 平票优先级=列表顺序。实测 gemini 在朝向/拼图题更准,opus(claude) 偏离谱→放最后(权重最低)。
|
||||||
|
# 网关/key 全走 config(.env)。某个 key 留空则该模型自动不参与(_ask_one 拿空 key 直接跳过)。
|
||||||
|
ZZ_BASE = _c("VOTE_ZZ_BASE")
|
||||||
|
ZZ_KEY = _c("VOTE_ZZ_KEY")
|
||||||
|
GPT_KEY = _c("VOTE_GPT_KEY") or ZZ_KEY
|
||||||
|
OPUS_BASE = _c("VOTE_OPUS_BASE") # claude opus 专用网关(Anthropic 原生 /v1/messages)
|
||||||
|
OPUS_KEY = _c("VOTE_OPUS_KEY")
|
||||||
|
_FREE_BASE = "http://127.0.0.1:16432/v1" # local dashscope pool proxy (free, verified 2026-10-08)
|
||||||
|
VOTER_MODELS = [(b, k, m) for (b, k, m) in [
|
||||||
|
(ZZ_BASE, ZZ_KEY, "gemini-3.5-flash-c"), # 平票最优先(实测最准)
|
||||||
|
(ZZ_BASE, GPT_KEY, "gpt-5.5"),
|
||||||
|
(ZZ_BASE, ZZ_KEY, "gemini-3.1-pro-preview-c"),
|
||||||
|
(OPUS_BASE, OPUS_KEY, "claude-opus-4-8"), # 权重最低(claude 在这些图上偏离谱)
|
||||||
|
# FREE default voters: qwen vision models via local dashscope proxy ($0, ~1-3s each)
|
||||||
|
(_FREE_BASE, "free", "qwen3-vl-flash"),
|
||||||
|
(_FREE_BASE, "free", "qwen-vl-max"),
|
||||||
|
(_FREE_BASE, "free", "qwen-vl-plus"),
|
||||||
|
] if b and k] # 缺网关/key 的模型剔除
|
||||||
|
import re as _re_mod
|
||||||
|
|
||||||
|
|
||||||
|
def _ask_one(base, key, model, prompt, image_b64, max_tokens=900):
|
||||||
|
"""单模型单网关问一次,返回文本或 None。
|
||||||
|
base 以 /messages 结尾或含 ai-wave/claude → 走 Anthropic 原生 /v1/messages 协议;
|
||||||
|
否则走 OpenAI 兼容 /v1/chat/completions。"""
|
||||||
|
if not base or not key:
|
||||||
|
return None
|
||||||
|
# 检测图片格式(JPEG base64 以 /9j/ 开头, PNG 以 iVBOR),喂对 media_type
|
||||||
|
mtype = "image/jpeg" if image_b64.startswith("/9j/") else "image/png"
|
||||||
|
try:
|
||||||
|
is_anthropic = base.rstrip("/").endswith("/claude") or "/v1/messages" in base
|
||||||
|
if is_anthropic:
|
||||||
|
ep = base.rstrip("/")
|
||||||
|
if not ep.endswith("/v1/messages"):
|
||||||
|
ep = ep + "/v1/messages"
|
||||||
|
r = requests.post(
|
||||||
|
ep,
|
||||||
|
headers={"x-api-key": key, "anthropic-version": "2023-06-01", "content-type": "application/json"},
|
||||||
|
json={"model": model, "max_tokens": max_tokens, "messages": [{"role": "user", "content": [
|
||||||
|
{"type": "text", "text": prompt},
|
||||||
|
{"type": "image", "source": {"type": "base64", "media_type": mtype, "data": image_b64}}]}]},
|
||||||
|
timeout=35,
|
||||||
|
)
|
||||||
|
if r.status_code == 200:
|
||||||
|
txt = "".join(b.get("text", "") for b in r.json().get("content", []))
|
||||||
|
if txt and not _looks_like_refusal(txt):
|
||||||
|
return txt
|
||||||
|
return None
|
||||||
|
r = requests.post(
|
||||||
|
f"{base.rstrip('/')}/v1/chat/completions",
|
||||||
|
headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
|
||||||
|
json={"model": model, "messages": [{"role": "user", "content": [
|
||||||
|
{"type": "text", "text": prompt},
|
||||||
|
{"type": "image_url", "image_url": {"url": f"data:{mtype};base64,{image_b64}"}}]}],
|
||||||
|
"max_tokens": max_tokens, "temperature": 0.0},
|
||||||
|
timeout=35,
|
||||||
|
)
|
||||||
|
if r.status_code == 200:
|
||||||
|
txt = r.json()["choices"][0]["message"]["content"]
|
||||||
|
if not _looks_like_refusal(txt):
|
||||||
|
return txt
|
||||||
|
except Exception as e:
|
||||||
|
print(f" [vote] {model} err: {str(e)[:50]}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def vote_answer(prompt, image_b64, n_options, max_tokens=900, deadline=55):
|
||||||
|
"""多模型并发投票,解析各自 ANSWER=N,返回 (best, votes_dict, raw_list)。
|
||||||
|
多数票胜出;平票时按 VOTER_MODELS 顺序优先。
|
||||||
|
deadline: 整轮最多等这么多秒,掉队的模型直接放弃(避免某个慢模型拖到 150s 把整轮拖超 Arkose 倒计时)。"""
|
||||||
|
import concurrent.futures as cf
|
||||||
|
answers = []
|
||||||
|
raws = []
|
||||||
|
done_models = set()
|
||||||
|
with cf.ThreadPoolExecutor(max_workers=len(VOTER_MODELS)) as ex:
|
||||||
|
futs = {ex.submit(_ask_one, b, k, m, prompt, image_b64, max_tokens): m
|
||||||
|
for (b, k, m) in VOTER_MODELS}
|
||||||
|
try:
|
||||||
|
for fut in cf.as_completed(futs, timeout=deadline):
|
||||||
|
model = futs[fut]
|
||||||
|
done_models.add(model)
|
||||||
|
txt = fut.result()
|
||||||
|
a = None
|
||||||
|
if txt:
|
||||||
|
mm = _re_mod.findall(r"ANSWER\s*=\s*(\d+)", txt)
|
||||||
|
if mm:
|
||||||
|
a = int(mm[-1])
|
||||||
|
if a is not None and 0 <= a < n_options:
|
||||||
|
answers.append((model, a))
|
||||||
|
raws.append((model, a, (txt or "")[-120:]))
|
||||||
|
print(f" [vote] {model} -> {a}")
|
||||||
|
except cf.TimeoutError:
|
||||||
|
# 超过整轮 deadline:放弃还没回来的模型,用已有票
|
||||||
|
for fut, model in futs.items():
|
||||||
|
if model not in done_models:
|
||||||
|
fut.cancel()
|
||||||
|
raws.append((model, None, "[deadline timeout]"))
|
||||||
|
print(f" [vote] {model} -> None (deadline {deadline}s)")
|
||||||
|
if not answers:
|
||||||
|
return None, {}, raws
|
||||||
|
# 计票
|
||||||
|
from collections import Counter
|
||||||
|
cnt = Counter(a for _, a in answers)
|
||||||
|
top, topn = cnt.most_common(1)[0]
|
||||||
|
# 平票:按 VOTER_MODELS 顺序找第一个投了高票答案的
|
||||||
|
order = [m for (_, _, m) in VOTER_MODELS]
|
||||||
|
if list(cnt.values()).count(topn) > 1:
|
||||||
|
for m in order:
|
||||||
|
for mm, a in answers:
|
||||||
|
if mm == m and cnt[a] == topn:
|
||||||
|
top = a; break
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
break
|
||||||
|
return top, dict(cnt), raws
|
||||||
|
|
||||||
|
|
||||||
|
def parse_json_answer(text):
|
||||||
|
"""从 LLM 回复里抠出第一个 JSON 对象(容忍 ```json 包裹和前后文字)。"""
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
import re
|
||||||
|
# 抓最后一个平衡的 {...}(容忍 CoT 推理后才给 JSON、且 JSON 内含数组)。
|
||||||
|
candidates = []
|
||||||
|
depth = 0
|
||||||
|
start = -1
|
||||||
|
for i, ch in enumerate(text):
|
||||||
|
if ch == "{":
|
||||||
|
if depth == 0:
|
||||||
|
start = i
|
||||||
|
depth += 1
|
||||||
|
elif ch == "}":
|
||||||
|
if depth > 0:
|
||||||
|
depth -= 1
|
||||||
|
if depth == 0 and start >= 0:
|
||||||
|
candidates.append(text[start:i + 1])
|
||||||
|
for blob in reversed(candidates):
|
||||||
|
try:
|
||||||
|
return json.loads(blob)
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def screenshot_frame_region(page, frame, path):
|
||||||
|
"""截某 iframe 在主页面里的可视区域为 png,返回 base64。
|
||||||
|
Arkose 拼图渲染在深层 frame,直接截它对应的 iframe 元素最稳。"""
|
||||||
|
try:
|
||||||
|
# 找到承载该 frame 的 iframe 元素
|
||||||
|
handle = await frame.frame_element()
|
||||||
|
await handle.screenshot(path=path)
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
return base64.b64encode(f.read()).decode()
|
||||||
|
except Exception as e:
|
||||||
|
print(f" [vision] frame screenshot err: {str(e)[:70]}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# Arkose game frame 里两块图的选择器(实测 v4.2.2 布局):
|
||||||
|
# 参考图("Match This!" 目标)= .key-frame-image
|
||||||
|
# 候选图(当前显示的那张/那个网格)= .answer-frame img
|
||||||
|
SEL_REFERENCE = ".key-frame-image"
|
||||||
|
SEL_CANDIDATE = ".answer-frame img, .answer-frame canvas, .answer-frame"
|
||||||
|
|
||||||
|
|
||||||
|
async def shot_element(frame, selector, path, scale=3):
|
||||||
|
"""截 game frame 里某元素并放大 scale 倍(提升小图的细节可读性)。
|
||||||
|
返回放大后的 png base64,失败返回 None。"""
|
||||||
|
try:
|
||||||
|
el = frame.locator(selector).first
|
||||||
|
if await el.count() == 0:
|
||||||
|
return None
|
||||||
|
await el.screenshot(path=path)
|
||||||
|
except Exception as e:
|
||||||
|
print(f" [vision] shot_element({selector}) err: {str(e)[:60]}")
|
||||||
|
return None
|
||||||
|
# 放大
|
||||||
|
try:
|
||||||
|
from PIL import Image
|
||||||
|
im = Image.open(path).convert("RGB")
|
||||||
|
im = im.resize((im.width * scale, im.height * scale), Image.LANCZOS)
|
||||||
|
im.save(path)
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
return base64.b64encode(f.read()).decode()
|
||||||
|
except Exception:
|
||||||
|
# 没 PIL 就用原图
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
return base64.b64encode(f.read()).decode()
|
||||||
|
|
||||||
|
|
||||||
|
def _b64_concat_side_by_side(b64_left, b64_right, path):
|
||||||
|
"""把参考图+候选图横向拼成一张(有参照系,LLM 比较判断更准)。返回拼图 base64。"""
|
||||||
|
try:
|
||||||
|
from PIL import Image
|
||||||
|
import io
|
||||||
|
L = Image.open(io.BytesIO(base64.b64decode(b64_left))).convert("RGB")
|
||||||
|
R = Image.open(io.BytesIO(base64.b64decode(b64_right))).convert("RGB")
|
||||||
|
h = max(L.height, R.height)
|
||||||
|
gap = 20
|
||||||
|
canvas = Image.new("RGB", (L.width + gap + R.width, h), (255, 255, 255))
|
||||||
|
canvas.paste(L, (0, 0))
|
||||||
|
canvas.paste(R, (L.width + gap, 0))
|
||||||
|
canvas.save(path)
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
return base64.b64encode(f.read()).decode()
|
||||||
|
except Exception as e:
|
||||||
|
print(f" [vision] concat err: {str(e)[:60]}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def stitch_options_grid(b64_list, path, reference_b64=None, cols=4, label_h=24, return_geom=False):
|
||||||
|
"""把一组候选图拼成一张带编号(0,1,2...)的网格大图,可选在最上方放参考图。
|
||||||
|
这样 LLM 一次调用就能横向对比所有候选、挑出正确编号——把 N 次调用压成 1 次,
|
||||||
|
既省配额又给模型对比视角(你的"拼成一张"思路)。
|
||||||
|
return_geom=True 时返回 (base64, geom),geom={"cells":[(x,y,w,h),...],"size":(W,H)},
|
||||||
|
供复盘标注(annotate_choice)在正确格子上画框。否则返回 base64。"""
|
||||||
|
try:
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
import io
|
||||||
|
imgs = [Image.open(io.BytesIO(base64.b64decode(b))).convert("RGB") for b in b64_list]
|
||||||
|
if not imgs:
|
||||||
|
return (None, None) if return_geom else None
|
||||||
|
cw = max(i.width for i in imgs)
|
||||||
|
ch = max(i.height for i in imgs)
|
||||||
|
n = len(imgs)
|
||||||
|
cols = min(cols, n)
|
||||||
|
rows = (n + cols - 1) // cols
|
||||||
|
gap = 12
|
||||||
|
cell_w, cell_h = cw + gap, ch + label_h + gap
|
||||||
|
ref_block = 0
|
||||||
|
ref_img = None
|
||||||
|
if reference_b64:
|
||||||
|
ref_img = Image.open(io.BytesIO(base64.b64decode(reference_b64))).convert("RGB")
|
||||||
|
ref_block = ref_img.height + label_h + gap
|
||||||
|
W = cols * cell_w + gap
|
||||||
|
H = ref_block + rows * cell_h + gap
|
||||||
|
canvas = Image.new("RGB", (W, H), (255, 255, 255))
|
||||||
|
draw = ImageDraw.Draw(canvas)
|
||||||
|
y0 = gap
|
||||||
|
if ref_img is not None:
|
||||||
|
draw.text((gap, 2), "REFERENCE (target):", fill=(200, 0, 0))
|
||||||
|
canvas.paste(ref_img, (gap, label_h))
|
||||||
|
y0 = ref_block + gap
|
||||||
|
cells = []
|
||||||
|
for idx, im in enumerate(imgs):
|
||||||
|
r, c = divmod(idx, cols)
|
||||||
|
x = gap + c * cell_w
|
||||||
|
y = y0 + r * cell_h
|
||||||
|
draw.text((x, y), f"#{idx}", fill=(0, 0, 200))
|
||||||
|
canvas.paste(im, (x, y + label_h))
|
||||||
|
cells.append((x, y + label_h, im.width, im.height)) # 候选图本体的像素矩形
|
||||||
|
canvas.save(path)
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
b64 = base64.b64encode(f.read()).decode()
|
||||||
|
if return_geom:
|
||||||
|
return b64, {"cells": cells, "size": (W, H)}
|
||||||
|
return b64
|
||||||
|
except Exception as e:
|
||||||
|
print(f" [vision] stitch err: {str(e)[:60]}")
|
||||||
|
return (None, None) if return_geom else None
|
||||||
|
|
||||||
|
|
||||||
|
def annotate_choice(grid_path, geom, best_idx, out_path, note="", votes_raw=None):
|
||||||
|
"""复盘标注:在拼图网格上标注最终票(粗红框)+每个模型各自的投票(彩色小框+标签)。
|
||||||
|
votes_raw: [(model, answer_idx, txt_tail), ...],给每个模型选的那张画不同颜色边框,
|
||||||
|
并在图底列出"模型->答案"清单。方便人工核对是谁选了谁、谁对谁错。"""
|
||||||
|
try:
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
im = Image.open(grid_path).convert("RGB")
|
||||||
|
draw = ImageDraw.Draw(im)
|
||||||
|
cells = (geom or {}).get("cells", [])
|
||||||
|
# 每个模型一种颜色
|
||||||
|
palette = [(0,120,255),(255,140,0),(0,200,0),(200,0,200),(0,200,200)]
|
||||||
|
votes_raw = votes_raw or []
|
||||||
|
# 每个模型在它选的格子画一圈细彩框(不同 offset 错开避免重叠)
|
||||||
|
for mi,(model,a,_tail) in enumerate(votes_raw):
|
||||||
|
if a is None or not (0<=a<len(cells)): continue
|
||||||
|
col=palette[mi%len(palette)]
|
||||||
|
x,y,w,h=cells[a]
|
||||||
|
off=8+mi*4
|
||||||
|
draw.rectangle([x-off,y-off,x+w+off,y+h+off],outline=col,width=2)
|
||||||
|
short=model.split("/")[-1].replace("-preview-c","").replace("-c","")[:10]
|
||||||
|
draw.text((x+2,y+2+mi*12),f"{short}>#{a}",fill=col)
|
||||||
|
# 最终投票结果:粗红框
|
||||||
|
if 0 <= best_idx < len(cells):
|
||||||
|
x, y, w, h = cells[best_idx]
|
||||||
|
for t in range(5):
|
||||||
|
draw.rectangle([x - 3 - t, y - 3 - t, x + w + 3 + t, y + h + 3 + t], outline=(255, 0, 0))
|
||||||
|
draw.text((x + 2, y + h - 14), f"FINAL #{best_idx}", fill=(255, 0, 0))
|
||||||
|
# 底部清单:模型->答案
|
||||||
|
if votes_raw:
|
||||||
|
line=" | ".join(f"{m.split('/')[-1].replace('-preview-c','').replace('-c','')[:10]}:{a}" for m,a,_ in votes_raw)
|
||||||
|
draw.text((6, im.height - 30), line[:150], fill=(255,255,0))
|
||||||
|
if note:
|
||||||
|
draw.text((6, im.height - 16), note[:140], fill=(255, 0, 0))
|
||||||
|
im.save(out_path)
|
||||||
|
return out_path
|
||||||
|
except Exception as e:
|
||||||
|
print(f" [vision] annotate err: {str(e)[:60]}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# 图像增强网关(gpt-image-2 的 images/edits)。默认与 VISION 同一网关,外加一个兜底网关。
|
||||||
|
IMAGE_EDIT_BASE = _c("IMAGE_EDIT_BASE", VISION_API_BASE)
|
||||||
|
IMAGE_EDIT_KEY = _c("IMAGE_EDIT_KEY", VISION_API_KEY)
|
||||||
|
IMAGE_EDIT_MODEL = _c("IMAGE_EDIT_MODEL", "gpt-image-2")
|
||||||
|
# 兜底图像增强网关(主网关失败/超时时切换)
|
||||||
|
IMAGE_EDIT_BASE2 = _c("IMAGE_EDIT_BASE2")
|
||||||
|
IMAGE_EDIT_KEY2 = _c("IMAGE_EDIT_KEY2")
|
||||||
|
|
||||||
|
_ENHANCE_PROMPT = (
|
||||||
|
"Upscale and sharpen this captcha puzzle image for maximum clarity. "
|
||||||
|
"Preserve EXACTLY every icon, dotted connecting line, ring color, circle and position. "
|
||||||
|
"Do NOT invent, add, remove, or alter anything. Only increase resolution and reduce blur."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def enhance_local(image_b64, path, scale=2, max_side=1600, jpeg_quality=82):
|
||||||
|
"""本地传统图像增强(毫秒级、无网络):Lanczos 缩放 + 锐化 + 对比度/亮度 + 去噪。
|
||||||
|
纯保真处理。关键:限制最大边 max_side 并存为 JPEG,把体积压到 ~几百KB
|
||||||
|
(否则 7 张 3D 大图拼起来 PNG 可达 13MB,发给模型会全部传输超时→空票)。
|
||||||
|
返回增强后 base64。"""
|
||||||
|
try:
|
||||||
|
from PIL import Image, ImageEnhance, ImageFilter
|
||||||
|
import io
|
||||||
|
im = Image.open(io.BytesIO(base64.b64decode(image_b64))).convert("RGB")
|
||||||
|
if scale and scale != 1:
|
||||||
|
im = im.resize((im.width * scale, im.height * scale), Image.LANCZOS)
|
||||||
|
# 限制最大边,避免体积爆炸
|
||||||
|
long_side = max(im.width, im.height)
|
||||||
|
if long_side > max_side:
|
||||||
|
r = max_side / long_side
|
||||||
|
im = im.resize((max(1, int(im.width * r)), max(1, int(im.height * r))), Image.LANCZOS)
|
||||||
|
im = im.filter(ImageFilter.MedianFilter(size=3))
|
||||||
|
im = ImageEnhance.Contrast(im).enhance(1.6)
|
||||||
|
im = ImageEnhance.Brightness(im).enhance(1.15)
|
||||||
|
im = ImageEnhance.Sharpness(im).enhance(2.2)
|
||||||
|
im = im.filter(ImageFilter.UnsharpMask(radius=2, percent=150, threshold=2))
|
||||||
|
# 存 JPEG 控体积(PNG 对照片型 3D 图体积巨大)
|
||||||
|
jpath = path.rsplit(".", 1)[0] + ".jpg"
|
||||||
|
im.save(jpath, "JPEG", quality=jpeg_quality)
|
||||||
|
with open(jpath, "rb") as f:
|
||||||
|
raw = f.read()
|
||||||
|
b64 = base64.b64encode(raw).decode()
|
||||||
|
print(f" [vision] image enhanced locally ({im.width}x{im.height}, {len(raw)//1024}KB)")
|
||||||
|
return b64
|
||||||
|
except Exception as e:
|
||||||
|
print(f" [vision] local enhance err: {str(e)[:60]}")
|
||||||
|
return image_b64
|
||||||
|
|
||||||
|
|
||||||
|
def enhance_image(image_b64, path, prompt=None, size="1024x1024"):
|
||||||
|
"""用 gpt-image-2 的 images/edits 对图做保真增强(去糊放大,不改内容)。
|
||||||
|
实测对 Arkose 小图标拼图能显著提清晰度且不篡改结构(gpt-5 校验 identical)。
|
||||||
|
主网关失败/超时则切兜底网关。返回增强后 png 的 base64;都失败返回原图 base64(降级不致命)。
|
||||||
|
注意:云端往返 ~20-40s,可能撞 Arkose 超时;要快用 enhance_local。"""
|
||||||
|
import io
|
||||||
|
raw = base64.b64decode(image_b64)
|
||||||
|
endpoints = [
|
||||||
|
(IMAGE_EDIT_BASE, IMAGE_EDIT_KEY),
|
||||||
|
(IMAGE_EDIT_BASE2, IMAGE_EDIT_KEY2),
|
||||||
|
]
|
||||||
|
for bi, (base, key) in enumerate(endpoints):
|
||||||
|
if not (base and key):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
files = {"image": ("in.png", io.BytesIO(raw), "image/png")}
|
||||||
|
data = {"model": IMAGE_EDIT_MODEL, "prompt": prompt or _ENHANCE_PROMPT, "size": size}
|
||||||
|
r = requests.post(
|
||||||
|
f"{base.rstrip('/')}/v1/images/edits",
|
||||||
|
headers={"Authorization": f"Bearer {key}"},
|
||||||
|
files=files, data=data, timeout=120,
|
||||||
|
)
|
||||||
|
if r.status_code == 200:
|
||||||
|
out_b64 = r.json()["data"][0]["b64_json"]
|
||||||
|
try:
|
||||||
|
with open(path, "wb") as f:
|
||||||
|
f.write(base64.b64decode(out_b64))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
print(f" [vision] image enhanced via gpt-image-2 (gw#{bi})")
|
||||||
|
return out_b64
|
||||||
|
print(f" [vision] enhance gw#{bi} failed {r.status_code} {r.text[:60]}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f" [vision] enhance gw#{bi} err: {str(e)[:60]}")
|
||||||
|
return image_b64 # 都失败,降级用原图
|
||||||
|
|
||||||
|
|
||||||
|
def vote_score(prompt, image_b64, rounds=3, **kw):
|
||||||
|
"""同一张图问 rounds 次,取 score 中位数,抹平单次抖动。返回 (median_score, [all])。"""
|
||||||
|
import statistics
|
||||||
|
vals = []
|
||||||
|
for _ in range(rounds):
|
||||||
|
ans = ask_vision(prompt, image_b64, **kw)
|
||||||
|
js = parse_json_answer(ans) or {}
|
||||||
|
s = js.get("score")
|
||||||
|
if isinstance(s, (int, float)):
|
||||||
|
vals.append(float(s))
|
||||||
|
if not vals:
|
||||||
|
return -1, []
|
||||||
|
return statistics.median(vals), vals
|
||||||
|
|
||||||
|
|
||||||
|
# ============ GitHub Arkose 拼图:变体分派 + 投票求解(整链路复用,已实测10/10通过)============
|
||||||
|
SEL_REF_GH = ".key-frame-image"
|
||||||
|
SEL_CAND_GH = ".answer-frame img, .answer-frame canvas, .answer-frame"
|
||||||
|
|
||||||
|
|
||||||
|
def _pp_sequence(qtext, n):
|
||||||
|
return ("You are solving an Arkose visual puzzle (accessibility helper). "
|
||||||
|
"Top = REFERENCE (4 icons stacked vertically, each in a colored ring; ring colors top-to-bottom "
|
||||||
|
"are CYAN, YELLOW, RED, GREEN). Below = numbered candidates #0..#%d, same 4 colored rings, icons "
|
||||||
|
"placed differently. Instruction: \"%s\".\n"
|
||||||
|
"Correct candidate = each colored ring holds the SAME icon as that color ring in the reference. "
|
||||||
|
"Compare RING BY RING (by color), NOT by screen position.\n"
|
||||||
|
"MATCHING RULE: the same icon may be ROTATED and its BLACK/WHITE FILL INVERTED (solid vs hollow). "
|
||||||
|
"Match by underlying SHAPE, ignoring rotation and fill inversion.\n"
|
||||||
|
"TIE-BREAKER: candidates often look almost identical; distinguish by tiny details - protruding dots, "
|
||||||
|
"notches, number of legs/prongs, internal patterns. All FOUR rings must match on shape AND fine detail.\n"
|
||||||
|
"PROXIMITY WARNING: two icons are often placed close together; never guess by proximity - read each "
|
||||||
|
"icon by its OWN ring color (cyan/yellow/red/green), never swap two adjacent icons.\n"
|
||||||
|
"Reason briefly per ring, then output the VERY LAST line exactly: ANSWER=<number> (e.g. ANSWER=3)."
|
||||||
|
% (n - 1, qtext))
|
||||||
|
|
||||||
|
|
||||||
|
def _pp_character(qtext, n):
|
||||||
|
return ("You are solving an Arkose visual puzzle (accessibility helper). "
|
||||||
|
"Top-left = REFERENCE ('Match This!'): it shows ONE OR TWO target icons (look carefully — often TWO "
|
||||||
|
"icons stacked). Below = candidates #0..#%d: the SAME tilted 3D grid of icon tiles, with a pink "
|
||||||
|
"CHARACTER standing on a DIFFERENT tile in each candidate.\n"
|
||||||
|
"Instruction: \"%s\".\n"
|
||||||
|
"GOAL: pick the candidate where the character stands on the tile(s) whose icon matches the reference.\n"
|
||||||
|
"USE ELIMINATION (this is the reliable method, because the character's feet OCCLUDE the tile it stands "
|
||||||
|
"on so you often cannot read that tile directly):\n"
|
||||||
|
"1. Identify the reference target icon shape(s) precisely.\n"
|
||||||
|
"2. In the grid, find WHICH grid position holds the target icon — do this by reading all the OTHER, "
|
||||||
|
"clearly visible tiles and locating the target icon's cell (or noticing which cell is hidden under the "
|
||||||
|
"character).\n"
|
||||||
|
"3. For each candidate, determine which grid cell the character is standing on (by its feet position in "
|
||||||
|
"the 3x3/grid layout).\n"
|
||||||
|
"4. The correct candidate = the one where the character occupies the target-icon cell. Elimination: if a "
|
||||||
|
"candidate's character stands on a cell whose icon IS clearly visible AND is NOT the target, reject it. "
|
||||||
|
"The right answer is usually the candidate where the target icon's cell is the one HIDDEN under the "
|
||||||
|
"character's feet (because the others show non-target icons clearly).\n"
|
||||||
|
"Account for: grid TILT (3D skew), icon ROTATION and black/white fill inversion — match by SHAPE.\n"
|
||||||
|
"Reason step by step (reference shape; target cell location; each candidate's character cell; "
|
||||||
|
"eliminate), then output the VERY LAST line exactly: ANSWER=<number> (e.g. ANSWER=2)." % (n - 1, qtext))
|
||||||
|
|
||||||
|
|
||||||
|
def _pp_rotate(qtext, n):
|
||||||
|
return ("You are solving an Arkose visual puzzle (accessibility helper). "
|
||||||
|
"Top-left = REFERENCE ('Match the Direction!'): a 3D object facing a specific direction. "
|
||||||
|
"Below = candidates #0..#%d: the SAME object rotated to different orientations.\n"
|
||||||
|
"Instruction: \"%s\".\n"
|
||||||
|
"TASK: pick the candidate facing the SAME direction as the reference. Note where the front (head/face) "
|
||||||
|
"points and the body profile; match on both head direction and body tilt.\n"
|
||||||
|
"Reason briefly, then output VERY LAST line exactly: ANSWER=<number> (e.g. ANSWER=2)." % (n - 1, qtext))
|
||||||
|
|
||||||
|
|
||||||
|
def gh_pick_prompt(qtext, n, variant="sequence"):
|
||||||
|
if variant == "character":
|
||||||
|
return _pp_character(qtext, n)
|
||||||
|
if variant == "rotate":
|
||||||
|
return _pp_rotate(qtext, n)
|
||||||
|
return _pp_sequence(qtext, n)
|
||||||
|
|
||||||
|
|
||||||
|
def gh_variant(qfull):
|
||||||
|
ql = (qfull or "").lower()
|
||||||
|
if "rotate" in ql or "direction" in ql:
|
||||||
|
return "rotate"
|
||||||
|
if "move the character" in ql or "tiles" in ql:
|
||||||
|
return "character"
|
||||||
|
return "sequence"
|
||||||
|
|
||||||
|
|
||||||
|
async def gh_find_game(page):
|
||||||
|
"""找真正的拼图 game frame(有 Navigate 箭头=已进拼图,非选择页)。返回 (frame,text) 或 (None,'')"""
|
||||||
|
for f in page.frames:
|
||||||
|
u = f.url or ""
|
||||||
|
if "index.html" in u and ("arkose" in u or "funcaptcha" in u):
|
||||||
|
try:
|
||||||
|
if await f.get_by_role("button", name="Navigate to next image").count() > 0:
|
||||||
|
t = await f.evaluate("()=>document.body.innerText||''")
|
||||||
|
return f, t
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return None, ""
|
||||||
|
|
||||||
|
|
||||||
|
async def gh_count_options(game):
|
||||||
|
"""数进度点 .pip 得候选张数,回退 6。"""
|
||||||
|
try:
|
||||||
|
n = await game.evaluate("()=>document.querySelectorAll('.pip').length")
|
||||||
|
if isinstance(n, int) and 2 <= n <= 12:
|
||||||
|
return n
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return 6
|
||||||
|
|
||||||
|
|
||||||
|
async def solve_puzzle_voting(page, shot_dir="screenshots_github", max_rounds=10, on_round=None, skip_variants=("character",)):
|
||||||
|
"""GitHub Arkose 拼图整关求解(实测10/10通过):等PoW→点Visual puzzle→每轮变体分派+4模型投票
|
||||||
|
→导航提交→直到 octocaptcha 消失(过)或答错(停)。返回 True=过验证。
|
||||||
|
调用前需已点 Create account 触发验证。"""
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
os.makedirs(shot_dir, exist_ok=True)
|
||||||
|
for it in range(50):
|
||||||
|
await asyncio.sleep(3)
|
||||||
|
g, _ = await gh_find_game(page)
|
||||||
|
if g:
|
||||||
|
break
|
||||||
|
# octocaptcha 整个没了 = 可能已过
|
||||||
|
if not any("octocaptcha" in (f.url or "") for f in page.frames):
|
||||||
|
# 但也可能是还没触发;只有在确实出现过又消失才算过——这里保守不退,继续触发
|
||||||
|
pass
|
||||||
|
hit = False
|
||||||
|
for f in page.frames:
|
||||||
|
if any(k in (f.url or "") for k in ["octocaptcha", "arkose", "funcaptcha"]):
|
||||||
|
hit = True
|
||||||
|
try:
|
||||||
|
el = f.get_by_text("Visual puzzle", exact=False).first
|
||||||
|
if await el.count() > 0:
|
||||||
|
await el.click(timeout=4000)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
# 白屏/卡加载自救:每 ~21s 重点一次 Create account 重新触发挑战(Arkose 偶发不渲染)
|
||||||
|
if not g and it in (6, 13, 20, 27, 34, 41):
|
||||||
|
try:
|
||||||
|
bb2 = page.get_by_role("button", name="Create account", exact=True)
|
||||||
|
for i in range(await bb2.count()):
|
||||||
|
x = bb2.nth(i)
|
||||||
|
if await x.get_attribute("disabled") is None:
|
||||||
|
await x.click(timeout=3000)
|
||||||
|
print(f" [solve] 重触发 Create account @ ~{it*3}s (hit_frame={hit})")
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
await asyncio.sleep(4)
|
||||||
|
|
||||||
|
rnd = -1
|
||||||
|
while True:
|
||||||
|
rnd += 1
|
||||||
|
if rnd > max_rounds:
|
||||||
|
print(" [solve] 跑满轮数,停")
|
||||||
|
return False
|
||||||
|
game = None
|
||||||
|
for w in range(16):
|
||||||
|
game, qt = await gh_find_game(page)
|
||||||
|
if game:
|
||||||
|
break
|
||||||
|
if not any("octocaptcha" in (f.url or "") for f in page.frames):
|
||||||
|
print(f" [solve] octocaptcha 消失 @ R{rnd},验证通过")
|
||||||
|
return True
|
||||||
|
for f in page.frames:
|
||||||
|
if any(k in (f.url or "") for k in ["octocaptcha", "arkose", "funcaptcha"]):
|
||||||
|
try:
|
||||||
|
b = f.get_by_text("Visual puzzle", exact=False).first
|
||||||
|
if await b.count() > 0:
|
||||||
|
await b.click(timeout=3000)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
await asyncio.sleep(3)
|
||||||
|
if not game:
|
||||||
|
if not any("octocaptcha" in (f.url or "") for f in page.frames):
|
||||||
|
return True
|
||||||
|
print(f" [solve] R{rnd} 拿不到拼图,停")
|
||||||
|
return False
|
||||||
|
qfull = (qt or "").replace("\n", " ").strip()
|
||||||
|
qline = qfull[:200]
|
||||||
|
variant = gh_variant(qfull)
|
||||||
|
N = await gh_count_options(game)
|
||||||
|
print(f" [solve] R{rnd} variant={variant} N={N} q={qline!r}")
|
||||||
|
# 难变体(character 小人踩图标)模型识别极差且达不成共识,第一轮就遇到直接放弃,让上层重开窗口换题
|
||||||
|
if rnd == 0 and variant in skip_variants:
|
||||||
|
print(f" [solve] 遇到难变体 '{variant}',放弃本窗口换一批验证")
|
||||||
|
return "SKIP_VARIANT"
|
||||||
|
for _ld in range(8):
|
||||||
|
try:
|
||||||
|
rel = game.locator(SEL_REF_GH).first
|
||||||
|
if await rel.count() > 0:
|
||||||
|
bx = await rel.bounding_box()
|
||||||
|
if bx and bx["width"] > 20 and bx["height"] > 20:
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
await asyncio.sleep(2.5 if rnd == 0 else 1.0)
|
||||||
|
nxt = game.get_by_role("button", name="Navigate to next image")
|
||||||
|
ref = await shot_element(game, SEL_REF_GH, f"{shot_dir}/v_ref{rnd}.png", scale=3)
|
||||||
|
cands = []
|
||||||
|
for i in range(N):
|
||||||
|
c = await shot_element(game, SEL_CAND_GH, f"{shot_dir}/v_c{rnd}_{i}.png", scale=3)
|
||||||
|
if c:
|
||||||
|
cands.append(c)
|
||||||
|
if i < N - 1:
|
||||||
|
try:
|
||||||
|
await nxt.first.click(timeout=3000)
|
||||||
|
except Exception:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(0.8)
|
||||||
|
grid, geom = stitch_options_grid(cands, f"{shot_dir}/v_grid{rnd}.png", reference_b64=ref, cols=3, return_geom=True)
|
||||||
|
if not grid:
|
||||||
|
print(" [solve] stitch failed")
|
||||||
|
return False
|
||||||
|
# character 变体图大(3D网格多张),并发会把慢模型打掉票→只剩1个模型。压更小让4模型都能按时回票。
|
||||||
|
if variant == "character":
|
||||||
|
grid_hd = enhance_local(grid, f"{shot_dir}/v_grid{rnd}_hd.png", scale=2, max_side=1000, jpeg_quality=72)
|
||||||
|
else:
|
||||||
|
grid_hd = enhance_local(grid, f"{shot_dir}/v_grid{rnd}_hd.png", scale=2)
|
||||||
|
prm = gh_pick_prompt(qline, len(cands), variant)
|
||||||
|
best, votes, raws = vote_answer(prm, grid_hd, len(cands), max_tokens=900)
|
||||||
|
if not votes:
|
||||||
|
await asyncio.sleep(2)
|
||||||
|
best, votes, raws = vote_answer(prm, grid_hd, len(cands), max_tokens=900)
|
||||||
|
if best is None or best < 0 or best >= len(cands):
|
||||||
|
best = 0
|
||||||
|
print(f" [solve] R{rnd} vote -> #{best} votes={votes}")
|
||||||
|
try:
|
||||||
|
annotate_choice(f"{shot_dir}/v_grid{rnd}.png", geom, best,
|
||||||
|
f"{shot_dir}/REVIEW_r{rnd}.png", note=f"r{rnd} #{best} {votes}", votes_raw=raws)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if on_round:
|
||||||
|
try:
|
||||||
|
on_round(rnd, best, votes)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
game = None
|
||||||
|
for _w in range(8):
|
||||||
|
game, _ = await gh_find_game(page)
|
||||||
|
if game:
|
||||||
|
break
|
||||||
|
if not any("octocaptcha" in (f.url or "") for f in page.frames):
|
||||||
|
return True
|
||||||
|
await asyncio.sleep(2)
|
||||||
|
if not game:
|
||||||
|
if not any("octocaptcha" in (f.url or "") for f in page.frames):
|
||||||
|
return True
|
||||||
|
continue
|
||||||
|
back = (N - 1 - best)
|
||||||
|
prv = game.get_by_role("button", name="Navigate to previous image")
|
||||||
|
for _ in range(back):
|
||||||
|
try:
|
||||||
|
await prv.first.click(timeout=3000)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
await asyncio.sleep(0.6)
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
for attempt in range(4):
|
||||||
|
try:
|
||||||
|
await game.get_by_role("button", name="Submit").first.click(timeout=4000)
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
game, _ = await gh_find_game(page)
|
||||||
|
if not game:
|
||||||
|
break
|
||||||
|
await asyncio.sleep(1.5)
|
||||||
|
await asyncio.sleep(4)
|
||||||
|
if not any("octocaptcha" in (f.url or "") for f in page.frames):
|
||||||
|
print(" [solve] 验证通过")
|
||||||
|
return True
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Sync Arkose FunCaptcha solver — multi-LLM voting, $0.
|
||||||
|
|
||||||
|
Field-verified multi-LLM voting solver for the SYNC Playwright/Camoufox API
|
||||||
|
used by this project's runner.
|
||||||
|
|
||||||
|
Flow:
|
||||||
|
1. Wait for Arkose proof-of-work, click "Visual puzzle" inside octocaptcha iframe
|
||||||
|
2. Per round: detect variant (sequence/rotate/character/wires)
|
||||||
|
3. Screenshot reference + N candidates, stitch numbered grid, enhance (PIL)
|
||||||
|
4. Parallel vote: qwen3-vl-flash / qwen-vl-max / qwen-vl-plus via local
|
||||||
|
dashscope proxy (free) + any configured premium gateways
|
||||||
|
5. Majority wins -> navigate back to winning candidate -> Submit
|
||||||
|
6. Repeat until octocaptcha disappears (passed) or max_rounds
|
||||||
|
|
||||||
|
Env overrides:
|
||||||
|
VOTE_BASE default http://127.0.0.1:16432/v1 (OpenAI-compatible vision gateway)
|
||||||
|
VOTE_KEY default "free"
|
||||||
|
VOTE_MODELS default qwen3-vl-flash,qwen-vl-max,qwen-vl-plus (comma separated)
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from . import agent_captcha as AC
|
||||||
|
|
||||||
|
_DEFAULT_BASE = os.environ.get("VOTE_BASE", "http://127.0.0.1:16432/v1")
|
||||||
|
_DEFAULT_KEY = os.environ.get("VOTE_KEY", "free")
|
||||||
|
_DEFAULT_MODELS = [
|
||||||
|
m.strip() for m in
|
||||||
|
os.environ.get("VOTE_MODELS", "qwen3-vl-flash,qwen-vl-max,qwen-vl-plus").split(",")
|
||||||
|
if m.strip()
|
||||||
|
]
|
||||||
|
|
||||||
|
SEL_REF = ".key-frame-image"
|
||||||
|
SEL_CAND = ".answer-frame img, .answer-frame canvas, .answer-frame"
|
||||||
|
|
||||||
|
|
||||||
|
def _frames(page):
|
||||||
|
try:
|
||||||
|
return list(page.frames)
|
||||||
|
except Exception:
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def _is_arkose_frame(f):
|
||||||
|
u = (f.url or "").lower()
|
||||||
|
return any(k in u for k in ("octocaptcha", "arkose", "funcaptcha"))
|
||||||
|
|
||||||
|
|
||||||
|
def _find_game(page):
|
||||||
|
"""Return (frame, question_text) of the real puzzle game frame or (None, '')."""
|
||||||
|
for f in _frames(page):
|
||||||
|
u = f.url or ""
|
||||||
|
if "index.html" in u and ("arkose" in u.lower() or "funcaptcha" in u.lower()):
|
||||||
|
try:
|
||||||
|
if f.get_by_role("button", name="Navigate to next image").count() > 0:
|
||||||
|
t = f.evaluate("() => document.body.innerText || ''")
|
||||||
|
return f, t
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return None, ""
|
||||||
|
|
||||||
|
|
||||||
|
def _count_options(game) -> int:
|
||||||
|
try:
|
||||||
|
n = game.evaluate("() => document.querySelectorAll('.pip').length")
|
||||||
|
if isinstance(n, int) and 2 <= n <= 12:
|
||||||
|
return n
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return 6
|
||||||
|
|
||||||
|
|
||||||
|
def _shot_element(frame, selector, path, scale=3):
|
||||||
|
"""Screenshot an element inside the game frame, upscaled. Returns b64 or None."""
|
||||||
|
try:
|
||||||
|
el = frame.locator(selector).first
|
||||||
|
if el.count() == 0:
|
||||||
|
return None
|
||||||
|
el.screenshot(path=path)
|
||||||
|
except Exception as exc:
|
||||||
|
print(f" [vote] shot_element({selector}) err: {str(exc)[:60]}")
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
from PIL import Image
|
||||||
|
im = Image.open(path).convert("RGB")
|
||||||
|
im = im.resize((im.width * scale, im.height * scale), Image.LANCZOS)
|
||||||
|
im.save(path)
|
||||||
|
with open(path, "rb") as fh:
|
||||||
|
return base64.b64encode(fh.read()).decode()
|
||||||
|
except Exception:
|
||||||
|
with open(path, "rb") as fh:
|
||||||
|
return base64.b64encode(fh.read()).decode()
|
||||||
|
|
||||||
|
|
||||||
|
def arkose_present(page) -> bool:
|
||||||
|
"""Is an Arkose/Octocaptcha challenge frame on the page right now?"""
|
||||||
|
return any(_is_arkose_frame(f) for f in _frames(page))
|
||||||
|
|
||||||
|
|
||||||
|
def _click_visual_puzzle(page, deadline_s: float) -> bool:
|
||||||
|
"""Wait out the Arkose PoW and click 'Visual puzzle'. Returns True on click."""
|
||||||
|
deadline = time.time() + deadline_s
|
||||||
|
while time.time() < deadline:
|
||||||
|
for f in _frames(page):
|
||||||
|
if _is_arkose_frame(f):
|
||||||
|
try:
|
||||||
|
el = f.get_by_text("Visual puzzle", exact=False).first
|
||||||
|
if el.count() > 0:
|
||||||
|
el.click(timeout=4000)
|
||||||
|
print(" [vote] clicked 'Visual puzzle'")
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
time.sleep(3)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def solve_arkose_voting(page, shot_dir: str = "screenshots_captcha",
|
||||||
|
max_rounds: int = 12, log=print,
|
||||||
|
skip_variants=("character",)) -> bool:
|
||||||
|
"""Solve the GitHub Arkose FunCaptcha via multi-model voting (sync API).
|
||||||
|
|
||||||
|
Call AFTER 'Create account' was clicked and the challenge appeared.
|
||||||
|
Returns True when the octocaptcha frame disappears (verification passed).
|
||||||
|
Returns 'SKIP_VARIANT' when round 0 is the hard character variant
|
||||||
|
(caller should reload for a new challenge). Returns False on failure.
|
||||||
|
"""
|
||||||
|
Path(shot_dir).mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
# --- trigger / wait for the game ---
|
||||||
|
for it in range(16): # up to ~48s of PoW + settle
|
||||||
|
game, qt = _find_game(page)
|
||||||
|
if game:
|
||||||
|
break
|
||||||
|
if not arkose_present(page):
|
||||||
|
log("[vote] no arkose frame — nothing to solve")
|
||||||
|
return True
|
||||||
|
_click_visual_puzzle(page, deadline_s=6)
|
||||||
|
time.sleep(3)
|
||||||
|
else:
|
||||||
|
log("[vote] game frame never appeared")
|
||||||
|
return False
|
||||||
|
|
||||||
|
rnd = -1
|
||||||
|
while True:
|
||||||
|
rnd += 1
|
||||||
|
if rnd > max_rounds:
|
||||||
|
log("[vote] max rounds exhausted")
|
||||||
|
return False
|
||||||
|
game = None
|
||||||
|
for _w in range(16):
|
||||||
|
game, qt = _find_game(page)
|
||||||
|
if game:
|
||||||
|
break
|
||||||
|
if not arkose_present(page):
|
||||||
|
log(f"[vote] octocaptcha gone @ R{rnd} — PASSED")
|
||||||
|
return True
|
||||||
|
_click_visual_puzzle(page, deadline_s=3)
|
||||||
|
time.sleep(3)
|
||||||
|
if not game:
|
||||||
|
if not arkose_present(page):
|
||||||
|
return True
|
||||||
|
log(f"[vote] R{rnd}: cannot grab puzzle frame")
|
||||||
|
return False
|
||||||
|
|
||||||
|
qfull = (qt or "").replace("\n", " ").strip()
|
||||||
|
qline = qfull[:200]
|
||||||
|
variant = AC.gh_variant(qfull)
|
||||||
|
N = _count_options(game)
|
||||||
|
log(f"[vote] R{rnd} variant={variant} N={N} q={qline!r}")
|
||||||
|
|
||||||
|
if rnd == 0 and variant in skip_variants:
|
||||||
|
log(f"[vote] hard variant '{variant}' on first round — skip window")
|
||||||
|
return "SKIP_VARIANT"
|
||||||
|
|
||||||
|
# wait for reference image to render
|
||||||
|
for _ld in range(8):
|
||||||
|
try:
|
||||||
|
rel = game.locator(SEL_REF).first
|
||||||
|
if rel.count() > 0:
|
||||||
|
bx = rel.bounding_box()
|
||||||
|
if bx and bx["width"] > 20 and bx["height"] > 20:
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
time.sleep(1)
|
||||||
|
time.sleep(2.5 if rnd == 0 else 1.0)
|
||||||
|
|
||||||
|
nxt = game.get_by_role("button", name="Navigate to next image")
|
||||||
|
ref = _shot_element(game, SEL_REF, f"{shot_dir}/v_ref{rnd}.png", scale=3)
|
||||||
|
cands = []
|
||||||
|
for i in range(N):
|
||||||
|
c = _shot_element(game, SEL_CAND, f"{shot_dir}/v_c{rnd}_{i}.png", scale=3)
|
||||||
|
if c:
|
||||||
|
cands.append(c)
|
||||||
|
if i < N - 1:
|
||||||
|
try:
|
||||||
|
nxt.first.click(timeout=3000)
|
||||||
|
except Exception:
|
||||||
|
break
|
||||||
|
time.sleep(0.8)
|
||||||
|
grid, geom = AC.stitch_options_grid(
|
||||||
|
cands, f"{shot_dir}/v_grid{rnd}.png", reference_b64=ref,
|
||||||
|
cols=3, return_geom=True)
|
||||||
|
if not grid:
|
||||||
|
log("[vote] grid stitch failed")
|
||||||
|
return False
|
||||||
|
if variant == "character":
|
||||||
|
grid_hd = AC.enhance_local(grid, f"{shot_dir}/v_grid{rnd}_hd.png",
|
||||||
|
scale=2, max_side=1000, jpeg_quality=72)
|
||||||
|
else:
|
||||||
|
grid_hd = AC.enhance_local(grid, f"{shot_dir}/v_grid{rnd}_hd.png", scale=2)
|
||||||
|
|
||||||
|
prm = AC.gh_pick_prompt(qline, len(cands), variant)
|
||||||
|
|
||||||
|
# vote with the FREE qwen pool unless premium gateways are configured
|
||||||
|
models = [(_DEFAULT_BASE, _DEFAULT_KEY, m) for m in _DEFAULT_MODELS]
|
||||||
|
if AC.VOTER_MODELS:
|
||||||
|
models = list(AC.VOTER_MODELS) + models
|
||||||
|
saved = AC.VOTER_MODELS
|
||||||
|
try:
|
||||||
|
AC.VOTER_MODELS = models
|
||||||
|
best, votes, raws = AC.vote_answer(prm, grid_hd, len(cands), max_tokens=900)
|
||||||
|
if not votes:
|
||||||
|
time.sleep(2)
|
||||||
|
best, votes, raws = AC.vote_answer(prm, grid_hd, len(cands), max_tokens=900)
|
||||||
|
finally:
|
||||||
|
AC.VOTER_MODELS = saved
|
||||||
|
if best is None or best < 0 or best >= len(cands):
|
||||||
|
best = 0
|
||||||
|
log(f"[vote] R{rnd} -> #{best} votes={votes}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
AC.annotate_choice(f"{shot_dir}/v_grid{rnd}.png", geom, best,
|
||||||
|
f"{shot_dir}/REVIEW_r{rnd}.png",
|
||||||
|
note=f"r{rnd} #{best} {votes}", votes_raw=raws)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# re-acquire the game frame (it may have re-rendered)
|
||||||
|
game = None
|
||||||
|
for _w in range(8):
|
||||||
|
game, _ = _find_game(page)
|
||||||
|
if game:
|
||||||
|
break
|
||||||
|
if not arkose_present(page):
|
||||||
|
return True
|
||||||
|
time.sleep(2)
|
||||||
|
if not game:
|
||||||
|
if not arkose_present(page):
|
||||||
|
return True
|
||||||
|
continue
|
||||||
|
|
||||||
|
# navigate back from the last candidate to the winning one, then Submit
|
||||||
|
back = (N - 1 - best)
|
||||||
|
prv = game.get_by_role("button", name="Navigate to previous image")
|
||||||
|
for _ in range(back):
|
||||||
|
try:
|
||||||
|
prv.first.click(timeout=3000)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
time.sleep(0.6)
|
||||||
|
time.sleep(1)
|
||||||
|
for attempt in range(4):
|
||||||
|
try:
|
||||||
|
game.get_by_role("button", name="Submit").first.click(timeout=4000)
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
game, _ = _find_game(page)
|
||||||
|
if not game:
|
||||||
|
break
|
||||||
|
time.sleep(1.5)
|
||||||
|
time.sleep(4)
|
||||||
|
if not arkose_present(page):
|
||||||
|
log("[vote] verification PASSED")
|
||||||
|
return True
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"""Configuration loading for the GitHub register toolkit."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Config:
|
||||||
|
# Mail provider: "mailcx" (free, default), "litensi" (paid, reliable),
|
||||||
|
# "gmail" / "outlook" — your own mailbox via IMAP with +alias addresses
|
||||||
|
# "temptf" — temp.tf free pool (gmail/outlook/hotmail/high.edu.pl aliases)
|
||||||
|
mail_provider: str = "mailcx" # "mailcx" | "litensi" | "gmail" | "outlook" | "temptf"
|
||||||
|
# temp.tf providers (comma list; pools can be empty -> rotated)
|
||||||
|
temptf_providers: str = "gmail.com,outlook.com,hotmail.com,high.edu.pl"
|
||||||
|
temptf_dot: bool = True # gmail dot-aliases
|
||||||
|
temptf_plus: bool = True # +tag aliases
|
||||||
|
# IMAP (gmail/outlook providers): App Password recommended, IMAP enabled
|
||||||
|
imap_user: str = "" # e.g. mybox@gmail.com or mybox@outlook.com
|
||||||
|
imap_password: str = "" # App Password (NOT the account password)
|
||||||
|
imap_host: str = "" # blank = provider default
|
||||||
|
imap_port: int = 993
|
||||||
|
imap_alias_domain: str = "" # blank = gmail.com / outlook.com
|
||||||
|
# Mail.cx temp email settings
|
||||||
|
mailcx_domain: str = "" # empty = auto-pick from uqu.me, ddker.com, 9k3r.com
|
||||||
|
# Litensi Mail settings
|
||||||
|
litensi_api_id: str = ""
|
||||||
|
litensi_api_key: str = ""
|
||||||
|
litensi_site: str = "" # e.g. "github.com"
|
||||||
|
litensi_zone: str = "" # blank = auto-pick cheapest in-stock zone
|
||||||
|
register_count: int = 1
|
||||||
|
proxy: str = ""
|
||||||
|
proxy_file: str = "" # proxy pool file in project root (one URL per line); overrides proxy
|
||||||
|
headless: bool = False
|
||||||
|
delay_sec: float = 5.0
|
||||||
|
max_username_tries: int = 6
|
||||||
|
otp_timeout_sec: int = 240
|
||||||
|
browser_profile_dir: str = ".browser-profile"
|
||||||
|
# fresh browser per account (incognito-like, zero cached state); the
|
||||||
|
# DataDome trust cookie is carried over via .datadome-trust.json so the
|
||||||
|
# signup page keeps loading without hard 403s
|
||||||
|
fresh_profile: bool = True
|
||||||
|
proxy_hard_block_retries: int = 2
|
||||||
|
proxy_rate_limit_retries: int = 2
|
||||||
|
# post-signup stages (from user recording)
|
||||||
|
# PRIME: Arkose FunCaptcha multi-LLM voting solver ($0 qwen pool by default)
|
||||||
|
solve_captcha: bool = True
|
||||||
|
captcha_max_rounds: int = 12
|
||||||
|
create_repo: bool = True # stage 4: create first repository
|
||||||
|
repo_name: str = "hello" # repo name prefix (username-suffix appended on conflict)
|
||||||
|
enable_2fa: bool = True # stage 5: enable TOTP 2FA and store the secret
|
||||||
|
create_pat: bool = False # stage 6: classic PAT (repo+workflow scopes)
|
||||||
|
set_profile_status: bool = True
|
||||||
|
profile_status: str = "On vacation" # blank disables custom status text
|
||||||
|
complete_profile: bool = True
|
||||||
|
profile_name: str = "" # blank = Random User
|
||||||
|
profile_bio: str = "" # blank = ZenQuotes
|
||||||
|
profile_location: str = "" # blank = Random User country
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_dict(cls, data: dict) -> "Config":
|
||||||
|
known = set(cls.__dataclass_fields__)
|
||||||
|
mapped = {k: v for k, v in data.items() if k in known}
|
||||||
|
return cls(**mapped)
|
||||||
|
|
||||||
|
|
||||||
|
def load_config(path: str | Path) -> Config:
|
||||||
|
p = Path(path)
|
||||||
|
if not p.is_file():
|
||||||
|
raise FileNotFoundError(
|
||||||
|
f"config not found: {p} (copy config.example.json to config.json and fill it in)"
|
||||||
|
)
|
||||||
|
data = json.loads(p.read_text(encoding="utf-8"))
|
||||||
|
return Config.from_dict(data)
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
"""Litensi Mail API client.
|
||||||
|
|
||||||
|
Endpoints (docs):
|
||||||
|
POST /api/profile -> balance info
|
||||||
|
POST /api/mail/prices -> zones for a site
|
||||||
|
POST /api/mail/order -> create mailbox
|
||||||
|
POST /api/mail/getstatus -> poll message (min 5s interval!)
|
||||||
|
POST /api/mail/setstatus -> SUCCESS (code used) / CANCELED (abort)
|
||||||
|
POST /api/mail/reorder -> re-order the SAME email for another window
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
from typing import Callable, Iterable, Optional
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from .mail_errors import MailboxCancelled, MailboxTimeoutError
|
||||||
|
|
||||||
|
API_BASE = "https://litensi.id/api/mail"
|
||||||
|
PROFILE_BASE = "https://litensi.id/api/profile"
|
||||||
|
|
||||||
|
|
||||||
|
class LitensiError(RuntimeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class LitensiClient:
|
||||||
|
def __init__(self, api_id: str, api_key: str, site: str, zone: str = ""):
|
||||||
|
if not api_id or not api_key:
|
||||||
|
raise LitensiError("litensi_api_id / litensi_api_key not configured")
|
||||||
|
if not site:
|
||||||
|
raise LitensiError("litensi_site not configured")
|
||||||
|
self.api_id = api_id
|
||||||
|
self.api_key = api_key
|
||||||
|
self.site = site
|
||||||
|
self.zone = zone
|
||||||
|
self.session = requests.Session()
|
||||||
|
|
||||||
|
def _post(self, path: str, data: dict, base: Optional[str] = None) -> dict:
|
||||||
|
url = f"{base or API_BASE}/{path}" if path else (base or API_BASE)
|
||||||
|
last_exc: Exception | None = None
|
||||||
|
for attempt in range(3): # transient network hiccups: retry
|
||||||
|
try:
|
||||||
|
resp = self.session.post(url, data=data, timeout=30)
|
||||||
|
break
|
||||||
|
except requests.RequestException as exc:
|
||||||
|
last_exc = exc
|
||||||
|
time.sleep(2 * (attempt + 1))
|
||||||
|
else:
|
||||||
|
raise LitensiError(f"litensi {url} unreachable: {last_exc}")
|
||||||
|
try:
|
||||||
|
payload = resp.json()
|
||||||
|
except ValueError:
|
||||||
|
payload = None
|
||||||
|
if not resp.ok or not (payload and payload.get("success")):
|
||||||
|
reason = payload.get("data") if isinstance(payload, dict) else None
|
||||||
|
# Litensi error codes (docs: {"success": false, "data": "XXXXXX"})
|
||||||
|
hints = {
|
||||||
|
"BAD SITE": " — litensi_site must be a domain (for example: github.com)",
|
||||||
|
"BAD API": " — check litensi_api_id / litensi_api_key",
|
||||||
|
"BAD API ID": " — litensi_api_id is invalid or inactive",
|
||||||
|
"BAD API KEY": " — litensi_api_key is invalid",
|
||||||
|
"BAD ZONE": " — zone is unavailable for this site (leave blank for automatic selection)",
|
||||||
|
"OUT OF STOCK": " — mailbox stock is empty for this zone/site",
|
||||||
|
"NOT ENOUGH BALANCE": " — Litensi balance is insufficient",
|
||||||
|
"IP NOT ALLOWED": " — server IP is not whitelisted in the Litensi dashboard",
|
||||||
|
}
|
||||||
|
hint = hints.get(str(reason).strip().upper(), "")
|
||||||
|
raise LitensiError(
|
||||||
|
f"litensi {path or 'profile'} failed (HTTP {resp.status_code}): "
|
||||||
|
f"{reason or payload or resp.text[:200]}{hint}"
|
||||||
|
)
|
||||||
|
return payload.get("data") if payload.get("data") is not None else {}
|
||||||
|
|
||||||
|
def profile(self) -> dict:
|
||||||
|
"""GET /api/profile — username, full_name, balance."""
|
||||||
|
return self._post(
|
||||||
|
"",
|
||||||
|
{"api_id": self.api_id, "api_key": self.api_key},
|
||||||
|
base=PROFILE_BASE,
|
||||||
|
)
|
||||||
|
|
||||||
|
def prices(self) -> list[dict]:
|
||||||
|
data = self._post(
|
||||||
|
"prices",
|
||||||
|
{"api_id": self.api_id, "api_key": self.api_key, "site": self.site},
|
||||||
|
)
|
||||||
|
return data if isinstance(data, list) else []
|
||||||
|
|
||||||
|
def pick_zone(self) -> str:
|
||||||
|
stock = [z for z in self.prices() if float(z.get("stock") or 0) > 0]
|
||||||
|
if not stock:
|
||||||
|
raise LitensiError(f"litensi has no zones in stock for site {self.site!r}")
|
||||||
|
return min(stock, key=lambda z: float(z.get("price") or 0))["zone"]
|
||||||
|
|
||||||
|
def create_mailbox(self) -> tuple[str, str]:
|
||||||
|
zone = self.zone or self.pick_zone()
|
||||||
|
data = self._post(
|
||||||
|
"order",
|
||||||
|
{
|
||||||
|
"api_id": self.api_id,
|
||||||
|
"api_key": self.api_key,
|
||||||
|
"zone": zone,
|
||||||
|
"site": self.site,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
email = data.get("email")
|
||||||
|
order_id = data.get("order_id")
|
||||||
|
if not email or order_id is None:
|
||||||
|
raise LitensiError(f"litensi order bad response: {data}")
|
||||||
|
return email, str(order_id)
|
||||||
|
|
||||||
|
def get_status(self, order_id: str) -> dict:
|
||||||
|
return self._post(
|
||||||
|
"getstatus",
|
||||||
|
{"api_id": self.api_id, "api_key": self.api_key, "order_id": order_id},
|
||||||
|
)
|
||||||
|
|
||||||
|
def set_status(self, order_id: str, status: str) -> dict:
|
||||||
|
"""setstatus: only SUCCESS (code used) or CANCELED (abort)."""
|
||||||
|
if status not in ("SUCCESS", "CANCELED"):
|
||||||
|
raise LitensiError(f"invalid setstatus value: {status}")
|
||||||
|
return self._post(
|
||||||
|
"setstatus",
|
||||||
|
{
|
||||||
|
"api_id": self.api_id,
|
||||||
|
"api_key": self.api_key,
|
||||||
|
"order_id": order_id,
|
||||||
|
"status": status,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
def mark_success(self, order_id: str) -> dict:
|
||||||
|
"""Confirm the activation code was used (docs: setstatus SUCCESS)."""
|
||||||
|
return self.set_status(order_id, "SUCCESS")
|
||||||
|
|
||||||
|
def reorder(self, email: str) -> dict:
|
||||||
|
"""Re-order the SAME email for a fresh window (docs: /api/mail/reorder).
|
||||||
|
|
||||||
|
Returns {'order_id', 'email', 'expired_at'} — use the new order_id for
|
||||||
|
further getstatus polling.
|
||||||
|
"""
|
||||||
|
return self._post(
|
||||||
|
"reorder",
|
||||||
|
{
|
||||||
|
"api_id": self.api_id,
|
||||||
|
"api_key": self.api_key,
|
||||||
|
"site": self.site,
|
||||||
|
"email": email,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
def wait_for_code(
|
||||||
|
self,
|
||||||
|
order_id: str,
|
||||||
|
email: str = "",
|
||||||
|
timeout: int = 240,
|
||||||
|
poll_interval: int = 5,
|
||||||
|
reorder_after: int = 150,
|
||||||
|
log: Optional[Callable[[str], None]] = None,
|
||||||
|
cancel_cb: Optional[Callable[[], bool]] = None,
|
||||||
|
exclude_codes: Optional[Iterable[str]] = None,
|
||||||
|
) -> str:
|
||||||
|
"""Poll the mailbox until the GitHub code arrives.
|
||||||
|
|
||||||
|
Litensi mailboxes expire fast (minutes). If no code arrives within
|
||||||
|
`reorder_after` seconds, automatically re-order the SAME email for a
|
||||||
|
fresh window and keep polling under the new order_id.
|
||||||
|
|
||||||
|
``exclude_codes`` — codes already consumed (e.g. the signup launch
|
||||||
|
code). When GitHub asks for a SECOND launch code (device verification
|
||||||
|
on login), skipping those already-used codes lets us wait for the new
|
||||||
|
one instead of returning the same message again.
|
||||||
|
|
||||||
|
IMPORTANT: returns only; setstatus SUCCESS is the CALLER's job once the
|
||||||
|
code has actually been submitted to GitHub (see runner).
|
||||||
|
"""
|
||||||
|
from .profiles import extract_github_code
|
||||||
|
|
||||||
|
poll_interval = max(5, poll_interval) # litensi: >= 5s between getstatus
|
||||||
|
started = time.time()
|
||||||
|
current_order = str(order_id)
|
||||||
|
reordered_at: Optional[float] = None
|
||||||
|
# Once a reorder call has failed with a definitive error (e.g. the
|
||||||
|
# provider returns UNSUPPORT ACTIVATION, or the plan does not allow
|
||||||
|
# reorder for this zone), don't retry it every poll — otherwise the
|
||||||
|
# log fills with dozens of identical failures. We keep polling the
|
||||||
|
# original order until the total ``timeout`` expires.
|
||||||
|
reorder_disabled = False
|
||||||
|
skip = {str(c).strip() for c in (exclude_codes or ()) if str(c).strip()}
|
||||||
|
while time.time() - started < timeout:
|
||||||
|
if cancel_cb and cancel_cb():
|
||||||
|
raise MailboxCancelled("cancelled while waiting for mail")
|
||||||
|
try:
|
||||||
|
data = self.get_status(current_order)
|
||||||
|
except Exception as exc:
|
||||||
|
msg = str(exc).lower()
|
||||||
|
if "activation does not exist" in msg or "email activation expired" in msg:
|
||||||
|
# mailbox window closed — re-order the same email if we can
|
||||||
|
if email and not reorder_disabled:
|
||||||
|
if log:
|
||||||
|
log(f"[*] litensi order {current_order} expired — reordering {email}")
|
||||||
|
try:
|
||||||
|
data = self.reorder(email)
|
||||||
|
current_order = str(data.get("order_id") or current_order)
|
||||||
|
reordered_at = time.time()
|
||||||
|
continue
|
||||||
|
except Exception as reorder_exc:
|
||||||
|
reorder_disabled = True
|
||||||
|
if log:
|
||||||
|
log(f"[!] litensi reorder failed permanently: {reorder_exc} — "
|
||||||
|
f"will keep polling the original order until timeout")
|
||||||
|
if log:
|
||||||
|
log(f"[!] litensi getstatus failed: {exc}")
|
||||||
|
time.sleep(poll_interval)
|
||||||
|
continue
|
||||||
|
status = str(data.get("status") or "")
|
||||||
|
if log:
|
||||||
|
log(f"[*] litensi order {current_order} status: {status}")
|
||||||
|
if status == "CANCELED":
|
||||||
|
raise LitensiError("litensi order canceled")
|
||||||
|
text = "\n".join(
|
||||||
|
x for x in (data.get("message", ""), data.get("full_message", "")) if x
|
||||||
|
)
|
||||||
|
code = extract_github_code(text)
|
||||||
|
if code:
|
||||||
|
if code in skip:
|
||||||
|
if log:
|
||||||
|
log(f"[*] litensi skipped already-used code {code}")
|
||||||
|
else:
|
||||||
|
self._last_order_id = current_order
|
||||||
|
return code
|
||||||
|
# no code yet and the window is running out -> reorder the same email
|
||||||
|
elapsed = time.time() - (reordered_at or started)
|
||||||
|
if email and not reorder_disabled and elapsed >= reorder_after:
|
||||||
|
if log:
|
||||||
|
log(f"[*] no code after {int(elapsed)}s — reordering mailbox {email}")
|
||||||
|
try:
|
||||||
|
data = self.reorder(email)
|
||||||
|
current_order = str(data.get("order_id") or current_order)
|
||||||
|
reordered_at = time.time()
|
||||||
|
except Exception as exc:
|
||||||
|
# Reorder is not supported for this order / plan / zone.
|
||||||
|
# Disable further reorder attempts so we don't spam the
|
||||||
|
# provider every poll_interval seconds until timeout.
|
||||||
|
reorder_disabled = True
|
||||||
|
if log:
|
||||||
|
log(f"[!] reorder failed: {exc} — reorder disabled, "
|
||||||
|
f"will keep polling original order")
|
||||||
|
time.sleep(poll_interval)
|
||||||
|
# Per-mailbox timeout — NOT a fatal provider error. One mailbox that
|
||||||
|
# never received the GitHub code must fail only this account; the job
|
||||||
|
# continues with the next one (see github_register.mail_errors).
|
||||||
|
raise MailboxTimeoutError(f"no GitHub code after {timeout}s")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def last_order_id(self) -> str:
|
||||||
|
"""Order id that actually delivered the code (may differ after reorder)."""
|
||||||
|
return getattr(self, "_last_order_id", "")
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""Shared mailbox-provider exceptions.
|
||||||
|
|
||||||
|
Two very different failure classes must not be conflated:
|
||||||
|
|
||||||
|
* Fatal provider/config errors — bad API key, empty balance, out of stock,
|
||||||
|
IP not allowed. These are raised as ``LitensiError`` / ``MailCxError``.
|
||||||
|
Retrying the next account would fail identically, so the whole job aborts.
|
||||||
|
|
||||||
|
* Per-mailbox transient errors — a single mailbox never received the GitHub
|
||||||
|
verification code within the timeout. This is raised as
|
||||||
|
``MailboxTimeoutError``. It must fail ONLY that account and let the batch
|
||||||
|
continue; aborting a 50-account run because one mailbox timed out is wrong.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
|
class MailboxTimeoutError(RuntimeError):
|
||||||
|
"""No verification code arrived in time for a single mailbox.
|
||||||
|
|
||||||
|
Deliberately NOT a subclass of ``LitensiError`` / ``MailCxError`` so the
|
||||||
|
runner's fatal-provider-error handling does not catch it and abort the job.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class MailboxCancelled(RuntimeError):
|
||||||
|
"""The wait for a verification code was cancelled (user pressed Stop).
|
||||||
|
|
||||||
|
Also NOT a ``LitensiError`` / ``MailCxError`` so it is not reported as a
|
||||||
|
provider failure. The runner converts it into a clean cancellation.
|
||||||
|
"""
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""IMAP mail providers: Gmail (+alias) and Outlook (+alias).
|
||||||
|
|
||||||
|
Same duck-typed interface as MailCxClient so the runner can swap providers:
|
||||||
|
create_mailbox() -> (address, order_id)
|
||||||
|
wait_for_code(address, ...) -> code
|
||||||
|
set_status / mark_success / last_order_id (no-ops here)
|
||||||
|
|
||||||
|
Gmail: base+<random>@gmail.com — Google delivers plus-addressed mail to the
|
||||||
|
base inbox; we match the To: header. Requires an App Password (2FA on).
|
||||||
|
Outlook: base+<random>@outlook.com — Outlook.com supports plus addressing
|
||||||
|
the same way. Also App Password or OAuth; IMAP must be enabled.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import email
|
||||||
|
import email.header
|
||||||
|
import email.utils
|
||||||
|
import imaplib
|
||||||
|
import random
|
||||||
|
import re
|
||||||
|
import string
|
||||||
|
import time
|
||||||
|
from typing import Callable, Iterable, Optional
|
||||||
|
|
||||||
|
from .mail_errors import MailboxCancelled, MailboxTimeoutError
|
||||||
|
|
||||||
|
GMAIL_IMAP = ("imap.gmail.com", 993)
|
||||||
|
OUTLOOK_IMAP = ("outlook.office365.com", 993)
|
||||||
|
TONLINE_IMAP = ("secureimap.t-online.de", 993)
|
||||||
|
|
||||||
|
_CODE_RE = re.compile(r"\b(\d{4}[-\s]?\d{4}|\d{8})\b")
|
||||||
|
|
||||||
|
|
||||||
|
class ImapMailError(RuntimeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ImapMailClient:
|
||||||
|
"""One real mailbox, unlimited +alias addresses."""
|
||||||
|
|
||||||
|
def __init__(self, provider: str, user: str, password: str,
|
||||||
|
host: str = "", port: int = 993, alias_domain: str = ""):
|
||||||
|
self.provider = (provider or "").strip().lower()
|
||||||
|
self.user = (user or "").strip()
|
||||||
|
self.password = password or ""
|
||||||
|
self.alias_domain = (alias_domain or "").strip().lstrip("@")
|
||||||
|
if self.provider == "gmail":
|
||||||
|
default_host, default_port = GMAIL_IMAP
|
||||||
|
self.alias_domain = self.alias_domain or "gmail.com"
|
||||||
|
elif self.provider == "outlook":
|
||||||
|
default_host, default_port = OUTLOOK_IMAP
|
||||||
|
self.alias_domain = self.alias_domain or "outlook.com"
|
||||||
|
elif self.provider == "tonline":
|
||||||
|
default_host, default_port = TONLINE_IMAP
|
||||||
|
self.alias_domain = self.alias_domain or "t-online.de"
|
||||||
|
else:
|
||||||
|
raise ImapMailError(f"unknown imap provider: {provider}")
|
||||||
|
self.host = (host or "").strip() or default_host
|
||||||
|
self.port = int(port or default_port)
|
||||||
|
if not self.user or not self.password:
|
||||||
|
raise ImapMailError(
|
||||||
|
f"{self.provider}: imap_user and imap_password (App Password) are required")
|
||||||
|
self._last_order_id = ""
|
||||||
|
self._used_suffixes: set[str] = set()
|
||||||
|
|
||||||
|
# --- mailbox creation: just mint a fresh +alias ---
|
||||||
|
@staticmethod
|
||||||
|
def _random_suffix(n: int = 10) -> str:
|
||||||
|
return "".join(random.choices(string.ascii_lowercase + string.digits, k=n))
|
||||||
|
|
||||||
|
def create_mailbox(self) -> tuple[str, str]:
|
||||||
|
base = self.user.split("@")[0]
|
||||||
|
for _ in range(50):
|
||||||
|
suffix = self._random_suffix()
|
||||||
|
if suffix in self._used_suffixes:
|
||||||
|
continue
|
||||||
|
self._used_suffixes.add(suffix)
|
||||||
|
address = f"{base}+{suffix}@{self.alias_domain}"
|
||||||
|
self._last_order_id = address
|
||||||
|
return address, address
|
||||||
|
raise ImapMailError("could not mint a unique alias suffix")
|
||||||
|
|
||||||
|
# --- IMAP helpers ---
|
||||||
|
def _connect(self) -> imaplib.IMAP4_SSL:
|
||||||
|
conn = imaplib.IMAP4_SSL(self.host, self.port, timeout=30)
|
||||||
|
conn.login(self.user, self.password)
|
||||||
|
conn.select("INBOX")
|
||||||
|
return conn
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _decode_hdr(raw) -> str:
|
||||||
|
if not raw:
|
||||||
|
return ""
|
||||||
|
parts = email.header.decode_header(raw)
|
||||||
|
out = []
|
||||||
|
for txt, enc in parts:
|
||||||
|
if isinstance(txt, bytes):
|
||||||
|
try:
|
||||||
|
out.append(txt.decode(enc or "utf-8", errors="replace"))
|
||||||
|
except LookupError:
|
||||||
|
# bogus charsets in the wild (e.g. 'unknown-8bit' in old
|
||||||
|
# t-online spam) must not kill the poll loop
|
||||||
|
out.append(txt.decode("utf-8", errors="replace"))
|
||||||
|
else:
|
||||||
|
out.append(txt)
|
||||||
|
return "".join(out)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _body_of(msg) -> str:
|
||||||
|
chunks = []
|
||||||
|
if msg.is_multipart():
|
||||||
|
for part in msg.walk():
|
||||||
|
ctype = part.get_content_type()
|
||||||
|
if ctype in ("text/plain", "text/html"):
|
||||||
|
try:
|
||||||
|
payload = part.get_payload(decode=True)
|
||||||
|
if payload:
|
||||||
|
charset = part.get_content_charset() or "utf-8"
|
||||||
|
chunks.append(payload.decode(charset, errors="replace"))
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
payload = msg.get_payload(decode=True)
|
||||||
|
if payload:
|
||||||
|
charset = msg.get_content_charset() or "utf-8"
|
||||||
|
chunks.append(payload.decode(charset, errors="replace"))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return "\n".join(chunks)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def extract_github_code(body: str) -> str:
|
||||||
|
"""GitHub launch code: 8 digits (XXXX-XXXX or plain). Prefer the
|
||||||
|
context around 'launch code' / 'verification'."""
|
||||||
|
if not body:
|
||||||
|
return ""
|
||||||
|
text = re.sub(r"<[^>]+>", " ", body)
|
||||||
|
# window around keywords first
|
||||||
|
for kw in ("launch code", "verification code", "confirm"):
|
||||||
|
idx = text.lower().find(kw)
|
||||||
|
if idx >= 0:
|
||||||
|
window = text[idx:idx + 200]
|
||||||
|
m = _CODE_RE.search(window)
|
||||||
|
if m:
|
||||||
|
return re.sub(r"[-\s]", "", m.group(1))
|
||||||
|
m = _CODE_RE.search(text)
|
||||||
|
if m:
|
||||||
|
return re.sub(r"[-\s]", "", m.group(1))
|
||||||
|
return ""
|
||||||
|
|
||||||
|
def get_messages(self, address: str, limit: int = 15) -> list[dict]:
|
||||||
|
"""Fetch the newest messages whose To: matches the alias address."""
|
||||||
|
try:
|
||||||
|
conn = self._connect()
|
||||||
|
except imaplib.IMAP4.error as exc:
|
||||||
|
raise ImapMailError(f"{self.provider} IMAP login failed: {exc}") from exc
|
||||||
|
out = []
|
||||||
|
try:
|
||||||
|
status, data = conn.search(None, "ALL")
|
||||||
|
if status != "OK":
|
||||||
|
return out
|
||||||
|
ids = data[0].split()
|
||||||
|
target = address.lower()
|
||||||
|
for num in reversed(ids[-60:]):
|
||||||
|
status, mdata = conn.fetch(num, "(RFC822)")
|
||||||
|
if status != "OK" or not mdata or not mdata[0]:
|
||||||
|
continue
|
||||||
|
raw = mdata[0][1]
|
||||||
|
if not isinstance(raw, (bytes, bytearray)):
|
||||||
|
continue
|
||||||
|
msg = email.message_from_bytes(raw)
|
||||||
|
to_hdr = self._decode_hdr(msg.get("To", "")).lower()
|
||||||
|
if target not in to_hdr:
|
||||||
|
continue
|
||||||
|
subj = self._decode_hdr(msg.get("Subject", ""))
|
||||||
|
frm = self._decode_hdr(msg.get("From", ""))
|
||||||
|
out.append({
|
||||||
|
"subject": subj,
|
||||||
|
"from": frm,
|
||||||
|
"body": self._body_of(msg),
|
||||||
|
})
|
||||||
|
if len(out) >= limit:
|
||||||
|
break
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
conn.logout()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return out
|
||||||
|
|
||||||
|
def wait_for_code(
|
||||||
|
self,
|
||||||
|
address: str,
|
||||||
|
timeout: int = 330,
|
||||||
|
poll_interval: int = 8,
|
||||||
|
log: Optional[Callable[[str], None]] = None,
|
||||||
|
cancel_cb: Optional[Callable[[], bool]] = None,
|
||||||
|
email: str = "",
|
||||||
|
exclude_codes: Optional[Iterable[str]] = None,
|
||||||
|
) -> str:
|
||||||
|
started = time.time()
|
||||||
|
attempts = 0
|
||||||
|
skip = {str(c).strip() for c in (exclude_codes or ()) if str(c).strip()}
|
||||||
|
while time.time() - started < timeout:
|
||||||
|
if cancel_cb and cancel_cb():
|
||||||
|
raise MailboxCancelled("cancelled while waiting for mail")
|
||||||
|
try:
|
||||||
|
messages = self.get_messages(address)
|
||||||
|
except ImapMailError as exc:
|
||||||
|
if log:
|
||||||
|
log(f"[!] {exc}; retrying")
|
||||||
|
messages = []
|
||||||
|
attempts += 1
|
||||||
|
for msg in messages:
|
||||||
|
if log:
|
||||||
|
log(f"[*] {self.provider} message from={msg.get('from','')} "
|
||||||
|
f"subject={msg.get('subject','')[:60]}")
|
||||||
|
code = self.extract_github_code(msg.get("body", ""))
|
||||||
|
if not code or code in skip:
|
||||||
|
if code and code in skip and log:
|
||||||
|
log(f"[*] {self.provider} skipped already-used code {code}")
|
||||||
|
continue
|
||||||
|
return code
|
||||||
|
elapsed = int(time.time() - started)
|
||||||
|
if log:
|
||||||
|
log(f"[*] {self.provider} imap poll #{attempts} — no code yet "
|
||||||
|
f"({elapsed}s/{timeout}s)")
|
||||||
|
time.sleep(max(poll_interval, 5))
|
||||||
|
raise MailboxTimeoutError(
|
||||||
|
f"no GitHub code after {timeout}s ({attempts} polls)")
|
||||||
|
|
||||||
|
# --- order lifecycle: no-ops for a personal mailbox ---
|
||||||
|
def set_status(self, order_id: str, status: str) -> dict:
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
def mark_success(self, order_id: str) -> dict:
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
@property
|
||||||
|
def last_order_id(self) -> str:
|
||||||
|
return self._last_order_id
|
||||||
|
|
||||||
|
|
||||||
|
class TOnlinePoolClient(ImapMailClient):
|
||||||
|
"""Pool of individual t-online.de mailboxes (one 'email:password' per line).
|
||||||
|
|
||||||
|
Each registration consumes the NEXT unused pair — no plus-aliasing, so no
|
||||||
|
per-inbox Gmail-style delivery throttling (375 launch-code mails in one
|
||||||
|
Gmail inbox caused 40min+ delivery lag). Consumption index persists in
|
||||||
|
state_file so restarts never reuse a pair.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, pool_file: str, state_file: str, **kw):
|
||||||
|
super().__init__(provider="tonline", user="pool", password="pool", **kw)
|
||||||
|
self._pairs: list[tuple[str, str]] = []
|
||||||
|
with open(pool_file, encoding="utf-8", errors="ignore") as f:
|
||||||
|
for line in f:
|
||||||
|
line = line.strip()
|
||||||
|
if not line or line.startswith("#") or ":" not in line:
|
||||||
|
continue
|
||||||
|
u, p = line.split(":", 1)
|
||||||
|
u, p = u.strip(), p.strip()
|
||||||
|
if u and p and "@" in u:
|
||||||
|
self._pairs.append((u, p))
|
||||||
|
if not self._pairs:
|
||||||
|
raise ImapMailError(f"t-online pool empty: {pool_file}")
|
||||||
|
self._pool_file = pool_file
|
||||||
|
self._state_file = state_file
|
||||||
|
try:
|
||||||
|
self._idx = int(open(state_file, encoding="utf-8").read().strip() or "0")
|
||||||
|
except Exception:
|
||||||
|
self._idx = 0
|
||||||
|
|
||||||
|
def create_mailbox(self) -> tuple[str, str]:
|
||||||
|
if self._idx >= len(self._pairs):
|
||||||
|
raise ImapMailError("t-online pool exhausted")
|
||||||
|
user, pw = self._pairs[self._idx]
|
||||||
|
self._idx += 1
|
||||||
|
try:
|
||||||
|
with open(self._state_file, "w", encoding="utf-8") as f:
|
||||||
|
f.write(str(self._idx))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self.user = user
|
||||||
|
self.password = pw
|
||||||
|
self._last_order_id = user
|
||||||
|
return user, user
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""temp.tf mailboxes — free, no keys, gmail/outlook/hotmail/high.edu.pl pool.
|
||||||
|
|
||||||
|
Duck-typed like MailCxClient so the runner can swap providers:
|
||||||
|
create_mailbox() -> (address, order_id)
|
||||||
|
wait_for_code(address, ...) -> code
|
||||||
|
set_status / mark_success / last_order_id (no-ops)
|
||||||
|
|
||||||
|
NOTE: temp.tf addresses are SHARED (not reserved) — fine for GitHub launch
|
||||||
|
codes, not for sensitive mail. Providers list is configurable; when a
|
||||||
|
provider pool is empty the API returns {"email": null} — we rotate the
|
||||||
|
requested providers until one yields an address.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import random
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
from typing import Callable, Iterable, Optional
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from .mail_errors import MailboxCancelled, MailboxTimeoutError
|
||||||
|
|
||||||
|
BASE = "https://temp.tf"
|
||||||
|
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
|
||||||
|
DEFAULT_PROVIDERS = "gmail.com,outlook.com,hotmail.com,high.edu.pl"
|
||||||
|
|
||||||
|
_CODE_RE = re.compile(r"\b(\d{4}[-\s]?\d{4}|\d{8})\b")
|
||||||
|
|
||||||
|
|
||||||
|
class TempTfError(RuntimeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class TempTfClient:
|
||||||
|
def __init__(self, providers: str = DEFAULT_PROVIDERS,
|
||||||
|
dot: bool = True, plus: bool = True, timeout: int = 30):
|
||||||
|
self.providers = [p.strip() for p in (providers or DEFAULT_PROVIDERS).split(",") if p.strip()]
|
||||||
|
self.dot = dot
|
||||||
|
self.plus = plus
|
||||||
|
self.timeout = timeout
|
||||||
|
self._last_order_id = ""
|
||||||
|
self._session = requests.Session()
|
||||||
|
self._session.headers.update(HEADERS)
|
||||||
|
|
||||||
|
# --- mailbox creation ---
|
||||||
|
def _request_email(self, providers: list[str]) -> str:
|
||||||
|
url = (f"{BASE}/api/account?providers={','.join(providers)}"
|
||||||
|
f"&dot={1 if self.dot else 0}&plus={1 if self.plus else 0}")
|
||||||
|
r = self._session.get(url, timeout=self.timeout)
|
||||||
|
if r.status_code == 429:
|
||||||
|
wait = int(r.headers.get("Retry-After", "5") or 5)
|
||||||
|
time.sleep(min(wait, 30))
|
||||||
|
r = self._session.get(url, timeout=self.timeout)
|
||||||
|
r.raise_for_status()
|
||||||
|
data = r.json()
|
||||||
|
return (data or {}).get("email") or ""
|
||||||
|
|
||||||
|
def create_mailbox(self) -> tuple[str, str]:
|
||||||
|
# try the full provider list first, then fall back one-by-one
|
||||||
|
attempts: list[list[str]] = [self.providers] + [[p] for p in self.providers]
|
||||||
|
last_err = ""
|
||||||
|
for provs in attempts:
|
||||||
|
try:
|
||||||
|
email = self._request_email(provs)
|
||||||
|
except requests.RequestException as exc:
|
||||||
|
last_err = str(exc)
|
||||||
|
continue
|
||||||
|
if email and "@" in email:
|
||||||
|
self._last_order_id = email
|
||||||
|
return email, email
|
||||||
|
last_err = "pool empty for " + ",".join(provs)
|
||||||
|
raise TempTfError(f"temp.tf could not issue an address: {last_err}")
|
||||||
|
|
||||||
|
# --- inbox polling ---
|
||||||
|
def get_messages(self, address: str) -> list[dict]:
|
||||||
|
r = self._session.post(f"{BASE}/api/check",
|
||||||
|
json={"email": address, "wait": False},
|
||||||
|
timeout=self.timeout)
|
||||||
|
r.raise_for_status()
|
||||||
|
data = r.json() or {}
|
||||||
|
msgs = data.get("data") or []
|
||||||
|
out = []
|
||||||
|
for m in msgs:
|
||||||
|
out.append({
|
||||||
|
"subject": m.get("subject") or "",
|
||||||
|
"from": m.get("from") or "",
|
||||||
|
"body": (m.get("text") or "") + "\n" + (m.get("html") or ""),
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def extract_github_code(body: str) -> str:
|
||||||
|
if not body:
|
||||||
|
return ""
|
||||||
|
text = re.sub(r"<[^>]+>", " ", body)
|
||||||
|
for kw in ("launch code", "verification code", "confirm"):
|
||||||
|
idx = text.lower().find(kw)
|
||||||
|
if idx >= 0:
|
||||||
|
m = _CODE_RE.search(text[idx:idx + 200])
|
||||||
|
if m:
|
||||||
|
return re.sub(r"[-\s]", "", m.group(1))
|
||||||
|
m = _CODE_RE.search(text)
|
||||||
|
if m:
|
||||||
|
return re.sub(r"[-\s]", "", m.group(1))
|
||||||
|
return ""
|
||||||
|
|
||||||
|
def wait_for_code(
|
||||||
|
self,
|
||||||
|
address: str,
|
||||||
|
timeout: int = 240,
|
||||||
|
poll_interval: int = 8,
|
||||||
|
log: Optional[Callable[[str], None]] = None,
|
||||||
|
cancel_cb: Optional[Callable[[], bool]] = None,
|
||||||
|
email: str = "",
|
||||||
|
exclude_codes: Optional[Iterable[str]] = None,
|
||||||
|
) -> str:
|
||||||
|
started = time.time()
|
||||||
|
attempts = 0
|
||||||
|
skip = {str(c).strip() for c in (exclude_codes or ()) if str(c).strip()}
|
||||||
|
seen: set[str] = set()
|
||||||
|
while time.time() - started < timeout:
|
||||||
|
if cancel_cb and cancel_cb():
|
||||||
|
raise MailboxCancelled("cancelled while waiting for mail")
|
||||||
|
try:
|
||||||
|
messages = self.get_messages(address)
|
||||||
|
except requests.RequestException as exc:
|
||||||
|
if log:
|
||||||
|
log(f"[!] temp.tf check failed ({exc}); retrying")
|
||||||
|
messages = []
|
||||||
|
attempts += 1
|
||||||
|
for msg in messages:
|
||||||
|
key = msg.get("subject", "") + msg.get("from", "")
|
||||||
|
if log and key not in seen:
|
||||||
|
log(f"[*] temptf message from={msg.get('from','')} "
|
||||||
|
f"subject={msg.get('subject','')[:60]}")
|
||||||
|
seen.add(key)
|
||||||
|
code = self.extract_github_code(msg.get("body", ""))
|
||||||
|
if not code or code in skip:
|
||||||
|
continue
|
||||||
|
return code
|
||||||
|
if log:
|
||||||
|
elapsed = int(time.time() - started)
|
||||||
|
log(f"[*] temptf poll #{attempts} — no code yet ({elapsed}s/{timeout}s)")
|
||||||
|
time.sleep(max(poll_interval, 5))
|
||||||
|
raise MailboxTimeoutError(
|
||||||
|
f"no GitHub code after {timeout}s ({attempts} polls)")
|
||||||
|
|
||||||
|
# --- order lifecycle: no-ops ---
|
||||||
|
def set_status(self, order_id: str, status: str) -> dict:
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
def mark_success(self, order_id: str) -> dict:
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
@property
|
||||||
|
def last_order_id(self) -> str:
|
||||||
|
return self._last_order_id
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
"""Mail.cx temporary email API client.
|
||||||
|
|
||||||
|
Mail.cx is a free disposable email service — no inbox creation needed.
|
||||||
|
The mailbox is implicit: mail starts buffering the moment SMTP accepts it.
|
||||||
|
|
||||||
|
System domains (from GET /v1/config): uqu.me (default), ddker.com, 9k3r.com
|
||||||
|
|
||||||
|
Endpoints used:
|
||||||
|
GET /v1/config → available domains (cached)
|
||||||
|
GET /v1/inbox/<address> → long-poll emails (25s timeout, 204=nothing)
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import random
|
||||||
|
import re
|
||||||
|
import string
|
||||||
|
import time
|
||||||
|
from typing import Callable, Iterable, Optional
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from .mail_errors import MailboxCancelled, MailboxTimeoutError
|
||||||
|
|
||||||
|
API_BASE = "https://mail.cx/v1"
|
||||||
|
|
||||||
|
# Default system domains — fetched live from /v1/config on first use
|
||||||
|
_DEFAULT_DOMAINS = ["uqu.me", "ddker.com", "9k3r.com"]
|
||||||
|
|
||||||
|
# Localpart rules (from /v1/config):
|
||||||
|
# 2-20 chars, lowercase alphanumeric + . _ -
|
||||||
|
_LOCALPART_CHARS = string.ascii_lowercase + string.digits + "._-"
|
||||||
|
_LOCALPART_MIN = 4
|
||||||
|
_LOCALPART_MAX = 16
|
||||||
|
|
||||||
|
# Reserved localparts that mail.cx rejects
|
||||||
|
_RESERVED = {
|
||||||
|
"abuse", "admin", "administrator", "billing", "compliance", "contact",
|
||||||
|
"daemon", "do-not-reply", "donotreply", "finance", "ftp", "help",
|
||||||
|
"helpdesk", "hostmaster", "info", "legal", "mail", "mailer",
|
||||||
|
"mailer-daemon", "marketing", "no-reply", "nobody", "noreply",
|
||||||
|
"payment", "postmaster", "privacy", "root", "sales", "secadmin",
|
||||||
|
"security", "service", "ssl-admin", "support", "system", "webmaster",
|
||||||
|
"www",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class MailCxError(RuntimeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class MailCxClient:
|
||||||
|
"""Mail.cx temp email client — no authentication needed for free tier.
|
||||||
|
|
||||||
|
The mailbox is implicit: generate any localpart@domain and start polling.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, domain: str = ""):
|
||||||
|
self.domain = domain
|
||||||
|
self.session = requests.Session()
|
||||||
|
self._domains: list[str] = []
|
||||||
|
self._last_email: str = ""
|
||||||
|
|
||||||
|
def _get_domains(self) -> list[str]:
|
||||||
|
"""Fetch available domains from /v1/config (cached)."""
|
||||||
|
if self._domains:
|
||||||
|
return self._domains
|
||||||
|
try:
|
||||||
|
resp = self.session.get(
|
||||||
|
f"{API_BASE}/config",
|
||||||
|
headers={"Accept": "application/json"},
|
||||||
|
timeout=10,
|
||||||
|
)
|
||||||
|
data = resp.json()
|
||||||
|
domains = data.get("system_domains", [])
|
||||||
|
self._domains = [d["domain"] for d in domains if isinstance(d, dict)]
|
||||||
|
except Exception:
|
||||||
|
self._domains = list(_DEFAULT_DOMAINS)
|
||||||
|
return self._domains or _DEFAULT_DOMAINS
|
||||||
|
|
||||||
|
def _pick_domain(self) -> str:
|
||||||
|
"""Pick a domain: user-configured or random from available."""
|
||||||
|
if self.domain:
|
||||||
|
return self.domain
|
||||||
|
domains = self._get_domains()
|
||||||
|
return random.choice(domains)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _random_localpart() -> str:
|
||||||
|
"""Generate a random localpart: 4-16 chars, alphanumeric."""
|
||||||
|
length = random.randint(_LOCALPART_MIN, _LOCALPART_MAX)
|
||||||
|
chars = string.ascii_lowercase + string.digits
|
||||||
|
part = "".join(random.choices(chars, k=length))
|
||||||
|
# Avoid reserved words
|
||||||
|
if part in _RESERVED:
|
||||||
|
part = "gh" + part
|
||||||
|
return part
|
||||||
|
|
||||||
|
def create_mailbox(self) -> tuple[str, str]:
|
||||||
|
"""Create a new email address. Returns (email, order_id).
|
||||||
|
|
||||||
|
Mail.cx doesn't need explicit creation — the mailbox is implicit.
|
||||||
|
We just generate the address and start polling.
|
||||||
|
"""
|
||||||
|
localpart = self._random_localpart()
|
||||||
|
domain = self._pick_domain()
|
||||||
|
email = f"{localpart}@{domain}"
|
||||||
|
self._last_email = email
|
||||||
|
return email, email # order_id = email (no separate order concept)
|
||||||
|
|
||||||
|
def get_messages(self, address: str) -> list[dict]:
|
||||||
|
"""Long-poll for messages at the given address.
|
||||||
|
|
||||||
|
GET /v1/inbox/<encoded_address>
|
||||||
|
Returns list of message dicts or empty list.
|
||||||
|
204 = no messages within 25s window.
|
||||||
|
"""
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
encoded = quote(address, safe="")
|
||||||
|
try:
|
||||||
|
resp = self.session.get(
|
||||||
|
f"{API_BASE}/inbox/{encoded}",
|
||||||
|
headers={"Accept": "application/json"},
|
||||||
|
timeout=30, # long-poll can take up to 25s
|
||||||
|
)
|
||||||
|
if resp.status_code == 204:
|
||||||
|
return []
|
||||||
|
if resp.status_code == 429:
|
||||||
|
raise MailCxError("mail.cx rate limit (429) — too many concurrent requests")
|
||||||
|
data = resp.json()
|
||||||
|
if isinstance(data, list):
|
||||||
|
return data
|
||||||
|
# Single message or wrapped response
|
||||||
|
if isinstance(data, dict):
|
||||||
|
if "error" in data:
|
||||||
|
raise MailCxError(f"mail.cx error: {data['error']}")
|
||||||
|
if "emails" in data:
|
||||||
|
return data["emails"]
|
||||||
|
if "items" in data:
|
||||||
|
return data["items"]
|
||||||
|
return []
|
||||||
|
except requests.RequestException as exc:
|
||||||
|
raise MailCxError(f"mail.cx network error: {exc}")
|
||||||
|
|
||||||
|
def wait_for_code(
|
||||||
|
self,
|
||||||
|
address: str,
|
||||||
|
timeout: int = 240,
|
||||||
|
poll_interval: int = 5,
|
||||||
|
log: Optional[Callable[[str], None]] = None,
|
||||||
|
cancel_cb: Optional[Callable[[], bool]] = None,
|
||||||
|
email: str = "", # ignored — present for API compat with LitensiClient
|
||||||
|
exclude_codes: Optional[Iterable[str]] = None,
|
||||||
|
) -> str:
|
||||||
|
"""Poll the mailbox until the GitHub verification code arrives.
|
||||||
|
|
||||||
|
Mail.cx long-polls for 25s per request, then we retry.
|
||||||
|
Total timeout is controlled by `timeout` parameter.
|
||||||
|
|
||||||
|
``exclude_codes`` — codes already consumed (e.g. the signup launch
|
||||||
|
code). When GitHub asks for a SECOND launch code (device verification
|
||||||
|
on login), the first message still sits in the inbox; skipping those
|
||||||
|
codes lets us wait for the new one instead of returning the old one.
|
||||||
|
"""
|
||||||
|
started = time.time()
|
||||||
|
attempts = 0
|
||||||
|
skip = {str(c).strip() for c in (exclude_codes or ()) if str(c).strip()}
|
||||||
|
|
||||||
|
while time.time() - started < timeout:
|
||||||
|
if cancel_cb and cancel_cb():
|
||||||
|
raise MailboxCancelled("cancelled while waiting for mail")
|
||||||
|
|
||||||
|
messages = self.get_messages(address)
|
||||||
|
attempts += 1
|
||||||
|
|
||||||
|
for msg in messages:
|
||||||
|
# Extract body — check multiple fields
|
||||||
|
body = ""
|
||||||
|
for field in ("body", "text", "html", "content", "preview_text"):
|
||||||
|
val = msg.get(field, "")
|
||||||
|
if val:
|
||||||
|
body += "\n" + str(val)
|
||||||
|
|
||||||
|
subject = msg.get("subject", "")
|
||||||
|
from_addr = msg.get("from", msg.get("from_address", ""))
|
||||||
|
|
||||||
|
if log:
|
||||||
|
log(f"[*] mailcx message from={from_addr} subject={subject[:60]}")
|
||||||
|
|
||||||
|
code = self.extract_github_code(body)
|
||||||
|
if not code:
|
||||||
|
continue
|
||||||
|
if code in skip:
|
||||||
|
if log:
|
||||||
|
log(f"[*] mailcx skipped already-used code {code}")
|
||||||
|
continue
|
||||||
|
return code
|
||||||
|
|
||||||
|
elapsed = int(time.time() - started)
|
||||||
|
if log:
|
||||||
|
log(f"[*] mailcx poll #{attempts} — no code yet ({elapsed}s/{timeout}s)")
|
||||||
|
|
||||||
|
# Short sleep between polls to respect rate limits
|
||||||
|
time.sleep(min(poll_interval, 5))
|
||||||
|
|
||||||
|
# Per-mailbox timeout — NOT a fatal provider error (see mail_errors.py):
|
||||||
|
# fail only this account and keep the batch running.
|
||||||
|
raise MailboxTimeoutError(f"no GitHub code after {timeout}s ({attempts} polls)")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def extract_github_code(body: str) -> str:
|
||||||
|
"""Extract GitHub verification code from email body.
|
||||||
|
|
||||||
|
GitHub sends codes in format: XXXX-XXXX (8 digits with dash).
|
||||||
|
Falls back to other patterns.
|
||||||
|
"""
|
||||||
|
if not body:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
# Strip HTML tags to plain text
|
||||||
|
plain = re.sub(r"<[^>]+>", " ", body)
|
||||||
|
plain = re.sub(r"\s+", " ", plain).strip()
|
||||||
|
|
||||||
|
patterns = [
|
||||||
|
(r"(\d{4})-(\d{4})", True), # XXXX-XXXX (GitHub style) — capture 2 groups
|
||||||
|
(r"code\s*[:\s]\s*(\d{6,8})", False), # code: NNNNNN
|
||||||
|
(r">\s*(\d{6,8})\s*<", False), # inside HTML tag
|
||||||
|
(r"\b(\d{6,8})\b", False), # standalone 6-8 digit
|
||||||
|
]
|
||||||
|
|
||||||
|
for pat, two_groups in patterns:
|
||||||
|
m = re.search(pat, plain, re.IGNORECASE)
|
||||||
|
if m:
|
||||||
|
if two_groups:
|
||||||
|
return m.group(1) + m.group(2)
|
||||||
|
return m.group(1)
|
||||||
|
|
||||||
|
return ""
|
||||||
|
|
||||||
|
def mark_success(self, order_id: str) -> dict:
|
||||||
|
"""Confirm code was used. No-op for mail.cx (no order to confirm)."""
|
||||||
|
return {"status": "ok", "note": "mail.cx has no order system"}
|
||||||
|
|
||||||
|
def set_status(self, order_id: str, status: str) -> dict:
|
||||||
|
"""Set status. No-op for mail.cx."""
|
||||||
|
return self.mark_success(order_id)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def last_order_id(self) -> str:
|
||||||
|
"""Last email address used (acts as order_id)."""
|
||||||
|
return self._last_email
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
"""Profile helpers: passwords, GitHub usernames, OTP extraction."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import string
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
_LOWER = string.ascii_lowercase
|
||||||
|
_UPPER = string.ascii_uppercase
|
||||||
|
_DIGITS = string.digits
|
||||||
|
_SYMBOLS = "!@#$%^&*"
|
||||||
|
|
||||||
|
_WORDS = [
|
||||||
|
"novak", "rava", "kelby", "orin", "zephyr", "marlow", "quill", "sable",
|
||||||
|
"tenzin", "fable", "gable", "harlow", "irwin", "jasper", "keaton",
|
||||||
|
"landry", "moss", "nolan", "otter", "pascal", "quinn", "rivers", "silas",
|
||||||
|
"tobin", "ulric", "vance", "wren", "xander", "yates", "zane",
|
||||||
|
]
|
||||||
|
|
||||||
|
_USERNAME_RE = re.compile(r"^[a-z0-9](?:[a-z0-9]|-(?!-))*[a-z0-9]$")
|
||||||
|
|
||||||
|
|
||||||
|
def generate_password(length: int = 16) -> str:
|
||||||
|
"""Random password that clears GitHub's strength/blocklist checks."""
|
||||||
|
charset = _LOWER + _UPPER + _DIGITS + _SYMBOLS
|
||||||
|
while True:
|
||||||
|
pw = "".join(secrets.choice(charset) for _ in range(length))
|
||||||
|
if (
|
||||||
|
any(c in _LOWER for c in pw)
|
||||||
|
and any(c in _UPPER for c in pw)
|
||||||
|
and any(c in _DIGITS for c in pw)
|
||||||
|
):
|
||||||
|
return pw
|
||||||
|
|
||||||
|
|
||||||
|
def generate_username() -> str:
|
||||||
|
"""GitHub-safe username: [a-z0-9-], no consecutive hyphens, <= 39 chars."""
|
||||||
|
suffix = "".join(secrets.choice(_LOWER + _DIGITS) for _ in range(6))
|
||||||
|
return f"{secrets.choice(_WORDS)}{suffix}"
|
||||||
|
|
||||||
|
|
||||||
|
def username_from_email(email: str, suffix: str = "") -> str:
|
||||||
|
"""Derive a GitHub username from the mailbox local-part.
|
||||||
|
|
||||||
|
myname123@mail.example.com -> 'myname123'
|
||||||
|
Falls back to a random username when the local-part is unusable.
|
||||||
|
A short random suffix can be appended when the name is taken.
|
||||||
|
|
||||||
|
Short local-parts (mail.cx issues 4-char ones like 'kt78') collide
|
||||||
|
constantly on GitHub — always pad them with random alnum chars so the
|
||||||
|
base name is unique before the first attempt.
|
||||||
|
"""
|
||||||
|
local = (email or "").split("@", 1)[0].strip().lower()
|
||||||
|
local = re.sub(r"[^a-z0-9-]", "", local)
|
||||||
|
local = local.strip("-").replace("--", "-")
|
||||||
|
if not is_valid_username(local):
|
||||||
|
return generate_username()
|
||||||
|
if len(local) < 10:
|
||||||
|
local += "".join(secrets.choice(_LOWER + _DIGITS) for _ in range(10 - len(local)))
|
||||||
|
name = (local + suffix)[:39]
|
||||||
|
return name if is_valid_username(name) else generate_username()
|
||||||
|
|
||||||
|
|
||||||
|
def is_valid_username(name: str) -> bool:
|
||||||
|
return 1 <= len(name) <= 39 and bool(_USERNAME_RE.match(name))
|
||||||
|
|
||||||
|
|
||||||
|
def extract_github_code(text: str) -> str | None:
|
||||||
|
"""8-digit GitHub code; the email body may separate the halves with a space."""
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
m = re.search(r"\b(\d{4})\s*(\d{4})\b", text)
|
||||||
|
if m:
|
||||||
|
return m.group(1) + m.group(2)
|
||||||
|
for pat in (
|
||||||
|
r"verification\s+code[:\s]+(\d{4,8})",
|
||||||
|
r"your\s+code[:\s]+(\d{4,8})",
|
||||||
|
r"enter\s+this\s+code[:\s]+(\d{4,8})",
|
||||||
|
):
|
||||||
|
m = re.search(pat, text, re.IGNORECASE)
|
||||||
|
if m:
|
||||||
|
return m.group(1)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_public_profile(random_user: Any, quote: Any) -> dict[str, str]:
|
||||||
|
"""Extract public display fields from Random User and ZenQuotes payloads.
|
||||||
|
|
||||||
|
Contact details and generated credentials in the Random User response are
|
||||||
|
intentionally ignored.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
user = random_user["results"][0]
|
||||||
|
person = user["name"]
|
||||||
|
full_name = " ".join(
|
||||||
|
part.strip()
|
||||||
|
for part in (person.get("title", ""), person["first"], person["last"])
|
||||||
|
if part.strip()
|
||||||
|
)
|
||||||
|
location = str(user["location"]["country"]).strip()
|
||||||
|
bio = str(quote[0]["q"]).strip()
|
||||||
|
except (IndexError, KeyError, TypeError, AttributeError) as exc:
|
||||||
|
raise ValueError(f"invalid public profile payload: {exc}") from exc
|
||||||
|
if not full_name or not location or not bio:
|
||||||
|
raise ValueError("public profile payload has an empty required field")
|
||||||
|
return {"name": full_name, "location": location, "bio": bio}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,49 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""CLI entry: automated GitHub sign-up with Camoufox + Litensi mail."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import shutil
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from github_register.config import load_config
|
||||||
|
from github_register.runner import run_job, silence_playwright_noise
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
silence_playwright_noise() # hide TargetClosedError spam on browser exit
|
||||||
|
ap = argparse.ArgumentParser(
|
||||||
|
prog="github-regkit",
|
||||||
|
description="Auto-register GitHub accounts (Camoufox + Litensi mail).",
|
||||||
|
)
|
||||||
|
ap.add_argument("--config", default="config.json", help="path to config json")
|
||||||
|
ap.add_argument("--count", type=int, default=None, help="override register_count")
|
||||||
|
ap.add_argument("--headless", action="store_true", help="run browsers hidden")
|
||||||
|
ap.add_argument("--proxy", default="", help="override proxy, e.g. http://user:pass@host:port")
|
||||||
|
args = ap.parse_args()
|
||||||
|
|
||||||
|
cfg_path = Path(args.config)
|
||||||
|
if not cfg_path.is_file() and Path("config.example.json").is_file():
|
||||||
|
shutil.copy("config.example.json", cfg_path)
|
||||||
|
print(f"[!] created {cfg_path} from config.example.json — enter your Litensi credentials")
|
||||||
|
|
||||||
|
cfg = load_config(cfg_path)
|
||||||
|
if args.count is not None:
|
||||||
|
cfg.register_count = max(1, args.count)
|
||||||
|
if args.headless:
|
||||||
|
cfg.headless = True
|
||||||
|
if args.proxy:
|
||||||
|
cfg.proxy = args.proxy
|
||||||
|
|
||||||
|
try:
|
||||||
|
ok, fail, out = run_job(cfg)
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("[!] interrupted")
|
||||||
|
return 130
|
||||||
|
print(f"[*] output: {out}")
|
||||||
|
return 0 if fail == 0 else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,675 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Local rotating HTTP/HTTPS proxy.
|
||||||
|
|
||||||
|
Reads proxies from proxies.txt (one per line: scheme://user:pass@host:port),
|
||||||
|
listens on a local port, and forwards each connection through a rotating proxy.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python proxy_rotator.py # default port 8099
|
||||||
|
python proxy_rotator.py --port 9090 # custom port
|
||||||
|
python proxy_rotator.py --proxies my.txt # custom proxy list
|
||||||
|
python proxy_rotator.py --ban-threshold 3 # ban after N failures (default 5)
|
||||||
|
|
||||||
|
The proxies are rotated in round-robin order. Proxies that fail are temporarily
|
||||||
|
banned (exponential backoff, max 5 min). When all proxies are banned, the
|
||||||
|
rotator waits until the oldest ban expires.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import socket
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from collections import deque
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s [%(levelname)s] %(message)s",
|
||||||
|
datefmt="%H:%M:%S",
|
||||||
|
)
|
||||||
|
log = logging.getLogger("proxy-rotator")
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Proxy pool
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ProxyEntry:
|
||||||
|
raw: str
|
||||||
|
host: str
|
||||||
|
port: int
|
||||||
|
scheme: str
|
||||||
|
username: str = ""
|
||||||
|
password: str = ""
|
||||||
|
fail_count: int = 0
|
||||||
|
ban_until: float = 0.0 # timestamp
|
||||||
|
total_requests: int = 0
|
||||||
|
total_failures: int = 0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_banned(self) -> bool:
|
||||||
|
return time.time() < self.ban_until
|
||||||
|
|
||||||
|
@property
|
||||||
|
def display(self) -> str:
|
||||||
|
return f"{self.scheme}://{self.host}:{self.port}"
|
||||||
|
|
||||||
|
def record_failure(self, ban_threshold: int) -> None:
|
||||||
|
self.fail_count += 1
|
||||||
|
self.total_failures += 1
|
||||||
|
if self.fail_count >= ban_threshold:
|
||||||
|
# exponential backoff: 30s, 60s, 120s, 300s (max 5 min)
|
||||||
|
delay = min(30 * (2 ** (self.fail_count - ban_threshold)), 300)
|
||||||
|
self.ban_until = time.time() + delay
|
||||||
|
log.warning(f"BANNED {self.display} for {int(delay)}s (fail#{self.fail_count})")
|
||||||
|
|
||||||
|
def record_success(self) -> None:
|
||||||
|
self.fail_count = 0
|
||||||
|
self.ban_until = 0.0
|
||||||
|
self.total_requests += 1
|
||||||
|
|
||||||
|
def short_info(self) -> str:
|
||||||
|
status = f"BANNED {int(self.ban_until - time.time())}s" if self.is_banned else "OK"
|
||||||
|
return f"{self.display} [{status}] req={self.total_requests} fail={self.total_failures}"
|
||||||
|
|
||||||
|
|
||||||
|
class ProxyPool:
|
||||||
|
def __init__(self, proxies_file: str | Path, ban_threshold: int = 5):
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._entries: list[ProxyEntry] = []
|
||||||
|
self._index = 0
|
||||||
|
self._ban_threshold = ban_threshold
|
||||||
|
self._proxies_file = Path(proxies_file)
|
||||||
|
self._last_used: Optional[ProxyEntry] = None
|
||||||
|
self._load(proxies_file)
|
||||||
|
|
||||||
|
def _load(self, path: str | Path) -> None:
|
||||||
|
p = Path(path)
|
||||||
|
if not p.is_file():
|
||||||
|
log.error(f"proxy file not found: {p}")
|
||||||
|
return
|
||||||
|
for line in p.read_text(encoding="utf-8").splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if not line or line.startswith("#"):
|
||||||
|
continue
|
||||||
|
entry = self._parse(line)
|
||||||
|
if entry:
|
||||||
|
self._entries.append(entry)
|
||||||
|
log.info(f"loaded {len(self._entries)} proxies from {p.name}")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _parse(raw: str) -> Optional[ProxyEntry]:
|
||||||
|
try:
|
||||||
|
p = urlsplit(raw)
|
||||||
|
if not p.hostname:
|
||||||
|
return None
|
||||||
|
scheme = (p.scheme or "http").lower()
|
||||||
|
if scheme in ("socks", "socks5h"):
|
||||||
|
scheme = "socks5"
|
||||||
|
return ProxyEntry(
|
||||||
|
raw=raw,
|
||||||
|
host=p.hostname,
|
||||||
|
port=p.port or (1080 if scheme.startswith("socks") else 80),
|
||||||
|
scheme=scheme,
|
||||||
|
username=p.username or "",
|
||||||
|
password=p.password or "",
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def next(self) -> Optional[ProxyEntry]:
|
||||||
|
"""Get the next non-banned proxy (round-robin)."""
|
||||||
|
with self._lock:
|
||||||
|
if not self._entries:
|
||||||
|
return None
|
||||||
|
n = len(self._entries)
|
||||||
|
for _ in range(n):
|
||||||
|
entry = self._entries[self._index % n]
|
||||||
|
self._index += 1
|
||||||
|
if not entry.is_banned:
|
||||||
|
self._last_used = entry
|
||||||
|
return entry
|
||||||
|
# all banned — return the one whose ban expires soonest
|
||||||
|
earliest = min(self._entries, key=lambda e: e.ban_until)
|
||||||
|
wait = earliest.ban_until - time.time()
|
||||||
|
if wait > 0:
|
||||||
|
log.info(f"all proxies banned, waiting {int(wait)}s for {earliest.display}")
|
||||||
|
time.sleep(min(wait + 0.5, 60))
|
||||||
|
self._last_used = earliest
|
||||||
|
return earliest
|
||||||
|
|
||||||
|
def get_raw(self) -> str:
|
||||||
|
"""Get the raw URL of the next proxy (for upstream CONNECT)."""
|
||||||
|
entry = self.next()
|
||||||
|
return entry.raw if entry else ""
|
||||||
|
|
||||||
|
def status(self) -> list[dict]:
|
||||||
|
with self._lock:
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"host": e.host,
|
||||||
|
"port": e.port,
|
||||||
|
"scheme": e.scheme,
|
||||||
|
"banned": e.is_banned,
|
||||||
|
"ban_remaining": max(0, int(e.ban_until - time.time())),
|
||||||
|
"requests": e.total_requests,
|
||||||
|
"failures": e.total_failures,
|
||||||
|
}
|
||||||
|
for e in self._entries
|
||||||
|
]
|
||||||
|
|
||||||
|
def count(self) -> int:
|
||||||
|
return len(self._entries)
|
||||||
|
|
||||||
|
def active_count(self) -> int:
|
||||||
|
with self._lock:
|
||||||
|
return sum(1 for e in self._entries if not e.is_banned)
|
||||||
|
|
||||||
|
def on_success(self, entry: ProxyEntry) -> None:
|
||||||
|
with self._lock:
|
||||||
|
entry.record_success()
|
||||||
|
|
||||||
|
def on_failure(self, entry: ProxyEntry) -> None:
|
||||||
|
with self._lock:
|
||||||
|
entry.record_failure(self._ban_threshold)
|
||||||
|
|
||||||
|
def disable_last_used(self) -> dict:
|
||||||
|
"""Permanently disable the last-used proxy: comment it out in the file and
|
||||||
|
remove from the active pool. Returns a status dict."""
|
||||||
|
with self._lock:
|
||||||
|
entry = self._last_used
|
||||||
|
if not entry:
|
||||||
|
return {"ok": False, "error": "no proxy has been used yet"}
|
||||||
|
raw = entry.raw
|
||||||
|
host_port = f"{entry.host}:{entry.port}"
|
||||||
|
# remove from pool
|
||||||
|
idx = next((i for i, e in enumerate(self._entries) if e is entry), None)
|
||||||
|
if idx is not None:
|
||||||
|
self._entries.pop(idx)
|
||||||
|
if self._index >= len(self._entries):
|
||||||
|
self._index = 0
|
||||||
|
self._last_used = None
|
||||||
|
|
||||||
|
# comment out in file
|
||||||
|
try:
|
||||||
|
lines = self._proxies_file.read_text(encoding="utf-8").splitlines(keepends=True)
|
||||||
|
commented = 0
|
||||||
|
for i, line in enumerate(lines):
|
||||||
|
stripped = line.strip()
|
||||||
|
if stripped == raw or stripped.rstrip("\r\n") == raw:
|
||||||
|
if not stripped.startswith("#"):
|
||||||
|
lines[i] = f"# {stripped}\n"
|
||||||
|
commented += 1
|
||||||
|
if commented:
|
||||||
|
self._proxies_file.write_text("".join(lines), encoding="utf-8")
|
||||||
|
log.warning(f"PERMANENTLY DISABLED: {host_port} (commented in proxies.txt)")
|
||||||
|
except Exception as exc:
|
||||||
|
log.error(f"failed to comment out proxy in file: {exc}")
|
||||||
|
|
||||||
|
return {"ok": True, "disabled": host_port, "remaining": len(self._entries)}
|
||||||
|
|
||||||
|
def disable_by_host_port(self, host: str, port: int) -> dict:
|
||||||
|
"""Disable a specific proxy by host:port. If no entry matches, try
|
||||||
|
commenting all lines that resolve to that host:port."""
|
||||||
|
entry = None
|
||||||
|
with self._lock:
|
||||||
|
entry = next((e for e in self._entries if e.host == host and e.port == port), None)
|
||||||
|
if entry:
|
||||||
|
with self._lock:
|
||||||
|
idx = next((i for i, e in enumerate(self._entries) if e is entry), None)
|
||||||
|
if idx is not None:
|
||||||
|
self._entries.pop(idx)
|
||||||
|
if self._index >= len(self._entries):
|
||||||
|
self._index = 0
|
||||||
|
raw = entry.raw
|
||||||
|
else:
|
||||||
|
raw = f"://{host}:{port}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
lines = self._proxies_file.read_text(encoding="utf-8").splitlines(keepends=True)
|
||||||
|
matches = [
|
||||||
|
(i, line.strip())
|
||||||
|
for i, line in enumerate(lines)
|
||||||
|
if line.strip() and not line.strip().startswith("#")
|
||||||
|
and host in line and f":{port}" in line
|
||||||
|
]
|
||||||
|
# AMBIGUITY GUARD: authed residential pools share host:port across
|
||||||
|
# many session-usernames — host:port matching would wipe the whole
|
||||||
|
# pool. Only proceed when the match is unique or auth-free.
|
||||||
|
if len(matches) > 1 and any("@" in m[1] for m in matches):
|
||||||
|
log.warning(
|
||||||
|
f"disable_by_host_port skipped: {host}:{port} matches "
|
||||||
|
f"{len(matches)} authed lines (ambiguous — send exact url)"
|
||||||
|
)
|
||||||
|
return {"ok": False, "error": "ambiguous: host:port matches multiple authed lines; send 'url'", "matches": len(matches)}
|
||||||
|
commented = 0
|
||||||
|
for i, stripped in matches:
|
||||||
|
lines[i] = f"# {stripped}\n"
|
||||||
|
commented += 1
|
||||||
|
if commented:
|
||||||
|
self._proxies_file.write_text("".join(lines), encoding="utf-8")
|
||||||
|
log.warning(f"PERMANENTLY DISABLED: {host}:{port} ({commented} lines commented)")
|
||||||
|
except Exception as exc:
|
||||||
|
log.error(f"failed to comment out proxy: {exc}")
|
||||||
|
|
||||||
|
return {"ok": True, "disabled": f"{host}:{port}", "commented_lines": commented, "remaining": len(self._entries)}
|
||||||
|
|
||||||
|
def disable_by_url(self, url: str) -> dict:
|
||||||
|
"""Disable one exact proxy URL (comment its line). Residential pools
|
||||||
|
share host:port across sessions — only the full URL (with per-session
|
||||||
|
username) identifies a single line."""
|
||||||
|
url = url.strip()
|
||||||
|
variants = {url}
|
||||||
|
if "://" in url:
|
||||||
|
variants.add(url.split("://", 1)[1])
|
||||||
|
variants.add("http://" + url.split("://", 1)[1])
|
||||||
|
else:
|
||||||
|
variants.add("http://" + url)
|
||||||
|
try:
|
||||||
|
# scan main pool file first, then sibling pool files (proxies_b.txt etc.)
|
||||||
|
# so one rotator instance can serve disables for ALL local pools —
|
||||||
|
# batch B uses a different proxy_file but the same :8100 endpoint.
|
||||||
|
files = [self._proxies_file]
|
||||||
|
try:
|
||||||
|
for sib in sorted(Path(ROOT).glob("proxies*.txt")):
|
||||||
|
if sib.resolve() != self._proxies_file.resolve() and "backup" not in sib.name and "free" not in sib.name and "pre_" not in sib.name:
|
||||||
|
files.append(sib)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
commented = 0
|
||||||
|
hit_file = None
|
||||||
|
for fpath in files:
|
||||||
|
try:
|
||||||
|
lines = fpath.read_text(encoding="utf-8").splitlines(keepends=True)
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
n_here = 0
|
||||||
|
for i, line in enumerate(lines):
|
||||||
|
stripped = line.strip()
|
||||||
|
if stripped.startswith("#") or not stripped:
|
||||||
|
continue
|
||||||
|
if stripped in variants:
|
||||||
|
lines[i] = f"# {stripped}\n"
|
||||||
|
n_here += 1
|
||||||
|
if n_here:
|
||||||
|
fpath.write_text("".join(lines), encoding="utf-8")
|
||||||
|
commented += n_here
|
||||||
|
hit_file = fpath.name
|
||||||
|
if commented:
|
||||||
|
# FIX: also drop from the in-memory pool — previously the file
|
||||||
|
# line was commented but _entries kept serving the dead proxy
|
||||||
|
# for the whole process lifetime (runner saw "None remaining").
|
||||||
|
try:
|
||||||
|
with self._lock:
|
||||||
|
self._entries = [
|
||||||
|
e for e in self._entries
|
||||||
|
if e.raw.strip() not in variants
|
||||||
|
and e.display not in variants
|
||||||
|
and f"{e.host}:{e.port}" not in variants
|
||||||
|
]
|
||||||
|
if self._index >= len(self._entries):
|
||||||
|
self._index = 0
|
||||||
|
except Exception as mem_exc:
|
||||||
|
log.error(f"memory pool removal failed: {mem_exc}")
|
||||||
|
safe = re.sub(r"://[^@/]+@", "://***@", url)
|
||||||
|
log.warning(f"PERMANENTLY DISABLED (exact URL): {safe} ({commented} line in {hit_file})")
|
||||||
|
return {"ok": True, "disabled": safe, "commented_lines": commented, "file": hit_file, "remaining": len(self._entries)}
|
||||||
|
safe = re.sub(r"://[^@/]+@", "://***@", url)
|
||||||
|
return {"ok": False, "error": f"url not found in pool: {safe}"}
|
||||||
|
except Exception as exc:
|
||||||
|
log.error(f"failed to disable by url: {exc}")
|
||||||
|
return {"ok": False, "error": str(exc)}
|
||||||
|
|
||||||
|
@property
|
||||||
|
def last_used_info(self) -> Optional[dict]:
|
||||||
|
"""Info about the last-used proxy."""
|
||||||
|
with self._lock:
|
||||||
|
e = self._last_used
|
||||||
|
if not e:
|
||||||
|
return None
|
||||||
|
return {"host": e.host, "port": e.port, "raw": e.raw}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Local proxy handler
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
_pool: Optional[ProxyPool] = None
|
||||||
|
|
||||||
|
class ProxyHandler:
|
||||||
|
"""Handle one local client connection by relaying through an upstream proxy."""
|
||||||
|
|
||||||
|
def __init__(self, client: socket.socket, addr: tuple, pool: ProxyPool):
|
||||||
|
self.client = client
|
||||||
|
self.addr = addr
|
||||||
|
self.pool = pool
|
||||||
|
self._entry: Optional[ProxyEntry] = None
|
||||||
|
|
||||||
|
def run(self) -> None:
|
||||||
|
try:
|
||||||
|
self.client.settimeout(30)
|
||||||
|
first = self.client.recv(65536)
|
||||||
|
if not first:
|
||||||
|
return
|
||||||
|
|
||||||
|
# Pick a proxy
|
||||||
|
self._entry = self.pool.next()
|
||||||
|
if not self._entry:
|
||||||
|
self.client.sendall(b"HTTP/1.1 503 No proxies available\r\n\r\n")
|
||||||
|
return
|
||||||
|
|
||||||
|
if first[:7] == b"CONNECT":
|
||||||
|
self._handle_connect(first)
|
||||||
|
else:
|
||||||
|
self._handle_http(first)
|
||||||
|
except (ConnectionResetError, BrokenPipeError, OSError):
|
||||||
|
pass
|
||||||
|
except Exception as exc:
|
||||||
|
log.debug(f"handler error: {exc}")
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
self.client.close()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _connect_upstream(self) -> socket.socket:
|
||||||
|
"""Connect to the selected upstream proxy."""
|
||||||
|
entry = self._entry
|
||||||
|
s = socket.create_connection((entry.host, entry.port), timeout=15)
|
||||||
|
|
||||||
|
if entry.scheme.startswith("socks"):
|
||||||
|
self._socks5_handshake(s, entry)
|
||||||
|
elif entry.username:
|
||||||
|
# HTTP proxy with auth — inject Proxy-Authorization
|
||||||
|
pass # handled per-request below
|
||||||
|
return s
|
||||||
|
|
||||||
|
def _socks5_handshake(self, s: socket.socket, entry: ProxyEntry) -> None:
|
||||||
|
"""SOCKS5 greeting + optional user/pass auth."""
|
||||||
|
if entry.username:
|
||||||
|
s.sendall(b"\x05\x01\x02") # support user/pass auth
|
||||||
|
else:
|
||||||
|
s.sendall(b"\x05\x01\x00") # no auth
|
||||||
|
resp = s.recv(2)
|
||||||
|
if len(resp) < 2 or resp[0] != 5:
|
||||||
|
raise OSError(f"socks5: bad greeting {resp!r}")
|
||||||
|
|
||||||
|
if resp[1] == 0x02 and entry.username:
|
||||||
|
user = entry.username.encode()
|
||||||
|
pwd = entry.password.encode()
|
||||||
|
s.sendall(bytes([1, len(user)]) + user + bytes([len(pwd)]) + pwd)
|
||||||
|
resp = s.recv(2)
|
||||||
|
if len(resp) < 2 or resp[1] != 0:
|
||||||
|
raise OSError("socks5: auth rejected")
|
||||||
|
elif resp[1] != 0x00:
|
||||||
|
raise OSError(f"socks5: no acceptable method (got {resp[1]})")
|
||||||
|
|
||||||
|
def _socks5_connect(self, s: socket.socket, host: str, port: int) -> None:
|
||||||
|
"""SOCKS5 CONNECT with hostname (remote DNS)."""
|
||||||
|
h = host.encode()
|
||||||
|
s.sendall(b"\x05\x01\x00\x03" + bytes([len(h)]) + h + port.to_bytes(2, "big"))
|
||||||
|
resp = s.recv(10)
|
||||||
|
if len(resp) < 2 or resp[1] != 0:
|
||||||
|
raise OSError(f"socks5: connect failed code={resp[1] if len(resp) > 1 else '?'}")
|
||||||
|
|
||||||
|
def _inject_auth(self, data: bytes) -> bytes:
|
||||||
|
"""Add Proxy-Authorization header for HTTP upstream proxies."""
|
||||||
|
entry = self._entry
|
||||||
|
if not entry or not entry.username:
|
||||||
|
return data
|
||||||
|
token = base64.b64encode(f"{entry.username}:{entry.password}".encode()).decode()
|
||||||
|
head, sep, rest = data.partition(b"\r\n\r\n")
|
||||||
|
if not sep:
|
||||||
|
return data
|
||||||
|
lines = head.split(b"\r\n")
|
||||||
|
out = [lines[0]]
|
||||||
|
for ln in lines[1:]:
|
||||||
|
if ln.lower().startswith(b"proxy-authorization:"):
|
||||||
|
continue
|
||||||
|
out.append(ln)
|
||||||
|
out.append(f"Proxy-Authorization: Basic {token}".encode())
|
||||||
|
return b"\r\n".join(out) + b"\r\n\r\n" + rest
|
||||||
|
|
||||||
|
def _relay(self, src: socket.socket, dst: socket.socket, timeout: float = 180) -> None:
|
||||||
|
"""Bidirectional relay."""
|
||||||
|
src.settimeout(timeout)
|
||||||
|
dst.settimeout(timeout)
|
||||||
|
|
||||||
|
def pump(a: socket.socket, b: socket.socket):
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
data = a.recv(65536)
|
||||||
|
if not data:
|
||||||
|
break
|
||||||
|
b.sendall(data)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
for sock in (a, b):
|
||||||
|
try:
|
||||||
|
sock.shutdown(socket.SHUT_RDWR)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
t1 = threading.Thread(target=pump, args=(src, dst), daemon=True)
|
||||||
|
t2 = threading.Thread(target=pump, args=(dst, src), daemon=True)
|
||||||
|
t1.start()
|
||||||
|
t2.start()
|
||||||
|
t1.join()
|
||||||
|
t2.join()
|
||||||
|
|
||||||
|
def _handle_connect(self, first: bytes) -> None:
|
||||||
|
"""Handle HTTPS CONNECT tunnel."""
|
||||||
|
line = first.split(b"\r\n", 1)[0]
|
||||||
|
hostport = line.split()[1].decode()
|
||||||
|
host, _, port_s = hostport.rpartition(":")
|
||||||
|
port = int(port_s or "443")
|
||||||
|
|
||||||
|
entry = self._entry
|
||||||
|
try:
|
||||||
|
upstream = self._connect_upstream()
|
||||||
|
|
||||||
|
if entry.scheme.startswith("socks"):
|
||||||
|
self._socks5_connect(upstream, host, port)
|
||||||
|
self.client.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
|
||||||
|
else:
|
||||||
|
# HTTP upstream: forward CONNECT with auth
|
||||||
|
authed = self._inject_auth(first)
|
||||||
|
upstream.sendall(authed)
|
||||||
|
# Read upstream's reply
|
||||||
|
reply = b""
|
||||||
|
while b"\r\n\r\n" not in reply and len(reply) < 8192:
|
||||||
|
chunk = upstream.recv(4096)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
reply += chunk
|
||||||
|
if not reply:
|
||||||
|
reply = b"HTTP/1.1 502 Bad Gateway\r\n\r\n"
|
||||||
|
self.client.sendall(reply)
|
||||||
|
|
||||||
|
self.pool.on_success(entry)
|
||||||
|
self._relay(self.client, upstream)
|
||||||
|
except Exception as exc:
|
||||||
|
self.pool.on_failure(entry)
|
||||||
|
log.debug(f"CONNECT failed via {entry.display}: {exc}")
|
||||||
|
try:
|
||||||
|
self.client.sendall(b"HTTP/1.1 502 Bad Gateway\r\n\r\n")
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _handle_http(self, first: bytes) -> None:
|
||||||
|
"""Handle plain HTTP request."""
|
||||||
|
entry = self._entry
|
||||||
|
try:
|
||||||
|
upstream = self._connect_upstream()
|
||||||
|
upstream.sendall(self._inject_auth(first))
|
||||||
|
self.pool.on_success(entry)
|
||||||
|
self._relay(self.client, upstream)
|
||||||
|
except Exception as exc:
|
||||||
|
self.pool.on_failure(entry)
|
||||||
|
log.debug(f"HTTP failed via {entry.display}: {exc}")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Status server (optional: localhost JSON endpoint)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _status_server(port: int, pool: ProxyPool) -> None:
|
||||||
|
"""Tiny HTTP server that returns pool status as JSON."""
|
||||||
|
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||||
|
srv.bind(("127.0.0.1", port))
|
||||||
|
srv.listen(20)
|
||||||
|
srv.settimeout(1.0)
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
client, _ = srv.accept()
|
||||||
|
client.settimeout(5)
|
||||||
|
data = client.recv(4096)
|
||||||
|
# read the FULL body: urllib may split headers/body across TCP
|
||||||
|
# segments — a single recv() can truncate the JSON payload, which
|
||||||
|
# made /disable fall through to 'no proxy has been used yet'.
|
||||||
|
try:
|
||||||
|
hdr_end = data.find(b"\r\n\r\n")
|
||||||
|
if hdr_end >= 0:
|
||||||
|
m = re.search(rb"[Cc]ontent-[Ll]ength:\s*(\d+)", data[:hdr_end])
|
||||||
|
if m:
|
||||||
|
need = int(m.group(1))
|
||||||
|
have = len(data) - (hdr_end + 4)
|
||||||
|
client.settimeout(2)
|
||||||
|
while have < need:
|
||||||
|
chunk = client.recv(min(4096, need - have))
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
data += chunk
|
||||||
|
have += len(chunk)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if b"GET /status" in data:
|
||||||
|
body = json.dumps({
|
||||||
|
"total": pool.count(),
|
||||||
|
"active": pool.active_count(),
|
||||||
|
"last_used": pool.last_used_info,
|
||||||
|
"proxies": pool.status(),
|
||||||
|
}).encode()
|
||||||
|
resp = (
|
||||||
|
f"HTTP/1.1 200 OK\r\n"
|
||||||
|
f"Content-Type: application/json\r\n"
|
||||||
|
f"Content-Length: {len(body)}\r\n"
|
||||||
|
f"Connection: close\r\n\r\n"
|
||||||
|
).encode() + body
|
||||||
|
elif b"POST /disable" in data:
|
||||||
|
# Parse JSON body
|
||||||
|
try:
|
||||||
|
body_start = data.find(b"\r\n\r\n")
|
||||||
|
body_bytes = data[body_start + 4:] if body_start >= 0 else b""
|
||||||
|
req = json.loads(body_bytes) if body_bytes else {}
|
||||||
|
except Exception:
|
||||||
|
req = {}
|
||||||
|
# disable by exact URL (residential pools share host:port!),
|
||||||
|
# else host:port, else last used
|
||||||
|
if req.get("url"):
|
||||||
|
result = pool.disable_by_url(req["url"])
|
||||||
|
elif "host" in req and "port" in req:
|
||||||
|
result = pool.disable_by_host_port(req["host"], int(req["port"]))
|
||||||
|
else:
|
||||||
|
result = pool.disable_last_used()
|
||||||
|
body = json.dumps(result).encode()
|
||||||
|
resp = (
|
||||||
|
f"HTTP/1.1 200 OK\r\n"
|
||||||
|
f"Content-Type: application/json\r\n"
|
||||||
|
f"Content-Length: {len(body)}\r\n"
|
||||||
|
f"Connection: close\r\n\r\n"
|
||||||
|
).encode() + body
|
||||||
|
elif b"GET /health" in data:
|
||||||
|
body = b'{"ok":true,"service":"proxy-rotator"}'
|
||||||
|
resp = (
|
||||||
|
f"HTTP/1.1 200 OK\r\n"
|
||||||
|
f"Content-Type: application/json\r\n"
|
||||||
|
f"Content-Length: {len(body)}\r\n"
|
||||||
|
f"Connection: close\r\n\r\n"
|
||||||
|
).encode() + body
|
||||||
|
else:
|
||||||
|
resp = b"HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n"
|
||||||
|
client.sendall(resp)
|
||||||
|
client.close()
|
||||||
|
except socket.timeout:
|
||||||
|
continue
|
||||||
|
except OSError:
|
||||||
|
break
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Main
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
global _pool
|
||||||
|
|
||||||
|
ap = argparse.ArgumentParser(description="Local rotating proxy server")
|
||||||
|
ap.add_argument("--port", type=int, default=8099, help="local listen port (default 8099)")
|
||||||
|
ap.add_argument("--status-port", type=int, default=8100, help="status HTTP port (default 8100)")
|
||||||
|
ap.add_argument("--proxies", default=str(ROOT / "proxies.txt"), help="proxy list file")
|
||||||
|
ap.add_argument("--ban-threshold", type=int, default=5, help="failures before ban (default 5)")
|
||||||
|
ap.add_argument("--verbose", action="store_true", help="debug logging")
|
||||||
|
args = ap.parse_args()
|
||||||
|
|
||||||
|
if args.verbose:
|
||||||
|
logging.getLogger().setLevel(logging.DEBUG)
|
||||||
|
|
||||||
|
_pool = ProxyPool(args.proxies, ban_threshold=args.ban_threshold)
|
||||||
|
if _pool.count() == 0:
|
||||||
|
log.error("no proxies loaded — check your proxy file")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
# Start status server in background
|
||||||
|
status_thread = threading.Thread(target=_status_server, args=(args.status_port, _pool), daemon=True)
|
||||||
|
status_thread.start()
|
||||||
|
log.info(f"status server: http://127.0.0.1:{args.status_port}/status")
|
||||||
|
|
||||||
|
# Main proxy server
|
||||||
|
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||||
|
try:
|
||||||
|
srv.bind(("127.0.0.1", args.port))
|
||||||
|
except OSError as exc:
|
||||||
|
log.error(f"cannot bind port {args.port}: {exc}")
|
||||||
|
return 1
|
||||||
|
srv.listen(100)
|
||||||
|
log.info(f"rotating proxy listening on http://127.0.0.1:{args.port}")
|
||||||
|
log.info(f"pool: {_pool.count()} proxies, ban threshold={args.ban_threshold}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
client, addr = srv.accept()
|
||||||
|
handler = ProxyHandler(client, addr, _pool)
|
||||||
|
threading.Thread(target=handler.run, daemon=True).start()
|
||||||
|
except socket.timeout:
|
||||||
|
continue
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
log.info("shutting down")
|
||||||
|
finally:
|
||||||
|
srv.close()
|
||||||
|
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,357 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Camoufox session recorder.
|
||||||
|
|
||||||
|
Records manual steps (clicks, fills, navigation) performed in a REAL Camoufox
|
||||||
|
browser — same launch options as production (persistent profile with DataDome
|
||||||
|
trust, geoip, os fingerprint, humanize). Output:
|
||||||
|
|
||||||
|
recorded_steps.json — full event data (action, selector, value, url, ts)
|
||||||
|
recorded_steps.py — human-readable Python preview (codegen-style)
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
.venv/bin/python record_camoufox.py
|
||||||
|
.venv/bin/python record_camoufox.py --url https://github.com/login
|
||||||
|
.venv/bin/python record_camoufox.py --out my_flow
|
||||||
|
|
||||||
|
Stop by closing the browser window or Ctrl+C. Passwords are masked ('***')
|
||||||
|
inside the page itself — they never leave the browser in plain text.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent
|
||||||
|
if str(ROOT) not in sys.path:
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
|
||||||
|
from github_register.config import load_config # noqa: E402
|
||||||
|
from github_register import runner # noqa: E402
|
||||||
|
from github_register.runner import _browser_ctx_options, silence_playwright_noise # noqa: E402
|
||||||
|
|
||||||
|
RECORDER_JS = r"""
|
||||||
|
(() => {
|
||||||
|
if (window.__recorder_installed) return;
|
||||||
|
window.__recorder_installed = true;
|
||||||
|
|
||||||
|
const describe = (el) => ({
|
||||||
|
tag: el.tagName ? el.tagName.toLowerCase() : '',
|
||||||
|
text: (el.innerText || el.value || el.getAttribute('aria-label') || '')
|
||||||
|
.trim().slice(0, 40),
|
||||||
|
});
|
||||||
|
|
||||||
|
const selectorFor = (el) => {
|
||||||
|
const tag = el.tagName ? el.tagName.toLowerCase() : '';
|
||||||
|
if (el.id) return '#' + CSS.escape(el.id);
|
||||||
|
if (tag === 'form') {
|
||||||
|
const a = el.getAttribute('action');
|
||||||
|
if (a) return `form[action="${a}"]`;
|
||||||
|
}
|
||||||
|
const name = el.getAttribute('name');
|
||||||
|
if (name) return `${tag}[name="${name}"]`;
|
||||||
|
const testid = el.getAttribute('data-testid');
|
||||||
|
if (testid) return `[data-testid="${testid}"]`;
|
||||||
|
const aria = el.getAttribute('aria-label');
|
||||||
|
if (aria) return `[aria-label="${aria}"]`;
|
||||||
|
const ph = el.getAttribute('placeholder');
|
||||||
|
if (ph) return `[placeholder="${ph}"]`;
|
||||||
|
// structural fallback: shortest nth-of-type chain
|
||||||
|
const parts = [];
|
||||||
|
let node = el;
|
||||||
|
while (node && node.nodeType === 1 && parts.length < 6) {
|
||||||
|
let part = node.tagName.toLowerCase();
|
||||||
|
if (node.id) { parts.unshift('#' + CSS.escape(node.id)); break; }
|
||||||
|
const parent = node.parentElement;
|
||||||
|
if (parent) {
|
||||||
|
const sibs = Array.from(parent.children).filter(c => c.tagName === node.tagName);
|
||||||
|
if (sibs.length > 1) part += `:nth-of-type(${sibs.indexOf(node) + 1})`;
|
||||||
|
}
|
||||||
|
parts.unshift(part);
|
||||||
|
node = node.parentElement;
|
||||||
|
}
|
||||||
|
return parts.join(' > ');
|
||||||
|
};
|
||||||
|
|
||||||
|
const send = (action, el, value) => {
|
||||||
|
try {
|
||||||
|
const { tag, text } = describe(el);
|
||||||
|
window.__record(JSON.stringify({
|
||||||
|
action,
|
||||||
|
selector: selectorFor(el),
|
||||||
|
tag,
|
||||||
|
text: text || null,
|
||||||
|
value: value === undefined ? null : String(value),
|
||||||
|
url: location.href,
|
||||||
|
frame: window === window.top ? null : (location.href || '(iframe)'),
|
||||||
|
ts: Date.now(),
|
||||||
|
}));
|
||||||
|
} catch (e) { /* never break the page */ }
|
||||||
|
};
|
||||||
|
|
||||||
|
// clicks — capture phase so we see them before page handlers
|
||||||
|
document.addEventListener('click', (e) => {
|
||||||
|
const el = e.target.closest(
|
||||||
|
'a, button, input[type="submit"], input[type="button"], [role="button"], input, select, label, summary'
|
||||||
|
) || e.target;
|
||||||
|
send('click', el);
|
||||||
|
}, true);
|
||||||
|
|
||||||
|
// text input (debounced) + password masking + checkbox/radio
|
||||||
|
let t = null;
|
||||||
|
document.addEventListener('input', (e) => {
|
||||||
|
const el = e.target;
|
||||||
|
if (!el.matches('input, textarea')) return;
|
||||||
|
const type = (el.getAttribute('type') || '').toLowerCase();
|
||||||
|
if (type === 'checkbox' || type === 'radio') return; // handled on change
|
||||||
|
if (type === 'password') { send('fill', el, '***'); return; }
|
||||||
|
clearTimeout(t);
|
||||||
|
t = setTimeout(() => send('fill', el, el.value), 600);
|
||||||
|
}, true);
|
||||||
|
|
||||||
|
document.addEventListener('change', (e) => {
|
||||||
|
const el = e.target;
|
||||||
|
const type = (el.getAttribute('type') || '').toLowerCase();
|
||||||
|
if (type === 'checkbox' || type === 'radio') send('check', el, el.checked);
|
||||||
|
else if (el.matches('select')) send('select', el, el.value);
|
||||||
|
}, true);
|
||||||
|
|
||||||
|
// explicit form submits (Enter key in a text field fires no click)
|
||||||
|
document.addEventListener('submit', (e) => send('submit', e.target), true);
|
||||||
|
})();
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _dedupe(events: list[dict]) -> list[dict]:
|
||||||
|
"""Collapse consecutive fills of the same field into the last value."""
|
||||||
|
out: list[dict] = []
|
||||||
|
for ev in events:
|
||||||
|
if (
|
||||||
|
ev.get("action") == "fill"
|
||||||
|
and out
|
||||||
|
and out[-1].get("action") == "fill"
|
||||||
|
and out[-1].get("selector") == ev.get("selector")
|
||||||
|
):
|
||||||
|
out[-1] = ev
|
||||||
|
else:
|
||||||
|
out.append(ev)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _dump(events: list[dict], base: str) -> None:
|
||||||
|
events = _dedupe(events)
|
||||||
|
json_path = (ROOT / base).with_suffix(".json")
|
||||||
|
py_path = (ROOT / base).with_suffix(".py")
|
||||||
|
|
||||||
|
json_path.write_text(json.dumps(events, indent=2), encoding="utf-8")
|
||||||
|
|
||||||
|
lines = [
|
||||||
|
"# Recorded steps (preview) — generated by record_camoufox.py",
|
||||||
|
"# Values marked '***' are masked passwords. Translate into runner.py stages.",
|
||||||
|
"from playwright.sync_api import sync_playwright",
|
||||||
|
"",
|
||||||
|
]
|
||||||
|
for ev in events:
|
||||||
|
act, sel, val = ev.get("action"), ev.get("selector"), ev.get("value")
|
||||||
|
if act == "goto":
|
||||||
|
lines.append(f"page.goto({ev['url']!r})")
|
||||||
|
elif act == "fill":
|
||||||
|
lines.append(f"page.locator({sel!r}).fill({val!r})")
|
||||||
|
elif act == "click":
|
||||||
|
lines.append(f"page.locator({sel!r}).click()")
|
||||||
|
elif act == "check":
|
||||||
|
lines.append(f"page.locator({sel!r}).set_checked({str(val).lower() if val in ('True','False',True,False) else 'True'})")
|
||||||
|
elif act == "select":
|
||||||
|
lines.append(f"page.locator({sel!r}).select_option({val!r})")
|
||||||
|
elif act == "submit":
|
||||||
|
lines.append(f"# form submit: {sel}")
|
||||||
|
py_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||||
|
|
||||||
|
counts: dict[str, int] = {}
|
||||||
|
for ev in events:
|
||||||
|
counts[ev.get("action", "?")] = counts.get(ev.get("action", "?"), 0) + 1
|
||||||
|
summary = ", ".join(f"{v}x {k}" for k, v in counts.items())
|
||||||
|
print(f"\n[*] saved {len(events)} steps ({summary})")
|
||||||
|
print(f" → {json_path.name}")
|
||||||
|
print(f" → {py_path.name}")
|
||||||
|
|
||||||
|
|
||||||
|
HARD_BLOCK_MARKERS = (
|
||||||
|
# English
|
||||||
|
"access is temporarily restricted",
|
||||||
|
"we detected unusual activity",
|
||||||
|
"you have been temporarily blocked",
|
||||||
|
# Indonesian (DataDome localizes)
|
||||||
|
"akses dibatasi untuk sementara",
|
||||||
|
"kami mendeteksi aktivitas yang tidak biasa",
|
||||||
|
"ada robot di jaringan",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _is_hard_block(page) -> bool:
|
||||||
|
try:
|
||||||
|
text = (page.locator("body").inner_text(timeout=3000) or "").lower()
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
return any(m in text for m in HARD_BLOCK_MARKERS)
|
||||||
|
|
||||||
|
|
||||||
|
def _warn_if_warp_ip(cfg=None, log=print) -> None:
|
||||||
|
"""Early network diagnostics: proxy info + direct exit IP + WARP warning.
|
||||||
|
|
||||||
|
Uses the SAME sticky URL that the browser will use — not the raw config
|
||||||
|
URL — so the exit-IP check reflects the actual traffic path.
|
||||||
|
"""
|
||||||
|
# proxy info first — resolve the sticky URL that _browser_ctx_options uses
|
||||||
|
if cfg is not None and (cfg.proxy or "").strip():
|
||||||
|
from urllib.parse import urlsplit as _us
|
||||||
|
|
||||||
|
from github_register.runner import _ensure_sticky_proxy, _socks_exit_ip
|
||||||
|
|
||||||
|
effective = _ensure_sticky_proxy(cfg.proxy, log=log)
|
||||||
|
p = _us(effective.strip())
|
||||||
|
masked = f"{p.scheme}://{p.hostname}:{p.port or ''}"
|
||||||
|
log(f"[*] browser will run via proxy: {masked}")
|
||||||
|
if (p.scheme or "").lower().startswith("socks"):
|
||||||
|
try:
|
||||||
|
exit_ip = _socks_exit_ip(effective)
|
||||||
|
log(f"[*] proxy exit IP (sticky): {exit_ip}")
|
||||||
|
except Exception as exc:
|
||||||
|
log(f"[!] proxy exit-IP lookup failed: {exc}")
|
||||||
|
log(" The gateway may be rejecting the connection — check proxy credentials / port.")
|
||||||
|
try:
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
with urllib.request.urlopen("http://ip-api.com/json/?fields=query,isp", timeout=8) as r:
|
||||||
|
data = json.loads(r.read().decode())
|
||||||
|
ip, isp = str(data.get("query") or "?"), str(data.get("isp") or "?")
|
||||||
|
if cfg is not None and (cfg.proxy or "").strip():
|
||||||
|
log(f"[*] direct (no-proxy) IP: {ip} ({isp}) — local reference only")
|
||||||
|
else:
|
||||||
|
log(f"[*] exit IP: {ip} ({isp})")
|
||||||
|
if "cloudflare" in isp.lower() or ip.startswith("104.28."):
|
||||||
|
log("[!] Your IP is Cloudflare WARP — this range is often blocked by DataDome.")
|
||||||
|
log(" Disable WARP from the Cloudflare menu bar for more stable recording.")
|
||||||
|
except Exception:
|
||||||
|
pass # never block the recorder on network diagnostics
|
||||||
|
|
||||||
|
|
||||||
|
def _open_with_warmup(page, url: str, log=print) -> None:
|
||||||
|
"""Homepage warm-up first (earns DataDome trust), then the target URL.
|
||||||
|
|
||||||
|
On a hard block, does NOT exit: warns, keeps the window open, and lets the
|
||||||
|
user solve it manually (or wait it out) — recording continues either way.
|
||||||
|
"""
|
||||||
|
log("[*] warm-up: github.com homepage")
|
||||||
|
page.goto("https://github.com/", wait_until="domcontentloaded", timeout=60_000)
|
||||||
|
time.sleep(4) # let DataDome tags.js execute and set the trust cookie
|
||||||
|
if _is_hard_block(page):
|
||||||
|
log("[!] hard block on homepage — IP flagged by DataDome (WARP/VPN?).")
|
||||||
|
log(" The window remains open: wait, reload manually (Cmd+R),")
|
||||||
|
log(" or disable WARP and restart this recorder.")
|
||||||
|
else:
|
||||||
|
log(f"[*] navigating to target: {url}")
|
||||||
|
page.goto(url, wait_until="domcontentloaded", timeout=60_000)
|
||||||
|
time.sleep(3)
|
||||||
|
if _is_hard_block(page):
|
||||||
|
log("[!] hard block on target page — the window remains open.")
|
||||||
|
log(" Wait briefly then reload manually (Cmd+R), or disable WARP.")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||||
|
ap.add_argument("--url", default="https://github.com/signup", help="start URL")
|
||||||
|
ap.add_argument("--out", default="recorded_steps", help="output base name")
|
||||||
|
ap.add_argument(
|
||||||
|
"--persistent", action="store_true",
|
||||||
|
help="use persistent profile (.browser-profile) instead of fresh mode",
|
||||||
|
)
|
||||||
|
args = ap.parse_args()
|
||||||
|
|
||||||
|
silence_playwright_noise() # hide TargetClosedError spam
|
||||||
|
cfg = load_config(ROOT / "config.json")
|
||||||
|
if args.persistent:
|
||||||
|
cfg.fresh_profile = False # recording is usually more stable with a profile
|
||||||
|
opts = _browser_ctx_options(cfg, log=print) # geoip + os + humanize (+proxy/bridge)
|
||||||
|
opts["headless"] = False # recording is a manual, visible session
|
||||||
|
|
||||||
|
_warn_if_warp_ip(cfg) # proxy info + IP diagnostics before opening browser
|
||||||
|
|
||||||
|
from camoufox.sync_api import Camoufox
|
||||||
|
|
||||||
|
events: list[dict] = []
|
||||||
|
live_path = (ROOT / args.out).with_suffix(".json")
|
||||||
|
|
||||||
|
def _flush_live() -> None:
|
||||||
|
"""Write events to disk on EVERY new event — crash-proof recording."""
|
||||||
|
try:
|
||||||
|
live_path.write_text(json.dumps(_dedupe(events), indent=2), encoding="utf-8")
|
||||||
|
except Exception:
|
||||||
|
pass # never let disk problems kill the recording session
|
||||||
|
|
||||||
|
try:
|
||||||
|
with Camoufox(**opts) as browser:
|
||||||
|
# works for both fresh (Browser) and persistent (BrowserContext)
|
||||||
|
context, page = runner._context_and_page(browser)
|
||||||
|
if getattr(cfg, "fresh_profile", False) and not args.persistent:
|
||||||
|
runner._restore_trust_cookie(context, print)
|
||||||
|
|
||||||
|
def on_record(source, payload: str) -> None:
|
||||||
|
try:
|
||||||
|
ev = json.loads(payload)
|
||||||
|
except Exception:
|
||||||
|
return
|
||||||
|
events.append(ev)
|
||||||
|
label = ev.get("text") or ""
|
||||||
|
val = ev.get("value")
|
||||||
|
extra = f" «{label}»" if label else ""
|
||||||
|
extra += f" = {val}" if val not in (None, "") else ""
|
||||||
|
frame = " [iframe]" if ev.get("frame") else ""
|
||||||
|
print(f"[REC] {ev['action']:<6} {ev['selector'][:58]:<58}{extra}{frame}", flush=True)
|
||||||
|
_flush_live() # persist immediately
|
||||||
|
|
||||||
|
context.expose_binding("__record", on_record)
|
||||||
|
context.add_init_script(RECORDER_JS)
|
||||||
|
|
||||||
|
page.set_default_timeout(20_000)
|
||||||
|
_open_with_warmup(page, args.url)
|
||||||
|
|
||||||
|
print(f"[*] recorder armed: {args.url}")
|
||||||
|
print(f"[*] live-saving tiap event → {live_path.name}")
|
||||||
|
print("[*] perform manual steps — close the browser window or press Ctrl+C to finish\n")
|
||||||
|
|
||||||
|
last_url = page.url
|
||||||
|
while True:
|
||||||
|
time.sleep(1)
|
||||||
|
try:
|
||||||
|
url = page.url
|
||||||
|
except Exception:
|
||||||
|
break # browser window closed by user
|
||||||
|
if url != last_url:
|
||||||
|
events.append({"action": "goto", "url": url, "ts": int(time.time() * 1000)})
|
||||||
|
print(f"[REC] goto {url[:76]}", flush=True)
|
||||||
|
last_url = url
|
||||||
|
_flush_live()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("\n[*] Ctrl+C — stopping recorder", flush=True)
|
||||||
|
except Exception as exc:
|
||||||
|
# browser already closed by the user (TargetClosedError etc.) — that's
|
||||||
|
# a NORMAL exit path, not a failure. Recording stays intact.
|
||||||
|
if "TargetClosedError" in type(exc).__name__ or "target" in str(exc).lower() or "closed" in str(exc).lower():
|
||||||
|
print("\n[*] browser closed — recording saved", flush=True)
|
||||||
|
else:
|
||||||
|
print(f"\n[!] recorder error: {exc}", flush=True)
|
||||||
|
finally:
|
||||||
|
runner._stop_proxy_bridge() # stop local auth bridge if it was started
|
||||||
|
if events:
|
||||||
|
_dump(events, args.out)
|
||||||
|
else:
|
||||||
|
print("[!] no events were recorded")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
camoufox[geoip]>=0.5.5
|
||||||
|
playwright>=1.60
|
||||||
|
requests>=2.32
|
||||||
|
fastapi>=0.141
|
||||||
|
uvicorn[standard]>=0.52
|
||||||
|
pyotp>=2.9
|
||||||
@@ -0,0 +1,230 @@
|
|||||||
|
"""Self-check for non-network logic. Run: python -m tests.test_core"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from github_register.profiles import (
|
||||||
|
extract_github_code,
|
||||||
|
generate_password,
|
||||||
|
generate_username,
|
||||||
|
is_valid_username,
|
||||||
|
parse_public_profile,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_extract_code():
|
||||||
|
assert extract_github_code("Here's your GitHub verification code: 1234 5678") == "12345678"
|
||||||
|
assert extract_github_code("Your verification code is 12345678. It expires soon.") == "12345678"
|
||||||
|
assert extract_github_code("verification code: 9876 5432") == "98765432"
|
||||||
|
assert extract_github_code("no code here") is None
|
||||||
|
assert extract_github_code("") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_password():
|
||||||
|
for _ in range(50):
|
||||||
|
pw = generate_password()
|
||||||
|
assert len(pw) >= 12
|
||||||
|
assert any(c.islower() for c in pw)
|
||||||
|
assert any(c.isupper() for c in pw)
|
||||||
|
assert any(c.isdigit() for c in pw)
|
||||||
|
|
||||||
|
|
||||||
|
def test_username():
|
||||||
|
for _ in range(100):
|
||||||
|
name = generate_username()
|
||||||
|
assert is_valid_username(name), name
|
||||||
|
|
||||||
|
|
||||||
|
def test_litensi_zone_pick():
|
||||||
|
from github_register.litensi import LitensiClient
|
||||||
|
|
||||||
|
cli = LitensiClient("id", "key", "github", "")
|
||||||
|
zones = [
|
||||||
|
{"zone": "a", "stock": 0, "price": 1},
|
||||||
|
{"zone": "b", "stock": 5, "price": 3},
|
||||||
|
{"zone": "c", "stock": 2, "price": 1.5},
|
||||||
|
]
|
||||||
|
stock = [z for z in zones if float(z.get("stock") or 0) > 0]
|
||||||
|
assert min(stock, key=lambda z: float(z.get("price") or 0))["zone"] == "c"
|
||||||
|
|
||||||
|
|
||||||
|
def test_proxy_pool_pick():
|
||||||
|
from github_register.config import Config
|
||||||
|
from github_register.runner import _pick_proxy_url, load_proxy_pool
|
||||||
|
|
||||||
|
from github_register import runner
|
||||||
|
|
||||||
|
pool_name = "_test_pool_tmp.txt"
|
||||||
|
pool_path = runner.ROOT / pool_name
|
||||||
|
pool_path.write_text(
|
||||||
|
"# comment\n"
|
||||||
|
"http://u:p@1.1.1.1:8080\n"
|
||||||
|
"\n"
|
||||||
|
"not a proxy line\n"
|
||||||
|
"socks5://u:p@2.2.2.2:1080\n",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
pool = load_proxy_pool(pool_name)
|
||||||
|
assert pool == ["http://u:p@1.1.1.1:8080", "socks5://u:p@2.2.2.2:1080"], pool
|
||||||
|
cfg = Config(proxy="http://fallback:1@3.3.3.3:80", proxy_file=pool_name)
|
||||||
|
assert _pick_proxy_url(cfg) in pool
|
||||||
|
cfg2 = Config(proxy="http://fallback:1@3.3.3.3:80", proxy_file="")
|
||||||
|
assert _pick_proxy_url(cfg2) == "http://fallback:1@3.3.3.3:80"
|
||||||
|
cfg3 = Config(proxy="http://fallback:1@3.3.3.3:80", proxy_file="_missing_pool.txt")
|
||||||
|
assert _pick_proxy_url(cfg3) == "http://fallback:1@3.3.3.3:80"
|
||||||
|
finally:
|
||||||
|
pool_path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_public_profile():
|
||||||
|
random_user = {
|
||||||
|
"results": [{
|
||||||
|
"name": {"title": "Mr", "first": "Caleb", "last": "Harvey"},
|
||||||
|
"location": {"country": "Ireland"},
|
||||||
|
# These must not be included in the resulting profile data.
|
||||||
|
"email": "caleb.harvey@example.com",
|
||||||
|
"login": {"password": "shop"},
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
quote = [{"q": "A public quote."}]
|
||||||
|
assert parse_public_profile(random_user, quote) == {
|
||||||
|
"name": "Mr Caleb Harvey", "location": "Ireland", "bio": "A public quote.",
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
parse_public_profile({}, [])
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise AssertionError("invalid profile payload must fail")
|
||||||
|
|
||||||
|
|
||||||
|
def test_mailbox_timeout_is_not_fatal_provider_error():
|
||||||
|
"""A per-mailbox 'no code' timeout must NOT abort the whole job.
|
||||||
|
|
||||||
|
Fatal provider/config errors (bad key, no balance, out of stock) are
|
||||||
|
LitensiError / MailCxError and DO abort. A single mailbox that never got
|
||||||
|
the GitHub code is a transient per-account failure and must be a separate,
|
||||||
|
non-fatal type.
|
||||||
|
"""
|
||||||
|
from github_register.litensi import LitensiError
|
||||||
|
from github_register.mailcx import MailCxError
|
||||||
|
from github_register.mail_errors import MailboxTimeoutError
|
||||||
|
|
||||||
|
# A mailbox timeout must not be classified as a fatal provider error.
|
||||||
|
assert not issubclass(MailboxTimeoutError, LitensiError)
|
||||||
|
assert not issubclass(MailboxTimeoutError, MailCxError)
|
||||||
|
|
||||||
|
|
||||||
|
def test_litensi_wait_for_code_raises_mailbox_timeout(monkeypatch=None):
|
||||||
|
"""wait_for_code timeout raises MailboxTimeoutError, not LitensiError."""
|
||||||
|
from github_register.litensi import LitensiClient, LitensiError
|
||||||
|
from github_register.mail_errors import MailboxTimeoutError
|
||||||
|
|
||||||
|
cli = LitensiClient("id", "key", "github.com", "zone")
|
||||||
|
# Every poll reports "no message yet" (no code in the payload).
|
||||||
|
cli.get_status = lambda order_id: {"status": "WAITING", "message": ""}
|
||||||
|
|
||||||
|
try:
|
||||||
|
cli.wait_for_code("123", timeout=0, poll_interval=5)
|
||||||
|
except MailboxTimeoutError:
|
||||||
|
pass
|
||||||
|
except LitensiError as exc: # the bug: a timeout looked like a fatal error
|
||||||
|
raise AssertionError(f"timeout raised fatal LitensiError instead: {exc}")
|
||||||
|
else:
|
||||||
|
raise AssertionError("wait_for_code must raise on timeout")
|
||||||
|
|
||||||
|
|
||||||
|
def test_mailcx_wait_for_code_raises_mailbox_timeout():
|
||||||
|
"""mail.cx timeout raises MailboxTimeoutError, not MailCxError."""
|
||||||
|
from github_register.mailcx import MailCxClient, MailCxError
|
||||||
|
from github_register.mail_errors import MailboxTimeoutError
|
||||||
|
|
||||||
|
cli = MailCxClient()
|
||||||
|
cli.get_messages = lambda address: []
|
||||||
|
|
||||||
|
try:
|
||||||
|
cli.wait_for_code("a@b.com", timeout=0, poll_interval=5)
|
||||||
|
except MailboxTimeoutError:
|
||||||
|
pass
|
||||||
|
except MailCxError as exc: # the bug: a timeout looked like a fatal error
|
||||||
|
raise AssertionError(f"timeout raised fatal MailCxError instead: {exc}")
|
||||||
|
else:
|
||||||
|
raise AssertionError("wait_for_code must raise on timeout")
|
||||||
|
|
||||||
|
|
||||||
|
def test_register_one_continues_after_mailbox_timeout():
|
||||||
|
"""register_one returns None (one failed account) on a mailbox timeout."""
|
||||||
|
from github_register import runner
|
||||||
|
from github_register.mail_errors import MailboxTimeoutError
|
||||||
|
|
||||||
|
cfg = runner.Config(mail_provider="litensi", litensi_api_id="id",
|
||||||
|
litensi_api_key="key", litensi_site="github.com")
|
||||||
|
|
||||||
|
def _boom(*args, **kwargs):
|
||||||
|
raise MailboxTimeoutError("no GitHub code after 240s")
|
||||||
|
|
||||||
|
orig = runner._run_signup
|
||||||
|
runner._run_signup = _boom
|
||||||
|
try:
|
||||||
|
result = runner.register_one(cfg, log=lambda m: None)
|
||||||
|
finally:
|
||||||
|
runner._run_signup = orig
|
||||||
|
assert result is None, f"mailbox timeout must fail one account, got {result!r}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_job_continues_after_mailbox_timeout():
|
||||||
|
"""run_job keeps going after mailbox timeouts (real register_one path)."""
|
||||||
|
from github_register import runner
|
||||||
|
from github_register.mail_errors import MailboxTimeoutError
|
||||||
|
|
||||||
|
cfg = runner.Config(mail_provider="mailcx", register_count=3, delay_sec=0)
|
||||||
|
calls = {"n": 0}
|
||||||
|
|
||||||
|
def _signup(*args, **kwargs):
|
||||||
|
# Every account times out waiting for the GitHub code.
|
||||||
|
calls["n"] += 1
|
||||||
|
raise MailboxTimeoutError("no GitHub code after 240s")
|
||||||
|
|
||||||
|
orig = runner._run_signup
|
||||||
|
runner._run_signup = _signup
|
||||||
|
try:
|
||||||
|
ok, fail, out = runner.run_job(cfg, log=lambda m: None)
|
||||||
|
finally:
|
||||||
|
runner._run_signup = orig
|
||||||
|
out.unlink(missing_ok=True)
|
||||||
|
# The job must attempt ALL accounts instead of aborting on the first one.
|
||||||
|
assert calls["n"] == 3, f"job stopped early after mailbox timeout (ran {calls['n']}/3)"
|
||||||
|
assert fail == 3 and ok == 0, f"expected 3 fail / 0 ok, got {fail}/{ok}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_job_aborts_on_fatal_provider_error():
|
||||||
|
"""A genuine provider error (bad key / no balance) still aborts the job."""
|
||||||
|
from github_register import runner
|
||||||
|
from github_register.litensi import LitensiError
|
||||||
|
|
||||||
|
cfg = runner.Config(mail_provider="litensi", register_count=3, delay_sec=0)
|
||||||
|
calls = {"n": 0}
|
||||||
|
|
||||||
|
def _one(cfg, log, stop):
|
||||||
|
calls["n"] += 1
|
||||||
|
raise LitensiError("NOT ENOUGH BALANCE — Litensi balance is insufficient")
|
||||||
|
|
||||||
|
orig = runner.register_one
|
||||||
|
runner.register_one = _one
|
||||||
|
try:
|
||||||
|
ok, fail, out = runner.run_job(cfg, log=lambda m: None)
|
||||||
|
finally:
|
||||||
|
runner.register_one = orig
|
||||||
|
out.unlink(missing_ok=True)
|
||||||
|
assert calls["n"] == 1, f"fatal provider error must abort after 1 attempt (ran {calls['n']})"
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
for name, fn in sorted((n, f) for n, f in globals().items() if n.startswith("test_")):
|
||||||
|
fn()
|
||||||
|
print(f"[OK] {name}")
|
||||||
|
print("[*] all tests passed")
|
||||||
+1333
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user