File size: 3,082 Bytes
cd80e89
 
 
 
 
 
 
 
 
d78ba45
 
 
cd80e89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d78ba45
cd80e89
 
d78ba45
 
 
 
 
 
 
 
cd80e89
 
 
 
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
"""Mint a device token for the robot (Chintani). Run on Karnak's own machine, never on the robot.

    python -m brain.cli.device --name chintani

It reads AUTH_SECRET and ALLOWED_EMAIL from backend/.env — the same values the Space uses — and
finds the user id from the brain's own login table in Supabase, so the robot lands on the same
rows (and the same memories) as the phone. The token is printed once; put it in the robot's
``~/.config/chintani/token`` file and nowhere else.

What the token can do is narrow on purpose: it is accepted only by the ``/robot/*`` routes, which
run Normal mode with no private memories and no tools. It lasts a year. To switch one token off,
add the token id this prints to REVOKED_DEVICE_TOKENS (comma-separated) on the Space.
"""

import argparse
import os
import sys
import time

import httpx

from .. import config  # noqa: F401 — importing config loads backend/.env
from ..auth import AuthConfig, User, issue_device_token


def find_user_id(url: str, key: str, email: str) -> str:
    """The user id the brain assigned this email at its last Google sign-in."""
    response = httpx.get(
        f"{url.rstrip('/')}/rest/v1/login_sessions",
        params={
            "select": "user_id",
            "email": f"eq.{email}",
            "order": "last_used_at.desc",
            "limit": "1",
        },
        headers={"apikey": key, "Authorization": f"Bearer {key}"},
        timeout=20,
    )
    response.raise_for_status()
    rows = response.json()
    if not rows:
        raise SystemExit(
            "No sign-in found for that email. Sign in once from the app first, so the brain knows "
            "the account, then run this again."
        )
    return str(rows[0]["user_id"])


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--name", required=True, help="A label for the device, e.g. chintani")
    parser.add_argument("--user-id", help="Skip the Supabase lookup and use this user id")
    args = parser.parse_args()

    auth = AuthConfig.from_env(dict(os.environ))
    if problems := auth.problems():
        raise SystemExit("Missing in backend/.env: " + ", ".join(problems))
    email = auth.allowed_emails[0]

    user_id = args.user_id
    if not user_id:
        url = os.environ.get("SUPABASE_URL", "")
        key = os.environ.get("SUPABASE_SECRET_KEY", "")
        if not url or not key:
            raise SystemExit("Set SUPABASE_URL and SUPABASE_SECRET_KEY, or pass --user-id.")
        user_id = find_user_id(url, key, email)

    minted = issue_device_token(
        auth, User(id=user_id, email=email), device=args.name, now=time.time()
    )
    expires = time.strftime("%Y-%m-%d", time.localtime(minted.expires_at))
    print(
        f"Device token for {args.name!r}, valid until {expires} (keep it secret).\n"
        f"Token id {minted.token_id}: add it to REVOKED_DEVICE_TOKENS on the Space to switch "
        "this token off.",
        file=sys.stderr,
    )
    print(minted.token)


if __name__ == "__main__":
    main()