diff --git a/.env.example b/.env.example index d1824ce..0ff8336 100644 --- a/.env.example +++ b/.env.example @@ -97,12 +97,12 @@ ADMIN_API_KEY= # --- Dashboard session cookie --- # The web dashboard signs in with an httpOnly cookie instead of keeping the -# API token in localStorage. Secure cookies work on http://localhost; set -# AUTH_COOKIE_SECURE=false only for a plain-http install on a LAN address. -# Keep SameSite=lax while the web app and the API share a site -# (app.example.com + api.example.com); use "none" (requires Secure) when -# they live on different sites. SOKHAN_CORS_ORIGINS must list the web origin. -AUTH_COOKIE_SECURE=true +# API token in localStorage. It reaches the API through its own /api path, +# so the cookie is first-party on any host. AUTH_COOKIE_SECURE=auto marks it +# Secure whenever the browser uses HTTPS (directly or via a proxy setting +# X-Forwarded-Proto); true/false force it. SameSite=none (with HTTPS) is only +# needed when NEXT_PUBLIC_API_BASE points at an API on a different site. +AUTH_COOKIE_SECURE=auto AUTH_COOKIE_SAMESITE=lax AUTH_COOKIE_MAX_AGE_DAYS=30 @@ -128,8 +128,12 @@ WEB_BASE_URL=http://localhost:3000 API_BASE_URL=http://localhost:8000 # --- Web --- -# Browser-facing API base URL used by the Next.js app. -NEXT_PUBLIC_API_BASE=http://localhost:8000 +# Browser-facing API base URL, baked into the web build. Leave empty: the +# dashboard then calls /api on its own origin, which the web server proxies +# to API_PROXY_TARGET. Set it only when the API is served from its own host +# (that also needs SOKHAN_CORS_ORIGINS and AUTH_COOKIE_SAMESITE=none). +NEXT_PUBLIC_API_BASE= +API_PROXY_TARGET=http://api:8000 # --- Job-completion webhooks (optional) --- # Jobs uploaded with a callback_url get a POST when they finish. The payload diff --git a/CHANGELOG.md b/CHANGELOG.md index 72f719a..863cbb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,23 +43,26 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje `deploy/.env`; the missing-password error names that path too. Copying it to the repo root left `POSTGRES_PASSWORD` unset for compose. - Sign-in through the dashboard flows (register, login, connect code) now - also sets the token as an `HttpOnly; Secure; SameSite=lax` session - cookie, and the API accepts it in place of a bearer header. Every + also sets the token as an `HttpOnly; SameSite=lax` session cookie + (`Secure` whenever the browser uses HTTPS), and the API accepts it in place of a bearer header. Every cookie-authenticated write must send the session's CSRF token in `X-CSRF-Token` (403 otherwise); the token is an HMAC of the session token, so nothing extra is stored. `GET /auth/session` returns the signed-in account and its CSRF token, and logout clears the cookie. Bearer auth (bot, API scripts, OpenAI-compatible clients) is unchanged - and needs no CSRF token. New settings: `AUTH_COOKIE_SECURE`, - `AUTH_COOKIE_SAMESITE`, `AUTH_COOKIE_MAX_AGE_DAYS`. CORS now allows - credentials for the configured `SOKHAN_CORS_ORIGINS` (#33). + and needs no CSRF token. New settings: `AUTH_COOKIE_SECURE` + (`auto`/`true`/`false`), `AUTH_COOKIE_SAMESITE`, + `AUTH_COOKIE_MAX_AGE_DAYS`. CORS now allows credentials for the + configured `SOKHAN_CORS_ORIGINS` (#33). - The dashboard no longer keeps the API token in `localStorage`, where an XSS could read it (CodeQL `js/clear-text-storage-of-sensitive-data`). It relies on the httpOnly session cookie, sends the CSRF token on writes, learns who is signed in from `GET /auth/session`, and wipes the token - earlier versions left in `localStorage`. **Self-hosters:** - `SOKHAN_CORS_ORIGINS` must list the dashboard's origin, and a plain-http - install on a LAN address needs `AUTH_COOKIE_SECURE=false` (#33). + earlier versions left in `localStorage`. The dashboard reaches the API + through its own `/api` path, proxied by the web server to + `API_PROXY_TARGET`, so the cookie is first-party on localhost, 127.0.0.1, + a LAN address or a domain alike; `NEXT_PUBLIC_API_BASE` now defaults to + empty and is only for an API on its own host (#33). ### Added diff --git a/README.fa.md b/README.fa.md index f9c4528..366d66c 100644 --- a/README.fa.md +++ b/README.fa.md @@ -181,10 +181,10 @@ docker pull ghcr.io/abolfazlrwm/sokhan-web:latest خودش نوشته: با `up -d --build` لوکال بسازید، یا با `docker compose -f deploy/docker-compose.yml pull` و `up -d --no-build` ایمیج‌های منتشرشده را اجرا کنید. نسخه‌های پین‌شده تابع تگ‌های گیت هستند -(مثل `ghcr.io/abolfazlrwm/sokhan-api:1.2.0`). توجه: ایمیج وب مقدار -`NEXT_PUBLIC_API_BASE` (پیش‌فرض `http://localhost:8000`) را موقع build -می‌گیرد — دیپلوی‌هایی که داشبورد را از origin دیگری سرو می‌کنند باید خودشان -این build argument را بدهند. +(مثل `ghcr.io/abolfazlrwm/sokhan-api:1.2.0`). داشبورد API را از +مسیر `/api` روی همان origin خودش صدا می‌زند و وب‌سرور آن را به +`API_PROXY_TARGET` (پیش‌فرض `http://api:8000`، موقع build) پراکسی می‌کند؛ +برای همین یک ایمیج روی هر هاست یا دامنه‌ای کار می‌کند. ## توسعه @@ -237,7 +237,8 @@ SOKHAN_REAL_MODEL_TEST=1 pytest backend/tests/test_real_model.py | `BOT_API_SECRET` | خالی | رمز مشترکی که ربات به `POST /auth/telegram` می‌فرستد؛ روی API و ربات یک مقدار بگذارید، خالی یعنی ورود تلگرامی غیرفعال | | `WEB_BASE_URL` | `http://localhost:3000` | لینک‌هایی که ربات می‌فرستد | | `API_BASE_URL` | `http://localhost:8000` | آدرس API که ربات صدا می‌زند | -| `NEXT_PUBLIC_API_BASE` | `http://localhost:8000` | آدرس API که اپ وب صدا می‌زند (زمان build) | +| `NEXT_PUBLIC_API_BASE` | خالی (همان origin، `/api`) | آدرس API که اپ وب صدا می‌زند، فقط وقتی API روی هاست جدا است (زمان build) | +| `API_PROXY_TARGET` | `http://api:8000` | مقصد پراکسی `/api` در وب‌سرور (زمان build) | فهرست کامنت‌دار در [.env.example](.env.example). diff --git a/README.md b/README.md index be4b768..99841e5 100644 --- a/README.md +++ b/README.md @@ -180,10 +180,10 @@ docker pull ghcr.io/abolfazlrwm/sokhan-web:latest `build:` blocks: keep `up -d --build` to build locally, or `docker compose -f deploy/docker-compose.yml pull` and `up -d --no-build` to run the published images. Pinned versions follow the -git tags (e.g. `ghcr.io/abolfazlrwm/sokhan-api:1.2.0`). Note the web image -bakes `NEXT_PUBLIC_API_BASE` (default `http://localhost:8000`) at build -time — deployments serving the dashboard from another origin pass the -build argument themselves. +git tags (e.g. `ghcr.io/abolfazlrwm/sokhan-api:1.2.0`). The dashboard calls +the API through its own `/api` path, which the web server proxies to +`API_PROXY_TARGET` (default `http://api:8000`, baked at build time), so one +image works on any host or domain. ## Development @@ -236,7 +236,8 @@ SOKHAN_REAL_MODEL_TEST=1 pytest backend/tests/test_real_model.py | `BOT_API_SECRET` | empty | shared secret the bot sends to `POST /auth/telegram`; set the same value on the API and the bot, empty disables Telegram login | | `WEB_BASE_URL` | `http://localhost:3000` | links the bot sends | | `API_BASE_URL` | `http://localhost:8000` | API address the bot calls | -| `NEXT_PUBLIC_API_BASE` | `http://localhost:8000` | API address the web app calls (build-time) | +| `NEXT_PUBLIC_API_BASE` | empty (same-origin `/api`) | API address the web app calls, only for an API on its own host (build-time) | +| `API_PROXY_TARGET` | `http://api:8000` | Where the web server proxies `/api` (build-time) | See [.env.example](.env.example) for the commented list. diff --git a/backend/sokhan/api/routes_auth.py b/backend/sokhan/api/routes_auth.py index 7ba5fbf..284e65a 100644 --- a/backend/sokhan/api/routes_auth.py +++ b/backend/sokhan/api/routes_auth.py @@ -75,7 +75,24 @@ def _validate_credentials(email: str, password: str) -> str: return email -def _start_session(response: Response, user: User, token: str) -> AuthResponse: +def _cookie_is_secure(request: Request) -> bool: + """Whether the session cookie gets the Secure attribute. + + `auto` (the default) follows the scheme the browser used: HTTPS directly + or behind a proxy that sets X-Forwarded-Proto. Browsers drop a Secure + cookie that arrives over plain http (Safari even on localhost), which + left plain-http installs unable to stay signed in. + """ + mode = get_settings().auth_cookie_secure.strip().lower() + if mode in ("true", "1", "yes"): + return True + if mode in ("false", "0", "no"): + return False + forwarded = request.headers.get("x-forwarded-proto", "").split(",")[0].strip().lower() + return request.url.scheme == "https" or forwarded == "https" + + +def _start_session(request: Request, response: Response, user: User, token: str) -> AuthResponse: """Set the httpOnly session cookie and answer with the CSRF token.""" settings = get_settings() response.set_cookie( @@ -84,7 +101,7 @@ def _start_session(response: Response, user: User, token: str) -> AuthResponse: max_age=settings.auth_cookie_max_age_days * 24 * 3600, path="/", httponly=True, - secure=settings.auth_cookie_secure, + secure=_cookie_is_secure(request), samesite=settings.auth_cookie_samesite, ) return AuthResponse( @@ -92,20 +109,23 @@ def _start_session(response: Response, user: User, token: str) -> AuthResponse: ) -def _end_session(response: Response) -> None: +def _end_session(request: Request, response: Response) -> None: settings = get_settings() response.delete_cookie( SESSION_COOKIE, path="/", httponly=True, - secure=settings.auth_cookie_secure, + secure=_cookie_is_secure(request), samesite=settings.auth_cookie_samesite, ) @router.post("/register", response_model=AuthResponse) def register( - payload: Credentials, response: Response, session: Session = Depends(get_db) + payload: Credentials, + request: Request, + response: Response, + session: Session = Depends(get_db), ) -> AuthResponse: email = _validate_credentials(payload.email, payload.password) if session.scalar(select(User).where(User.email == email)): @@ -119,7 +139,7 @@ def register( ) session.add(user) session.commit() - return _start_session(response, user, token) + return _start_session(request, response, user, token) _login_throttle: FailureThrottle | None = None @@ -167,17 +187,20 @@ def login( token = generate_token() user.token_hash = token_hash(token) session.commit() - return _start_session(response, user, token) + return _start_session(request, response, user, token) @router.post("/token-login", response_model=AuthResponse) def token_login( - payload: TokenLogin, response: Response, session: Session = Depends(get_db) + payload: TokenLogin, + request: Request, + response: Response, + session: Session = Depends(get_db), ) -> AuthResponse: user = session.scalar(select(User).where(User.token_hash == token_hash(payload.api_token))) if user is None: raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid connect code") - return _start_session(response, user, payload.api_token) + return _start_session(request, response, user, payload.api_token) @router.get("/session", response_model=SessionOut) @@ -193,7 +216,11 @@ def current_session( @router.post("/logout", status_code=status.HTTP_204_NO_CONTENT) -def logout(user: User = Depends(get_current_user), session: Session = Depends(get_db)) -> Response: +def logout( + request: Request, + user: User = Depends(get_current_user), + session: Session = Depends(get_db), +) -> Response: """Revoke the caller's token so it stops working everywhere. An account has a single active token, so this signs out every client @@ -204,7 +231,7 @@ def logout(user: User = Depends(get_current_user), session: Session = Depends(ge user.token_hash = token_hash(generate_token()) session.commit() response = Response(status_code=status.HTTP_204_NO_CONTENT) - _end_session(response) + _end_session(request, response) return response diff --git a/backend/sokhan/config.py b/backend/sokhan/config.py index 473d7f4..e826781 100644 --- a/backend/sokhan/config.py +++ b/backend/sokhan/config.py @@ -76,12 +76,12 @@ class Settings(BaseSettings): bot_api_secret: str = "" - # Dashboard session cookie (httpOnly). Secure by default: browsers still - # accept it on http://localhost, so only plain-http LAN installs need - # AUTH_COOKIE_SECURE=false. SameSite=lax works whenever the web app and - # the API share a site (localhost:3000 + localhost:8000, or - # app.example.com + api.example.com); different sites need "none". - auth_cookie_secure: bool = True + # Dashboard session cookie (httpOnly). AUTH_COOKIE_SECURE=auto sets the + # Secure attribute whenever the browser came in over HTTPS (directly or + # via X-Forwarded-Proto); true/false force it. The web app proxies the + # API under its own origin (/api), so SameSite=lax always applies; a + # separately hosted API on another site needs "none" plus HTTPS. + auth_cookie_secure: str = "auto" auth_cookie_samesite: str = "lax" auth_cookie_max_age_days: int = 30 diff --git a/backend/tests/test_cookie_session.py b/backend/tests/test_cookie_session.py index cf5cb41..f8068a6 100644 --- a/backend/tests/test_cookie_session.py +++ b/backend/tests/test_cookie_session.py @@ -31,8 +31,24 @@ def test_login_sets_an_httponly_session_cookie(cookie_client): assert body["csrf_token"] == csrf_token_for(body["api_token"]) -def test_cookie_is_secure_by_default(client): +def test_cookie_secure_follows_the_scheme_by_default(client): + # Plain http: a Secure cookie would be dropped by the browser. + plain = client.post("/auth/register", json=CREDENTIALS).headers["set-cookie"] + assert "Secure" not in plain + + # HTTPS terminated by a reverse proxy in front of the API. + behind_tls = client.post( + "/auth/login", json=CREDENTIALS, headers={"X-Forwarded-Proto": "https"} + ).headers["set-cookie"] + assert "Secure" in behind_tls + + +def test_cookie_secure_can_be_forced(client, monkeypatch): + monkeypatch.setenv("AUTH_COOKIE_SECURE", "true") + get_settings.cache_clear() + cookie = client.post("/auth/register", json=CREDENTIALS).headers["set-cookie"] + assert "Secure" in cookie diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index d610fbb..7f872f6 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -58,7 +58,7 @@ services: PLAN_PRO_MONTHLY_MINUTES: ${PLAN_PRO_MONTHLY_MINUTES:-1200} ADMIN_API_KEY: ${ADMIN_API_KEY:-} BOT_API_SECRET: ${BOT_API_SECRET:-} - AUTH_COOKIE_SECURE: ${AUTH_COOKIE_SECURE:-true} + AUTH_COOKIE_SECURE: ${AUTH_COOKIE_SECURE:-auto} AUTH_COOKIE_SAMESITE: ${AUTH_COOKIE_SAMESITE:-lax} AUTH_COOKIE_MAX_AGE_DAYS: ${AUTH_COOKIE_MAX_AGE_DAYS:-30} MAX_UPLOAD_MB: ${MAX_UPLOAD_MB:-200} @@ -100,7 +100,10 @@ services: build: context: ../web args: - NEXT_PUBLIC_API_BASE: ${NEXT_PUBLIC_API_BASE:-http://localhost:8000} + # Empty: the browser calls /api on the web origin, proxied to the api + # service, so the session cookie is first-party on any host. + NEXT_PUBLIC_API_BASE: ${NEXT_PUBLIC_API_BASE:-} + API_PROXY_TARGET: ${API_PROXY_TARGET:-http://api:8000} ports: - "${SOKHAN_WEB_PORT:-3000}:3000" depends_on: diff --git a/web/Dockerfile b/web/Dockerfile index 0162404..b938507 100644 --- a/web/Dockerfile +++ b/web/Dockerfile @@ -5,10 +5,14 @@ COPY package.json package-lock.json ./ RUN npm ci COPY . . -# NEXT_PUBLIC_ variables are inlined into the client bundle at build time, -# so the API base URL is provided as a build argument. -ARG NEXT_PUBLIC_API_BASE=http://localhost:8000 +# Both are baked into the build. The browser calls the API through this +# app's own /api path, proxied to API_PROXY_TARGET (the compose service by +# default). NEXT_PUBLIC_API_BASE stays empty unless the API is served from +# its own host. +ARG NEXT_PUBLIC_API_BASE= +ARG API_PROXY_TARGET=http://api:8000 ENV NEXT_PUBLIC_API_BASE=$NEXT_PUBLIC_API_BASE +ENV API_PROXY_TARGET=$API_PROXY_TARGET RUN npm run build diff --git a/web/next.config.mjs b/web/next.config.mjs index 89dfc26..e54d22d 100644 --- a/web/next.config.mjs +++ b/web/next.config.mjs @@ -1,8 +1,22 @@ import createNextIntlPlugin from "next-intl/plugin"; +// The dashboard talks to the API through its own origin (/api/*), so the +// httpOnly session cookie is always first-party: it works on localhost, +// 127.0.0.1, a LAN address or a real domain alike, without CORS. The +// target is baked into the build (standalone output); compose passes the +// in-network address, `next dev` defaults to a local API. +const apiProxyTarget = (process.env.API_PROXY_TARGET || "http://localhost:8000").replace(/\/$/, ""); + /** @type {import('next').NextConfig} */ const nextConfig = { output: "standalone", + async rewrites() { + return [{ source: "/api/:path*", destination: `${apiProxyTarget}/:path*` }]; + }, + experimental: { + // Uploads and transcript downloads can outlast the 30 s proxy default. + proxyTimeout: 10 * 60 * 1000, + }, }; const withNextIntl = createNextIntlPlugin("./src/i18n/request.ts"); diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index e7de38a..36ec8ea 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -4,7 +4,10 @@ // session's CSRF token. A 401 marks the session signed out and bounces the // user back to the login screen. -const API_BASE = process.env.NEXT_PUBLIC_API_BASE || "http://localhost:8000"; +// Same-origin by default: next.config.mjs proxies /api/* to the backend, so +// the session cookie is first-party wherever the dashboard is served from. +// Set NEXT_PUBLIC_API_BASE only for an API on its own host. +const API_BASE = (process.env.NEXT_PUBLIC_API_BASE || "/api").replace(/\/$/, ""); /** Fired on this tab whenever the session state changes. */ export const SESSION_CHANGE_EVENT = "sokhan:session-change"; diff --git a/web/src/middleware.ts b/web/src/middleware.ts index 73358a6..0cbb380 100644 --- a/web/src/middleware.ts +++ b/web/src/middleware.ts @@ -4,5 +4,6 @@ import { routing } from "./i18n/routing"; export default createMiddleware(routing); export const config = { - matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\..*).*)"], + // /api is the proxied backend: it must not get a locale prefix. + matcher: ["/((?!api/|_next/static|_next/image|favicon.ico|.*\\..*).*)"], };