:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(oauth): move first-party CIMD documents to posthog.com (#107422)
Rafael Audibertff2b82662492
diff --git a/docs/published/handbook/engineering/oauth-development-guide.md b/docs/published/handbook/engineering/oauth-development-guide.mdindex 206075373436..f1e49803a9e2 100644--- a/docs/published/handbook/engineering/oauth-development-guide.md+++ b/docs/published/handbook/engineering/oauth-development-guide.md@@ -322,6 +322,12 @@ tokens = token_response.json()print(tokens)```+## First-party client metadata documents++PostHog's own public clients (hogli, the Visual Review Chrome extension, and internal tools) authenticate with client ID metadata documents (CIMD) rather than a registered application or dynamic client registration. Their documents live in the [posthog.com repo](https://github.com/PostHog/posthog.com) at `static/.well-known/oauth/<app>/client-metadata.json`, served at `https://posthog.com/.well-known/oauth/<app>/client-metadata.json`. That URL is the `client_id`, so one ID works on US, EU, and self-hosted.++To add one, create a JSON file there with `client_id` set to its own URL. The CIMD fetcher follows no redirects, so the URL has to answer with a 200 directly. Put the scope ceiling in `com.posthog.scopes`. A new document is an unverified, not-first-party client until someone sets `is_verified` or `is_first_party` on its application in Django admin, in each region.+## Self-registered client logosBoth self-registration paths accept a `logo_uri`, and PostHog shows it on the consent screen and on the login, signup, and email verification screens. A client that sends none gets the first letter of its name instead.diff --git a/posthog/api/oauth/hogli_metadata.py b/posthog/api/oauth/hogli_metadata.pydeleted file mode 100644index 5aa6e926a8b2..000000000000--- a/posthog/api/oauth/hogli_metadata.py+++ /dev/null@@ -1,48 +0,0 @@-from django.conf import settings-from django.http import JsonResponse-from django.views import View--HOGLI_METADATA_PATH = "api/oauth/hogli/client-metadata"--# Scope ceiling: /authorize clamps to this, so keep it to what a hogli command actually reads.-HOGLI_SCOPES = [- "engineering_analytics:read",-]--# Tracked on `main` rather than pinned to a commit: a moved file only hides the image, while a-# pin would keep serving stale art through a rebrand.-HOGLI_LOGO_URI = "https://raw.githubusercontent.com/PostHog/brand/main/assets/crests/full/png/dev-experience.png"---class HogliClientMetadataView(View):- """- Serves a static CIMD (Client ID Metadata Document) for the hogli CLI.-- The client_id in the response is the canonical URL where this document is hosted,- constructed from SITE_URL so it's correct on each region (US, EU, self-hosted).-- The redirect is registered without a port because RFC 8252 section 7.3 obliges the server- to accept any port on a loopback address, which lets each login bind a free ephemeral port- against this one entry.- """-- http_method_names = ["get"]-- def get(self, request):- client_id = f"{settings.SITE_URL}/{HOGLI_METADATA_PATH}"-- metadata = {- "client_id": client_id,- "client_name": "hogli CLI for PostHog",- "logo_uri": HOGLI_LOGO_URI,- "redirect_uris": ["http://127.0.0.1/callback"],- "grant_types": ["authorization_code", "refresh_token"],- "response_types": ["code"],- "token_endpoint_auth_method": "none",- "com.posthog": {"scopes": HOGLI_SCOPES},- }-- response = JsonResponse(metadata)- response["Cache-Control"] = "public, max-age=3600"- response["Content-Type"] = "application/json"- return responsediff --git a/posthog/api/oauth/raycast_metadata.py b/posthog/api/oauth/raycast_metadata.pydeleted file mode 100644index 53808960e5df..000000000000--- a/posthog/api/oauth/raycast_metadata.py+++ /dev/null@@ -1,47 +0,0 @@-from django.conf import settings-from django.http import JsonResponse-from django.views import View--RAYCAST_METADATA_PATH = "api/oauth/raycast/client-metadata"--# Scope ceiling for tokens issued to the Raycast extension. OIDC scopes-# (openid/profile/email) bypass the ceiling via ALWAYS_ALLOWED_SCOPES.-RAYCAST_SCOPES = [- "project:read",- "feature_flag:read",- "cohort:read",- "dashboard:read",- "person:read",-]---class RaycastClientMetadataView(View):- """- Serves a static CIMD (Client ID Metadata Document) for the PostHog Raycast extension.-- The client_id in the response is the canonical URL where this document is hosted,- constructed from SITE_URL so it's correct on each region (US, EU, self-hosted).- """-- http_method_names = ["get"]-- def get(self, request):- client_id = f"{settings.SITE_URL}/{RAYCAST_METADATA_PATH}"-- metadata = {- "client_id": client_id,- "client_name": "Raycast extension for PostHog",- "redirect_uris": [- "https://raycast.com/redirect?packageName=Extension",- "https://raycast.com/redirect?packageName=posthog",- ],- "grant_types": ["authorization_code"],- "response_types": ["code"],- "token_endpoint_auth_method": "none",- "com.posthog": {"scopes": RAYCAST_SCOPES},- }-- response = JsonResponse(metadata)- response["Cache-Control"] = "public, max-age=3600"- response["Content-Type"] = "application/json"- return responsediff --git a/posthog/api/oauth/test_hogli_metadata.py b/posthog/api/oauth/test_hogli_metadata.pydeleted file mode 100644index 8bf88a5c4000..000000000000--- a/posthog/api/oauth/test_hogli_metadata.py+++ /dev/null@@ -1,122 +0,0 @@-import json-from ipaddress import ip_address-from urllib.parse import urlparse--from posthog.test.base import APIBaseTest-from unittest.mock import MagicMock, patch--from django.test import SimpleTestCase, override_settings--from oauth2_provider.models import AbstractApplication-from parameterized import parameterized--from posthog.api.oauth.cimd import fetch_and_upsert_cimd_application-from posthog.api.oauth.hogli_metadata import HOGLI_LOGO_URI, HOGLI_SCOPES-from posthog.models.oauth import is_loopback_host-from posthog.scopes import UNPRIVILEGED_SCOPES---def _mock_cimd_response(document: dict):- body = json.dumps(document).encode()- resp = MagicMock()- resp.status_code = 200- resp.headers = {}- resp.is_redirect = False- resp.is_permanent_redirect = False- resp.close = MagicMock()- resp.iter_content = MagicMock(return_value=iter([body]))- return resp---@override_settings(SITE_URL="https://us.posthog.com")-class TestHogliClientMetadataView(SimpleTestCase):- def test_returns_valid_cimd_metadata(self):- res = self.client.get("/api/oauth/hogli/client-metadata")- assert res.status_code == 200- assert res["Cache-Control"] == "public, max-age=3600"- assert "application/json" in res["Content-Type"]-- data = res.json()- assert data["client_name"] == "hogli CLI for PostHog"- assert data["redirect_uris"] == ["http://127.0.0.1/callback"]- assert data["grant_types"] == ["authorization_code", "refresh_token"]- assert data["response_types"] == ["code"]- assert data["token_endpoint_auth_method"] == "none"- assert data["com.posthog"]["scopes"] == HOGLI_SCOPES-- @parameterized.expand(- [- ("https://us.posthog.com", "https://us.posthog.com/api/oauth/hogli/client-metadata"),- ("https://eu.posthog.com", "https://eu.posthog.com/api/oauth/hogli/client-metadata"),- ]- )- def test_client_id_is_built_from_site_url(self, site_url: str, expected_client_id: str):- # hogli derives the same URL from whichever host it talks to, so a self-hosted- # instance resolves its own document with no client registered for it.- with override_settings(SITE_URL=site_url):- res = self.client.get("/api/oauth/hogli/client-metadata")- assert res.json()["client_id"] == expected_client_id-- def test_declared_scopes_are_unprivileged(self):- # A scope outside this set makes CIMD reject the whole document (cimd.py, _resolve_scopes).- assert set(HOGLI_SCOPES) <= set(UNPRIVILEGED_SCOPES)-- def test_redirect_is_a_portless_loopback_uri(self):- # The registered *host* is the binding part: hogli must redirect to 127.0.0.1, because a- # `localhost` request against this registration is rejected. The port is not load-bearing- # either way (the port check is waived for a registered loopback literal, with or without- # one), so portless is a convention that says so rather than a requirement.- [redirect] = self.client.get("/api/oauth/hogli/client-metadata").json()["redirect_uris"]- parsed = urlparse(redirect)- assert parsed.scheme == "http"- assert parsed.hostname == "127.0.0.1"- assert parsed.port is None- assert is_loopback_host(parsed.hostname)-- def test_logo_is_https_so_cimd_keeps_it(self):- # cimd.py drops a non-HTTPS logo_uri instead of failing, shipping a logo-less screen.- logo = self.client.get("/api/oauth/hogli/client-metadata").json()["logo_uri"]- assert logo == HOGLI_LOGO_URI and logo.startswith("https://")-- def test_post_not_allowed(self):- res = self.client.post("/api/oauth/hogli/client-metadata")- assert res.status_code == 405---@override_settings(SITE_URL="https://us.posthog.com")-class TestHogliClientMetadataRegistration(APIBaseTest):- @patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})- @patch("posthog.api.oauth.cimd.requests.Session.get")- def test_document_registers_through_cimd(self, mock_get, _url_mock):- # Serve the live document back through the CIMD fetch path, so the document and the- # CIMD validation rules cannot drift apart. The fetch is patched because client_ids- # must be HTTPS.- document = self.client.get("/api/oauth/hogli/client-metadata").json()- client_id = document["client_id"]- mock_get.return_value = _mock_cimd_response(document)-- app = fetch_and_upsert_cimd_application(client_id)-- assert app is not None- assert app.is_cimd_client- assert app.client_id == client_id- assert app.name == "hogli CLI for PostHog"- assert app.client_type == AbstractApplication.CLIENT_PUBLIC- assert app.authorization_grant_type == AbstractApplication.GRANT_AUTHORIZATION_CODE- assert app.redirect_uris == " ".join(document["redirect_uris"])- assert set(app.scopes) == set(HOGLI_SCOPES)- assert app.logo_uri == HOGLI_LOGO_URI-- @patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})- @patch("posthog.api.oauth.cimd.requests.Session.get")- def test_registration_leaves_verification_to_a_human(self, mock_get, _url_mock):- # Registration must not self-certify: the unverified warning only means something- # while `is_verified` stays staff-set.- document = self.client.get("/api/oauth/hogli/client-metadata").json()- mock_get.return_value = _mock_cimd_response(document)-- app = fetch_and_upsert_cimd_application(document["client_id"])-- assert app is not None- assert app.is_verified is False- assert app.skip_authorization is Falsediff --git a/posthog/api/oauth/test_raycast_metadata.py b/posthog/api/oauth/test_raycast_metadata.pydeleted file mode 100644index b86fc637c3f2..000000000000--- a/posthog/api/oauth/test_raycast_metadata.py+++ /dev/null@@ -1,92 +0,0 @@-import json-from ipaddress import ip_address--from posthog.test.base import APIBaseTest-from unittest.mock import MagicMock, patch--from django.test import SimpleTestCase, override_settings--from oauth2_provider.models import AbstractApplication-from parameterized import parameterized--from posthog.api.oauth.cimd import fetch_and_upsert_cimd_application-from posthog.api.oauth.raycast_metadata import RAYCAST_SCOPES-from posthog.scopes import UNPRIVILEGED_SCOPES---def _mock_cimd_response(document: dict):- body = json.dumps(document).encode()- resp = MagicMock()- resp.status_code = 200- resp.headers = {}- resp.is_redirect = False- resp.is_permanent_redirect = False- resp.close = MagicMock()- resp.iter_content = MagicMock(return_value=iter([body]))- return resp---@override_settings(SITE_URL="https://us.posthog.com")-class TestRaycastClientMetadataView(SimpleTestCase):- def test_returns_valid_cimd_metadata(self):- res = self.client.get("/api/oauth/raycast/client-metadata")- assert res.status_code == 200- assert res["Cache-Control"] == "public, max-age=3600"- assert "application/json" in res["Content-Type"]-- data = res.json()- assert data["client_name"] == "Raycast extension for PostHog"- assert data["redirect_uris"] == [- "https://raycast.com/redirect?packageName=Extension",- "https://raycast.com/redirect?packageName=posthog",- ]- assert data["grant_types"] == ["authorization_code"]- assert data["response_types"] == ["code"]- assert data["token_endpoint_auth_method"] == "none"- assert data["com.posthog"]["scopes"] == RAYCAST_SCOPES-- @parameterized.expand(- [- ("https://us.posthog.com", "https://us.posthog.com/api/oauth/raycast/client-metadata"),- ("https://eu.posthog.com", "https://eu.posthog.com/api/oauth/raycast/client-metadata"),- ]- )- def test_client_id_is_built_from_site_url(self, site_url: str, expected_client_id: str):- with override_settings(SITE_URL=site_url):- res = self.client.get("/api/oauth/raycast/client-metadata")- assert res.json()["client_id"] == expected_client_id-- def test_declared_scopes_are_unprivileged(self):- # A scope falling out of UNPRIVILEGED_SCOPES would make CIMD registration- # reject the metadata document outright (see _resolve_scopes in cimd.py).- assert set(RAYCAST_SCOPES) <= set(UNPRIVILEGED_SCOPES)-- def test_post_not_allowed(self):- res = self.client.post("/api/oauth/raycast/client-metadata")- assert res.status_code == 405---@override_settings(SITE_URL="https://us.posthog.com")-class TestRaycastClientMetadataRegistration(APIBaseTest):- @patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})- @patch("posthog.api.oauth.cimd.requests.Session.get")- def test_document_registers_through_cimd(self, mock_get, _url_mock):- # Serve the live document back through the CIMD fetch path (the HTTP fetch- # is patched since CIMD client_ids must be HTTPS), then assert it registers- # as the public client this endpoint promises. Locks the contract between- # this document and the CIMD validation rules.- document = self.client.get("/api/oauth/raycast/client-metadata").json()- client_id = document["client_id"]- mock_get.return_value = _mock_cimd_response(document)-- app = fetch_and_upsert_cimd_application(client_id)-- assert app is not None- assert app.is_cimd_client- assert app.client_id == client_id- assert app.name == "Raycast extension for PostHog"- assert app.client_type == AbstractApplication.CLIENT_PUBLIC- assert app.authorization_grant_type == AbstractApplication.GRANT_AUTHORIZATION_CODE- assert app.redirect_uris == " ".join(document["redirect_uris"])- assert set(app.scopes) == set(RAYCAST_SCOPES)- assert app.organization is Nonediff --git a/posthog/api/oauth/test_wizard_metadata.py b/posthog/api/oauth/test_wizard_metadata.pydeleted file mode 100644index 9827199fbf6c..000000000000--- a/posthog/api/oauth/test_wizard_metadata.py+++ /dev/null@@ -1,40 +0,0 @@-from django.test import SimpleTestCase, override_settings---@override_settings(SITE_URL="https://us.posthog.com")-class TestWizardClientMetadataView(SimpleTestCase):- def test_returns_valid_cimd_metadata(self):- res = self.client.get("/api/oauth/wizard/client-metadata")- assert res.status_code == 200- data = res.json()-- assert data["client_id"] == "https://us.posthog.com/api/oauth/wizard/client-metadata"- assert data["client_name"] == "PostHog Wizard"- assert data["redirect_uris"] == ["http://localhost:8239/callback"]- assert data["grant_types"] == ["authorization_code"]- assert data["response_types"] == ["code"]- assert data["token_endpoint_auth_method"] == "none"- assert data["com.posthog"] == {"provisioning": True}-- def test_client_id_matches_hosted_path(self):- res = self.client.get("/api/oauth/wizard/client-metadata")- data = res.json()- assert data["client_id"].endswith("/api/oauth/wizard/client-metadata")-- @override_settings(SITE_URL="https://eu.posthog.com")- def test_client_id_uses_site_url_for_eu(self):- res = self.client.get("/api/oauth/wizard/client-metadata")- data = res.json()- assert data["client_id"] == "https://eu.posthog.com/api/oauth/wizard/client-metadata"-- def test_cache_control_header_set(self):- res = self.client.get("/api/oauth/wizard/client-metadata")- assert res["Cache-Control"] == "public, max-age=3600"-- def test_content_type_is_json(self):- res = self.client.get("/api/oauth/wizard/client-metadata")- assert "application/json" in res["Content-Type"]-- def test_post_not_allowed(self):- res = self.client.post("/api/oauth/wizard/client-metadata")- assert res.status_code == 405diff --git a/posthog/api/oauth/wizard_metadata.py b/posthog/api/oauth/wizard_metadata.pydeleted file mode 100644index 688ccc58e6b1..000000000000--- a/posthog/api/oauth/wizard_metadata.py+++ /dev/null@@ -1,34 +0,0 @@-from django.conf import settings-from django.http import JsonResponse-from django.views import View--WIZARD_METADATA_PATH = "api/oauth/wizard/client-metadata"---class WizardClientMetadataView(View):- """- Serves a static CIMD (Client ID Metadata Document) for the PostHog Wizard CLI.-- The client_id in the response is the canonical URL where this document is hosted,- constructed from SITE_URL so it's correct on each region (US, EU, self-hosted).- """-- http_method_names = ["get"]-- def get(self, request):- client_id = f"{settings.SITE_URL}/{WIZARD_METADATA_PATH}"-- metadata = {- "client_id": client_id,- "client_name": "PostHog Wizard",- "redirect_uris": ["http://localhost:8239/callback"],- "grant_types": ["authorization_code"],- "response_types": ["code"],- "token_endpoint_auth_method": "none",- "com.posthog": {"provisioning": True},- }-- response = JsonResponse(metadata)- response["Cache-Control"] = "public, max-age=3600"- response["Content-Type"] = "application/json"- return responsediff --git a/posthog/urls.py b/posthog/urls.pyindex afc703dd7d45..2202a073fa1f 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -25,10 +25,7 @@ from posthog.api import (from posthog.api.github_callback.views import github_oauth_callback, github_setup_callbackfrom posthog.api.integration_connect import integration_connect_redirectfrom posthog.api.oauth.connected_apps import ConnectedAppsViewSet-from posthog.api.oauth.hogli_metadata import HOGLI_METADATA_PATH, HogliClientMetadataView-from posthog.api.oauth.raycast_metadata import RAYCAST_METADATA_PATH, RaycastClientMetadataViewfrom posthog.api.oauth.toolbar_views import authorize_and_redirect-from posthog.api.oauth.wizard_metadata import WIZARD_METADATA_PATH, WizardClientMetadataViewfrom posthog.api.sdk_health import sdk_healthfrom posthog.api.two_factor_qrcode import CacheAwareQRGeneratorViewfrom posthog.api.web_experiment import web_experiments@@ -283,21 +280,6 @@ urlpatterns = ["api/oauth/connected-apps/<uuid:pk>/revoke/",ConnectedAppsViewSet.as_view({"post": "revoke"}),),- path(- WIZARD_METADATA_PATH,- WizardClientMetadataView.as_view(),- name="wizard-client-metadata",- ),- path(- RAYCAST_METADATA_PATH,- RaycastClientMetadataView.as_view(),- name="raycast-client-metadata",- ),- path(- HOGLI_METADATA_PATH,- HogliClientMetadataView.as_view(),- name="hogli-client-metadata",- ),# The one slot for root routes products declare themselves, after every core api/ route and# before the API fallback and the frontend catch-all. See docs/internal/url-routing.md.*ProductRootRoutes.collect(),diff --git a/products/desktop/apps/web/README.md b/products/desktop/apps/web/README.mdindex c23059cfd200..1c6db5ea2344 100644--- a/products/desktop/apps/web/README.md+++ b/products/desktop/apps/web/README.md@@ -111,8 +111,8 @@ as database rows (Django admin → OAuth applications), and they must include:sign in to the region, check whether the registered localhost URI is portlessor pinned to `:8237`.-A CIMD client (the `raycast_metadata.py` / `wizard_metadata.py` pattern in-`posthog/api/oauth/`) is NOT suitable: CIMD registrations are capped to+A CIMD client (like the first-party documents under+`https://posthog.com/.well-known/oauth/<app>/client-metadata.json`) is NOT suitable: CIMD registrations are capped tounprivileged scopes, and Code requires `scope=*` like the desktop app.### S3 artifact-bucket CORS — required for attachment uploadsdiff --git a/products/desktop/tools/announcements-admin/README.md b/products/desktop/tools/announcements-admin/README.mdindex 7638a14e1f29..0f3c8f2f2741 100644--- a/products/desktop/tools/announcements-admin/README.md+++ b/products/desktop/tools/announcements-admin/README.md@@ -10,13 +10,13 @@ Live (employee-gated): https://desktop-announcements-admin.hosthog.dev## Auth"Log in with PostHog" — an OAuth authorization-code + PKCE flow using a-[client ID metadata document](public/.well-known/oauth-client-metadata.json)+[client ID metadata document](https://posthog.com/.well-known/oauth/desktop-announcements-admin/client-metadata.json)(the `client_id` is that document's URL, so no OAuth app registration and no-API keys). The document is the one public path on the otherwise employee-gated-site; tokens live in `localStorage` with `feature_flag:read/write` scope and+API keys). The document lives in PostHog/posthog.com at+`static/.well-known/oauth/desktop-announcements-admin/client-metadata.json`; tokens live in `localStorage` with `feature_flag:read/write` scope andrenew silently from the refresh token, so login persists across visits.-The deploy origin is baked into `src/config.ts` and the metadata document, so+The deploy origin's callback is baked into `src/config.ts` and the metadata document, sothe OAuth flow only works on the deployed site — `pnpm dev` renders the UI butlogin redirects back to the deployed origin.@@ -38,6 +38,5 @@ pnpm --filter @posthog/announcements-admin build# HostHog defaults the target slug to the zip name, so name it after the slug.cd tools/announcements-admin/dist && zip -r ../desktop-announcements-admin.zip . && cd -# publish desktop-announcements-admin.zip (MCP `publish` tool or `hosthog-# publish`), then ensure the metadata document is ungated:-# add_public_path /.well-known/oauth-client-metadata.json+# publish`)```diff --git a/products/desktop/tools/announcements-admin/public/.well-known/oauth-client-metadata.json b/products/desktop/tools/announcements-admin/public/.well-known/oauth-client-metadata.jsondeleted file mode 100644index 96312dfbc32d..000000000000--- a/products/desktop/tools/announcements-admin/public/.well-known/oauth-client-metadata.json+++ /dev/null@@ -1,14 +0,0 @@-{- "client_id": "https://desktop-announcements-admin.hosthog.dev/.well-known/oauth-client-metadata.json",- "client_name": "PostHog Desktop Announcements Admin",- "client_uri": "https://desktop-announcements-admin.hosthog.dev/",- "redirect_uris": [- "https://desktop-announcements-admin.hosthog.dev/oauth/callback"- ],- "grant_types": ["authorization_code"],- "response_types": ["code"],- "token_endpoint_auth_method": "none",- "com.posthog": {- "scopes": ["feature_flag:read", "feature_flag:write", "user:read"]- }-}diff --git a/products/desktop/tools/announcements-admin/src/config.ts b/products/desktop/tools/announcements-admin/src/config.tsindex 0774dc5a353d..3dfc6957a305 100644--- a/products/desktop/tools/announcements-admin/src/config.ts+++ b/products/desktop/tools/announcements-admin/src/config.ts@@ -1,10 +1,13 @@export const POSTHOG_HOST = "https://us.posthog.com";export const PROJECT_ID = 2;-// The deploy origin is the OAuth identity (CIMD client_id derives from it),-// so it is baked in rather than read from window.location.+// The CIMD client_id is the URL of the metadata document, published from+// PostHog/posthog.com (static/.well-known/oauth/desktop-announcements-admin/). It registers+// only the deployed origin's callback, so that origin is baked in rather than+// read from window.location.const APP_ORIGIN = "https://desktop-announcements-admin.hosthog.dev";-export const CLIENT_ID = `${APP_ORIGIN}/.well-known/oauth-client-metadata.json`;+export const CLIENT_ID =+ "https://posthog.com/.well-known/oauth/desktop-announcements-admin/client-metadata.json";export const REDIRECT_URI = `${APP_ORIGIN}/oauth/callback`;// user:read covers /api/users/@me/ for analytics identify. Also declared in-// public/.well-known/oauth-client-metadata.json — keep the two lists in sync.+// the metadata document — keep the two lists in sync.export const OAUTH_SCOPES = "feature_flag:read feature_flag:write user:read";diff --git a/tools/hogli-commands/hogli_commands/posthog_auth.py b/tools/hogli-commands/hogli_commands/posthog_auth.pyindex 5b3bc9e46113..2080acf4e0a7 100644--- a/tools/hogli-commands/hogli_commands/posthog_auth.py+++ b/tools/hogli-commands/hogli_commands/posthog_auth.py@@ -13,8 +13,8 @@ Three sources, in order:3. An interactive browser login, on a tty only.The browser path is the RFC 8252 native-app flow. The client_id is the URL of the client metadata-document PostHog serves for hogli, so there is nothing to register and every machine authorizes as-the same named client. The code comes back to an ephemeral port on 127.0.0.1 with PKCE.+document PostHog publishes for hogli on posthog.com, so there is nothing to register and every machine+authorizes as the same named client on every host. The code comes back to an ephemeral port on 127.0.0.1 with PKCE.RFC 8628 device flow is not used because PostHog does not advertise that grant. A login alwaysprints the URL as well as opening it, and accepts the redirect typed back in, so it also finisheson a machine whose browser lives somewhere else.@@ -62,8 +62,9 @@ KEY_ENV_VARS = ("POSTHOG_PERSONAL_API_KEY", "POSTHOG_AUTH_HEADER")_CACHE_ROOT = Path.home() / ".config" / "posthog" / "oauth"-# PostHog serves hogli's client metadata document here, and its own URL is the client_id.-_METADATA_PATH = "api/oauth/hogli/client-metadata"+# hogli's client metadata document, published from PostHog/posthog.com (static/.well-known/oauth/hogli/). Its own+# URL is the client_id, so US, EU, and self-hosted all know hogli as the same client.+_CLIENT_ID = "https://posthog.com/.well-known/oauth/hogli/client-metadata.json"# The document registers the redirect without a port: RFC 8252 §7.3 requires the server to allow# any port on a loopback redirect, so one entry covers whichever ephemeral port we get. 127.0.0.1# rather than localhost because django-oauth-toolkit's port exemption lists the literal addresses.@@ -347,15 +348,15 @@ def login(*, scopes: Sequence[str], host: str = DEFAULT_HOST) -> Credential:)superseded = load(host)- client = _client(host)+ client = _client()refused = [scope for scope in wanted if scope not in client.scopes]if refused:# Checked before the browser opens, since /authorize clamps to the published ceiling and# consenting would mint a token missing these, failing only after the user's click.raise AuthError(f"{host} does not offer {' '.join(refused)} to hogli.\n"- f" It publishes {' '.join(client.scopes)}. A new scope goes in the client metadata "- "document PostHog serves, not here."+ f" It publishes {' '.join(client.scopes)}. A new scope goes in hogli's client metadata "+ f"document ({_CLIENT_ID}), not here.")verifier = secrets.token_urlsafe(64)@@ -400,22 +401,20 @@ def login(*, scopes: Sequence[str], host: str = DEFAULT_HOST) -> Credential:return credential-def _client(host: str) -> ClientMetadata:- """The client PostHog publishes for hogli, fetched from the host itself.+def _client() -> ClientMetadata:+ """The client PostHog publishes for hogli.The document's own URL is the client_id, so there is nothing to register and every machineauthorizes as the same named client. Fetched rather than hardcoded so the scope ceiling comes- from the server that enforces it, and so a host too old to serve one says so before a browser- opens on an /authorize that cannot resolve the client.+ from the same document /authorize clamps to."""- url = f"{host}/{_METADATA_PATH}"- body = _get(url, action="Reading hogli's client metadata")- if body.get("client_id") != url:- raise AuthError(f"{host} published a client metadata document for a different client_id.")+ body = _get(_CLIENT_ID, action="Reading hogli's client metadata")+ if body.get("client_id") != _CLIENT_ID:+ raise AuthError(f"{_CLIENT_ID} names a different client_id.")scopes = body.get("com.posthog", {}).get("scopes") if isinstance(body.get("com.posthog"), dict) else Noneif not scopes:- raise AuthError(f"{host} published no scopes for hogli, so a login could ask for nothing.")- return ClientMetadata(client_id=url, scopes=tuple(str(scope) for scope in scopes))+ raise AuthError(f"{_CLIENT_ID} publishes no scopes for hogli, so a login could ask for nothing.")+ return ClientMetadata(client_id=_CLIENT_ID, scopes=tuple(str(scope) for scope in scopes))def _exchange(@@ -528,14 +527,6 @@ def _get(url: str, *, action: str) -> dict[str, Any]:response = requests.get(url, timeout=_HTTP_TIMEOUT_SECONDS)except requests.RequestException as exc:raise AuthError(f"{action} could not reach {url}: {exc}", exit_code=1) from exc- if response.status_code == 404:- # Named rather than left as a bare 404, because the fix is a PostHog version, not anything- # the user did wrong.- raise AuthError(- f"{url} is not served by this PostHog.\n"- " A browser login needs a version that publishes hogli's client metadata document.\n"- f" Set {KEY_ENV_VARS[0]} to use a personal API key against this host instead."- )body = _body_of(response, action=action)if not body:raise AuthError(f"{action} returned no object.")diff --git a/tools/hogli-commands/hogli_commands/tests/test_posthog_auth.py b/tools/hogli-commands/hogli_commands/tests/test_posthog_auth.pyindex d1097b53f82d..5bb35b645777 100644--- a/tools/hogli-commands/hogli_commands/tests/test_posthog_auth.py+++ b/tools/hogli-commands/hogli_commands/tests/test_posthog_auth.py@@ -47,11 +47,11 @@ def a_terminal() -> Iterator[None]:yield-_CLIENT_ID = f"{_HOST}/api/oauth/hogli/client-metadata"+_CLIENT_ID = "https://posthog.com/.well-known/oauth/hogli/client-metadata.json"def _metadata(*scopes: str) -> Any:- # Stands in for the client metadata document PostHog serves, which names hogli and its ceiling.+ # Stands in for the client metadata document on posthog.com, which names hogli and its ceiling.document = {"client_id": _CLIENT_ID, "com.posthog": {"scopes": list(scopes or (_SCOPE,))}}return patch.object(posthog_auth.requests, "get", lambda url, timeout: _Response(200, document))@@ -385,15 +385,6 @@ def test_a_login_keeps_its_new_credential_when_revoking_the_replaced_one_fails()assert cached is not None and cached.access_token == "pha_new"-def test_a_host_that_serves_no_client_document_names_the_way_out() -> None:- # An older self-hosted PostHog would otherwise fail at /authorize, which cannot say what to do.- with patch.object(posthog_auth.requests, "get", lambda url, timeout: _Response(404, {})):- with patch.object(posthog_auth.webbrowser, "open", side_effect=AssertionError("must not open")):- with pytest.raises(posthog_auth.AuthError) as caught:- posthog_auth.login(scopes=[_SCOPE], host=_HOST)- assert "POSTHOG_PERSONAL_API_KEY" in caught.value.message--def test_a_login_off_a_tty_refuses_instead_of_opening_a_browser() -> None:# A browser opened for a piped caller answers to nobody, and the login would sit out its whole# five-minute timeout before failing.