"""Signed frozen artifact links enforce phone binding and Amazon sign-in (C7, R85, R86, R97).""" from __future__ import annotations import base64 import binascii import hmac import json import os import re import secrets import time from hashlib import sha256 import assistant_artifacts import loopy_links TTL_S = 86400 # A separate key derived from the session secret, so a share token never verifies as a session. _KEY_LABEL = b"loopable artifact share v1" _SHARE_ID = re.compile(r"[A-Za-z0-9_\-]{22}") _PART = re.compile(r"[A-Za-z0-9_\-]+") MAX_TOKEN = 600 SENT = "A new link is on its way to your WhatsApp." ALREADY = "A new link was already sent to your WhatsApp." STILL_OPEN = "This link still works. Open it again." NOT_VALID = "This link is not valid." NOT_SENT = "We could not send a new link. Ask Loopy on WhatsApp for one." LINK_TEXT = "Here is your new Loopable link: {link}" class ShareRefused(ValueError): """A refused signed link with an optional normal artifact sign-in destination.""" def __init__(self, message, *, link=None): super().__init__(message) self.link = link def _secret() -> bytes | None: raw = os.environ.get("AIOS_SESSION_SECRET") or "" return hmac.new(raw.encode("utf-8"), _KEY_LABEL, sha256).digest() if raw else None def _b64(raw: bytes) -> str: return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=") def _unb64(text: str) -> bytes: return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)) def _sign(key: bytes, payload: bytes) -> str: return _b64(hmac.new(key, b"token:" + payload, sha256).digest()) def _phone_tag(key: bytes, phone: str) -> str: return _b64(hmac.new(key, b"phone:" + phone.encode("utf-8"), sha256).digest()[:12]) def _doc_key(share_id: str) -> str: return f"artifact_share_{share_id}" def needs_sign_in(row) -> bool: """Require normal sign-in for Amazon content and unknown provenance under R86.""" if not isinstance(row, dict): return True try: return assistant_artifacts.c7(row)["amazon"] is not False except Exception: return True def _lookup(phone): import whatsapp_identity return whatsapp_identity.lookup(phone) def _eligible(rt, artifact_id, phone): """Return the owner's username, or raise ShareRefused with a plain reason.""" if not isinstance(phone, str) or not phone: raise ShareRefused("This number is not connected to Loopable.") bound = _lookup(phone) if not bound: raise ShareRefused("This number is not connected to Loopable.") tenant, owner = bound if tenant != getattr(rt, "key", None): raise ShareRefused("This number belongs to another workspace.") row = assistant_artifacts.get(rt, owner, artifact_id) if row is None: raise ShareRefused("That item is not yours.") if row.get("status") != "active": raise ShareRefused("That item is no longer available.") if needs_sign_in(row): raise ShareRefused("That item requires sign in to open.", link=loopy_links.artifact_link(row["id"])) if row.get("kind") not in {"snapshot", "pdf", "xlsx", "image"} or not row.get("frozen_at"): raise ShareRefused("That item has no frozen content to share.") return owner def _mint(rt, artifact_id, owner, phone, key, now): share_id = _b64(secrets.token_bytes(16)) expires = int(now) + TTL_S record = {"artifact_id": artifact_id, "owner": owner, "phone": phone, "expires": expires, "created": int(now)} rt.update(_doc_key(share_id), lambda _raw: dict(record), flush="sync") claims = {"t": rt.key, "s": share_id, "a": artifact_id, "p": _phone_tag(key, phone), "x": expires} payload = json.dumps(claims, separators=(",", ":"), sort_keys=True).encode("utf-8") return f"{_b64(payload)}.{_sign(key, payload)}" def signed_link(rt, artifact_id, *, phone, now=None): """Mint a signed link, or refuse with a normal artifact link when sign-in is required.""" key = _secret() if key is None or loopy_links.public_base() is None: return None owner = _eligible(rt, artifact_id, phone) token = _mint(rt, artifact_id, owner, phone, key, time.time() if now is None else now) return loopy_links.shared_artifact_link(token) def _claims(token, key): """The verified claims of a token, or None for a bad shape or signature.""" if not isinstance(token, str) or len(token) > MAX_TOKEN or token.count(".") != 1: return None body, sig = token.split(".") if not _PART.fullmatch(body) or not _PART.fullmatch(sig): return None try: payload = _unb64(body) except (binascii.Error, ValueError): return None if _b64(payload) != body: return None if not hmac.compare_digest(sig, _sign(key, payload)): return None try: claims = json.loads(payload.decode("utf-8")) except (UnicodeDecodeError, ValueError): return None shape = {"t": str, "s": str, "a": str, "p": str, "x": int} if not isinstance(claims, dict) or set(claims) != set(shape) or not all( isinstance(claims[name], kind) and not isinstance(claims[name], bool) for name, kind in shape.items()): return None return claims if _SHARE_ID.fullmatch(claims["s"]) else None def _runtime(slug): from harness import runtime as _rt try: if slug not in _rt.known_tenants(): return None rt = _rt.get_runtime(slug) except Exception: return None return rt if getattr(rt, "key", None) == slug else None def resolve(token, now=None): """Return ok, expired, sign_in or invalid; only ok carries anonymous content rights.""" invalid = {"state": "invalid", "rt": None, "share": None, "row": None} key = _secret() if key is None: return invalid claims = _claims(token, key) if claims is None: return invalid rt = _runtime(claims["t"]) if rt is None or getattr(rt, "key", None) != claims["t"]: return invalid try: share = rt.get(_doc_key(claims["s"])) except Exception: return invalid if (not isinstance(share, dict) or share.get("artifact_id") != claims["a"] or share.get("expires") != claims["x"] or not isinstance(share.get("phone"), str) or not isinstance(share.get("owner"), str) or not hmac.compare_digest(_phone_tag(key, share["phone"]), claims["p"])): return invalid try: row = assistant_artifacts.get(rt, share["owner"], claims["a"]) except Exception: return invalid if (row is None or row.get("id") != claims["a"] or row.get("status") != "active" or row.get("kind") not in {"snapshot", "pdf", "xlsx", "image"} or not row.get("frozen_at")): return invalid now = time.time() if now is None else now created = share.get("created") if (not isinstance(created, int) or isinstance(created, bool) or claims["x"] - created != TTL_S or now < created): return invalid try: if _lookup(share["phone"]) != (rt.key, share["owner"]): return invalid except Exception: return invalid if needs_sign_in(row): return {"state": "sign_in", "rt": rt, "share": share, "row": {"id": row["id"], "status": row["status"]}} if now >= claims["x"]: return {"state": "expired", "rt": rt, "share": share, "row": row} return {"state": "ok", "rt": rt, "share": share, "row": row} def _send(phone, text, link, *, tenant, username): """Send inside the 24 hour window as text, outside it as the approved template.""" import telnyx_whatsapp send = getattr(telnyx_whatsapp, "send_reply", None) kwargs = {"purpose": "artifact_link", "tenant": tenant, "username": username} if send is not None: return send(phone, text, link=link, **kwargs) if telnyx_whatsapp.within_window(phone): return telnyx_whatsapp.send_text(phone, text, **kwargs) return telnyx_whatsapp.send_template(phone, telnyx_whatsapp.ping_template(), [text, link], **kwargs) def request_again(token, now=None): """Send a fresh link for an expired token to the same number; return {"outcome", "message"}.""" now = time.time() if now is None else now found = resolve(token, now) if found["state"] == "ok": return {"outcome": "still_open", "message": STILL_OPEN} if found["state"] != "expired": return {"outcome": "invalid", "message": NOT_VALID} rt, share = found["rt"], found["share"] share_id = _claims(token, _secret())["s"] try: owner = _eligible(rt, share["artifact_id"], share["phone"]) except ShareRefused: return {"outcome": "refused", "message": NOT_VALID} if owner != share["owner"]: return {"outcome": "refused", "message": NOT_VALID} claimed = [] def claim(raw): claimed.clear() raw = dict(raw or {}) if raw.get("renewed") is None: raw["renewed"] = int(now) claimed.append(True) return raw # One fresh link per expired token, so a visitor cannot flood the number. rt.update(_doc_key(share_id), claim, flush="sync") if not claimed: return {"outcome": "already", "message": ALREADY} try: link = signed_link(rt, share["artifact_id"], phone=share["phone"], now=now) delivery = _send(share["phone"], LINK_TEXT.format(link=link), link, tenant=rt.key, username=owner) if link else None if isinstance(delivery, dict) and delivery.get("status") in {"sandbox", "sent"}: return {"outcome": "sent", "message": SENT} except Exception: pass rt.update(_doc_key(share_id), lambda raw: {**(raw or {}), "renewed": None}, flush="sync") return {"outcome": "failed", "message": NOT_SENT}