"""Deliver human codes to one tenant-owned waiting executor through memory only.""" import re import threading import time from core import login_run, logins _LOCK = threading.RLock() _PENDING = {} _KINDS = frozenset({"text", "email"}) _DOORS = frozenset({"app", "whatsapp", "slack"}) class _CodeWait: def __init__(self, run_id, label, kind, seconds): self.run_id, self.kind = run_id, kind self.label = label.replace(chr(0x2014), "-").replace(chr(0x2013), "-") self.event = threading.Event() self.expires = time.monotonic() + min(900, seconds) self.value, self.delivered, self.cancelled = None, False, False def valid_code(value): return isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9]{4,32}", value) is not None def _key(rt, username): if not isinstance(rt.key, str) or not rt.key or not isinstance(username, str) or not username: raise logins.LoginAccessDenied("This Login run is unavailable.") return rt.key, username def _live(rt, username, wait): try: run = logins.run_for_owner(rt, wait.run_id, username) logins.entry_for_run(rt, run["entry_id"], username) return run["status"] == "waiting_for_code" and time.monotonic() < wait.expires except Exception: return False def pending(rt, username): """Return safe prompt metadata only for an owned, live code wait.""" with _LOCK: wait = _PENDING.get(_key(rt, username)) if wait is None: return None if not _live(rt, username, wait): _PENDING.pop(_key(rt, username), None) wait.cancelled = True wait.event.set() return None if wait.delivered: return None return {"run_id": wait.run_id, "login_label": wait.label, "kind": wait.kind} def _deliver(rt, username, text, door, run_id=None): if door not in _DOORS or not valid_code(text): return False with _LOCK: key = _key(rt, username) wait = _PENDING.get(key) if (wait is None or wait.delivered or (run_id is not None and wait.run_id != run_id) or not _live(rt, username, wait)): return False wait.value = text wait.delivered = True wait.event.set() return True def try_consume(rt, username, text, door="app"): """Intercept a valid code before history, memory, join guards and the model.""" if isinstance(text, str) and text.strip().casefold() in {"cancel", "stop"}: return False try: if door in _DOORS and valid_code(text): with _LOCK: wait = _PENDING.get(_key(rt, username)) if wait is not None and wait.delivered and _live(rt, username, wait): return True return _deliver(rt, username, text, door) except Exception: return False def submit(rt, username, run_id, code): """Deliver panel input only to the specified user's exact waiting run.""" return _deliver(rt, username, code, "app", run_id) def wait_for_code(rt, username, run_id, label, kind, breaker): """Wait within the run breaker and erase the code after one executor receives it.""" if kind not in _KINDS: raise login_run.BreakerOpen("code_unavailable") key = _key(rt, username) wait = _CodeWait(run_id, label, kind, breaker._seconds) with _LOCK: if key in _PENDING: raise login_run.BreakerOpen("code_wait_conflict") logins.set_wait_state(rt, run_id, username, "waiting_for_code") _PENDING[key] = wait try: while True: breaker.check() if not _live(rt, username, wait) or wait.cancelled: raise login_run.BreakerOpen("code_wait_ended") if wait.event.wait(0.25): with _LOCK: if wait.cancelled or not valid_code(wait.value): raise login_run.BreakerOpen("code_wait_ended") value, wait.value = wait.value, None logins.set_wait_state(rt, run_id, username, "running") return value finally: with _LOCK: if _PENDING.get(key) is wait: _PENDING.pop(key, None) wait.value = None