Gregory-L Professor Codephreak commited on
Commit
c2caad6
·
verified ·
1 Parent(s): e940395

Security: bound LUV credit, escape answers in the copy button, harden drAIML.dmind (router 0.3.0)

Browse files

Fixes from a code review of the Space.

Critical
- Router: credit came straight from the worker's own usage.completion_tokens, and a receipt is only a hash the worker computes itself, so one worker could mint any amount. Credit is now capped at the job's max_tokens and the answer's length, zero when the asker's IP is the worker's, and limited to 150,000 tokens per wallet per day.
- Copy button: the answer was embedded in a <script> block with json.dumps, so an answer containing </script> (from any worker or any model) could run script on the Space's origin and read the HF sign-in token. <, >, & and line separators are now escaped.

Important
- Cross-checks go to a different session, IP and wallet. A disagreement goes to a third worker, and only the odd one out is struck. Strikes are kept per wallet and IP, and copies earn credit only once they agree.
- Sign-in: messages are limited to 1 KB, nonce and verify requests to 10 per minute per IP, and each address to 3 open codes. The oldest code is evicted instead of locking everyone out.
- X-Forwarded-For: the router now uses the last entry, the one Apache appends, so the rate limit can no longer be bypassed with a forged header.
- HTTP layer: a body timeout, a connection cap, a per-IP cap on worker sessions, malformed requests answered with 400 instead of a traceback, exact CORS origins, CR/LF dropped from headers, and earnings summed in memory.
- Donor client: a stop followed by a start no longer leaves two loops running. The pause conditions are checked again after the long poll, and the browser counts what the host credited.

Minor
- Installers: on macOS, a running Firefox is detected by its process. PowerShell writes the Firefox files without a BOM and no longer needs 7.3 or later.

Tests: 51 Python tests, including new abuse cases (inflated counts, self-serving, daily ceiling, tie-break strikes, sign-in limits, malformed requests, session caps), plus 24 PowerShell checks.

Co-Authored-By: Professor Codephreak <codephreak@pythai.net>

app/draiml/share.py CHANGED
@@ -31,6 +31,13 @@ def response_text(m: dict, question: str = "") -> str:
31
  return "\n".join(lines)
32
 
33
 
 
 
 
 
 
 
 
34
  def _copy_button(text: str, dark: bool) -> None:
35
  fg, bd, bg = ("#e3efee", "#2c4a48", "#13201f") if dark else ("#12302f", "#cfdcdb", "#ffffff")
