Files
lintunes/lintunes/cassette/invite.py
T
trav 5520eb333e v0.27.0: Cassette invites — one paste connects two friends
- Connections ▸ Share Library with a Friend… makes a one-time invite code
  (device id, display name, token) and the inviter's send-only folder.
- Connections ▸ Add Friend Library… takes the pasted code: adds the
  inviter, shares our folder, and accepts theirs receive-only when it's
  offered back.
- Syncthing hides an unknown device's folders (verified on 1.30), so the
  inviter probes a new knock only while an invite is open: added with
  nothing shared, completed on the right token, otherwise removed and
  never probed again. Used and cancelled codes go nowhere.
- Sync Settings lists open invites (Cancel Invite) and gives each friend a
  page: avatar, plain-language status with a next step, last seen, last
  synced, Remove Friend. Removals are staged until OK.
- scripts/cassette_pair.py runs throwaway Syncthings on loopback;
  pytest --syncthing drives a real three-machine handshake.
2026-09-28 21:13:07 -07:00

95 lines
3.1 KiB
Python

"""Invite codes and the folder ids that carry their token.
An invite code is one line a person pastes into a chat:
LTC1.eyJkIjoiQUJDREVGRy0uLi4iLCJuIjoidHJhdiIsInQiOiIzZjE…
``LTC1.`` + base64url (unpadded) of ``{"d": device id, "n": display name,
"t": token}``. The token is a random one-time secret; it ends up in the ids of
the two Syncthing folders the friendship is made of:
* ``lintunes-cassette-<token>-a`` — the inviter's folder (inviter → invitee)
* ``lintunes-cassette-<token>-b`` — the invitee's folder (invitee → inviter)
The inviter's LinTunes accepts a newcomer only when it offers ``-b`` for an
invite still open on this machine, which is what makes the code single-use.
"""
from __future__ import annotations
import base64
import binascii
import json
import re
import secrets
from dataclasses import dataclass
PREFIX = "LTC1."
FOLDER_PREFIX = "lintunes-cassette-"
# Syncthing device id: 8 groups of 7 base32 characters.
_DEVICE_RE = re.compile(r"^[A-Z2-7]{7}(-[A-Z2-7]{7}){7}$")
_TOKEN_RE = re.compile(r"^[0-9a-f]{16}$")
_FOLDER_RE = re.compile(r"^lintunes-cassette-([0-9a-f]{16})-([ab])$")
NOT_VALID = ("That code isn't valid. Check that the whole code was copied — it "
"starts with LTC1. and is one long line.")
class InviteError(ValueError):
"""Shown to the user as is."""
@dataclass(frozen=True)
class InviteCode:
device_id: str
name: str
token: str
def new_token() -> str:
return secrets.token_hex(8)
def inviter_folder(token: str) -> str:
return f"{FOLDER_PREFIX}{token}-a"
def invitee_folder(token: str) -> str:
return f"{FOLDER_PREFIX}{token}-b"
def parse_folder_id(folder_id: str) -> tuple[str, str] | None:
"""(token, "a"|"b") for one of our folder ids, else None."""
match = _FOLDER_RE.match(folder_id or "")
return (match.group(1), match.group(2)) if match else None
def encode(device_id: str, name: str, token: str) -> str:
payload = json.dumps({"d": device_id, "n": name, "t": token},
separators=(",", ":"), ensure_ascii=False)
body = base64.urlsafe_b64encode(payload.encode("utf-8")).decode("ascii")
return PREFIX + body.rstrip("=")
def decode(text: str) -> InviteCode:
"""Parse a pasted code. Forgiving about whitespace and line breaks a chat
app may have added; strict about everything else."""
compact = "".join((text or "").split())
start = compact.find(PREFIX)
if start < 0:
raise InviteError(NOT_VALID)
body = compact[start + len(PREFIX):]
try:
raw = base64.urlsafe_b64decode(body + "=" * (-len(body) % 4))
data = json.loads(raw.decode("utf-8"))
except (binascii.Error, ValueError, UnicodeDecodeError):
raise InviteError(NOT_VALID) from None
if not isinstance(data, dict):
raise InviteError(NOT_VALID)
device_id = str(data.get("d", "")).upper()
token = str(data.get("t", "")).lower()
name = str(data.get("n", "")).strip()[:80] or "Your friend"
if not _DEVICE_RE.match(device_id) or not _TOKEN_RE.match(token):
raise InviteError(NOT_VALID)
return InviteCode(device_id=device_id, name=name, token=token)