v0.2: dashboard, mail fallback, API map, guide, honest results
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
config.json
|
||||
*.jsonl
|
||||
logs/
|
||||
__pycache__/
|
||||
*.log
|
||||
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
# API map — Proximus (proximus.sh / api.proximus.sh)
|
||||
|
||||
Reverse engineered 31 Oct 2026 from the public site and its Next.js chunks.
|
||||
Everything below was verified with live requests; statuses quoted are the ones
|
||||
actually observed.
|
||||
|
||||
## Web (proximus.sh)
|
||||
|
||||
| Endpoint | Method | Auth | Notes |
|
||||
|---|---|---|---|
|
||||
| `/api/csrf` | GET | none | sets cookie `proximus-csrf`, returns `{"ok":true,"csrfToken":"<32B>"}`. Same value in both places, `Max-Age=28800`, `SameSite=strict`, `Secure`. |
|
||||
| `/api/contact` | POST | `x-csrf-token` header + cookie | the grant/contact form |
|
||||
| `/api/waitinglist` | POST | `x-csrf-token` header + cookie | waiting-list intake |
|
||||
| `/api/auth/sign-up` | POST | `x-csrf-token` | early-access signup (server action; 405 on GET) |
|
||||
| `/api/proximus.sh/v1/*` | — | Bearer | see below, different host |
|
||||
|
||||
### POST /api/contact
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "Elena Marchetti",
|
||||
"email": "someone@example.com",
|
||||
"organization": "Northwind Payment Security",
|
||||
"reason": "Partnership",
|
||||
"message": "Applying for a Proxy Grants allocation ...",
|
||||
"website": "",
|
||||
"requestId": "b7d3f0a2-1c1f-4f6f-9d1a-7a2f0f1c9a11"
|
||||
}
|
||||
```
|
||||
|
||||
Rules that are enforced (all confirmed by error responses):
|
||||
|
||||
- `requestId`: must parse as a UUID, otherwise `400 {"ok":false,"error":"Invalid UUID"}`.
|
||||
- `website`: honeypot field. Present and empty. (Server-side behaviour for a
|
||||
filled value is not published; do not test it on someone else's site.)
|
||||
- `reason` enum: `Product and early access`, `Enterprise and self-hosting`,
|
||||
`Partnership`, `Security research`, `Security review`, `Other`.
|
||||
- `name` <= 120 chars, `email` <= 254, `organization` <= 160, `message` <= 4000.
|
||||
|
||||
Success: `200 {"ok":true,"copySent":true}` — the site also mails a copy to the
|
||||
address you submitted, so the address must be one you can read.
|
||||
|
||||
Failure modes observed:
|
||||
|
||||
| Status | Body | Meaning |
|
||||
|---|---|---|
|
||||
| 200 | `{"ok":true,"copySent":true}` | stored + copy mailed |
|
||||
| 200 | `{"ok":true,"copySent":false}` | stored, copy mail failed |
|
||||
| 400 | `{"ok":false,"error":"Invalid UUID"}` | bad `requestId` |
|
||||
| 429 | `{"errorCode":"common.rate_limited"}` | over the per-subnet window |
|
||||
| 503 | `{"ok":false,"error":"Your message could not be sent..."}` | their transactional mail is down |
|
||||
|
||||
Headers on every response: `x-ratelimit-limit: 3`, `x-ratelimit-remaining`,
|
||||
`x-ratelimit-reset` (seconds). The window is ~600 s and the counter did **not**
|
||||
reset when rotating IPv6 addresses inside one /64 — treat it as per subnet.
|
||||
|
||||
### POST /api/waitinglist
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "…", "email": "…", "kind": "company",
|
||||
"organization": "…", "role": "Security Engineer",
|
||||
"teamSize": "2-10", // 1 | 2-10 | 11-50 | 51-200 | 201+
|
||||
"interests": ["pentesting", "load-testing", "proxy-ai", "compute",
|
||||
"transaction-api", "website-scans"],
|
||||
"useCase": "…", // 10..2000 chars, required
|
||||
"consent": true,
|
||||
"website": ""
|
||||
}
|
||||
```
|
||||
|
||||
Success: `200 {"ok":true}`. The waiting-list reference/access code is delivered
|
||||
by email — while the site's mail provider is broken, entries are stored but no
|
||||
code ever arrives and `/api/auth/sign-up` stays unreachable.
|
||||
|
||||
## Customer API (api.proximus.sh)
|
||||
|
||||
`GET /` → `{"service":"Proximus API","base_url":"https://api.proximus.sh","version":"v1",
|
||||
"documentation":"https://www.proximus.sh/documentation","authentication":"Bearer API key"}`
|
||||
|
||||
Every route without a key:
|
||||
|
||||
```
|
||||
401 {"ok":false,"errorCode":"common.unauthorized","title":"API key required",
|
||||
"error":"Provide an active API key in the Authorization: Bearer ***","status":401}
|
||||
```
|
||||
|
||||
| Route | Method | Scope (from docs) |
|
||||
|---|---|---|
|
||||
| `/v1/review/action` | POST | `review:write` |
|
||||
| `/v1/policy/evaluate` | POST | `policy:evaluate` |
|
||||
| `/v1/web/session` | POST | `web:write` |
|
||||
| `/v1/reviews/{request_id}` | GET | `reviews:read` |
|
||||
| `/v1/integrations/{id}/events` | POST | `monitor:write` |
|
||||
| `/v1/evidence/commit` | POST | `evidence:write` |
|
||||
| `/v1/evidence/{id}` | GET | `evidence:read` |
|
||||
| `/v1/graph/query` | GET | `graph:read` |
|
||||
| `/v1/compute/catalog` | GET | security-compute catalogue |
|
||||
|
||||
Keys are issued in the dashboard only: no public signup, no sandbox key.
|
||||
|
||||
## Billing shape (from /pricing)
|
||||
|
||||
- 1 credit = $0.10 base. Packages: 10 000 = $950, 25 000 = $2 250,
|
||||
50 000 = $4 250 (−5/−10/−15 %). Minimum 100 credits ($10).
|
||||
- Paid in USDC or SOL on Solana; network fees separate.
|
||||
- Credits meter: dashboard API reviews (1 review = 1 credit), pentesting
|
||||
compute, load tests, model chat.
|
||||
- Transaction-security API is billed to end users (0.005–0.5 % of the payment),
|
||||
no subscription.
|
||||
- Proxy Grants: $5 000–$15 000 in credits for fintech-security teams at Solana
|
||||
and Hyperliquid hackathons; application = the contact form.
|
||||
|
||||
## What is deliberately not in this repo
|
||||
|
||||
No captcha bypass (there is no captcha on these routes today), no email
|
||||
verification bypass, no key derivation: the dashboard issues keys, and a key
|
||||
cannot be computed from an account id.
|
||||
@@ -0,0 +1,94 @@
|
||||
# Guide
|
||||
|
||||
## 1. Install
|
||||
|
||||
```bash
|
||||
git clone <repo> && cd form-intake
|
||||
cp config.example.json config.json # edit: your lanes, your email
|
||||
python form_intake.py --config config.json probe
|
||||
```
|
||||
|
||||
Python 3.8+. No pip install, no venv.
|
||||
|
||||
## 2. Lanes (egress budget)
|
||||
|
||||
`config.json` → `lanes` is a list of proxy URLs; `null` means "direct".
|
||||
|
||||
```json
|
||||
"lanes": [null, "http://user:pass@203.0.113.10:8888", "socks5h://127.0.0.1:1080"],
|
||||
"lane_quota": 3,
|
||||
"lane_window": 620
|
||||
```
|
||||
|
||||
`lane_quota` / `lane_window` must match the server's ceiling (3 per ~600 s per
|
||||
subnet). Raising them does not create capacity — it only buys you 429s. Lanes
|
||||
that sit in the same /64 as another lane do not add capacity either; verify
|
||||
with a plain `curl https://api.ipify.org` per lane before trusting the pool.
|
||||
|
||||
## 3. Submit
|
||||
|
||||
```bash
|
||||
python form_intake.py --config config.json contact --target 20
|
||||
python form_intake.py --config config.json waitlist --target 20
|
||||
python form_intake.py --config config.json report --out contact.jsonl
|
||||
```
|
||||
|
||||
Each attempt appends one JSONL row: `ts, lane, email, org, tier, ok, code, body`.
|
||||
`report` prints the attempt/accepted/code breakdown.
|
||||
|
||||
## 4. Mail fallback
|
||||
|
||||
When `/api/contact` answers 503 (their mailer is down), the site's own error
|
||||
text tells you to write to the intake mailbox. Put SMTP creds in
|
||||
`config.json`:
|
||||
|
||||
```json
|
||||
"smtp": {"host": "smtp.gmail.com", "port": 587, "user": "you@example.com", "pass": "app-password"},
|
||||
"mail_to": "hello@example.com"
|
||||
```
|
||||
|
||||
or export `SMTP_HOST / SMTP_PORT / SMTP_USER / SMTP_PASS`.
|
||||
|
||||
```bash
|
||||
python mail_wave.py --n 20 --pause 25 60
|
||||
```
|
||||
|
||||
Use an app password, not the account password, and keep the pause generous:
|
||||
mailbox providers rate-limit per account and per recipient domain.
|
||||
|
||||
## 5. Dashboard
|
||||
|
||||
```bash
|
||||
python dashboard.py --port 8765
|
||||
# http://127.0.0.1:8765
|
||||
```
|
||||
|
||||
Tabs: overview (live counters, code breakdown), jobs (start/stop contact,
|
||||
waitlist, mail with a target), log (tail of the JSONL), config (edit and save
|
||||
`config.json`). It binds 127.0.0.1 and never leaves the machine.
|
||||
|
||||
## 6. Pitfalls
|
||||
|
||||
1. **`400 Invalid UUID`** — the form validates `requestId` before anything else.
|
||||
2. **`429` even with fresh IPv6** — the limiter counts the subnet, not the
|
||||
address. Different providers, not different addresses.
|
||||
3. **`503 could not be sent`** — their transactional mail. Nothing client-side
|
||||
fixes it; retry later or use the mail fallback.
|
||||
4. **`csrf_failed`** — the cookie from `/api/csrf` must be sent back with the
|
||||
POST. Reuse one session per submission (the runner already does).
|
||||
5. **Honeypot** — `website` must exist and be empty; omitting the key and
|
||||
sending junk both differ from the intended path.
|
||||
6. **`200` but no mail** — `copySent:false` means the copy failed; the entry is
|
||||
still stored. Do not resubmit the same person on that basis.
|
||||
7. **Watching a lane** — `curl --socks5-hostname 127.0.0.1:1080 https://api.ipify.org`
|
||||
must print a different address per provider, otherwise your "pool" is one IP.
|
||||
8. **Windows console** — scripts set `sys.stdout.reconfigure(encoding="utf-8")`;
|
||||
without it Cyrillic output raises `UnicodeEncodeError` in cp866 terminals.
|
||||
9. **Dashboard from another machine** — don't. It has no auth; it is a local
|
||||
panel for a local worker.
|
||||
|
||||
## 7. Withdrawing
|
||||
|
||||
- `POST /api/contact` has no delete route: a submitted application stays.
|
||||
- Waiting-list entries cannot be withdrawn either.
|
||||
- So: submit only what you would defend in a support thread.
|
||||
@@ -16,9 +16,23 @@ cp config.example.json config.json # put your own lanes and email here
|
||||
python form_intake.py --config config.json probe
|
||||
python form_intake.py --config config.json contact --target 20
|
||||
python form_intake.py --config config.json report --out contact.jsonl
|
||||
python dashboard.py # http://127.0.0.1:8765
|
||||
```
|
||||
|
||||
`config.json` is gitignored — it holds your proxies and your mailbox.
|
||||
`config.json` is gitignored — it holds your proxies, your mailbox and your SMTP
|
||||
app password.
|
||||
|
||||
## Repo layout
|
||||
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `form_intake.py` | runner: lane pool, persona generator, `contact` / `waitlist` / `probe` / `report` |
|
||||
| `mail_wave.py` | mail fallback for when the form answers 503 |
|
||||
| `dashboard.py` | local panel on 127.0.0.1: live counters, start/stop jobs, log tail, config editor |
|
||||
| `API_MAP.md` | every endpoint, payload, status code and failure mode |
|
||||
| `GUIDE.md` | install, lanes, mail fallback, numbered pitfalls |
|
||||
| `RESULTS.md` | one live run, honest funnel |
|
||||
| `config.example.json` | the shape of your config |
|
||||
|
||||
## Endpoint map (reverse engineered, 31 Oct 2026)
|
||||
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
# Results — one live run (31 Oct 2026)
|
||||
|
||||
Funnel as measured, not as advertised.
|
||||
|
||||
| Stage | Count | Notes |
|
||||
|---|---|---|
|
||||
| `POST /api/contact` attempts | 196 | 11 lanes, 3 sends / ~620 s per lane |
|
||||
| — answered `200 {"ok":true}` | 3 | $5 000 + $10 000 + $15 000 tiers requested |
|
||||
| — answered `503` | 127 | site's transactional mail down |
|
||||
| — answered `429` | 36 | subnet quota |
|
||||
| — timeouts / transport | 30 | proxies, retried |
|
||||
| `POST /api/waitinglist` attempts | 44 | |
|
||||
| — `200 {"ok":true}` | 43 | entries stored |
|
||||
| access codes received | 0 | no mail arrives at all |
|
||||
| mails sent to intake address | 20 | 0 bounces, 0 replies |
|
||||
| API keys obtained | 0 | `api.proximus.sh/v1/*` → 401 for everyone |
|
||||
| credits granted | 0 | grant review is human and takes days |
|
||||
|
||||
## Reading the numbers
|
||||
|
||||
`200` means "the form stored this and tried to mail a copy". It is **not** an
|
||||
approval: nobody at the company has to read it, and the 3 accepted applications
|
||||
count as 3 rows in a queue, nothing more.
|
||||
|
||||
The 503 rate is the story: two thirds of submissions never reach a human
|
||||
because the site's own mail provider fails. Identical bodies answered `200` one
|
||||
minute and `503` two minutes later from the same lane, so this is upstream
|
||||
state, not payload shape.
|
||||
|
||||
## What would change the numbers
|
||||
|
||||
- Their mailer recovering → accepted ratio approaches 100 %.
|
||||
- Any captcha or pre-submit email verification → this toolkit stops working,
|
||||
which is the correct end state.
|
||||
- A dashboard key issued → `/v1/*` opens up, and only then do credits mean
|
||||
anything.
|
||||
|
||||
## Honest limits
|
||||
|
||||
- The 3 accepted applications requested $30 000 in credits; the granted amount
|
||||
is unknown and probably zero for all of them.
|
||||
- No account exists, so no credits could be spent even if granted.
|
||||
- Mail fallback reaches a human inbox but a human must still answer.
|
||||
@@ -50,5 +50,12 @@
|
||||
"local": "youraccount",
|
||||
"domain": "gmail.com",
|
||||
"tags": ["grant", "apply", "pg"]
|
||||
},
|
||||
"mail_to": "hello@example.com",
|
||||
"smtp": {
|
||||
"host": "smtp.gmail.com",
|
||||
"port": 587,
|
||||
"user": "you@example.com",
|
||||
"pass": "app-password"
|
||||
}
|
||||
}
|
||||
Executable
+276
@@ -0,0 +1,276 @@
|
||||
#!/usr/bin/env python3
|
||||
"""dashboard — local control panel for form_intake (stdlib only).
|
||||
|
||||
Serves a small web UI on 127.0.0.1 and controls the worker processes:
|
||||
|
||||
python dashboard.py # http://127.0.0.1:8765
|
||||
python dashboard.py --port 8790 --home C:/path/to/work
|
||||
|
||||
Everything it shows is read from the work dir (JSONL logs + config.json).
|
||||
No credential leaves the machine: the config is only ever read/written here.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
HOME = os.path.abspath(os.environ.get("FORM_INTAKE_HOME", os.getcwd()))
|
||||
JOBS = {
|
||||
"contact": {"script": "form_intake.py", "args": ["contact"], "log": "contact.jsonl"},
|
||||
"waitlist": {"script": "form_intake.py", "args": ["waitlist"], "log": "waitlist.jsonl"},
|
||||
"mail": {"script": "mail_wave.py", "args": [], "log": "mail.jsonl"},
|
||||
}
|
||||
PROCS = {}
|
||||
LOCK = threading.Lock()
|
||||
|
||||
INDEX = """<!doctype html><html><head><meta charset="utf-8"><title>form_intake</title>
|
||||
<style>
|
||||
:root{--bg:#0b0c10;--panel:#12141a;--line:#22262f;--fg:#d7dae0;--dim:#8b93a1;--acc:#5ad1a0}
|
||||
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:13px/1.5 ui-monospace,Menlo,Consolas,monospace}
|
||||
header{display:flex;gap:16px;align-items:center;padding:12px 18px;border-bottom:1px solid var(--line);background:var(--panel)}
|
||||
h1{font-size:14px;margin:0;letter-spacing:.08em;text-transform:uppercase;color:var(--acc)}
|
||||
nav a{color:var(--dim);text-decoration:none;padding:4px 8px;border:1px solid transparent;cursor:pointer}
|
||||
nav a.on{color:var(--fg);border-color:var(--line);background:#181b23}
|
||||
main{padding:18px;max-width:1180px}
|
||||
.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px}
|
||||
.card{background:var(--panel);border:1px solid var(--line);padding:12px}
|
||||
.card b{display:block;font-size:22px;color:var(--acc);font-weight:600}
|
||||
.card span{color:var(--dim);font-size:11px;text-transform:uppercase;letter-spacing:.06em}
|
||||
table{width:100%;border-collapse:collapse;margin-top:14px;font-size:12px}
|
||||
th,td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--line)}
|
||||
th{color:var(--dim);font-weight:500;text-transform:uppercase;font-size:10px;letter-spacing:.06em}
|
||||
button{background:#1b1f27;color:var(--fg);border:1px solid var(--line);padding:6px 12px;cursor:pointer;font:inherit}
|
||||
button:hover{border-color:var(--acc);color:var(--acc)}
|
||||
button.stop{border-color:#5a2a2a;color:#e08b8b}
|
||||
pre{background:#0e1016;border:1px solid var(--line);padding:10px;overflow:auto;max-height:340px;font-size:11px}
|
||||
input,textarea,select{background:#0e1016;border:1px solid var(--line);color:var(--fg);padding:6px;font:inherit;width:100%}
|
||||
.row{display:grid;grid-template-columns:160px 1fr;gap:8px;align-items:center;margin-bottom:8px}
|
||||
.muted{color:var(--dim)}
|
||||
</style></head><body>
|
||||
<header><h1>form_intake</h1><nav id="nav"></nav></header>
|
||||
<main id="view"></main>
|
||||
<script>
|
||||
const TABS=["overview","jobs","log","config"];
|
||||
let tab="overview";
|
||||
function el(h){const d=document.createElement("div");d.innerHTML=h;return d}
|
||||
async function j(u,o){const r=await fetch(u,o);return r.json()}
|
||||
function renderNav(){document.getElementById("nav").innerHTML=TABS.map(t=>`<a class="${t===tab?'on':''}" onclick="go('${t}')">${t.toUpperCase()}</a>`).join(" ")}
|
||||
function go(t){tab=t;renderNav();draw()}
|
||||
async function draw(){
|
||||
const v=document.getElementById("view");
|
||||
if(tab==="overview"){
|
||||
const s=await j("/api/status");
|
||||
v.innerHTML=`<div class="cards">
|
||||
<div class="card"><span>attempts</span><b>${s.contact.attempts}</b></div>
|
||||
<div class="card"><span>accepted</span><b>${s.contact.accepted}</b></div>
|
||||
<div class="card"><span>waitlist</span><b>${s.waitlist.accepted}/${s.waitlist.attempts}</b></div>
|
||||
<div class="card"><span>mails</span><b>${s.mail.sent}</b></div>
|
||||
<div class="card"><span>running</span><b>${s.running.join(",")||"-"}</b></div>
|
||||
</div>
|
||||
<table><tr><th>code</th><th>count</th></tr>
|
||||
${Object.entries(s.contact.codes).map(([k,c])=>`<tr><td>${k}</td><td>${c}</td></tr>`).join("")}
|
||||
</table>
|
||||
<p class="muted">Отказы 503 — почтовый бэкенд сайта. 429 — квота на подсеть (3 / окно).</p>`;
|
||||
}
|
||||
if(tab==="jobs"){
|
||||
const s=await j("/api/status");
|
||||
v.innerHTML=`<div class="cards">${Object.keys(s.jobs).map(n=>`<div class="card">
|
||||
<span>${n}</span><b>${s.jobs[n]?s.jobs[n].pid:"idle"}</b>
|
||||
<div style="margin-top:8px">
|
||||
<input id="t_${n}" placeholder="target" style="width:70px;display:inline-block">
|
||||
<button onclick="start('${n}')">start</button>
|
||||
<button class="stop" onclick="stop('${n}')">stop</button>
|
||||
</div></div>`).join("")}</div>`;
|
||||
}
|
||||
if(tab==="log"){
|
||||
const s=await j("/api/log?name=contact");
|
||||
v.innerHTML=`<pre>${(s.tail||[]).map(l=>l.replace(/</g,"<")).join("\\n")||"empty"}</pre>`;
|
||||
}
|
||||
if(tab==="config"){
|
||||
const c=await j("/api/config");
|
||||
v.innerHTML=`<textarea id="cfg" rows="26">${JSON.stringify(c.config,null,2).replace(/</g,"<")}</textarea>
|
||||
<p><button onclick="saveCfg()">save</button> <span id="msg" class="muted"></span></p>`;
|
||||
}
|
||||
}
|
||||
async function start(n){const t=document.getElementById("t_"+n).value||10;
|
||||
const r=await j("/api/start",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({job:n,target:+t})});
|
||||
alert(r.message||"started");go("jobs")}
|
||||
async function stop(n){const r=await j("/api/stop",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({job:n})});
|
||||
alert(r.message||"stopped");go("jobs")}
|
||||
async function saveCfg(){const c=document.getElementById("cfg").value;
|
||||
const r=await j("/api/config",{method:"POST",headers:{"content-type":"application/json"},body:c});
|
||||
document.getElementById("msg").textContent=r.ok?"saved":"error: "+r.error}
|
||||
renderNav();draw();setInterval(()=>{if(tab==="overview")draw()},4000);
|
||||
</script></body></html>"""
|
||||
|
||||
|
||||
def read_jsonl(path, limit=None):
|
||||
rows = []
|
||||
if not os.path.exists(path):
|
||||
return rows
|
||||
with open(path, encoding="utf-8", errors="ignore") as fh:
|
||||
for line in fh:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
rows.append(json.loads(line))
|
||||
except Exception:
|
||||
continue
|
||||
return rows[-limit:] if limit else rows
|
||||
|
||||
|
||||
def stats_for(name):
|
||||
spec = JOBS[name]
|
||||
rows = read_jsonl(os.path.join(HOME, spec["log"]))
|
||||
if name == "mail":
|
||||
return {"attempts": len(rows), "accepted": sum(1 for r in rows if r.get("ok")),
|
||||
"sent": sum(1 for r in rows if r.get("ok")), "codes": {}}
|
||||
codes = {}
|
||||
for r in rows:
|
||||
k = str(r.get("code"))
|
||||
codes[k] = codes.get(k, 0) + 1
|
||||
return {"attempts": len(rows), "accepted": sum(1 for r in rows if r.get("ok")),
|
||||
"codes": codes}
|
||||
|
||||
|
||||
def job_state():
|
||||
out = {}
|
||||
with LOCK:
|
||||
for name, p in list(PROCS.items()):
|
||||
alive = p.poll() is None
|
||||
if not alive:
|
||||
PROCS.pop(name, None)
|
||||
continue
|
||||
out[name] = {"pid": p.pid, "alive": True}
|
||||
return out
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "form_intake-dashboard"
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def _send(self, code, body, ctype="application/json"):
|
||||
data = body if isinstance(body, bytes) else body.encode("utf-8")
|
||||
self.send_response(code)
|
||||
self.send_header("content-type", ctype)
|
||||
self.send_header("content-length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def _json(self, obj, code=200):
|
||||
self._send(code, json.dumps(obj, ensure_ascii=False))
|
||||
|
||||
def do_GET(self):
|
||||
path = urllib.parse.urlparse(self.path).path
|
||||
if path == "/":
|
||||
return self._send(200, INDEX, "text/html; charset=utf-8")
|
||||
if path == "/api/status":
|
||||
jobs = job_state()
|
||||
return self._json({
|
||||
"home": HOME,
|
||||
"running": list(jobs.keys()),
|
||||
"jobs": jobs,
|
||||
"contact": stats_for("contact"),
|
||||
"waitlist": stats_for("waitlist"),
|
||||
"mail": stats_for("mail"),
|
||||
})
|
||||
if path == "/api/config":
|
||||
p = os.path.join(HOME, "config.json")
|
||||
try:
|
||||
cfg = json.load(open(p, encoding="utf-8-sig"))
|
||||
except Exception as e:
|
||||
return self._json({"config": {}, "error": str(e)})
|
||||
return self._json({"config": cfg})
|
||||
if path == "/api/log":
|
||||
q = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
|
||||
name = (q.get("name") or ["contact"])[0]
|
||||
spec = JOBS.get(name, JOBS["contact"])
|
||||
p = os.path.join(HOME, spec["log"])
|
||||
tail = []
|
||||
if os.path.exists(p):
|
||||
with open(p, encoding="utf-8", errors="ignore") as fh:
|
||||
tail = [l.rstrip("\n") for l in fh][-60:]
|
||||
return self._json({"tail": tail})
|
||||
return self._json({"error": "not found"}, 404)
|
||||
|
||||
def do_POST(self):
|
||||
path = urllib.parse.urlparse(self.path).path
|
||||
n = int(self.headers.get("content-length") or 0)
|
||||
raw = self.rfile.read(n).decode("utf-8") if n else "{}"
|
||||
if path == "/api/start":
|
||||
try:
|
||||
body = json.loads(raw)
|
||||
except Exception:
|
||||
return self._json({"ok": False, "error": "bad json"}, 400)
|
||||
name = body.get("job")
|
||||
if name not in JOBS:
|
||||
return self._json({"ok": False, "error": "unknown job"}, 400)
|
||||
with LOCK:
|
||||
if name in PROCS and PROCS[name].poll() is None:
|
||||
return self._json({"ok": False, "message": "already running"})
|
||||
spec = JOBS[name]
|
||||
cmd = [sys.executable, "-u", os.path.join(HOME, spec["script"])]
|
||||
if spec["args"]:
|
||||
cmd += spec["args"]
|
||||
if name in ("contact", "waitlist"):
|
||||
cmd += ["--target", str(int(body.get("target") or 10)),
|
||||
"--out", os.path.join(HOME, spec["log"])]
|
||||
else:
|
||||
cmd += ["--n", str(int(body.get("target") or 20)),
|
||||
"--out", os.path.join(HOME, spec["log"])]
|
||||
logs = os.path.join(HOME, "logs")
|
||||
os.makedirs(logs, exist_ok=True)
|
||||
logf = open(os.path.join(logs, name + ".log"), "a", encoding="utf-8")
|
||||
p = subprocess.Popen(cmd, cwd=HOME, stdout=logf, stderr=logf, stdin=subprocess.DEVNULL)
|
||||
PROCS[name] = p
|
||||
return self._json({"ok": True, "message": "started pid %d" % p.pid})
|
||||
if path == "/api/stop":
|
||||
try:
|
||||
body = json.loads(raw)
|
||||
except Exception:
|
||||
return self._json({"ok": False}, 400)
|
||||
name = body.get("job")
|
||||
with LOCK:
|
||||
p = PROCS.pop(name, None)
|
||||
if not p or p.poll() is not None:
|
||||
return self._json({"ok": False, "message": "not running"})
|
||||
p.terminate()
|
||||
return self._json({"ok": True, "message": "stopped"})
|
||||
if path == "/api/config":
|
||||
try:
|
||||
cfg = json.loads(raw)
|
||||
json.dumps(cfg)
|
||||
except Exception as e:
|
||||
return self._json({"ok": False, "error": str(e)}, 400)
|
||||
p = os.path.join(HOME, "config.json")
|
||||
with open(p, "w", encoding="utf-8") as fh:
|
||||
json.dump(cfg, fh, indent=2, ensure_ascii=False)
|
||||
return self._json({"ok": True})
|
||||
return self._json({"ok": False, "error": "not found"}, 404)
|
||||
|
||||
|
||||
def main():
|
||||
global HOME
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--port", type=int, default=8765)
|
||||
ap.add_argument("--home", default=None)
|
||||
a = ap.parse_args()
|
||||
if a.home:
|
||||
HOME = os.path.abspath(a.home)
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", a.port), Handler)
|
||||
print("form_intake dashboard on http://127.0.0.1:%d (home=%s)" % (a.port, HOME), flush=True)
|
||||
srv.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+104
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python3
|
||||
"""mail_wave — grant applications straight to the intake mailbox.
|
||||
|
||||
Use it when the site form is broken (it answers 503 "your message could not be
|
||||
sent" while its transactional mail provider is down). The message body reuses
|
||||
the persona generator from form_intake.py.
|
||||
|
||||
SMTP credentials are yours: put them in config.json under "smtp" or in the
|
||||
environment (SMTP_HOST / SMTP_PORT / SMTP_USER / SMTP_PASS). Nothing is stored
|
||||
by this script.
|
||||
|
||||
python mail_wave.py --n 20 --pause 25 60
|
||||
"""
|
||||
import argparse
|
||||
import email.utils
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import smtplib
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from form_intake import load_config, persona # noqa: E402
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
SUBJECTS = [
|
||||
"Grant application - {org} - {chain} hackathon",
|
||||
"Grant application - {org} - {chain} security build",
|
||||
"Grant request: {org} ({chain})",
|
||||
"Grant application, {org}, {chain}",
|
||||
]
|
||||
|
||||
|
||||
def smtp_settings(cfg):
|
||||
s = cfg.get("smtp") or {}
|
||||
return {
|
||||
"host": s.get("host") or os.environ.get("SMTP_HOST", "smtp.gmail.com"),
|
||||
"port": int(s.get("port") or os.environ.get("SMTP_PORT", 587)),
|
||||
"user": s.get("user") or os.environ.get("SMTP_USER", ""),
|
||||
"pass": s.get("pass") or os.environ.get("SMTP_PASS", ""),
|
||||
}
|
||||
|
||||
|
||||
def build(per):
|
||||
subj = random.choice(SUBJECTS).format(org=per["organization"], chain=per["chain"])
|
||||
body = ("Hello,\n\n"
|
||||
"The grant form answers \"Your message could not be sent\" right now, "
|
||||
"so sending the application by mail as that error suggests.\n\n"
|
||||
+ per["message"] + "\n\n"
|
||||
"We can share the test plan, target ownership proof and reporting format on request.\n\n"
|
||||
"Regards,\n" + per["name"] + "\n" + per["organization"] + "\n")
|
||||
return subj, body
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--config", default="config.json")
|
||||
ap.add_argument("--n", type=int, default=20)
|
||||
ap.add_argument("--to", default="")
|
||||
ap.add_argument("--pause", type=float, nargs=2, default=[25, 60])
|
||||
ap.add_argument("--out", default="mail.jsonl")
|
||||
a = ap.parse_args()
|
||||
cfg = load_config(a.config)
|
||||
s = smtp_settings(cfg)
|
||||
to = a.to or cfg.get("mail_to") or ""
|
||||
if not (s["user"] and s["pass"] and to):
|
||||
print("missing smtp credentials or recipient; set them in config.json or env")
|
||||
return 2
|
||||
sent = 0
|
||||
for i in range(a.n):
|
||||
per = persona(cfg)
|
||||
subj, body = build(per)
|
||||
msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n"
|
||||
"MIME-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n%s") % (
|
||||
s["user"], to, subj, email.utils.formatdate(localtime=True), body)
|
||||
rec = {"ts": int(time.time()), "to": to, "org": per["organization"],
|
||||
"tier": per["tier"], "chain": per["chain"], "subject": subj}
|
||||
try:
|
||||
c = smtplib.SMTP(s["host"], s["port"], timeout=30)
|
||||
c.ehlo()
|
||||
c.starttls(context=ssl.create_default_context())
|
||||
c.ehlo()
|
||||
c.login(s["user"], s["pass"])
|
||||
c.sendmail(s["user"], [to], msg.encode("utf-8"))
|
||||
c.quit()
|
||||
sent += 1
|
||||
rec["ok"] = True
|
||||
print("[%d] sent %s $%s" % (i + 1, per["organization"], per["tier"]), flush=True)
|
||||
except Exception as e:
|
||||
rec["ok"] = False
|
||||
rec["err"] = str(e)[:160]
|
||||
print("[%d] fail %s" % (i + 1, str(e)[:90]), flush=True)
|
||||
with open(a.out, "a", encoding="utf-8") as fh:
|
||||
fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
||||
time.sleep(random.uniform(*a.pause))
|
||||
print(json.dumps({"sent": sent, "of": a.n}))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user