36
  components.html(f"""
@@ -39,7 +46,7 @@ def _copy_button(text: str, dark: bool) -> None:
39
  style="font:14px 'Source Sans 3',system-ui,sans-serif;color:{fg};background:{bg};border:1px solid {bd};
40
  border-radius:8px;padding:4px 10px;cursor:pointer;width:100%;height:40px;box-sizing:border-box">⧉ Copy</button>
41
  <script>
42
- const t = {json.dumps(text)};
43
  const b = document.getElementById('b');
44
  b.onclick = async () => {{
45
  try {{ await navigator.clipboard.writeText(t); }}
 
31
  return "\n".join(lines)
32
 
33
 
34
+ def script_literal(text: str) -> str:
35
+ """A JS string literal safe inside an HTML <script> block. json.dumps alone lets a model's answer containing
36
+ "</script>" close the block and run its own HTML on the Space's origin (where the HF sign-in token lives)."""
37
+ return (json.dumps(text).replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")
38
+ .replace("\u2028", "\\u2028").replace("\u2029", "\\u2029"))
39
+
40
+
41
  def _copy_button(text: str, dark: bool) -> None:
42
  fg, bd, bg = ("#e3efee", "#2c4a48", "#13201f") if dark else ("#12302f", "#cfdcdb", "#ffffff")
43
  components.html(f"""
 
46
  style="font:14px 'Source Sans 3',system-ui,sans-serif;color:{fg};background:{bg};border:1px solid {bd};
47
  border-radius:8px;padding:4px 10px;cursor:pointer;width:100%;height:40px;box-sizing:border-box">⧉ Copy</button>
48
  <script>
49
+ const t = {script_literal(text)};
50
  const b = document.getElementById('b');
51
  b.onclick = async () => {{
52
  try {{ await navigator.clipboard.writeText(t); }}
dmind.js CHANGED
@@ -143,13 +143,18 @@ export class Donor {
143
  }
144
  async rest(ms) { await Promise.race([sleep(ms), new Promise((r) => { this.wake = r; })]); this.wake = null; }
145
  async start() {
 
 
 
 
146
  this.running = true;
147
  try { this.battery = navigator.getBattery ? await navigator.getBattery() : null; } catch { this.battery = null; }
148
  const h = await this.config();
 
149
  if (!h.url) { this.state = "waiting"; this.note = `${h.label} is not open yet: your pledge of ${this.ledger.pct}% is saved and sharing starts when it opens.`; this.running = false; this.emit(); return; }
150
  const b = await this.engine();
151
  let backoff = 0;
152
- while (this.running) {
153
  try {
154
  const why = this.pauseReason();
155
  if (why) { if (this.state !== "paused") { this.state = "paused"; this.emit(); } this.note = why; if (this.session) await this.call("/sharedcpu/update", { session: this.session, paused: true }).catch(() => {}); await this.rest(5000); continue; }
@@ -163,24 +168,29 @@ export class Donor {
163
  }
164
  if (this.state !== "sharing") { this.state = "sharing"; this.emit(); }
165
  this.note = `lending ${this.ledger.pct}% to ${h.label}`;
166
- const got = await this.call("/sharedcpu/pull", { session: this.session });
 
 
167
  if (got.barred || got.final) throw Object.assign(new Error(got.reason || "stopped by the host"), { final: true });
168
  if (!got.ok) { if (/session/.test(String(got.reason))) this.session = ""; await this.rest(got.retry_after_s ? got.retry_after_s * 1000 : 5000); continue; }
169
  const job = got.job; if (!job) continue;
170
  if (job.max_tokens > this.ledger.jobTokens) job.max_tokens = this.ledger.jobTokens; // the visitor's RAM limit
171
- if (this.busy()) { await this.call("/sharedcpu/decline", { session: this.session, job: job.job, reason: "the visitor is asking" }).catch(() => {}); continue; }
 
 
172
  let cancelled = false;
173
- const beat = setInterval(() => { this.call("/sharedcpu/update", { session: this.session }).then((u) => { if (u.cancelled === job.job) cancelled = true; }).catch(() => {}); }, 30000);
174
  const t0 = performance.now(); let text = "", res;
175
  try { res = await b.chat({ messages: job.messages, max_tokens: job.max_tokens, temperature: job.temperature }, (p) => { text += p; }); }
176
  finally { clearInterval(beat); }
177
  const ms = performance.now() - t0;
178
  if (cancelled) continue;
179
  const rc = res && res.bankml_receipt;
180
- if (!rc || (await sha256hex(text)) !== rc.response_sha256) { await this.call("/sharedcpu/fail", { session: this.session, job: job.job, reason: "receipt did not match" }).catch(() => {}); continue; }
181
- const r = await this.call("/sharedcpu/result", { session: this.session, job: job.job, text, receipt: rc, usage: res.usage, timings: res.timings });
182
  if (r.ok) {
183
- const n = BigInt((res.usage && res.usage.completion_tokens) || 0);
 
184
  this.ledger.tokens += n; this.ledger.jobs++; this.ledger.engineMs += Math.round(ms); writeLedger(this.ledger);
185
  const t = res.timings || {};
186
  Object.assign(this.m, { engineMs: this.m.engineMs + ms, jobs: this.m.jobs + 1, tokens: this.m.tokens + Number(n),
@@ -196,9 +206,10 @@ export class Donor {
196
  await this.rest(backoff);
197
  }
198
  }
199
- this.running = false;
200
  }
201
  stop() {
 
202
  this.running = false; this.state = "off"; this.note = ""; this.emit();
203
  if (this.session) { this.call("/sharedcpu/leave", { session: this.session }, true).catch(() => {}); this.session = ""; }
204
  if (this.wake) this.wake();
 
143
  }
144
  async rest(ms) { await Promise.race([sleep(ms), new Promise((r) => { this.wake = r; })]); this.wake = null; }
145
  async start() {
146
+ // each run has a generation: a stop() followed by a start() (sign-in, sign-out, GPU change) must not leave the old
147
+ // loop running beside the new one
148
+ const gen = this.gen = (this.gen || 0) + 1;
149
+ const live = () => this.running && gen === this.gen;
150
  this.running = true;
151
  try { this.battery = navigator.getBattery ? await navigator.getBattery() : null; } catch { this.battery = null; }
152
  const h = await this.config();
153
+ if (!live()) return;
154
  if (!h.url) { this.state = "waiting"; this.note = `${h.label} is not open yet: your pledge of ${this.ledger.pct}% is saved and sharing starts when it opens.`; this.running = false; this.emit(); return; }
155
  const b = await this.engine();
156
  let backoff = 0;
157
+ while (live()) {
158
  try {
159
  const why = this.pauseReason();
160
  if (why) { if (this.state !== "paused") { this.state = "paused"; this.emit(); } this.note = why; if (this.session) await this.call("/sharedcpu/update", { session: this.session, paused: true }).catch(() => {}); await this.rest(5000); continue; }
 
168
  }
169
  if (this.state !== "sharing") { this.state = "sharing"; this.emit(); }
170
  this.note = `lending ${this.ledger.pct}% to ${h.label}`;
171
+ const sess = this.session;
172
+ const got = await this.call("/sharedcpu/pull", { session: sess });
173
+ if (!live()) { if (got.job) await this.call("/sharedcpu/decline", { session: sess, job: got.job.job, reason: "stopped" }).catch(() => {}); break; }
174
  if (got.barred || got.final) throw Object.assign(new Error(got.reason || "stopped by the host"), { final: true });
175
  if (!got.ok) { if (/session/.test(String(got.reason))) this.session = ""; await this.rest(got.retry_after_s ? got.retry_after_s * 1000 : 5000); continue; }
176
  const job = got.job; if (!job) continue;
177
  if (job.max_tokens > this.ledger.jobTokens) job.max_tokens = this.ledger.jobTokens; // the visitor's RAM limit
178
+ // the long poll can last 25 s: the tab may have been hidden or the charger unplugged meanwhile
179
+ const late = this.pauseReason();
180
+ if (late) { await this.call("/sharedcpu/decline", { session: sess, job: job.job, reason: late }).catch(() => {}); continue; }
181
  let cancelled = false;
182
+ const beat = setInterval(() => { this.call("/sharedcpu/update", { session: sess }).then((u) => { if (u.cancelled === job.job) cancelled = true; }).catch(() => {}); }, 30000);
183
  const t0 = performance.now(); let text = "", res;
184
  try { res = await b.chat({ messages: job.messages, max_tokens: job.max_tokens, temperature: job.temperature }, (p) => { text += p; }); }
185
  finally { clearInterval(beat); }
186
  const ms = performance.now() - t0;
187
  if (cancelled) continue;
188
  const rc = res && res.bankml_receipt;
189
+ if (!rc || (await sha256hex(text)) !== rc.response_sha256) { await this.call("/sharedcpu/fail", { session: sess, job: job.job, reason: "receipt did not match" }).catch(() => {}); continue; }
190
+ const r = await this.call("/sharedcpu/result", { session: sess, job: job.job, text, receipt: rc, usage: res.usage, timings: res.timings });
191
  if (r.ok) {
192
+ // count what the host credited (it bounds the claim, and answering your own question earns nothing)
193
+ const n = BigInt(r.credited_tokens ?? ((res.usage && res.usage.completion_tokens) || 0));
194
  this.ledger.tokens += n; this.ledger.jobs++; this.ledger.engineMs += Math.round(ms); writeLedger(this.ledger);
195
  const t = res.timings || {};
196
  Object.assign(this.m, { engineMs: this.m.engineMs + ms, jobs: this.m.jobs + 1, tokens: this.m.tokens + Number(n),
 
206
  await this.rest(backoff);
207
  }
208
  }
209
+ if (gen === this.gen) this.running = false;
210
  }
211
  stop() {
212
+ this.gen = (this.gen || 0) + 1;
213
  this.running = false; this.state = "off"; this.note = ""; this.emit();
214
  if (this.session) { this.call("/sharedcpu/leave", { session: this.session }, true).catch(() => {}); this.session = ""; }
215
  if (this.wake) this.wake();
router/README.md CHANGED
@@ -29,18 +29,31 @@ a ledger, and hands every question to someone who lends compute.
29
  - Declined jobs are re-queued without counting a try (the donor's own question came first).
30
  - A failed job counts a try.
31
  - If the client gives up, the job is withdrawn (`cancelled` on the next heartbeat).
32
- - **Trust:** a bad receipt is refused and the job re-queued.
33
- - 5% of temperature-0 jobs also go to a second worker; members of one engine group must agree token for token.
34
- - Three strikes bar a worker.
 
 
 
 
 
 
 
35
  - **Ledger:** `ledger.jsonl` records wallet, job, tokens, `luv_wei` (1 SHAMBA LUV = 10^18 wei per generated token,
36
  dmind's paymint rule, SCIEN·TIFIC 18-decimal measurement) and the answer's sha256.
37
  - `GET /sharedcpu/me?wallet=0x…` sums it.
38
  - The router signs and pays nothing: payout is a separate, operator-run step.
39
  - **Visibility:** `GET /health` and `GET /insight/sharedcpu` (workers, lending, queue, counters); `GET /v1/models`.
40
  - **Abuse limits:**
41
- - Open clients get 6 requests per minute per IP (or pass `--keys` for keyed clients).
42
- - Queue cap 64, request body 64 KB.
43
- - CORS only for drAIML's origins.
 
 
 
 
 
 
44
 
45
  ## login333 · drAIML sign-in, earnings and payouts
46
  - `GET /auth/nonce?address=0x…` issues a one-time code, valid for 5 minutes.
 
29
  - Declined jobs are re-queued without counting a try (the donor's own question came first).
30
  - A failed job counts a try.
31
  - If the client gives up, the job is withdrawn (`cancelled` on the next heartbeat).
32
+ - **Trust:** a receipt shows only that the text hashes to what the worker said. The worker holds no key, so a receipt is
33
+ not proof of work, and credit is bounded by what the router itself can see:
34
+ - Tokens credited are capped at the job's `max_tokens` and at the answer's length in characters.
35
+ - Answering a question asked from your own IP earns nothing.
36
+ - Each wallet has a daily ceiling of 150,000 tokens.
37
+ - A bad receipt is refused, the job is re-queued and the worker gets a strike.
38
+ - 5% of temperature-0 jobs also go to a second worker with a different session, IP and wallet. If the two disagree, a
39
+ third worker breaks the tie and the odd one out gets a strike. A copy earns credit only once it agrees with someone.
40
+ - Strikes are kept per wallet and per IP, so a new session does not clear them. Three bar the worker.
41
+ - Payout stays a human step: the operator reviews claims before paying.
42
  - **Ledger:** `ledger.jsonl` records wallet, job, tokens, `luv_wei` (1 SHAMBA LUV = 10^18 wei per generated token,
43
  dmind's paymint rule, SCIEN·TIFIC 18-decimal measurement) and the answer's sha256.
44
  - `GET /sharedcpu/me?wallet=0x…` sums it.
45
  - The router signs and pays nothing: payout is a separate, operator-run step.
46
  - **Visibility:** `GET /health` and `GET /insight/sharedcpu` (workers, lending, queue, counters); `GET /v1/models`.
47
  - **Abuse limits:**
48
+ - Open clients get 6 requests per minute per IP (or pass `--keys` for keyed clients). The client IP is the last
49
+ X-Forwarded-For entry, the one Apache appends.
50
+ - Sign-in: 10 nonce or verify requests per minute per IP, messages of at most 1 KB, 3 open codes per address, and
51
+ the oldest code is evicted when the table is full.
52
+ - Workers: 8 sessions per IP, 512 in all.
53
+ - Connections and requests: 256 connections at once, a 15 s limit to send headers and another to send the body, a
54
+ 64 KB body cap, and a queue cap of 64. Malformed requests get a 400.
55
+ - CORS only for drAIML's exact origins, plus `http://127.0.0.1` / `localhost` on any port for development.
56
+ - Earnings are summed in memory, not by re-reading the ledger.
57
 
58
  ## login333 · drAIML sign-in, earnings and payouts
59
  - `GET /auth/nonce?address=0x…` issues a one-time code, valid for 5 minutes.
router/draiml_router.py CHANGED
@@ -35,6 +35,7 @@ import hmac
35
  import json
36
  import os
37
  import random
 
38
  import secrets
39
  import time
40
  from dataclasses import dataclass, field
@@ -43,7 +44,7 @@ from urllib.parse import parse_qs, urlsplit
43
 
44
  import siwe
45
 
46
- VERSION = "0.2.0"
47
  HOST_LABEL = "drAIML.dmind"
48
  BONSAI_SHA256 = "3d7c6c90dd98717a203adb22d5eacd2581850e40aa5327e144b97766cae5f7e3"
49
  MODELS = { # what workers may serve: name -> pinned sha256 and engine group (members must agree token for token)
@@ -63,6 +64,17 @@ RATE = (6, 60) # client requests per IP: 6 per 60 s
63
  WEI_PER_TOKEN = 10**18 # 1 SHAMBA LUV per generated token
64
  SIWE_DOMAINS = ("pythai-draiml.static.hf.space", "127.0.0.1:8766", "localhost:8766")
65
  TOKEN_DAYS = 7
 
 
 
 
 
 
 
 
 
 
 
66
 
67
 
68
  def now() -> float:
@@ -98,9 +110,10 @@ class Job:
98
  holder: str = ""
99
  lease_until: float = 0.0
100
  done: asyncio.Future | None = None
 
101
  check_of: str = "" # a cross-check copy points at its original
102
- check_text: str | None = None
103
- check_worker: str = ""
104
 
105
 
106
  class Router:
@@ -120,8 +133,13 @@ class Router:
120
  self.ledger_path = ledger_path
121
  self.keys = self._load_keys(keys_path)
122
  self.rate: dict[str, collections.deque] = {}
 
123
  self.stats = collections.Counter()
124
  self.started = time.time()
 
 
 
 
125
 
126
  # ── helpers ──────────────────────────────────────────────────────────────────────────────────────────────────
127
  @staticmethod
@@ -131,20 +149,70 @@ class Router:
131
  with open(path) as f:
132
  return {line.strip() for line in f if line.strip() and not line.startswith("#")}
133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  def _ledger(self, entry: dict) -> None:
135
  with open(self.ledger_path, "a") as f:
136
  f.write(json.dumps(entry, separators=(",", ":")) + "\n")
 
137
 
138
- def _limited(self, ip: str) -> bool:
139
- q = self.rate.setdefault(ip, collections.deque())
140
  t = now()
141
- while q and t - q[0] > RATE[1]:
142
  q.popleft()
143
- if len(q) >= RATE[0]:
144
  return True
145
  q.append(t)
146
  return False
147
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  def _wake_one(self) -> None:
149
  for w in self.workers.values():
150
  if w.waiter and not w.waiter.done() and not w.paused:
@@ -159,8 +227,9 @@ class Router:
159
  if j.model != w.model:
160
  self.queue.append(j)
161
  continue
162
- if j.check_of and j.check_worker == w.session:
163
- self.queue.append(j) # a cross-check must go to another worker
 
164
  continue
165
  j.holder, j.lease_until, j.tries = w.session, now() + LEASE_S, j.tries + 1
166
  return j
@@ -186,7 +255,13 @@ class Router:
186
  if t - w.seen > SESSION_TTL_S:
187
  self.workers.pop(s, None)
188
  self.stats["workers_dropped"] += 1
 
 
 
189
  for j in list(self.jobs.values()):
 
 
 
190
  if j.holder and (t > j.lease_until or j.holder not in self.workers):
191
  self._requeue(j, "lease expired")
192
  elif not j.holder and j.done is not None and j.done.done() and not j.check_of:
@@ -198,6 +273,8 @@ class Router:
198
  model = next((m for m, v in MODELS.items() if v["sha256"] == sha), None)
199
  if not model:
200
  return {"ok": False, "reason": "this host serves only pinned models", "models": MODELS}
 
 
201
  s = secrets.token_hex(16) # the wallet comes only from a login333 · drAIML sign-in
202
  self.workers[s] = Worker(s, model, str(b.get("engine", ""))[:40], max(1, min(100, int(b.get("share_pct") or 10))),
203
  wallet, str(b.get("contributor", ""))[:20], ip)
@@ -234,7 +311,7 @@ class Router:
234
  w = self._worker(b)
235
  if not w:
236
  return {"ok": False, "reason": "unknown session"}
237
- if w.strikes >= 3:
238
  return {"ok": False, "barred": True, "reason": "answers did not match other workers"}
239
  w.paused = False
240
  j = self._take(w)
@@ -259,42 +336,76 @@ class Router:
259
  if not w or not j or j.holder != w.session:
260
  return {"ok": False, "reason": "not your job (lease expired?)"}
261
  text, rc, usage = str(b.get("text", "")), b.get("receipt") or {}, b.get("usage") or {}
 
 
262
  good = (hashlib.sha256(text.encode()).hexdigest() == rc.get("response_sha256")
263
  and str(rc.get("model_sha256", "")).lower() == MODELS[j.model]["sha256"])
264
  if not good:
265
  w.strikes += 1
 
266
  self._requeue(j, "receipt did not match")
267
  self.stats["receipts_bad"] += 1
268
  return {"ok": False, "reason": "the receipt does not match the text or the pinned model"}
269
- tokens = max(0, int(usage.get("completion_tokens") or 0))
270
  w.jobs += 1
271
- w.tokens += tokens
272
  self.stats["jobs_done"] += 1
 
 
 
 
273
  self.stats["tokens"] += tokens
274
  self._ledger({"t": int(time.time()), "host": HOST_LABEL, "wallet": w.wallet, "job": j.id, "tokens": tokens,
275
  "luv_wei": str(tokens * WEI_PER_TOKEN), "response_sha256": rc.get("response_sha256"),
276
- "engine": w.engine, "check": bool(j.check_of)})
277
- j.holder = ""
278
- if j.check_of: # a cross-check copy: compare with the original's answer
279
- if j.check_text != text:
280
- for s in (w.session, j.check_worker):
281
- if s in self.workers:
282
- self.workers[s].strikes += 1
283
- self.stats["cross_mismatch"] += 1
284
- else:
285
- self.stats["cross_match"] += 1
286
- self.jobs.pop(j.id, None)
287
- return {"ok": True, "credited_tokens": tokens, "luv_wei": str(tokens * WEI_PER_TOKEN), "audit": "cross-check"}
288
  if j.done and not j.done.done():
289
  j.done.set_result({"text": text, "receipt": rc, "usage": usage, "timings": b.get("timings") or {},
290
  "worker": {"engine": w.engine, "contributor": w.contributor}})
291
- if j.temperature == 0 and random.random() < CROSS_CHECK and len(self.workers) > 1:
 
292
  c = Job(secrets.token_hex(8), j.model, j.messages, j.max_tokens, 0.0, check_of=j.id,
293
- check_text=text, check_worker=w.session)
294
  self.jobs[c.id] = c
295
  self.queue.append(c)
296
  self._wake_one()
297
- return {"ok": True, "credited_tokens": tokens, "luv_wei": str(tokens * WEI_PER_TOKEN), "audit": "receipt"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
 
299
  def decline(self, b: dict, failed: bool = False) -> dict:
300
  w = self._worker(b)
@@ -331,6 +442,7 @@ class Router:
331
  return 503, {"error": {"message": "the queue is full; try again soon"}}
332
  j = Job(secrets.token_hex(8), model, msgs, max(1, min(MAX_TOKENS, int(b.get("max_tokens") or 400))),
333
  float(b.get("temperature") if b.get("temperature") is not None else 0.3))
 
334
  j.done = asyncio.get_running_loop().create_future()
335
  self.jobs[j.id] = j
336
  self.queue.append(j)
@@ -354,14 +466,17 @@ class Router:
354
  def nonce(self, address: str) -> dict:
355
  if not (address.startswith("0x") and len(address) == 42):
356
  return {"ok": False, "reason": "an Ethereum address is required"}
357
- t = now()
358
  for k, (_, exp) in list(self.nonces.items()):
359
  if exp < t:
360
  self.nonces.pop(k, None)
361
- if len(self.nonces) > 2000:
362
- return {"ok": False, "reason": "too many sign-ins in progress; try again soon"}
 
 
 
363
  n = secrets.token_hex(8)
364
- self.nonces[n] = (address.lower(), t + 300)
365
  return {"ok": True, "nonce": n, "expires_s": 300, "domains": SIWE_DOMAINS, "chain_id": 1}
366
 
367
  def _token(self, address: str) -> str:
@@ -380,6 +495,8 @@ class Router:
380
 
381
  def verify(self, b: dict) -> dict:
382
  msg, sig = str(b.get("message", "")), str(b.get("signature", ""))
 
 
383
  try:
384
  f = siwe.parse_siwe(msg)
385
  except ValueError as e:
@@ -402,24 +519,32 @@ class Router:
402
  return {"ok": True, "address": signer, "token": self._token(signer), "expires_days": TOKEN_DAYS}
403
 
404
  # ── earnings and payout claims ──────────────────────────────────────────────────────────────────────────────
405
- def _claims(self, wallet: str) -> tuple[int, int, list]:
406
- claimed = paid = 0
407
- rows: dict[str, dict] = {}
408
- if os.path.exists(self.claims_path):
 
 
 
 
409
  with open(self.claims_path) as f:
410
  for line in f:
411
  try:
412
  e = json.loads(line)
413
- except ValueError:
414
- continue
415
- if e.get("wallet", "").lower() != wallet.lower():
416
  continue
417
- rows.setdefault(e["id"], {}).update(e)
418
- for c in rows.values():
 
 
 
 
 
419
  claimed += int(c.get("luv_wei", 0))
420
  if c.get("status") == "paid":
421
  paid += int(c.get("luv_wei", 0))
422
- return claimed, paid, sorted(rows.values(), key=lambda c: c.get("t", 0))[-10:]
423
 
424
  def claim(self, wallet: str) -> dict:
425
  if not wallet:
@@ -441,28 +566,18 @@ class Router:
441
  "queue": len(self.queue), "models": list(MODELS), "stats": dict(self.stats)}
442
 
443
  def me(self, wallet: str) -> dict:
444
- tokens = jobs = wei = 0
445
- if wallet and os.path.exists(self.ledger_path):
446
- with open(self.ledger_path) as f:
447
- for line in f:
448
- try:
449
- e = json.loads(line)
450
- except ValueError:
451
- continue
452
- if e.get("wallet", "").lower() == wallet.lower():
453
- tokens += int(e.get("tokens", 0))
454
- wei += int(e.get("luv_wei", int(e.get("tokens", 0)) * WEI_PER_TOKEN)) # the rate when it was earned
455
- jobs += 1
456
  claimed, paid, claims = self._claims(wallet) if wallet else (0, 0, [])
457
  f18 = lambda x: f"{x // 10**18}.{x % 10**18:018d}" # noqa: E731
458
  return {"wallet": wallet, "jobs": jobs, "tokens": tokens, "luv_wei": str(wei), "luv": f18(wei),
459
  "claimed_wei": str(claimed), "paid_wei": str(paid), "available_wei": str(wei - claimed),
460
- "available": f18(wei - claimed), "claims": claims, "rule": "1 SHAMBA LUV per generated token"}
 
461
 
462
 
463
  # ── a minimal HTTP/1.1 server (stdlib asyncio) ───────────────────────────────────────────────────────────────────
464
  def cors(origin: str) -> dict:
465
- if origin in ALLOWED_ORIGINS or origin.endswith(".hf.space") or origin.startswith("http://127.0.0.1"):
466
  return {"Access-Control-Allow-Origin": origin, "Vary": "Origin",
467
  "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
468
  "Access-Control-Allow-Headers": "authorization, content-type",
@@ -470,7 +585,25 @@ def cors(origin: str) -> dict:
470
  return {}
471
 
472
 
 
 
 
473
  async def handle(router: Router, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, trust_proxy: bool):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474
  try:
475
  head = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), 15)
476
  except (asyncio.TimeoutError, asyncio.IncompleteReadError, asyncio.LimitOverrunError, ConnectionError):
@@ -482,23 +615,35 @@ async def handle(router: Router, reader: asyncio.StreamReader, writer: asyncio.S
482
  except ValueError:
483
  writer.close()
484
  return
485
- h = {k.strip().lower(): v.strip() for k, v in (ln.split(":", 1) for ln in lines[1:] if ":" in ln)}
486
- n = int(h.get("content-length") or 0)
487
  status, out, extra = 200, {}, {}
488
- ip = (h.get("x-forwarded-for", "").split(",")[0].strip() if trust_proxy else "") or \
 
489
  (writer.get_extra_info("peername") or ("?",))[0]
490
- path = urlsplit(target).path.rstrip("/") or "/"
491
- for prefix in ("/draiml-dmind",): # served under a path on a shared vhost
492
- if path.startswith(prefix):
493
- path = path[len(prefix):] or "/"
494
  try:
 
 
 
 
 
 
 
495
  if n > MAX_BODY:
496
  status, out = 413, {"error": "request too large"}
497
  elif method == "OPTIONS":
498
  status = 204
499
  else:
500
- body = json.loads(await reader.readexactly(n)) if n else {}
501
- stream = bool(body.get("stream")) if isinstance(body, dict) else False
 
 
 
 
 
 
 
502
  if method == "GET" and path in ("/", "/health", "/sharedcpu/health"):
503
  out = {"ok": True, "host": HOST_LABEL, "version": VERSION}
504
  elif method == "GET" and path == "/insight/sharedcpu":
@@ -509,9 +654,15 @@ async def handle(router: Router, reader: asyncio.StreamReader, writer: asyncio.S
509
  out = router.me(router.wallet_of(h.get("authorization", ""))
510
  or parse_qs(urlsplit(target).query).get("wallet", [""])[0])
511
  elif method == "GET" and path == "/auth/nonce":
512
- out = router.nonce(parse_qs(urlsplit(target).query).get("address", [""])[0])
 
 
 
513
  elif method == "POST" and path == "/auth/verify":
514
- out = router.verify(body)
 
 
 
515
  elif method == "POST" and path == "/sharedcpu/claim":
516
  out = router.claim(router.wallet_of(h.get("authorization", "")))
517
  elif method == "POST" and path == "/sharedcpu/join":
 
35
  import json
36
  import os
37
  import random
38
+ import re
39
  import secrets
40
  import time
41
  from dataclasses import dataclass, field
 
44
 
45
  import siwe
46
 
47
+ VERSION = "0.3.0"
48
  HOST_LABEL = "drAIML.dmind"
49
  BONSAI_SHA256 = "3d7c6c90dd98717a203adb22d5eacd2581850e40aa5327e144b97766cae5f7e3"
50
  MODELS = { # what workers may serve: name -> pinned sha256 and engine group (members must agree token for token)
 
64
  WEI_PER_TOKEN = 10**18 # 1 SHAMBA LUV per generated token
65
  SIWE_DOMAINS = ("pythai-draiml.static.hf.space", "127.0.0.1:8766", "localhost:8766")
66
  TOKEN_DAYS = 7
67
+ DAILY_TOKENS = 150_000 # credit ceiling per wallet per UTC day (about a full day of a fast donor at 50%)
68
+ SIWE_MAX = 1024 # a sign-in message is a few hundred bytes; hashing big ones in pure Python is a CPU sink
69
+ AUTH_RATE = (10, 60) # /auth/nonce and /auth/verify per IP
70
+ NONCES_PER_ADDRESS = 3
71
+ MAX_NONCES = 2000
72
+ MAX_WORKERS = 512
73
+ WORKERS_PER_IP = 8
74
+ MAX_CONNECTIONS = 256
75
+ BODY_TIMEOUT_S = 15
76
+ STRIKES_BAR = 3
77
+ _ORIGIN_DEV = re.compile(r"^http://(127\.0\.0\.1|localhost)(:\d{1,5})?$")
78
 
79
 
80
  def now() -> float:
 
110
  holder: str = ""
111
  lease_until: float = 0.0
112
  done: asyncio.Future | None = None
113
+ client_ip: str = ""
114
  check_of: str = "" # a cross-check copy points at its original
115
+ compare: dict = field(default_factory=dict) # cross-check: session -> answer, original first
116
+ who: dict = field(default_factory=dict) # cross-check: session -> (wallet, ip, engine)
117
 
118
 
119
  class Router:
 
133
  self.ledger_path = ledger_path
134
  self.keys = self._load_keys(keys_path)
135
  self.rate: dict[str, collections.deque] = {}
136
+ self.strikes = collections.Counter() # by "w:<wallet>" and "ip:<ip>": rejoining does not clear them
137
  self.stats = collections.Counter()
138
  self.started = time.time()
139
+ self.totals: dict[str, list] = {} # wallet -> [tokens, wei, jobs]; loaded once, kept current
140
+ self.daily: dict[tuple, int] = {} # (wallet, utc day) -> tokens credited
141
+ self._load_totals()
142
+ self._claims_cache: tuple[float, dict] = (-1.0, {})
143
 
144
  # ── helpers ──────────────────────────────────────────────────────────────────────────────────────────────────
145
  @staticmethod
 
149
  with open(path) as f:
150
  return {line.strip() for line in f if line.strip() and not line.startswith("#")}
151
 
152
+ def _load_totals(self) -> None:
153
+ if not os.path.exists(self.ledger_path):
154
+ return
155
+ with open(self.ledger_path) as f:
156
+ for line in f:
157
+ try:
158
+ self._count(json.loads(line))
159
+ except (ValueError, TypeError, AttributeError):
160
+ continue
161
+
162
+ def _count(self, e: dict) -> None:
163
+ wallet = str(e.get("wallet", "")).lower()
164
+ if not wallet:
165
+ return
166
+ tok = int(e.get("tokens", 0))
167
+ t = self.totals.setdefault(wallet, [0, 0, 0])
168
+ t[0] += tok
169
+ t[1] += int(e.get("luv_wei", tok * WEI_PER_TOKEN)) # the rate when it was earned
170
+ t[2] += 1
171
+ day = (wallet, int(e.get("t", time.time())) // 86400)
172
+ self.daily[day] = self.daily.get(day, 0) + tok
173
+
174
  def _ledger(self, entry: dict) -> None:
175
  with open(self.ledger_path, "a") as f:
176
  f.write(json.dumps(entry, separators=(",", ":")) + "\n")
177
+ self._count(entry)
178
 
179
+ def _limited(self, ip: str, rule: tuple = RATE, bucket: str = "") -> bool:
180
+ q = self.rate.setdefault(bucket + ip, collections.deque())
181
  t = now()
182
+ while q and t - q[0] > rule[1]:
183
  q.popleft()
184
+ if len(q) >= rule[0]:
185
  return True
186
  q.append(t)
187
  return False
188
 
189
+ def _barred(self, w: Worker) -> bool:
190
+ return self.strikes["ip:" + w.ip] >= STRIKES_BAR or (bool(w.wallet) and self.strikes["w:" + w.wallet.lower()] >= STRIKES_BAR)
191
+
192
+ def _strike(self, wallet: str, ip: str) -> None:
193
+ self.strikes["ip:" + ip] += 1
194
+ if wallet:
195
+ self.strikes["w:" + wallet.lower()] += 1
196
+
197
+ def _credit(self, w: Worker, j: Job, text: str, claimed) -> tuple[int, str]:
198
+ """Tokens to credit for an accepted answer, and why fewer than claimed. A receipt proves only that the text
199
+ hashes to what the worker said, so the claim is bounded by what the router can see: the job's limit, the
200
+ answer's length (every token is at least one character), no credit for answering yourself, and a daily ceiling
201
+ per wallet. Payout stays an operator step on top of this."""
202
+ try:
203
+ n = max(0, int(claimed or 0))
204
+ except (TypeError, ValueError):
205
+ n = 0
206
+ n = min(n, j.max_tokens, len(text))
207
+ if j.client_ip and j.client_ip == w.ip:
208
+ return 0, "self-served"
209
+ if w.wallet:
210
+ day = (w.wallet.lower(), int(time.time()) // 86400)
211
+ room = max(0, DAILY_TOKENS - self.daily.get(day, 0))
212
+ if n > room:
213
+ return room, "daily ceiling"
214
+ return n, ""
215
+
216
  def _wake_one(self) -> None:
217
  for w in self.workers.values():
218
  if w.waiter and not w.waiter.done() and not w.paused:
 
227
  if j.model != w.model:
228
  self.queue.append(j)
229
  continue
230
+ if j.check_of and (w.session in j.compare or w.ip in {v[1] for v in j.who.values()}
231
+ or (w.wallet and w.wallet.lower() in {v[0] for v in j.who.values() if v[0]})):
232
+ self.queue.append(j) # a cross-check must go to a different worker (session, IP and wallet)
233
  continue
234
  j.holder, j.lease_until, j.tries = w.session, now() + LEASE_S, j.tries + 1
235
  return j
 
255
  if t - w.seen > SESSION_TTL_S:
256
  self.workers.pop(s, None)
257
  self.stats["workers_dropped"] += 1
258
+ for k, q in list(self.rate.items()):
259
+ if not q or t - q[-1] > 120:
260
+ self.rate.pop(k, None)
261
  for j in list(self.jobs.values()):
262
+ if j.check_of and not j.holder and t - j.created > 3600:
263
+ self.jobs.pop(j.id, None) # a cross-check nobody else could take
264
+ continue
265
  if j.holder and (t > j.lease_until or j.holder not in self.workers):
266
  self._requeue(j, "lease expired")
267
  elif not j.holder and j.done is not None and j.done.done() and not j.check_of:
 
273
  model = next((m for m, v in MODELS.items() if v["sha256"] == sha), None)
274
  if not model:
275
  return {"ok": False, "reason": "this host serves only pinned models", "models": MODELS}
276
+ if len(self.workers) >= MAX_WORKERS or sum(1 for w in self.workers.values() if w.ip == ip) >= WORKERS_PER_IP:
277
+ return {"ok": False, "reason": "too many workers from here right now; try again later"}
278
  s = secrets.token_hex(16) # the wallet comes only from a login333 · drAIML sign-in
279
  self.workers[s] = Worker(s, model, str(b.get("engine", ""))[:40], max(1, min(100, int(b.get("share_pct") or 10))),
280
  wallet, str(b.get("contributor", ""))[:20], ip)
 
311
  w = self._worker(b)
312
  if not w:
313
  return {"ok": False, "reason": "unknown session"}
314
+ if self._barred(w):
315
  return {"ok": False, "barred": True, "reason": "answers did not match other workers"}
316
  w.paused = False
317
  j = self._take(w)
 
336
  if not w or not j or j.holder != w.session:
337
  return {"ok": False, "reason": "not your job (lease expired?)"}
338
  text, rc, usage = str(b.get("text", "")), b.get("receipt") or {}, b.get("usage") or {}
339
+ if not isinstance(rc, dict) or not isinstance(usage, dict):
340
+ rc, usage = {}, {}
341
  good = (hashlib.sha256(text.encode()).hexdigest() == rc.get("response_sha256")
342
  and str(rc.get("model_sha256", "")).lower() == MODELS[j.model]["sha256"])
343
  if not good:
344
  w.strikes += 1
345
+ self._strike(w.wallet, w.ip)
346
  self._requeue(j, "receipt did not match")
347
  self.stats["receipts_bad"] += 1
348
  return {"ok": False, "reason": "the receipt does not match the text or the pinned model"}
349
+ tokens, why = self._credit(w, j, text, usage.get("completion_tokens"))
350
  w.jobs += 1
 
351
  self.stats["jobs_done"] += 1
352
+ j.holder = ""
353
+ if j.check_of:
354
+ return self._checked(w, j, text, rc, tokens, why)
355
+ w.tokens += tokens
356
  self.stats["tokens"] += tokens
357
  self._ledger({"t": int(time.time()), "host": HOST_LABEL, "wallet": w.wallet, "job": j.id, "tokens": tokens,
358
  "luv_wei": str(tokens * WEI_PER_TOKEN), "response_sha256": rc.get("response_sha256"),
359
+ "engine": w.engine, "check": False, **({"uncredited": why} if why else {})})
 
 
 
 
 
 
 
 
 
 
 
360
  if j.done and not j.done.done():
361
  j.done.set_result({"text": text, "receipt": rc, "usage": usage, "timings": b.get("timings") or {},
362
  "worker": {"engine": w.engine, "contributor": w.contributor}})
363
+ if (j.temperature == 0 and random.random() < CROSS_CHECK and len(self.workers) > 1
364
+ and len(self.queue) < MAX_QUEUE):
365
  c = Job(secrets.token_hex(8), j.model, j.messages, j.max_tokens, 0.0, check_of=j.id,
366
+ compare={w.session: text}, who={w.session: (w.wallet.lower(), w.ip, w.engine)})
367
  self.jobs[c.id] = c
368
  self.queue.append(c)
369
  self._wake_one()
370
+ return {"ok": True, "credited_tokens": tokens, "luv_wei": str(tokens * WEI_PER_TOKEN), "audit": "receipt",
371
+ **({"uncredited": why} if why else {})}
372
+
373
+ def _checked(self, w: Worker, j: Job, text: str, rc: dict, tokens: int, why: str) -> dict:
374
+ """A cross-check copy came back. Agreement credits the checker. A disagreement goes to a third worker; the
375
+ side the third answer agrees with is right, and the other side gets a strike (on its wallet and IP, so a new
376
+ session does not clear it). Copies are credited only once they agree with someone."""
377
+ j.compare[w.session] = text
378
+ j.who[w.session] = (w.wallet.lower(), w.ip, w.engine)
379
+ texts = list(j.compare.values())
380
+ if len(texts) == 2 and texts[0] != texts[1]:
381
+ self.stats["cross_mismatch"] += 1
382
+ j.tries = 0
383
+ if len(self.queue) < MAX_QUEUE:
384
+ self.queue.append(j) # to a third worker, to break the tie
385
+ self._wake_one()
386
+ else:
387
+ self.jobs.pop(j.id, None)
388
+ return {"ok": True, "credited_tokens": 0, "luv_wei": "0", "audit": "cross-check (tie-break pending)"}
389
+ majority = max(set(texts), key=texts.count)
390
+ agreed = texts.count(majority) >= 2
391
+ self.stats["cross_match" if len(texts) == 2 else "cross_tiebreaks"] += 1
392
+ if agreed and len(texts) == 3:
393
+ for s, t in j.compare.items():
394
+ if t != majority:
395
+ self._strike(j.who[s][0], j.who[s][1])
396
+ if s in self.workers:
397
+ self.workers[s].strikes += 1
398
+ self.jobs.pop(j.id, None)
399
+ credit = tokens if (agreed and text == majority) else 0
400
+ why = why if credit else (why or "cross-check disagreed")
401
+ if credit:
402
+ w.tokens += credit
403
+ self.stats["tokens"] += credit
404
+ self._ledger({"t": int(time.time()), "host": HOST_LABEL, "wallet": w.wallet, "job": j.id, "tokens": credit,
405
+ "luv_wei": str(credit * WEI_PER_TOKEN), "response_sha256": rc.get("response_sha256"),
406
+ "engine": w.engine, "check": True, **({"uncredited": why} if why else {})})
407
+ return {"ok": True, "credited_tokens": credit, "luv_wei": str(credit * WEI_PER_TOKEN), "audit": "cross-check",
408
+ **({"uncredited": why} if why else {})}
409
 
410
  def decline(self, b: dict, failed: bool = False) -> dict:
411
  w = self._worker(b)
 
442
  return 503, {"error": {"message": "the queue is full; try again soon"}}
443
  j = Job(secrets.token_hex(8), model, msgs, max(1, min(MAX_TOKENS, int(b.get("max_tokens") or 400))),
444
  float(b.get("temperature") if b.get("temperature") is not None else 0.3))
445
+ j.client_ip = ip
446
  j.done = asyncio.get_running_loop().create_future()
447
  self.jobs[j.id] = j
448
  self.queue.append(j)
 
466
  def nonce(self, address: str) -> dict:
467
  if not (address.startswith("0x") and len(address) == 42):
468
  return {"ok": False, "reason": "an Ethereum address is required"}
469
+ t, addr = now(), address.lower()
470
  for k, (_, exp) in list(self.nonces.items()):
471
  if exp < t:
472
  self.nonces.pop(k, None)
473
+ mine = [k for k, (a, _) in self.nonces.items() if a == addr]
474
+ for k in mine[:max(0, len(mine) - NONCES_PER_ADDRESS + 1)]:
475
+ self.nonces.pop(k, None) # an address keeps only its latest few codes
476
+ while len(self.nonces) >= MAX_NONCES:
477
+ self.nonces.pop(next(iter(self.nonces))) # evict the oldest instead of locking everyone out
478
  n = secrets.token_hex(8)
479
+ self.nonces[n] = (addr, t + 300)
480
  return {"ok": True, "nonce": n, "expires_s": 300, "domains": SIWE_DOMAINS, "chain_id": 1}
481
 
482
  def _token(self, address: str) -> str:
 
495
 
496
  def verify(self, b: dict) -> dict:
497
  msg, sig = str(b.get("message", "")), str(b.get("signature", ""))
498
+ if len(msg) > SIWE_MAX or len(sig) > 200:
499
+ return {"ok": False, "reason": "the sign-in message is too long"}
500
  try:
501
  f = siwe.parse_siwe(msg)
502
  except ValueError as e:
 
519
  return {"ok": True, "address": signer, "token": self._token(signer), "expires_days": TOKEN_DAYS}
520
 
521
  # ── earnings and payout claims ──────────────────────────────────────────────────────────────────────────────
522
+ def _all_claims(self) -> dict:
523
+ """Claims by id, re-read only when the file changes (payout.py marks payments in it)."""
524
+ try:
525
+ mtime = os.stat(self.claims_path).st_mtime
526
+ except OSError:
527
+ return {}
528
+ if mtime != self._claims_cache[0]:
529
+ rows: dict[str, dict] = {}
530
  with open(self.claims_path) as f:
531
  for line in f:
532
  try:
533
  e = json.loads(line)
534
+ rows.setdefault(e["id"], {}).update(e)
535
+ except (ValueError, KeyError, TypeError):
 
536
  continue
537
+ self._claims_cache = (mtime, rows)
538
+ return self._claims_cache[1]
539
+
540
+ def _claims(self, wallet: str) -> tuple[int, int, list]:
541
+ claimed = paid = 0
542
+ rows = [c for c in self._all_claims().values() if str(c.get("wallet", "")).lower() == wallet.lower()]
543
+ for c in rows:
544
  claimed += int(c.get("luv_wei", 0))
545
  if c.get("status") == "paid":
546
  paid += int(c.get("luv_wei", 0))
547
+ return claimed, paid, sorted(rows, key=lambda c: c.get("t", 0))[-10:]
548
 
549
  def claim(self, wallet: str) -> dict:
550
  if not wallet:
 
566
  "queue": len(self.queue), "models": list(MODELS), "stats": dict(self.stats)}
567
 
568
  def me(self, wallet: str) -> dict:
569
+ tokens, wei, jobs = self.totals.get(wallet.lower(), [0, 0, 0]) if wallet else (0, 0, 0)
 
 
 
 
 
 
 
 
 
 
 
570
  claimed, paid, claims = self._claims(wallet) if wallet else (0, 0, [])
571
  f18 = lambda x: f"{x // 10**18}.{x % 10**18:018d}" # noqa: E731
572
  return {"wallet": wallet, "jobs": jobs, "tokens": tokens, "luv_wei": str(wei), "luv": f18(wei),
573
  "claimed_wei": str(claimed), "paid_wei": str(paid), "available_wei": str(wei - claimed),
574
+ "available": f18(wei - claimed), "claims": claims, "rule": "1 SHAMBA LUV per generated token",
575
+ "daily_ceiling_tokens": DAILY_TOKENS}
576
 
577
 
578
  # ── a minimal HTTP/1.1 server (stdlib asyncio) ───────────────────────────────────────────────────────────────────
579
  def cors(origin: str) -> dict:
580
+ if origin in ALLOWED_ORIGINS or _ORIGIN_DEV.match(origin):
581
  return {"Access-Control-Allow-Origin": origin, "Vary": "Origin",
582
  "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
583
  "Access-Control-Allow-Headers": "authorization, content-type",
 
585
  return {}
586
 
587
 
588
+ _open_connections = 0
589
+
590
+
591
  async def handle(router: Router, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, trust_proxy: bool):
592
+ global _open_connections
593
+ if _open_connections >= MAX_CONNECTIONS:
594
+ writer.close()
595
+ return
596
+ _open_connections += 1
597
+ try:
598
+ await _handle(router, reader, writer, trust_proxy)
599
+ except Exception: # never take the router down, never print a client's garbage as a traceback
600
+ router.stats["connection_errors"] += 1
601
+ writer.close()
602
+ finally:
603
+ _open_connections -= 1
604
+
605
+
606
+ async def _handle(router: Router, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, trust_proxy: bool):
607
  try:
608
  head = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), 15)
609
  except (asyncio.TimeoutError, asyncio.IncompleteReadError, asyncio.LimitOverrunError, ConnectionError):
 
615
  except ValueError:
616
  writer.close()
617
  return
618
+ h = {k.strip().lower(): v.strip() for k, v in (ln.split(":", 1) for ln in lines[1:] if ":" in ln)
619
+ if "\n" not in v and "\r" not in v}
620
  status, out, extra = 200, {}, {}
621
+ # Apache appends the address it saw to X-Forwarded-For: the last entry is the real one, earlier ones are the client's
622
+ ip = (h.get("x-forwarded-for", "").split(",")[-1].strip() if trust_proxy else "") or \
623
  (writer.get_extra_info("peername") or ("?",))[0]
624
+ path = "/"
 
 
 
625
  try:
626
+ n = int(h.get("content-length") or 0)
627
+ path = urlsplit(target).path.rstrip("/") or "/"
628
+ for prefix in ("/draiml-dmind",): # served under a path on a shared vhost
629
+ if path.startswith(prefix):
630
+ path = path[len(prefix):] or "/"
631
+ if n < 0:
632
+ raise ValueError("negative length")
633
  if n > MAX_BODY:
634
  status, out = 413, {"error": "request too large"}
635
  elif method == "OPTIONS":
636
  status = 204
637
  else:
638
+ try:
639
+ raw = await asyncio.wait_for(reader.readexactly(n), BODY_TIMEOUT_S) if n else b""
640
+ except (asyncio.TimeoutError, asyncio.IncompleteReadError):
641
+ writer.close()
642
+ return
643
+ body = json.loads(raw) if raw else {}
644
+ if not isinstance(body, dict):
645
+ raise ValueError("the body must be a JSON object")
646
+ stream = bool(body.get("stream"))
647
  if method == "GET" and path in ("/", "/health", "/sharedcpu/health"):
648
  out = {"ok": True, "host": HOST_LABEL, "version": VERSION}
649
  elif method == "GET" and path == "/insight/sharedcpu":
 
654
  out = router.me(router.wallet_of(h.get("authorization", ""))
655
  or parse_qs(urlsplit(target).query).get("wallet", [""])[0])
656
  elif method == "GET" and path == "/auth/nonce":
657
+ if router._limited(ip, AUTH_RATE, "auth:"):
658
+ status, out = 429, {"ok": False, "reason": "too many sign-in attempts; wait a minute"}
659
+ else:
660
+ out = router.nonce(parse_qs(urlsplit(target).query).get("address", [""])[0])
661
  elif method == "POST" and path == "/auth/verify":
662
+ if router._limited(ip, AUTH_RATE, "auth:"):
663
+ status, out = 429, {"ok": False, "reason": "too many sign-in attempts; wait a minute"}
664
+ else:
665
+ out = router.verify(body)
666
  elif method == "POST" and path == "/sharedcpu/claim":
667
  out = router.claim(router.wallet_of(h.get("authorization", "")))
668
  elif method == "POST" and path == "/sharedcpu/join":
tests/test_core.py CHANGED
@@ -174,3 +174,12 @@ def test_bonsai_unavailable_outside_browser():
174
  assert asyncio.run(bonsai.status()) == {}
175
  with pytest.raises(bonsai.BonsaiError):
176
  asyncio.run(bonsai.ensure())
 
 
 
 
 
 
 
 
 
 
174
  assert asyncio.run(bonsai.status()) == {}
175
  with pytest.raises(bonsai.BonsaiError):
176
  asyncio.run(bonsai.ensure())
177
+
178
+
179
+ def test_copy_button_text_cannot_close_its_script_block():
180
+ import json as _json
181
+ from draiml.share import script_literal
182
+ evil = "ok </script><img src=x onerror=alert(1)> & 
 done"
183
+ lit = script_literal(evil)
184
+ assert "</" not in lit and "<" not in lit and ">" not in lit and "
" not in lit
185
+ assert _json.loads(lit) == evil # still the same text once the browser parses the literal
tests/test_router.py CHANGED
@@ -12,10 +12,12 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "router"))
12
  import draiml_router as R # noqa: E402
13
 
14
 
15
- async def http(port, method, path, body=None, origin="", token=""):
16
  r, w = await asyncio.open_connection("127.0.0.1", port)
17
  data = json.dumps(body).encode() if body is not None else b""
18
  hdr = f"{method} {path} HTTP/1.1\r\nHost: x\r\nContent-Length: {len(data)}\r\n"
 
 
19
  if origin:
20
  hdr += f"Origin: {origin}\r\n"
21
  if token:
@@ -48,7 +50,8 @@ def receipt(text, sha=R.BONSAI_SHA256):
48
 
49
  async def scenario(tmp_path):
50
  router = R.Router(str(tmp_path / "ledger.jsonl"))
51
- server = await asyncio.start_server(lambda r, w: R.handle(router, r, w, False), "127.0.0.1", 0)
 
52
  port = server.sockets[0].getsockname()[1]
53
  out = {}
54
 
@@ -78,23 +81,26 @@ async def scenario(tmp_path):
78
  s, h, j = await http(port, "POST", "/draiml-dmind/sharedcpu/join",
79
  {"model_sha256": R.BONSAI_SHA256, "share_pct": 10,
80
  "engine": "browseml/draiml", "contributor": "browser"},
81
- origin="https://pythai-draiml.static.hf.space", token=token)
82
  out["join_wallet"] = j["wallet"]
83
  out["cors"] = h.get("access-control-allow-origin")
 
 
 
84
  session = j["session"]
85
 
86
  async def worker(bad=False):
87
- _, _, p = await http(port, "POST", "/sharedcpu/pull", {"session": session})
88
  job = p["job"]
89
  text = "Rest, ice and gentle movement."
90
  rc = receipt("tampered" if bad else text)
91
  _, _, r = await http(port, "POST", "/sharedcpu/result", {"session": session, "job": job["job"], "text": text,
92
- "receipt": rc, "usage": {"completion_tokens": 7}})
93
  return job, r
94
 
95
  async def client():
96
  return await http(port, "POST", "/v1/chat/completions",
97
- {"messages": [{"role": "user", "content": "sprained ankle?"}], "max_tokens": 5000})
98
 
99
  # a bad receipt is refused and the job is re-queued; the second try succeeds
100
  c = asyncio.create_task(client())
@@ -142,3 +148,122 @@ def test_router_delegates_and_maintains(tmp_path):
142
  assert out["claim_again"] is False and out["claim_anon"] is False
143
  assert out["insight"] == (1, 1, 1)
144
  assert out["after_leave"] == 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  import draiml_router as R # noqa: E402
13
 
14
 
15
+ async def http(port, method, path, body=None, origin="", token="", xff=""):
16
  r, w = await asyncio.open_connection("127.0.0.1", port)
17
  data = json.dumps(body).encode() if body is not None else b""
18
  hdr = f"{method} {path} HTTP/1.1\r\nHost: x\r\nContent-Length: {len(data)}\r\n"
19
+ if xff:
20
+ hdr += f"X-Forwarded-For: {xff}\r\n"
21
  if origin:
22
  hdr += f"Origin: {origin}\r\n"
23
  if token:
 
50
 
51
  async def scenario(tmp_path):
52
  router = R.Router(str(tmp_path / "ledger.jsonl"))
53
+ server = await asyncio.start_server(lambda r, w: R.handle(router, r, w, True), "127.0.0.1", 0)
54
+ WORKER = "6.6.6.6, 198.51.100.7" # Apache appends the real address; the first entry is the client's own claim
55
  port = server.sockets[0].getsockname()[1]
56
  out = {}
57
 
 
81
  s, h, j = await http(port, "POST", "/draiml-dmind/sharedcpu/join",
82
  {"model_sha256": R.BONSAI_SHA256, "share_pct": 10,
83
  "engine": "browseml/draiml", "contributor": "browser"},
84
+ origin="https://pythai-draiml.static.hf.space", token=token, xff=WORKER)
85
  out["join_wallet"] = j["wallet"]
86
  out["cors"] = h.get("access-control-allow-origin")
87
+ _, h2, _ = await http(port, "GET", "/health", origin="http://127.0.0.1.evil.example")
88
+ out["cors_spoof"] = h2.get("access-control-allow-origin")
89
+ out["worker_ip"] = router.workers[j["session"]].ip
90
  session = j["session"]
91
 
92
  async def worker(bad=False):
93
+ _, _, p = await http(port, "POST", "/sharedcpu/pull", {"session": session}, xff=WORKER)
94
  job = p["job"]
95
  text = "Rest, ice and gentle movement."
96
  rc = receipt("tampered" if bad else text)
97
  _, _, r = await http(port, "POST", "/sharedcpu/result", {"session": session, "job": job["job"], "text": text,
98
+ "receipt": rc, "usage": {"completion_tokens": 7}}, xff=WORKER)
99
  return job, r
100
 
101
  async def client():
102
  return await http(port, "POST", "/v1/chat/completions",
103
+ {"messages": [{"role": "user", "content": "sprained ankle?"}], "max_tokens": 5000}, xff="203.0.113.5")
104
 
105
  # a bad receipt is refused and the job is re-queued; the second try succeeds
106
  c = asyncio.create_task(client())
 
148
  assert out["claim_again"] is False and out["claim_anon"] is False
149
  assert out["insight"] == (1, 1, 1)
150
  assert out["after_leave"] == 0
151
+ assert out["cors_spoof"] is None and out["worker_ip"] == "198.51.100.7"
152
+
153
+
154
+ # ── abuse cases (the router's own methods, no HTTP) ──────────────────────────────────────────────────────────────
155
+ def _router(tmp_path):
156
+ return R.Router(str(tmp_path / "ledger.jsonl"))
157
+
158
+
159
+ def _job(r, ip="203.0.113.5", max_tokens=600, temperature=0.3):
160
+ j = R.Job("j" + str(len(r.jobs)), "Bonsai-1.7B-Q1_0", [{"role": "user", "content": "q"}], max_tokens, temperature)
161
+ j.client_ip = ip
162
+ r.jobs[j.id] = j
163
+ r.queue.append(j)
164
+ return j
165
+
166
+
167
+ def _worker(r, ip, wallet=""):
168
+ return r.join({"model_sha256": R.BONSAI_SHA256}, ip, wallet)["session"]
169
+
170
+
171
+ def _answer(r, session, text, claimed):
172
+ w = r.workers[session]
173
+ j = r._take(w)
174
+ return j, r.result({"session": session, "job": j.id, "text": text, "receipt": receipt(text),
175
+ "usage": {"completion_tokens": claimed}})
176
+
177
+
178
+ def test_inflated_token_count_is_capped(tmp_path):
179
+ r = _router(tmp_path)
180
+ s = _worker(r, "198.51.100.7", "0xabc")
181
+ _job(r, max_tokens=50)
182
+ _, res = _answer(r, s, "x" * 30, 10**30)
183
+ assert res["credited_tokens"] == 30 # bounded by the answer's length
184
+ _job(r, max_tokens=50)
185
+ _, res = _answer(r, s, "y" * 500, 10**30)
186
+ assert res["credited_tokens"] == 50 # bounded by the job's limit
187
+ assert r.me("0xabc")["tokens"] == 80
188
+
189
+
190
+ def test_self_served_answers_earn_nothing(tmp_path):
191
+ r = _router(tmp_path)
192
+ s = _worker(r, "198.51.100.7", "0xabc")
193
+ _job(r, ip="198.51.100.7")
194
+ _, res = _answer(r, s, "an answer", 9)
195
+ assert res["credited_tokens"] == 0 and res["uncredited"] == "self-served"
196
+
197
+
198
+ def test_daily_ceiling(tmp_path):
199
+ r = _router(tmp_path)
200
+ s = _worker(r, "198.51.100.7", "0xabc")
201
+ r.daily[("0xabc", int(R.time.time()) // 86400)] = R.DAILY_TOKENS - 5
202
+ _job(r)
203
+ _, res = _answer(r, s, "z" * 100, 100)
204
+ assert res["credited_tokens"] == 5 and res["uncredited"] == "daily ceiling"
205
+
206
+
207
+ def test_cross_check_tie_break_strikes_the_odd_one_out(tmp_path):
208
+ r = _router(tmp_path)
209
+ honest, liar, judge = (_worker(r, ip, wal) for ip, wal in
210
+ (("10.0.0.1", "0xa1"), ("10.0.0.2", "0xb2"), ("10.0.0.3", "0xc3")))
211
+ j = _job(r, temperature=0)
212
+ j_ = r._take(r.workers[honest])
213
+ r.result({"session": honest, "job": j_.id, "text": "rest", "receipt": receipt("rest"), "usage": {"completion_tokens": 4}})
214
+ c = R.Job("chk", j.model, j.messages, j.max_tokens, 0.0, check_of=j.id, compare={honest: "rest"},
215
+ who={honest: ("0xa1", "10.0.0.1", "")})
216
+ r.jobs[c.id] = c
217
+ r.queue.append(c)
218
+ assert r._take(r.workers[honest]) is None # never back to the original worker
219
+ _, res = _answer(r, liar, "lies", 4)
220
+ assert res["credited_tokens"] == 0 and "tie-break" in res["audit"]
221
+ assert r._take(r.workers[liar]) is None # nor to the one it disagreed with
222
+ _, res = _answer(r, judge, "rest", 4)
223
+ assert res["credited_tokens"] == 4
224
+ assert r.strikes["w:0xb2"] == 1 and r.strikes["ip:10.0.0.2"] == 1 and r.strikes["w:0xa1"] == 0
225
+ r.strikes["w:0xb2"] = R.STRIKES_BAR # barred by wallet: a new session does not help
226
+ again = _worker(r, "10.9.9.9", "0xb2")
227
+ assert asyncio.run(r.pull({"session": again}))["barred"] is True
228
+
229
+
230
+ def test_signin_limits(tmp_path):
231
+ r = _router(tmp_path)
232
+ addr = "0x" + "11" * 20
233
+ codes = [r.nonce(addr)["nonce"] for _ in range(10)]
234
+ assert sum(1 for k in codes if k in r.nonces) == R.NONCES_PER_ADDRESS
235
+ for i in range(R.MAX_NONCES + 50):
236
+ r.nonce("0x" + f"{i:040x}")
237
+ assert len(r.nonces) <= R.MAX_NONCES and r.nonce(addr)["ok"] # evicts instead of locking everyone out
238
+ assert "too long" in r.verify({"message": "x" * 5000, "signature": "0x"})["reason"]
239
+
240
+
241
+ async def _raw(port, data, read=True):
242
+ rd, wr = await asyncio.open_connection("127.0.0.1", port)
243
+ wr.write(data)
244
+ await wr.drain()
245
+ out = await asyncio.wait_for(rd.read(), 5) if read else b""
246
+ wr.close()
247
+ return out
248
+
249
+
250
+ def test_malformed_requests_do_not_crash(tmp_path):
251
+ async def go():
252
+ r = _router(tmp_path)
253
+ srv = await asyncio.start_server(lambda a, b: R.handle(r, a, b, True), "127.0.0.1", 0)
254
+ port = srv.sockets[0].getsockname()[1]
255
+ bad_len = await _raw(port, b"POST /x HTTP/1.1\r\nContent-Length: abc\r\n\r\n")
256
+ bad_url = await _raw(port, b"GET http://[::1/x HTTP/1.1\r\n\r\n")
257
+ not_obj = await _raw(port, b"POST /sharedcpu/join HTTP/1.1\r\nContent-Length: 2\r\n\r\n[]")
258
+ ok = await _raw(port, b"GET /health HTTP/1.1\r\n\r\n")
259
+ srv.close()
260
+ return bad_len, bad_url, not_obj, ok
261
+ bad_len, bad_url, not_obj, ok = asyncio.run(go())
262
+ assert bad_len.startswith(b"HTTP/1.1 400") and bad_url.startswith(b"HTTP/1.1 400")
263
+ assert not_obj.startswith(b"HTTP/1.1 400") and ok.startswith(b"HTTP/1.1 200")
264
+
265
+
266
+ def test_worker_sessions_are_capped_per_ip(tmp_path):
267
+ r = _router(tmp_path)
268
+ got = [r.join({"model_sha256": R.BONSAI_SHA256}, "10.0.0.9")["ok"] for _ in range(R.WORKERS_PER_IP + 3)]
269
+ assert got.count(True) == R.WORKERS_PER_IP
webgpu/installer/webgpu-enable.ps1 CHANGED
@@ -38,7 +38,7 @@ function Read-Labs($path) {
38
  $doc = [System.Text.Json.Nodes.JsonNode]::Parse($text)
39
  if ($null -eq $doc["browser"]) { $doc["browser"] = [System.Text.Json.Nodes.JsonObject]::new() }
40
  if ($null -eq $doc["browser"]["enabled_labs_experiments"]) { $doc["browser"]["enabled_labs_experiments"] = [System.Text.Json.Nodes.JsonArray]::new() }
41
- $labs = @($doc["browser"]["enabled_labs_experiments"] | ForEach-Object { $_.GetValue[string]() })
42
  } else {
43
  Add-Type -AssemblyName System.Web.Extensions
44
  $js = New-Object System.Web.Script.Serialization.JavaScriptSerializer; $js.MaxJsonLength = [int]::MaxValue
@@ -90,6 +90,7 @@ function Set-Chromium($b) {
90
  }
91
 
92
  $A = "// >>> drAIML WebGPU helper"; $B = "// <<< drAIML WebGPU helper"
 
93
  function Set-Firefox($prof) {
94
  if (-not (Test-Path (Join-Path $prof "prefs.js"))) { return }
95
  $uj = Join-Path $prof "user.js"
@@ -99,12 +100,12 @@ function Set-Firefox($prof) {
99
  if (-not $has) { Write-Host "* $prof - unchanged"; return }
100
  Write-Host "* $prof - $(if ($DryRun) { 'would ' })remove dom.webgpu.enabled"; if ($DryRun) { return }
101
  $keep = $true; $out = foreach ($ln in Get-Content $uj) { if ($ln -eq $A) { $keep = $false } elseif ($ln -eq $B) { $keep = $true } elseif ($keep) { $ln } }
102
- Set-Content -Encoding UTF8 $uj $out
103
- $p = Join-Path $prof "prefs.js"; Set-Content -Encoding UTF8 $p (Get-Content $p | Where-Object { $_ -notmatch '"dom\.webgpu\.enabled"' })
104
  } else {
105
  if ($has) { Write-Host "* $prof - unchanged"; return }
106
  Write-Host "* $prof - $(if ($DryRun) { 'would ' })add dom.webgpu.enabled = true"; if ($DryRun) { return }
107
- Add-Content -Encoding UTF8 $uj @($A, 'user_pref("dom.webgpu.enabled", true);', $B)
108
  }
109
  $script:changed++
110
  }
 
38
  $doc = [System.Text.Json.Nodes.JsonNode]::Parse($text)
39
  if ($null -eq $doc["browser"]) { $doc["browser"] = [System.Text.Json.Nodes.JsonObject]::new() }
40
  if ($null -eq $doc["browser"]["enabled_labs_experiments"]) { $doc["browser"]["enabled_labs_experiments"] = [System.Text.Json.Nodes.JsonArray]::new() }
41
+ $labs = @($doc["browser"]["enabled_labs_experiments"] | ForEach-Object { $_.ToString() }) # works on 7.0+
42
  } else {
43
  Add-Type -AssemblyName System.Web.Extensions
44
  $js = New-Object System.Web.Script.Serialization.JavaScriptSerializer; $js.MaxJsonLength = [int]::MaxValue
 
90
  }
91
 
92
  $A = "// >>> drAIML WebGPU helper"; $B = "// <<< drAIML WebGPU helper"
93
+ $utf8 = New-Object Text.UTF8Encoding $false # no BOM: Windows PowerShell 5.1's -Encoding UTF8 would add one
94
  function Set-Firefox($prof) {
95
  if (-not (Test-Path (Join-Path $prof "prefs.js"))) { return }
96
  $uj = Join-Path $prof "user.js"
 
100
  if (-not $has) { Write-Host "* $prof - unchanged"; return }
101
  Write-Host "* $prof - $(if ($DryRun) { 'would ' })remove dom.webgpu.enabled"; if ($DryRun) { return }
102
  $keep = $true; $out = foreach ($ln in Get-Content $uj) { if ($ln -eq $A) { $keep = $false } elseif ($ln -eq $B) { $keep = $true } elseif ($keep) { $ln } }
103
+ [IO.File]::WriteAllLines($uj, [string[]]@($out), $utf8)
104
+ $p = Join-Path $prof "prefs.js"; [IO.File]::WriteAllLines($p, [string[]]@(Get-Content $p | Where-Object { $_ -notmatch '"dom\.webgpu\.enabled"' }), $utf8)
105
  } else {
106
  if ($has) { Write-Host "* $prof - unchanged"; return }
107
  Write-Host "* $prof - $(if ($DryRun) { 'would ' })add dom.webgpu.enabled = true"; if ($DryRun) { return }
108
+ [IO.File]::AppendAllText($uj, "$A`nuser_pref(`"dom.webgpu.enabled`", true);`n$B`n", $utf8)
109
  }
110
  $script:changed++
111
  }
webgpu/installer/webgpu-enable.sh CHANGED
@@ -99,7 +99,10 @@ MARK_A="// >>> drAIML WebGPU helper"; MARK_B="// <<< drAIML WebGPU helper"
99
  firefox() {
100
  local prof="$1" uj="$1/user.js"
101
  [ -f "$prof/prefs.js" ] || return 0
102
- if running "$prof/lock"; then echo "• $prof — Firefox is running: close it and run this again"; skipped=$((skipped+1)); return 0; fi
 
 
 
103
  if [ "$UNDO" = 1 ]; then
104
  grep -qF "$MARK_A" "$uj" 2>/dev/null || { echo "• $prof — unchanged"; return 0; }
105
  echo "• $prof — $([ "$DRY" = 1 ] && echo "would remove" || echo "remove") dom.webgpu.enabled"
 
99
  firefox() {
100
  local prof="$1" uj="$1/user.js"
101
  [ -f "$prof/prefs.js" ] || return 0
102
+ # Linux: the "lock" symlink names the PID. macOS uses .parentlock (no PID), so there any running Firefox counts
103
+ if running "$prof/lock" || { [ "$OS" = Darwin ] && pgrep -xq firefox; }; then
104
+ echo "• $prof — Firefox is running: close it and run this again"; skipped=$((skipped+1)); return 0
105
+ fi
106
  if [ "$UNDO" = 1 ]; then
107
  grep -qF "$MARK_A" "$uj" 2>/dev/null || { echo "• $prof — unchanged"; return 0; }
108
  echo "• $prof — $([ "$DRY" = 1 ] && echo "would remove" || echo "remove") dom.webgpu.enabled"