File size: 9,888 Bytes
1ad1eea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
"""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}