Commit 7baf7ba5 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add real invite code, PIN, and location discovery to Rooms

Rooms were open-join-by-id only with no geo features, despite that being the
intended design. Generates a unique invite code server-side on every create,
adds an optional PIN (hashed like account passwords, rate-limited on guesses
via a third reuse of AuthAttempt) gating join/stream/websocket alike, and adds
optional lat/lon with a haversine-sorted nearby lookup (haversine itself
extracted to a shared geo service once a second caller needed it).
parent f05e01b4
Pipeline #1222 failed with stage
in 3 minutes and 41 seconds
"""add invite code, PIN, and location to rooms
Revision ID: c3a7e5f91b04
Revises: b1f4a0d7e3c2
Create Date: 2026-10-12 13:05:00.000000
"""
import secrets
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'c3a7e5f91b04'
down_revision: Union[str, Sequence[str], None] = 'b1f4a0d7e3c2'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
# No 0/O or 1/I - avoids ambiguity when a code is read aloud or typed from a photo.
INVITE_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
INVITE_CODE_LENGTH = 7
def upgrade() -> None:
"""Upgrade schema."""
# Note: autogenerate also wanted to add a FK constraint on remix_jobs.user_id - a known
# pre-existing drift between the model and the actual schema history in this project, not
# related to this change. Deliberately left out, same as every prior migration that's hit it.
op.add_column('live_rooms', sa.Column('invite_code', sa.String(), nullable=True))
op.add_column('live_rooms', sa.Column('pin_hash', sa.String(), nullable=True))
op.add_column('live_rooms', sa.Column('latitude', sa.Float(), nullable=True))
op.add_column('live_rooms', sa.Column('longitude', sa.Float(), nullable=True))
# Every pre-existing room needs a real, unique invite_code before the unique index below
# can be created - SQLite can't generate random unique strings in SQL, so this loops in
# Python instead, same spirit as any other data-backfill migration in this project.
conn = op.get_bind()
existing_ids = conn.execute(sa.text("SELECT id FROM live_rooms")).fetchall()
used = set()
for (room_id,) in existing_ids:
while True:
code = "".join(secrets.choice(INVITE_CODE_ALPHABET) for _ in range(INVITE_CODE_LENGTH))
if code not in used:
used.add(code)
break
conn.execute(sa.text("UPDATE live_rooms SET invite_code = :code WHERE id = :id"), {"code": code, "id": room_id})
op.create_index(op.f('ix_live_rooms_invite_code'), 'live_rooms', ['invite_code'], unique=True)
op.add_column('auth_attempts', sa.Column('room_id', sa.Integer(), nullable=True))
op.create_index(op.f('ix_auth_attempts_room_id'), 'auth_attempts', ['room_id'])
op.add_column('auth_attempts', sa.Column('user_id', sa.Integer(), nullable=True))
op.create_index(op.f('ix_auth_attempts_user_id'), 'auth_attempts', ['user_id'])
def downgrade() -> None:
"""Downgrade schema."""
op.drop_index(op.f('ix_auth_attempts_user_id'), table_name='auth_attempts')
op.drop_column('auth_attempts', 'user_id')
op.drop_index(op.f('ix_auth_attempts_room_id'), table_name='auth_attempts')
op.drop_column('auth_attempts', 'room_id')
op.drop_index(op.f('ix_live_rooms_invite_code'), table_name='live_rooms')
op.drop_column('live_rooms', 'longitude')
op.drop_column('live_rooms', 'latitude')
op.drop_column('live_rooms', 'pin_hash')
op.drop_column('live_rooms', 'invite_code')
This diff is collapsed.
import math
import os
from datetime import datetime, timedelta, timezone
from typing import Optional
......@@ -21,6 +20,7 @@ from src.core.database import (
User,
)
from src.core.security import get_current_business_admin, get_current_super_admin, get_current_user, get_current_user_for_stream, hash_password, is_super_admin
from src.services.geo import haversine_meters as _haversine_meters
router = APIRouter(prefix="/soundmarks", tags=["Soundmarks"])
......@@ -32,14 +32,6 @@ VALID_TIERS = {"major", "business", "community"}
NOMINATIM_USER_AGENT = "StaxSoundmarks/1.0 (location picker for the Stax soundmarks feature)"
def _haversine_meters(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
R = 6371000.0 # Earth radius in meters
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2) ** 2
return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
def _validate_tier_and_owner(tier: str, business_owner_id: Optional[int]) -> None:
if tier not in VALID_TIERS:
raise HTTPException(status_code=422, detail=f"tier must be one of {sorted(VALID_TIERS)}")
......
......@@ -67,14 +67,18 @@ class RefreshToken(Base):
class AuthAttempt(Base):
"""Logged on every /auth/telegram/request_code call (phone_number set) to rate-limit our
own Telegram API usage, and on every /auth/login call (username set) to rate-limit
brute-force login attempts - the two purposes share this table but stay independent of
each other (queries always filter on whichever column is relevant, never mix the two)."""
own Telegram API usage, on every /auth/login call (username set) to rate-limit
brute-force login attempts, and on every room-PIN join/websocket attempt (room_id +
user_id set) to rate-limit PIN brute-forcing - three purposes sharing this table, each
staying independent of the others (queries always filter on whichever columns are
relevant to that purpose, never mix them)."""
__tablename__ = "auth_attempts"
id = Column(Integer, primary_key=True, index=True)
phone_number = Column(String, index=True, nullable=True)
username = Column(String, index=True, nullable=True)
ip_address = Column(String, index=True)
room_id = Column(Integer, ForeignKey("live_rooms.id"), index=True, nullable=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class DiscoveryAttempt(Base):
......@@ -289,14 +293,24 @@ class LiveRoom(Base):
current_song_id = Column(Integer, ForeignKey("library_songs.id"), nullable=True)
name = Column(String)
is_active = Column(Boolean, default=True)
# Alternate join key, shareable out-of-band (a link/code) instead of the bare numeric id.
# Nullable at the DB level only because the SQLite add-column migration couldn't backfill
# and add a unique index in one statement - create_live_room always sets it on every new row.
invite_code = Column(String, unique=True, index=True, nullable=True)
# PBKDF2 hash via hash_password (security.py) - same mechanism as User.password_hash, not
# new crypto. Null means no PIN required to join.
pin_hash = Column(String, nullable=True)
latitude = Column(Float, nullable=True)
longitude = Column(Float, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class RoomMessage(Base):
"""Persisted room group chat - replaces what used to be an in-memory-only
deque(maxlen=50) on RoomState (room_manager.py) that was discarded entirely the instant a
room's last connection dropped. Rooms are open/unscoped shared content by existing design
(any authenticated user can join any active room, same as Posts) - there's no membership
check on reading these, only on who's *connected live* right now (room_manager.py)."""
room's last connection dropped. Rooms are open/unscoped shared content by default (any
authenticated user can join any active room, same as Posts) unless the creator has set a
PIN (social.py's _verify_room_pin) - there's no membership check on reading chat history,
only on who's *connected live* right now (room_manager.py) or streaming its audio."""
__tablename__ = "room_messages"
id = Column(Integer, primary_key=True, index=True)
room_id = Column(Integer, ForeignKey("live_rooms.id"), index=True, nullable=False)
......
import math
def haversine_meters(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
"""Great-circle distance in meters. Shared by Soundmarks' /nearby, Rooms' /nearby, and
Radio's local-scope visibility check - originally a private copy inside soundmarks.py,
moved here once a second and third consumer needed the exact same math."""
R = 6371000.0 # Earth radius in meters
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2) ** 2
return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
from src.services.geo import haversine_meters
def test_haversine_zero_distance_for_identical_points():
assert haversine_meters(40.0, -73.0, 40.0, -73.0) == 0.0
def test_haversine_known_city_pair_within_tolerance():
# New York City <-> Los Angeles, real-world great-circle distance is ~3936 km.
nyc = (40.7128, -74.0060)
la = (34.0522, -118.2437)
distance_km = haversine_meters(*nyc, *la) / 1000.0
assert 3900 <= distance_km <= 3970
def test_haversine_small_distance_is_small():
# Two points ~111m apart (0.001 degrees of latitude) should read as roughly that, not
# some wildly different value from a sign/unit error.
distance = haversine_meters(40.0, -73.0, 40.001, -73.0)
assert 100 <= distance <= 120
def test_haversine_is_symmetric():
a = (51.5074, -0.1278) # London
b = (48.8566, 2.3522) # Paris
assert haversine_meters(*a, *b) == haversine_meters(*b, *a)
def test_haversine_antipodal_points_near_earth_circumference_half():
# Roughly opposite sides of the globe - should be close to half the Earth's circumference
# (~20015 km), a sanity check that the formula doesn't blow up or wrap incorrectly.
distance_km = haversine_meters(0.0, 0.0, 0.0, 179.9) / 1000.0
assert 19900 <= distance_km <= 20020
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment