# Bareeed OAuth Integration Guide This guide is the canonical technical reference for AI coding agents, developers, and server-side integrations with Bareeed OAuth. - Product: [Bareeed](https://bareeed.com) - Human-readable information: [https://bareeed.com/info/](https://bareeed.com/info/) - This guide: [https://bareeed.com/bareeed_oauth.txt](https://bareeed.com/bareeed_oauth.txt) - Documentation index: [https://bareeed.com/llms.txt](https://bareeed.com/llms.txt) - Developer console: [https://bareeed.com/profile/developer_tools/](https://bareeed.com/profile/developer_tools/) ## Product Overview Bareeed is a privacy-focused email application and account gateway for Khwarzma applications. This guide describes only the currently implemented OAuth behavior; it does not imply support for unimplemented OAuth or OpenID Connect features. ## Integration in five steps 1. Sign in to Bareeed and create a confidential web application in the developer console. 2. Register the exact callback URI used by the web application. Production callbacks must use HTTPS; HTTP is accepted only for localhost. 3. Keep the one-time client secret on the server. Store the client ID, secret, callback URI, and endpoint URLs in environment variables; never expose the secret in browser code or source control. 4. Generate a cryptographically random `state`, bind it to the user's server-side session, and send the browser to the authorization endpoint. 5. On the callback, validate and consume `state`, then exchange the returned authorization code from the server. Store the access token server-side and use it as a bearer token for the userinfo endpoint. The examples below demonstrate endpoint requests and environment-variable usage. Callback routing, session storage, and state validation are application responsibilities; adapt them to the web framework in use. ## Core Authentication Flow Bareeed currently implements a confidential-client authorization-code flow: 1. The application sends the user to `/oauth/authorize/` with `client_id`, the exact registered `redirect_uri`, and an unpredictable `state`. The user must already have an authenticated Bareeed browser session. 2. Bareeed displays a consent screen with the application name, registered callback address, requested data fields, and account selection when multiple accounts are available. 3. On approval, Bareeed redirects to the exact callback URI with a short-lived authorization `code` and the original `state`. Authorization codes expire after five minutes and are single-use. 4. The application's server verifies `state` against the value held in the user's session, then posts the code, client credentials, and the same exact `redirect_uri` to `/oauth/token/`. 5. On successful exchange, the application receives a one-hour JWT access token. There is no refresh-token grant or refresh-token rotation. 6. The application calls `/oauth/userinfo/` with `Authorization: Bearer ` to retrieve the identity fields granted by the authorization. Bareeed does **not** currently implement PKCE. The examples use `state` for CSRF protection; `state` is not a substitute for PKCE. Do not describe this integration as PKCE-protected. ## Endpoints The same OAuth routes are mounted at the root and under `/oauth/`. Use the `/oauth/` paths in new integrations. ### `GET /oauth/authorize/` Requires a signed-in Bareeed browser session. Query parameters: | Parameter | Required | Meaning | |---|---:|---| | `client_id` | Yes | Confidential application's client ID | | `redirect_uri` | Yes | Must exactly match a URI registered for the client | | `state` | Integrators must send it; the endpoint does not enforce it | Opaque, unpredictable value that the application must bind to its session | | `phone_number` | No | Set to `true` to request the user's phone number | Approval redirects with `code` and `state`. Denial redirects with `error=access_denied` and `state`. Do not send a client secret or access token through the browser. ### `POST /oauth/token/` Send `application/x-www-form-urlencoded` data from the confidential application's server: | Parameter | Required | Meaning | |---|---:|---| | `grant_type` | Yes | Must be `authorization_code` | | `code` | Yes | Authorization code received by the callback | | `client_id` | Yes | Client ID for the code's application | | `client_secret` | Yes | Plaintext secret, sent only server-to-server over HTTPS | | `redirect_uri` | Yes | Exact same registered URI used in the authorization request | Success response fields: `access_token`, `token_type` (`Bearer`), and `expires_in` (`3600`). The endpoint does not issue a refresh token. ### `GET /oauth/userinfo/` Send `Authorization: Bearer `. The response contains `sub`, `email`, `name`, and `avatar_url`. It also contains `phone_number` if that field was requested and granted. Treat the response as personal data and request only fields the application needs. ### Error responses The current implementation returns these errors. Authorization-endpoint validation errors are plain-text HTTP 400 responses; token and userinfo errors are JSON. | Endpoint | HTTP status | Response | |---|---:|---| | `/oauth/authorize/` | 400 | `Invalid Client ID` | | `/oauth/authorize/` | 400 | `Invalid redirect URI` | | `/oauth/token/` | 405 | `{"error":"method_not_allowed"}` for non-POST/non-OPTIONS methods | | `/oauth/token/` | 400 | `{"error":"unsupported_grant_type"}` | | `/oauth/token/` | 400 | `{"error":"invalid_grant"}` for missing, expired, or redeemed code | | `/oauth/token/` | 400 | `{"error":"invalid_grant_redirect_uri"}` | | `/oauth/token/` | 401 | `{"error":"invalid_client"}` | | `/oauth/userinfo/` | 401 | `{"error":"invalid_token"}` for missing, invalid, expired, or unrecognized-client token | | OAuth endpoints | 429 | `{"error":"rate_limit_exceeded"}` with a `Retry-After` header | Use the status code and error body to fail closed. Do not retry invalid credentials or grants as though authentication succeeded. ## Security Standards and Current Implementation ### Redirect URI validation Redirect URIs are compared as exact strings against the client's registered URI list at authorization and token exchange. Scheme, hostname, path, port, query, and trailing slash must match exactly. Production callback registrations must use HTTPS; HTTP is allowed only for localhost development. The registered URL is not proof of domain ownership. Review the hostname carefully; IDN lookalikes can be confusing. ### Client secrets New client secrets are generated by the developer console and shown only once. The database stores a Django PBKDF2-SHA256 password hash; token exchange verifies the submitted secret against that hash. Legacy plaintext secrets may be upgraded to a hash on successful verification while compatibility mode is enabled. Keep secrets in server environment or a secret manager, not in frontend JavaScript, browser storage, logs, or repositories. ### Authorization codes and access tokens Authorization codes expire after five minutes, are redeemed inside a database transaction, and are deleted on successful exchange. Access tokens are JWTs signed using HS256 and `JWT_SECRET`; they expire after one hour. Configure `JWT_SECRET` as a high-entropy production secret: the current settings file contains a development fallback value, which must not be used in production. This deployment does not currently use asymmetric RS256 signing, provide refresh tokens, or support token rotation. ### PKCE and state PKCE (`code_challenge` / `code_verifier`) is **not implemented or enforced**. The authorization endpoint does not validate PKCE parameters. Integrators must use a confidential server-side client and a random, session-bound, one-time `state` value. Do not put client secrets in public clients. ### Consent and scopes The current userinfo fields are `sub`, `email`, `name`, and `avatar_url`; `phone_number` is conditional on requesting it during authorization. The implementation records these field names on authorization-code and OAuth activity records. The API does not currently implement arbitrary named OAuth scopes or a general grant-revocation endpoint. ## Rate Limits OAuth rate limits use fixed windows in the configured Django cache. The production configuration is: | Endpoint | Per-IP maximum | Per-client maximum | Window | |---|---:|---:|---:| | `/oauth/authorize/` | 30 requests | 60 requests | 60 seconds | | `/oauth/token/` | 20 requests | 30 requests | 60 seconds | | `/oauth/userinfo/` | 120 requests | Not configured | 60 seconds | Client limits apply when the request includes `client_id`. Limits are configurable with `OAUTH_RATE_LIMITS` in Django settings. IP identification uses `REMOTE_ADDR`; configure trusted proxy handling at the deployment edge rather than trusting arbitrary forwarded headers. Excess requests receive HTTP `429` and a `Retry-After` header. ## Environment File Create a server-side `.env` file and keep it out of source control. Fill the client ID and secret using values from the developer console. ```dotenv BAREED_CLIENT_ID= BAREED_CLIENT_SECRET= BAREED_REDIRECT_URI= BAREED_AUTHORIZE_URL=https://bareeed.com/oauth/authorize/ BAREED_TOKEN_URL=https://bareeed.com/oauth/token/ BAREED_USERINFO_URL=https://bareeed.com/oauth/userinfo/ ``` Load these values through the runtime's environment API or an environment-file loader. Never ship `BAREED_CLIENT_SECRET` to the browser. ## Python SDK Example ```python import os import secrets from urllib.parse import urlencode import requests client_id = os.getenv("BAREED_CLIENT_ID") client_secret = os.getenv("BAREED_CLIENT_SECRET") redirect_uri = os.getenv("BAREED_REDIRECT_URI") authorize_url = os.getenv("BAREED_AUTHORIZE_URL") token_url = os.getenv("BAREED_TOKEN_URL") state = secrets.token_urlsafe(32) login_url = authorize_url + "?" + urlencode({ "client_id": client_id, "redirect_uri": redirect_uri, "state": state, }) # Store state in the server-side session before redirecting the browser. # In your callback handler, validate and consume state before exchanging. response = requests.post(token_url, data={ "grant_type": "authorization_code", "client_id": client_id, "client_secret": client_secret, "redirect_uri": redirect_uri, "code": authorization_code, }, timeout=10) response.raise_for_status() access_token = response.json()["access_token"] ``` ## Node.js / JavaScript SDK Example ```javascript import crypto from "node:crypto"; const clientId = process.env.BAREED_CLIENT_ID; const clientSecret = process.env.BAREED_CLIENT_SECRET; const redirectUri = process.env.BAREED_REDIRECT_URI; const authorizeUrl = process.env.BAREED_AUTHORIZE_URL; const tokenUrl = process.env.BAREED_TOKEN_URL; const state = crypto.randomBytes(32).toString("base64url"); const loginUrl = new URL(authorizeUrl); loginUrl.search = new URLSearchParams({ client_id: clientId, redirect_uri: redirectUri, state, }); // Store state in the server-side session before redirecting the browser. // In your callback handler, validate and consume state before exchanging. const tokenResponse = await fetch(tokenUrl, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "authorization_code", client_id: clientId, client_secret: clientSecret, redirect_uri: redirectUri, code: authorizationCode, }), }); if (!tokenResponse.ok) throw new Error("OAuth token exchange failed"); const { access_token: accessToken } = await tokenResponse.json(); ``` ## Go SDK Example ```go clientID := os.Getenv("BAREED_CLIENT_ID") clientSecret := os.Getenv("BAREED_CLIENT_SECRET") redirectURI := os.Getenv("BAREED_REDIRECT_URI") authorizeURL := os.Getenv("BAREED_AUTHORIZE_URL") tokenURL := os.Getenv("BAREED_TOKEN_URL") state := makeSecureRandomState() loginURL := authorizeURL + "?" + url.Values{ "client_id": {clientID}, "redirect_uri": {redirectURI}, "state": {state}, }.Encode() // Store state in the server-side session before redirecting the browser. // In your callback handler, validate and consume state before exchanging. form := url.Values{ "grant_type": {"authorization_code"}, "client_id": {clientID}, "client_secret": {clientSecret}, "redirect_uri": {redirectURI}, "code": {authorizationCode}, } response, err := http.PostForm(tokenURL, form) if err != nil { return err } defer response.Body.Close() if response.StatusCode != http.StatusOK { return errors.New("OAuth token exchange failed") } ``` The Go fragment assumes `makeSecureRandomState` returns a cryptographically random value and that `state` is bound to the server-side session. Add the required standard-library imports and callback/session handling in the host application. ## PHP SDK Example ```php $clientId = getenv("BAREED_CLIENT_ID"); $clientSecret = getenv("BAREED_CLIENT_SECRET"); $redirectUri = getenv("BAREED_REDIRECT_URI"); $authorizeUrl = getenv("BAREED_AUTHORIZE_URL"); $tokenUrl = getenv("BAREED_TOKEN_URL"); $state = bin2hex(random_bytes(32)); $loginUrl = $authorizeUrl . "?" . http_build_query([ "client_id" => $clientId, "redirect_uri" => $redirectUri, "state" => $state, ]); // Store state in the server-side session before redirecting the browser. // In your callback handler, validate and consume state before exchanging. $handle = curl_init($tokenUrl); curl_setopt_array($handle, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query([ "grant_type" => "authorization_code", "client_id" => $clientId, "client_secret" => $clientSecret, "redirect_uri" => $redirectUri, "code" => $authorizationCode, ]), CURLOPT_RETURNTRANSFER => true, ]); $tokenResponse = curl_exec($handle); if ($tokenResponse === false) { throw new RuntimeException(curl_error($handle)); } $tokenData = json_decode($tokenResponse, true); $accessToken = $tokenData["access_token"]; ``` ## Java SDK Example ```java String clientId = System.getenv("BAREED_CLIENT_ID"); String clientSecret = System.getenv("BAREED_CLIENT_SECRET"); String redirectUri = System.getenv("BAREED_REDIRECT_URI"); String authorizeUrl = System.getenv("BAREED_AUTHORIZE_URL"); String tokenUrl = System.getenv("BAREED_TOKEN_URL"); String state = secureRandomState(); String loginQuery = "client_id=" + URLEncoder.encode(clientId, StandardCharsets.UTF_8) + "&redirect_uri=" + URLEncoder.encode(redirectUri, StandardCharsets.UTF_8) + "&state=" + URLEncoder.encode(state, StandardCharsets.UTF_8); String loginUrl = authorizeUrl + "?" + loginQuery; // Store state in the server-side session before redirecting the browser. // In your callback handler, validate and consume state before exchanging. String form = "grant_type=authorization_code" + "&client_id=" + URLEncoder.encode(clientId, StandardCharsets.UTF_8) + "&client_secret=" + URLEncoder.encode(clientSecret, StandardCharsets.UTF_8) + "&redirect_uri=" + URLEncoder.encode(redirectUri, StandardCharsets.UTF_8) + "&code=" + URLEncoder.encode(authorizationCode, StandardCharsets.UTF_8); HttpRequest tokenRequest = HttpRequest.newBuilder(URI.create(tokenUrl)) .header("Content-Type", "application/x-www-form-urlencoded") .POST(HttpRequest.BodyPublishers.ofString(form)) .build(); HttpResponse tokenResponse = HttpClient.newHttpClient().send( tokenRequest, HttpResponse.BodyHandlers.ofString() ); ``` The Java fragment assumes `secureRandomState` returns a cryptographically random value and that `state` is bound to the server-side session. Add the required imports and callback/session handling in the host application. ## Implementation Notes for AI Coding Agents - Implement the callback and token exchange on a trusted server. Do not place a confidential client secret in a browser, mobile app, or public repository. - Validate the callback's `state` against server-side session data using a constant-time comparison where available, then consume it once. - Use the exact same registered `redirect_uri` at authorization and token exchange; do not normalize it. - Do not claim PKCE support, arbitrary scopes, refresh tokens, token rotation, OIDC ID tokens, RS256 signing, or grant revocation. These are not part of the current implementation. - Handle `invalid_client`, `invalid_grant`, `invalid_grant_redirect_uri`, `invalid_token`, and HTTP `429` as failures; never treat an error response as a successful login. - Store access tokens securely on the server, keep them out of URLs and logs, and honor the one-hour expiration.