Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
Cloudflare Turnstile (``turnstile.py``, off without keys).
"""

from collections.abc import Awaitable, Callable
from typing import Annotated

from fastapi import APIRouter, Depends, Form, HTTPException, Request, Response, status
Expand Down Expand Up @@ -39,7 +40,7 @@ async def guest_sign_in(
403 when the human check fails."""
ip = get_client_ip(request)
if not await STARTS.take(ip or "unknown"):
raise too_many(STARTS.window_seconds)
raise too_many(STARTS.window_seconds, detail="guest_limited")
if not await turnstile.passed(human, ip):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="guest_human")
user = await guest_user(users)
Expand All @@ -48,3 +49,35 @@ async def guest_sign_in(
access_token = await sign_in(request, response, user, GUEST, refresh_service)
await audit.emit("auth.guest_sign_in", actor_id=user.id, ip_address=ip)
return TokenResponse(access_token=access_token)


# A page's way to start a guest (``guest_starter``): the sign-in above with
# its cookies on the page's own response; the reason it was refused (the
# sign-in's detail: guest_limited, guest_human, guest_closed), else None.
GuestStart = Callable[[Response, str | None], Awaitable[str | None]]


async def guest_starter(
request: Request,
users: UserService = Depends(get_user_service),
refresh_service: RefreshService = Depends(get_refresh_service),
audit: AuditEmitter = Depends(get_audit),
) -> GuestStart:
"""What a page that starts guests depends on, so each words only its
own refusals and no page repeats the sign-in's dependencies."""

async def start(response: Response, human: str | None) -> str | None:
try:
await guest_sign_in(
request=request,
response=response,
human=human,
users=users,
refresh_service=refresh_service,
audit=audit,
)
except HTTPException as exc:
return str(exc.detail)
return None

return start
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,14 @@ def get_session_metadata(request: Request) -> dict[str, str | None]:



def too_many(window_seconds: int) -> HTTPException:
"""The 429 every limit answers with, saying when to try again."""
def too_many(
window_seconds: int, detail: str = "Too many requests. Please try again later."
) -> HTTPException:
"""The 429 every limit answers with, saying when to try again; a limit
whose callers word it themselves gives its reason as ``detail``."""
return HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="Too many requests. Please try again later.",
detail=detail,
headers={"Retry-After": str(window_seconds)},
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ def enabled() -> bool:
return bool(settings.TURNSTILE_SITE_KEY and settings.TURNSTILE_SECRET_KEY)


def site_key() -> str:
"""The key a page renders the widget with; blank while the check is off."""
return settings.TURNSTILE_SITE_KEY if enabled() else ""


async def passed(token: str | None, ip: str | None) -> bool:
"""Whether ``token`` is one Cloudflare gave a human just now; True
while the check is off."""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ class ChatSurface:
# of them beside the thread. A mount whose agent only reads leaves it
# out.
approvals: bool = True
# Whether its users may speak a turn and hear one read aloud: paid per
# use, so a mount whose users spend from a budget that does not count
# them leaves the microphone, read-aloud and their routes out.
speech: bool = True
# Whether its users may call, on what the install calls with. None
# follows ``operator_controls``; True lets in a caller with no controls
# (a signed-out visitor), and ``bind`` may decide it per request.
Expand Down Expand Up @@ -131,6 +135,12 @@ def page_at(self, path: str | None) -> Page | None:
return self.pages.get(path or "")


def speaks(chat: ChatSurface) -> bool:
"""Whether the mount takes a spoken turn and reads a reply aloud:
voice and the mount's say (``speech``)."""
return HAS_VOICE and chat.speech


def offers_calls(chat: ChatSurface) -> bool:
"""Whether the mount takes live calls: voice, a database and the
mount's say (``calls``, else the operator's controls)."""
Expand Down Expand Up @@ -356,7 +366,7 @@ def settled(
"turns_url": f"{chat.path}/turns",
"continue_vals": {"message": CONTINUE, "conversation_id": conversation_id},
"model_icon": (icons or {}).get(str(meta.get("provider") or "")),
"speech": f"{url}/speech" if HAS_VOICE else None,
"speech": f"{url}/speech" if speaks(chat) else None,
"eval_url": f"{chat.eval_cases}?{urlencode({'turn': message.id})}"
if chat.eval_cases and message.role.value == "assistant"
else None,
Expand Down Expand Up @@ -436,7 +446,7 @@ def _call_context(chat: ChatSurface) -> dict[str, Any]:
"""What a call needs on any page it is held on (``partials/chat/_call.html``)."""
return {
"chat_path": chat.path,
"voice": _voice(chat) if HAS_VOICE else None,
"voice": _voice(chat) if speaks(chat) else None,
"calls": offers_calls(chat),
# A call's engine and running cost are the operator's figures.
"operator": chat.operator_controls,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,7 @@
"password_input": """
{{ password_input("password", placeholder="Password", required=False) }}""",
"or_divider": "{{ or_divider() }}",
"human_check": """{{ human_check("1x00000000000000000000AA") }}""",
"honeypot": "{{ honeypot() }}",
"no_autofill": """{{ text_input("api_key", placeholder="Paste a key", attrs=no_autofill()) }}""",
"range_chips": """{{ range_chips([(1, "1d"), (7, "7d"), (30, "30d")], 7) }}""",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def guest_sign_in() -> str | None:
return None
from app.components.backend.security import turnstile # auth[guest] only

return settings.TURNSTILE_SITE_KEY if turnstile.enabled() else ""
return turnstile.site_key()


templates.env.globals["guest_sign_in"] = guest_sign_in
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,47 +3,31 @@

from typing import Annotated

from fastapi import APIRouter, Depends, Form, HTTPException, Request
from fastapi import APIRouter, Depends, Form, HTTPException
from fastapi.responses import RedirectResponse

from app.components.backend.api.auth.guest import guest_sign_in as api_guest_sign_in
from app.components.backend.api.auth.guest import GuestStart, guest_starter
from app.components.backend.security import turnstile
from app.components.backend.api.auth.sessions import refused_sign_in
from app.core.audit import AuditEmitter, get_audit
from app.core.config import settings
from app.core.formatting import site_path
from app.services.auth.deps import get_refresh_service, get_user_service
from app.services.auth.service import RefreshService, UserService

router = APIRouter()


@router.post("/login/guest", include_in_schema=False)
async def guest_submit(
request: Request,
next: Annotated[str, Form()] = "",
human: Annotated[str | None, Form(alias=turnstile.FIELD)] = None,
user_service: UserService = Depends(get_user_service),
refresh_service: RefreshService = Depends(get_refresh_service),
audit: AuditEmitter = Depends(get_audit),
start: GuestStart = Depends(guest_starter),
) -> RedirectResponse:
"""The sign-in page's guest button: the API's guest sign-in, with
its cookies on the redirect back to ``next``. Closed with the button
(``GUEST_ON_SIGN_IN_PAGE``)."""
if not settings.GUEST_ON_SIGN_IN_PAGE:
raise HTTPException(status_code=404)
redirect = RedirectResponse(url=site_path(next, "/"), status_code=303)
try:
await api_guest_sign_in(
request=request,
response=redirect,
human=human,
users=user_service,
refresh_service=refresh_service,
audit=audit,
)
except HTTPException as exc:
reason = "guest_limited" if exc.status_code == 429 else str(exc.detail)
if reason := await start(redirect, human):
return refused_sign_in("/login", reason, next)
return redirect
{%- endif %}
Original file line number Diff line number Diff line change
Expand Up @@ -282,9 +282,9 @@ async def pick_model(
chip_oob=True,
)

# --- Speech: only where voice is installed --------------------------------
# --- Speech: only where voice is installed and the mount speaks ----------

if chat.HAS_VOICE:
if chat.speaks(mount):

@router.post("/speech/transcripts")
async def transcribe(audio: UploadFile) -> Response:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,19 +107,30 @@ async function fetchAuth(path, opts = {}) {
return resp;
}

// A drawer that opens on its own entry (chat_drawer.html's
// data-signed-out) takes a visitor whose session went back there, never to
// /login: that visitor may be on a host the app's sign-in is not.
function reopenedSignedOut(el) {
if (!el?.closest?.('[data-signed-out]')) return false;
window.dispatchEvent(new CustomEvent('chat:signed-out'));
return true;
}
window.reopenedSignedOut = reopenedSignedOut;

// If htmx gets a 401 from a protected endpoint, kick to /login. If it gets a
// 403 with `email_not_verified`, kick to /verify-pending so the user can
// resend the verification email.
document.addEventListener('htmx:responseError', (evt) => {
const xhr = evt.detail.xhr;
if (xhr.status === 401) {
const from = evt.detail.elt;
// Same refresh-first flow as fetchAuth. On success reload the page rather
// than replaying the htmx request - the swap target may be mid-transition,
// and a full reload re-renders the current URL with the fresh session.
_tryRefresh().then((ok) => {
if (ok) {
window.location.reload();
} else {
} else if (!reopenedSignedOut(from)) {
window.location = _loginUrlWithNext();
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,7 @@ function pageAction({ action, target, value }) {
let marker = text;
try {
const answer = await fetch(`${config().path}/pastes`, { method: 'POST', body });
if (answer.status === 401 && window.reopenedSignedOut?.(box)) return;
if (answer.ok) marker = (await answer.json()).marker;
} catch (_) { /* offline: the text goes in as text */ }
box.value = box.value.slice(0, at) + marker + box.value.slice(to);
Expand Down Expand Up @@ -413,6 +414,7 @@ function pageAction({ action, target, value }) {
page: chatPage(), // what it declares is the mount's to say
}),
});
if (resp.status === 401 && window.reopenedSignedOut?.(bubble)) return;
if (!resp.ok || !resp.body) throw new Error(`bad response ${resp.status}`);
for await (const { event, data } of frames(resp.body)) {
if (event === 'waiting') {
Expand Down Expand Up @@ -506,7 +508,7 @@ function pageAction({ action, target, value }) {
// The AI page's Chat section IS the surface, so while it shows the drawer
// empties and its button steps aside: one surface per document.
document.addEventListener('alpine:init', () => {
Alpine.data('chatDrawer', (path) => ({
Alpine.data('chatDrawer', (entry) => ({
open: false,
onChat: false,
init() { this.settled(); },
Expand All @@ -516,7 +518,13 @@ function pageAction({ action, target, value }) {
},
show() {
this.open = true;
if (!this.$refs.body.children.length) htmx.ajax('GET', `${path}/drawer`, { target: '#chat-drawer-body', swap: 'innerHTML' });
if (!this.$refs.body.children.length) htmx.ajax('GET', entry, { target: this.$refs.body, swap: 'innerHTML' });
},
// Its visitor's session went (reopenedSignedOut, auth.js): back to
// the entry, a notice they read before starting again.
reopen() {
this.$refs.body.innerHTML = '';
this.show();
},
}));
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,14 @@
page swaps. On the AI page's Chat section the page IS the surface, so
the panel empties and the button steps aside (``chatDrawer`` in
static/js/chat.js). No @click.stop on the panel: it would swallow the
delegated clicks chat.js listens for on the document. #}
delegated clicks chat.js listens for on the document. ``chat_entry`` is
what it opens on (default: the mount's drawer), where a mount shows
something first (a notice before a visitor starts), and where it goes
back to once its visitor's session is gone (``data-signed-out``,
``reopenedSignedOut`` in static/js/auth.js); a ``chat:open``
event on the window opens it from anywhere on the page. #}
{% from "components/macros/chat.html" import chat_toolbar %}
<div x-data="chatDrawer('{{ chat_path }}')" @htmx:after-settle.window="settled()">
<div x-data="chatDrawer('{{ chat_entry | default(chat_path ~ "/drawer") }}')" @htmx:after-settle.window="settled()" @chat:open.window="show()" @chat:signed-out.window="reopen()">
<button type="button" id="chat-fab" x-show="!onChat && !open" x-cloak @click="show()"
class="fixed bottom-5 right-5 z-40 rounded-xl transition-transform hover:scale-105 focus-visible:outline-2 focus-visible:outline-aegis-teal"
aria-label="Open chat" title="Chat">
Expand All @@ -28,7 +33,7 @@
</div>
</div>
{# The surface's bubble insets are page-scale; a narrow panel trims them. #}
<div id="chat-drawer-body" x-ref="body" class="flex-1 min-h-0 min-w-0 px-5 py-3 [&_.pl-24]:pl-4 [&_.pr-24]:pr-4"></div>
<div id="chat-drawer-body" x-ref="body"{% if chat_entry is defined %} data-signed-out{% endif %} class="flex-1 min-h-0 min-w-0 px-5 py-3 [&_.pl-24]:pl-4 [&_.pr-24]:pr-4"></div>
</div>
</div>
</template>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@
}[kind] }}
{%- endmacro %}

{# Cloudflare Turnstile in front of guest sign-in (``turnstile.site_key``):
its widget, which fetches Cloudflare's script itself (``humanCheck``). #}
{% macro human_check(key) %}<div class="cf-turnstile" data-sitekey="{{ key }}" data-theme="dark" x-data="humanCheck"></div>{% endmacro %}

{# Buttons are DaisyUI's: outline so the data stays louder than the
controls; ``tone`` is default (quiet: muted text and border, which
DaisyUI has no outline variant for), primary (teal), danger or warn;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{% extends "pages/auth/_layout.html" %}
{% from "components/macros/form.html" import button_classes, or_divider, submit_button %}
{% from "components/macros/form.html" import button_classes, human_check, or_divider, submit_button %}
{% from "components/auth_macros.html" import auth_field, auth_banner %}

{% block title %}Sign in - {{ project_name }}{% endblock %}
Expand Down Expand Up @@ -42,7 +42,7 @@ <h1 class="text-2xl font-semibold text-aegis-text mb-2">Welcome back</h1>
<form action="/login/guest" method="post" class="space-y-3">
{% if next %}<input type="hidden" name="next" value="{{ next }}">{% endif %}
{% if guest_key %}
<div class="cf-turnstile" data-sitekey="{{ guest_key }}" data-theme="dark" x-data="humanCheck"></div>
{{ human_check(guest_key) }}
{% endif %}
<button type="submit" class="{{ button_classes('default') }} w-full">Continue as guest</button>
</form>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ from app.core.security import SESSION_COOKIE
from app.models.user import User
from app.services.auth.service import get_current_user_from_token
{%- if include_auth_guest %}
from app.services.auth.service import is_guest
from app.services.auth.service import visitor
from app.services.auth.service import session_id_of
{%- endif %}
Expand Down Expand Up @@ -70,10 +71,26 @@ async def get_current_active_user(
return await get_current_user_from_token(token, user_service)


{%- if include_auth_guest %}
async def get_session_user(
token: str | None = Depends(get_session_token),
user_service: UserService = Depends(get_user_service),
) -> User | None:
"""Whoever the session is, a guest included; None signed out. The one
read of the session that ``get_optional_user`` and ``get_visitor``
share, so a route asking for both looks it up once."""
return await _optional_user(token, user_service, guests=True)


async def get_optional_user(
user: User | None = Depends(get_session_user),
) -> User | None:
{%- else %}
async def get_optional_user(
token: str | None = Depends(get_session_token),
user_service: UserService = Depends(get_user_service),
) -> User | None:
{%- endif %}
"""Resolve the session to a User if present, else return ``None``.

For routes that render differently for anon vs authed visitors
Expand All @@ -84,7 +101,11 @@ async def get_optional_user(
session still resolves, to the synthetic dev user.{% if include_auth_guest %} A guest is
``None`` here: it is a visitor (``get_visitor``), never a user.{% endif %}
"""
{%- if include_auth_guest %}
return None if user is None or is_guest(user) else user
{%- else %}
return await _optional_user(token, user_service)
{%- endif %}


async def _optional_user(
Expand All @@ -103,10 +124,9 @@ async def _optional_user(

async def get_visitor(
token: str | None = Depends(get_session_token),
user_service: UserService = Depends(get_user_service),
user: User | None = Depends(get_session_user),
) -> str | None:
"""``visitor()`` for this request; None signed out."""
user = await _optional_user(token, user_service, guests=True)
return visitor(user, session_id_of(token)) if user else None
{%- endif %}

Expand Down
Loading