OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
docs: self-hosting guides for social login and Google Search Console
Carl-Gerhard Lindesvärd48376323728c
diff --git a/.env.example b/.env.exampleindex 67de7b717..bfd92108a 100644--- a/.env.example+++ b/.env.example@@ -28,6 +28,19 @@ NEXT_PUBLIC_API_URL="http://localhost:3333"WORKER_PORT=9999API_PORT=3333+# SOCIAL LOGIN (optional). Docs: https://openpanel.dev/docs/self-hosting/social-login+# The redirect URIs must match what you register at the provider exactly.+# GOOGLE_CLIENT_ID=""+# GOOGLE_CLIENT_SECRET=""+# GOOGLE_REDIRECT_URI="http://localhost:3333/oauth/google/callback"+# GITHUB_CLIENT_ID=""+# GITHUB_CLIENT_SECRET=""+# GITHUB_REDIRECT_URI="http://localhost:3333/oauth/github/callback"++# GOOGLE SEARCH CONSOLE (optional). Docs: https://openpanel.dev/docs/self-hosting/google-search-console+# Reuses GOOGLE_CLIENT_ID/SECRET above. Requires ENCRYPTION_KEY.+# GSC_GOOGLE_REDIRECT_URI="http://localhost:3333/gsc/callback"+# KAFKA / REDPANDA (optional, runs in parallel with the groupmq events queue)# Empty KAFKA_BROKERS disables both producer and consumer; everything falls# back to groupmq. Enable ENABLED_QUEUES=events_kafka on the worker(s) that@@ -55,6 +68,18 @@ API_PORT=3333# KAFKA_PRODUCER_MAX_IN_FLIGHT="1"# Local dev with docker-compose:# KAFKA_BROKERS="localhost:23092"+# TLS / SASL for an external broker (docs: self-hosting/environment-variables#kafka_ssl).+# Unauthenticated plaintext when unset. SASL credentials imply KAFKA_SSL=true;+# a partial pair, an unknown mechanism or TLS options without TLS fail boot.+# KAFKA_SSL="true"+# KAFKA_SSL_CA_PATH="/etc/openpanel/kafka-ca.pem"+# KAFKA_SSL_REJECT_UNAUTHORIZED="true"+# KAFKA_SASL_USERNAME=""+# KAFKA_SASL_PASSWORD=""+# KAFKA_SASL_MECHANISM="scram-sha-512" # plain | scram-sha-256 | scram-sha-512+# Local SASL/TLS broker for trying these out: `bun run dock:kafka-auth`, then+# KAFKA_BROKERS="localhost:23094" with user op512 / op512-secret and+# KAFKA_SSL_CA_PATH="$PWD/docker/data/op-rp-auth-certs/ca.crt".# EMAIL - set one or both; SMTP takes priority over Resend if SMTP_HOST is set# Option A - Resenddiff --git a/apps/public/content/docs/self-hosting/deploy-coolify.mdx b/apps/public/content/docs/self-hosting/deploy-coolify.mdxindex 6ef7dbbdf..8b94420c7 100644--- a/apps/public/content/docs/self-hosting/deploy-coolify.mdx+++ b/apps/public/content/docs/self-hosting/deploy-coolify.mdx@@ -111,9 +111,18 @@ Coolify automatically handles these variables:- `API_URL`: API endpoint URL (set via `SERVICE_FQDN_OPAPI`)- `DASHBOARD_URL`: Dashboard URL (set via `SERVICE_FQDN_OPDASHBOARD`)- `COOKIE_SECRET`: Automatically generated secret+- `ENCRYPTION_KEY`: Automatically generated key (shared by the API and worker)You can configure optional variables like `ALLOW_REGISTRATION`, `RESEND_API_KEY`, `OPENAI_API_KEY`, etc. through Coolify's environment variable interface.+The compose template exposes the following inputs for [social login](/docs/self-hosting/social-login) and [Google Search Console](/docs/self-hosting/google-search-console); Coolify maps each one to the containers that need it:++- `OPENPANEL_GOOGLE_CLIENT_ID`, `OPENPANEL_GOOGLE_CLIENT_SECRET`, `OPENPANEL_GOOGLE_REDIRECT_URI`+- `OPENPANEL_GITHUB_CLIENT_ID`, `OPENPANEL_GITHUB_CLIENT_SECRET`, `OPENPANEL_GITHUB_REDIRECT_URI`+- `OPENPANEL_GSC_GOOGLE_REDIRECT_URI`++The redirect URIs use the API's FQDN, e.g. `https://your-domain.com/api/oauth/google/callback`.+### Updating OpenPanelTo update OpenPanel in Coolify:@@ -212,6 +221,8 @@ To restore from a backup:- [Configure email settings](/docs/self-hosting/self-hosting#e-mail) for password resets and invitations- [Set up AI integration](/docs/self-hosting/self-hosting#ai-integration) for the analytics assistant- [Configure SDK](/docs/self-hosting/self-hosting#always-use-correct-api-url) to track events from your applications+- [Enable social login](/docs/self-hosting/social-login) with Google or GitHub+- [Connect Google Search Console](/docs/self-hosting/google-search-console) for SEO data## Additional Resourcesdiff --git a/apps/public/content/docs/self-hosting/deploy-docker-compose.mdx b/apps/public/content/docs/self-hosting/deploy-docker-compose.mdxindex c515022e1..80fb62740 100644--- a/apps/public/content/docs/self-hosting/deploy-docker-compose.mdx+++ b/apps/public/content/docs/self-hosting/deploy-docker-compose.mdx@@ -121,6 +121,8 @@ For a complete reference of all available environment variables, see the [EnviroIf you change the `.env` file, you need to restart the services for the changes to take effect. Use `./stop` and `./start` or `docker compose restart`.</Callout>+The generated `.env` also contains commented-out blocks for optional features. Uncomment and fill them in to enable [social login with Google or GitHub](/docs/self-hosting/social-login) and the [Google Search Console integration](/docs/self-hosting/google-search-console).+### Using Custom Docker ImagesIf you want to use specific image versions, edit the `docker-compose.yml` file and update the image tags:@@ -352,4 +354,6 @@ If you want to use NGINX, Traefik, or another reverse proxy instead of the bundl- [Configure email settings](/docs/self-hosting/self-hosting#e-mail) for password resets and invitations- [Set up AI integration](/docs/self-hosting/self-hosting#ai-integration) for the analytics assistant- [Configure SDK](/docs/self-hosting/self-hosting#always-use-correct-api-url) to track events from your applications+- [Enable social login](/docs/self-hosting/social-login) with Google or GitHub+- [Connect Google Search Console](/docs/self-hosting/google-search-console) for SEO datadiff --git a/apps/public/content/docs/self-hosting/deploy-kubernetes.mdx b/apps/public/content/docs/self-hosting/deploy-kubernetes.mdxindex 19bc20ee1..9eda522b5 100644--- a/apps/public/content/docs/self-hosting/deploy-kubernetes.mdx+++ b/apps/public/content/docs/self-hosting/deploy-kubernetes.mdx@@ -262,7 +262,7 @@ secrets:```<Callout>-Set up Google OAuth in [Google Cloud Console](https://console.cloud.google.com). Add authorized redirect URI: `https://your-domain.com/api/oauth/google/callback`+Set up Google OAuth in [Google Cloud Console](https://console.cloud.google.com). Add authorized redirect URI: `https://your-domain.com/api/oauth/google/callback`. The full walkthrough is in the [social login guide](/docs/self-hosting/social-login). The chart does not currently have values for GitHub login or the [Google Search Console integration](/docs/self-hosting/google-search-console); those need `GITHUB_*`, `GSC_GOOGLE_REDIRECT_URI` and `ENCRYPTION_KEY` on the API (and worker) pods.</Callout>#### Redis Configurationdiff --git a/apps/public/content/docs/self-hosting/environment-variables.mdx b/apps/public/content/docs/self-hosting/environment-variables.mdxindex cad504930..c0da6a438 100644--- a/apps/public/content/docs/self-hosting/environment-variables.mdx+++ b/apps/public/content/docs/self-hosting/environment-variables.mdx@@ -198,6 +198,24 @@ COOKIE_SECRET=your-random-secret-hereNever use the default value in production! Always generate a unique secret.</Callout>+### ENCRYPTION_KEY++**Type**: `string` (64 hexadecimal characters)+**Required**: For [Google Search Console](/docs/self-hosting/google-search-console), two-factor authentication (TOTP) and object-store exports+**Default**: None++AES-256 key used for everything OpenPanel encrypts at rest: Google Search Console tokens, users' 2FA secrets and S3/GCS export credentials. Must be exactly 32 bytes encoded as 64 hex characters, and must be identical on the API and worker services. The Docker Compose setup script generates one for you.++**Example**:+```bash+# Generate with: openssl rand -hex 32+ENCRYPTION_KEY=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef+```++<Callout type="warn">+Rotating this key makes every existing ciphertext unreadable. Search Console connections must be re-authorised, 2FA must be re-enrolled and export credentials re-entered. Back it up together with your database.+</Callout>+### COOKIE_TLDS**Type**: `string` (comma-separated)@@ -508,6 +526,101 @@ If `SMTP_HOST` is set and an SMTP send attempt fails, the system will **not** au## OAuth & Integrations+### GOOGLE_CLIENT_ID++**Type**: `string`+**Required**: No+**Default**: None++OAuth client ID from Google Cloud Console. Enables [Sign in with Google](/docs/self-hosting/social-login#google) and is also used by the [Google Search Console integration](/docs/self-hosting/google-search-console). Set it on the API, and on the worker if you use Search Console.++**Example**:+```bash+GOOGLE_CLIENT_ID=123456789012-abcdefghijklmnop.apps.googleusercontent.com+```++### GOOGLE_CLIENT_SECRET++**Type**: `string`+**Required**: No (required together with `GOOGLE_CLIENT_ID`)+**Default**: None++OAuth client secret matching `GOOGLE_CLIENT_ID`. Only the API and worker need it.++**Example**:+```bash+GOOGLE_CLIENT_SECRET=GOCSPX-xxxxxxxxxxxxxxxxxxxxxxxx+```++### GOOGLE_REDIRECT_URI++**Type**: `string`+**Required**: For Google sign-in+**Default**: None++Full callback URL for Google sign-in: `${API_URL}/oauth/google/callback`. Must exactly match an authorized redirect URI on the Google OAuth client. It is not derived from `API_URL`, so set it explicitly. See [Social login](/docs/self-hosting/social-login).++**Example**:+```bash+GOOGLE_REDIRECT_URI=https://analytics.example.com/api/oauth/google/callback+```++### GSC_GOOGLE_REDIRECT_URI++**Type**: `string`+**Required**: For the Google Search Console integration+**Default**: None++Full callback URL for connecting Google Search Console: `${API_URL}/gsc/callback`. Must be registered as an authorized redirect URI on the same Google OAuth client as `GOOGLE_REDIRECT_URI`. Only the API needs it. See [Google Search Console](/docs/self-hosting/google-search-console).++**Example**:+```bash+GSC_GOOGLE_REDIRECT_URI=https://analytics.example.com/api/gsc/callback+```++### GITHUB_CLIENT_ID++**Type**: `string`+**Required**: No+**Default**: None++Client ID of a GitHub OAuth App. Enables [Sign in with GitHub](/docs/self-hosting/social-login#github). Only the API needs it.++**Example**:+```bash+GITHUB_CLIENT_ID=Iv1.xxxxxxxxxxxxxxxx+```++### GITHUB_CLIENT_SECRET++**Type**: `string`+**Required**: No (required together with `GITHUB_CLIENT_ID`)+**Default**: None++Client secret of the GitHub OAuth App. Only the API needs it.++**Example**:+```bash+GITHUB_CLIENT_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx+```++### GITHUB_REDIRECT_URI++**Type**: `string`+**Required**: For GitHub sign-in+**Default**: None++Full callback URL for GitHub sign-in: `${API_URL}/oauth/github/callback`. Must exactly match the authorization callback URL of the GitHub OAuth App. It is not derived from `API_URL`, so set it explicitly.++**Example**:+```bash+GITHUB_REDIRECT_URI=https://analytics.example.com/api/oauth/github/callback+```++<Callout>+The dashboard only shows the social login buttons and the Search Console settings when the API has both the client ID and the redirect URI for that feature. The dashboard itself needs none of these variables.+</Callout>+### SLACK_CLIENT_ID**Type**: `string`@@ -646,6 +759,19 @@ Number of concurrent event processing jobs per worker.EVENT_JOB_CONCURRENCY=20```+### GSC_CONCURRENCY++**Type**: `number`+**Required**: No+**Default**: `5`++Number of [Google Search Console](/docs/self-hosting/google-search-console) sync/backfill jobs a worker runs in parallel. Only relevant when the integration is enabled; requires `gsc` (and `cron`) in `ENABLED_QUEUES` if that variable is set.++**Example**:+```bash+GSC_CONCURRENCY=2+```+### EVENT_BLOCKING_TIMEOUT_SEC**Type**: `number`@@ -742,6 +868,8 @@ OpenPanel can optionally ingest events through a Kafka-compatible broker (KafkaRouting is all-or-nothing: if `KAFKA_BROKERS` is set, every event is produced to the Kafka topic; otherwise all events stay on the default Redis-backed `events` queue. Set `ENABLED_QUEUES=events` on the worker(s) that should consume from Kafka.+Connections are unauthenticated plaintext by default. For managed or production clusters, enable TLS with `KAFKA_SSL` and SASL authentication (`plain`, `scram-sha-256` or `scram-sha-512`) with the `KAFKA_SASL_*` variables below.+<Callout>The client speaks the Kafka wire protocol via [kafkajs](https://kafka.js.org/), so any Kafka-compatible broker works. `self-hosting/docker-compose.template.yml` ships an `op-rp` service running [Redpanda](https://redpanda.com/) — a lightweight, single-binary broker — by default, with `KAFKA_BROKERS` already pointed at it. You can instead point `KAFKA_BROKERS` at any Kafka cluster of your own.</Callout>@@ -761,6 +889,98 @@ KAFKA_BROKERS=redpanda:9092KAFKA_BROKERS=kafka-1:9092,kafka-2:9092,kafka-3:9092```+### KAFKA_SSL++**Type**: `boolean`+**Required**: No+**Default**: `false` (automatically `true` when SASL credentials are set)++Connect to the brokers over TLS. Set this to `true` for a TLS-only cluster without authentication. When `KAFKA_SASL_USERNAME`/`KAFKA_SASL_PASSWORD` are set, TLS is enabled automatically; set `KAFKA_SSL=false` explicitly to send SASL over plaintext (only sensible on a trusted internal network). Any value other than `true`/`1`/`false`/`0` fails startup.++**Example**:+```bash+KAFKA_SSL=true+```++### KAFKA_SSL_CA_PATH++**Type**: `string`+**Required**: No+**Default**: None (system trust store)++Path to a PEM-encoded CA certificate (or bundle) to trust in addition to the system trust store. Use this when your brokers present certificates signed by a private or self-signed CA. Requires TLS to be enabled; an unreadable file fails startup.++**Example**:+```bash+KAFKA_SSL_CA_PATH=/etc/openpanel/kafka-ca.pem+```++### KAFKA_SSL_REJECT_UNAUTHORIZED++**Type**: `boolean`+**Required**: No+**Default**: `true`++Whether to reject broker certificates that cannot be verified. Only set to `false` for local development against a self-signed broker; prefer `KAFKA_SSL_CA_PATH` in production. Requires TLS to be enabled.++**Example**:+```bash+KAFKA_SSL_REJECT_UNAUTHORIZED=false+```++### KAFKA_SASL_USERNAME++**Type**: `string`+**Required**: No (required together with `KAFKA_SASL_PASSWORD` to enable SASL)+**Default**: None++SASL username. Setting a username without a password (or vice versa) is a configuration error and the process refuses to start. Credential values are never logged.++**Example**:+```bash+KAFKA_SASL_USERNAME=openpanel+```++### KAFKA_SASL_PASSWORD++**Type**: `string`+**Required**: No (required together with `KAFKA_SASL_USERNAME` to enable SASL)+**Default**: None++SASL password.++**Example**:+```bash+KAFKA_SASL_PASSWORD=your-secret+```++### KAFKA_SASL_MECHANISM++**Type**: `string`+**Required**: No+**Default**: `scram-sha-512`++SASL mechanism to authenticate with. One of `plain`, `scram-sha-256` or `scram-sha-512` (case-insensitive). Any other value is rejected at startup, before a Kafka client is created.++**Example**:+```bash+# TLS + SASL/SCRAM-SHA-512 (the default when credentials are set)+KAFKA_BROKERS=kafka-1.example.com:9093,kafka-2.example.com:9093+KAFKA_SASL_USERNAME=openpanel+KAFKA_SASL_PASSWORD=your-secret++# TLS + SASL/PLAIN with a private CA+KAFKA_BROKERS=kafka.internal:9093+KAFKA_SASL_MECHANISM=plain+KAFKA_SASL_USERNAME=openpanel+KAFKA_SASL_PASSWORD=your-secret+KAFKA_SSL_CA_PATH=/etc/openpanel/kafka-ca.pem+```++<Callout>+The producer runs in idempotent mode, so the SASL principal needs the `IdempotentWrite` cluster permission in addition to `Write`/`Describe` on the topic and `Read` on the consumer group. Managed Kafka providers usually grant this by default; on a locked-down cluster you may need to add it explicitly.+</Callout>+### KAFKA_EVENTS_TOPIC**Type**: `string`@@ -1251,6 +1471,10 @@ For a basic self-hosted installation, these variables are required:- `RESEND_API_KEY` or `SMTP_HOST` - For email features (pick one)- `EMAIL_SENDER` - Email sender address- `OPENAI_API_KEY` and/or `ANTHROPIC_API_KEY` - For the in-app AI chat assistant+- `ENCRYPTION_KEY` - Required for Google Search Console, 2FA and exports+- `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `GOOGLE_REDIRECT_URI` - [Sign in with Google](/docs/self-hosting/social-login)+- `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `GITHUB_REDIRECT_URI` - [Sign in with GitHub](/docs/self-hosting/social-login)+- `GSC_GOOGLE_REDIRECT_URI` - [Google Search Console integration](/docs/self-hosting/google-search-console)### See Alsodiff --git a/apps/public/content/docs/self-hosting/google-search-console.mdx b/apps/public/content/docs/self-hosting/google-search-console.mdxnew file mode 100644index 000000000..7193164c5--- /dev/null+++ b/apps/public/content/docs/self-hosting/google-search-console.mdx@@ -0,0 +1,135 @@+---+title: Google Search Console+description: Enable the Google Search Console integration on your self-hosted OpenPanel to import clicks, impressions and keyword rankings+---++import { Step, Steps } from 'fumadocs-ui/components/steps';+import { Callout } from 'fumadocs-ui/components/callout';++The Google Search Console (GSC) integration imports search performance data into OpenPanel: clicks, impressions, CTR and average position per page and per query. Once enabled it powers the SEO page in each project (`/<organization>/<project>/seo`), Search Console insights on page reports, and the `gsc_*` tools in the [MCP server](/docs/mcp#google-search-console) and the AI assistant.++Enabling it is an instance-level setup (this page) plus a per-project connection that any project admin does from the project's settings under "Google Search".++## How it works++1. A project admin clicks "Connect Google Search Console" and is sent to Google with the read-only `webmasters.readonly` scope.+2. Google redirects back to the API with a code. The API exchanges it for an access token and a refresh token and stores both in PostgreSQL, encrypted with `ENCRYPTION_KEY`.+3. The admin picks which Search Console property to use. A backfill of the last 6 months starts immediately, in 14-day chunks.+4. Every night at 03:00 (worker time zone) the worker re-syncs a rolling 3-day window, because Google finalises data a couple of days late.+5. Data lands in the ClickHouse tables `gsc_daily`, `gsc_pages_daily` and `gsc_queries_daily`. Re-syncs overwrite earlier rows. There is no retention limit.++A few views (keyword cannibalization, page and query detail drill-downs) query Google live from the API and cache the result for 4 hours, so both the API and the worker need the Google credentials and `ENCRYPTION_KEY`.++## Prerequisites++You need a Google Cloud OAuth client. If you already set up [Google sign-in](/docs/self-hosting/social-login), reuse it. The integration uses the same `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`. Google sign-in does not have to be enabled; the OAuth client alone is enough.++You also need `ENCRYPTION_KEY` set on the API and worker. The Docker Compose setup script generates one. Other deployments must create it with `openssl rand -hex 32`.++Finally, you need the public `API_URL` of your instance, e.g. `https://analytics.example.com/api`.++## Setup++<Steps>+<Step>+### Enable the Search Console API++In the [Google Cloud Console](https://console.cloud.google.com/), open "APIs & Services", "Library", search for "Google Search Console API" and click "Enable". Without this every request fails with `403 Google Search Console API has not been used in project ... before or it is disabled`.+</Step>++<Step>+### Configure the consent screen and scope++Open "APIs & Services", "OAuth consent screen" (or "Google Auth Platform") and make sure the app exists. See the [Google sign-in guide](/docs/self-hosting/social-login#google) if you are starting from scratch.++Under "Data access" (or "Scopes"), add `https://www.googleapis.com/auth/webmasters.readonly` ("View Search Console data for your verified sites").++<Callout type="warn">+Testing versus published matters here. While the consent screen is in Testing mode, Google expires refresh tokens after 7 days. The nightly sync will then fail with status `token_expired` and the project will need to be reconnected every week. For a stable connection, click "Publish app".++`webmasters.readonly` is classed as a sensitive scope. Publishing an External app that requests it may trigger a request for Google's verification process. In practice this is only enforced when the app is used by many users outside your organisation. For an internal instance you can usually publish and keep using it, but Google will show an "unverified app" warning on the consent screen until verified. If everyone who will connect Search Console is in your Google Workspace, choose Internal as the user type. Internal apps never need verification and their refresh tokens do not expire after 7 days.+</Callout>+</Step>++<Step>+### Add the callback URL to the OAuth client++Open "APIs & Services", "Credentials", select your OAuth 2.0 client (or create a Web application client as described in the [sign-in guide](/docs/self-hosting/social-login#google)) and add another authorized redirect URI:++```+${API_URL}/gsc/callback+```++For example `https://analytics.example.com/api/gsc/callback`. This is a different URL from the sign-in callback (`/oauth/google/callback`). Both can coexist on the same client.+</Step>++<Step>+### Add the environment variables++```bash title=".env"+GOOGLE_CLIENT_ID=123456789012-abcdefghijklmnop.apps.googleusercontent.com+GOOGLE_CLIENT_SECRET=GOCSPX-xxxxxxxxxxxxxxxxxxxxxxxx+GSC_GOOGLE_REDIRECT_URI=https://analytics.example.com/api/gsc/callback+ENCRYPTION_KEY=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef+```++`GSC_GOOGLE_REDIRECT_URI` must match the redirect URI registered in the previous step exactly. `ENCRYPTION_KEY` must be exactly 64 hexadecimal characters (32 bytes). Generate one with `openssl rand -hex 32`.+</Step>++<Step>+### Restart the services++Which services need which variables:++| Variable | API | Worker | Dashboard |+|---|---|---|---|+| `GOOGLE_CLIENT_ID` | yes | yes | no |+| `GOOGLE_CLIENT_SECRET` | yes | yes | no |+| `GSC_GOOGLE_REDIRECT_URI` | yes | no | no |+| `ENCRYPTION_KEY` | yes | yes (must be identical to the API's) | no |++The dashboard needs none of these. It asks the API whether the integration is configured.++How you set them depends on how you deployed OpenPanel. With the Docker Compose setup, add them to `self-hosting/.env` (all services read it) and run `docker compose up -d --force-recreate op-api op-worker`. With Coolify, the bundled template exposes `OPENPANEL_GOOGLE_CLIENT_ID`, `OPENPANEL_GOOGLE_CLIENT_SECRET` and `OPENPANEL_GSC_GOOGLE_REDIRECT_URI`, and generates `ENCRYPTION_KEY` for you. For any other setup, add them to the API and worker environment and restart both.+</Step>++<Step>+### Connect a project++In the dashboard, open the project's settings, go to the "Google Search" tab and click "Connect Google Search Console". Sign in with a Google account that has at least Restricted access to the property in Search Console, and grant the read-only permission.++You are returned to the settings tab with a list of every property that account can see. Both domain properties (`sc-domain:example.com`) and URL-prefix properties (`https://example.com/`) are listed. Pick the one that matches the site the project tracks. A 6-month backfill starts as soon as you click "Connect property". The badge on the settings page shows its progress, and the SEO page fills in as chunks complete.+</Step>+</Steps>++## Things to know++Each project has at most one Search Console connection. Disconnecting keeps the data already imported into ClickHouse. Reconnecting to a different property overwrites overlapping dates.++The refresh token belongs to the Google user who clicked "Connect". If that person loses access to the property, or leaves the organisation, syncing stops with `token_expired` and someone else must reconnect.++Rotating `ENCRYPTION_KEY` breaks existing connections. Stored tokens can no longer be decrypted and every project must reconnect. The same key also protects two-factor secrets and export credentials, so treat it as permanent.++If you restrict the worker with [`ENABLED_QUEUES`](/docs/self-hosting/environment-variables#enabled_queues), it must include both `gsc` (sync and backfill jobs) and `cron` (the nightly trigger). `GSC_CONCURRENCY` (default `5`) controls how many projects sync in parallel.++Search Console allows thousands of requests per site per day. A 6-month backfill makes roughly 40 requests, and the nightly sync makes 3 per project. You are unlikely to hit limits unless you connect hundreds of projects.++Google typically finalises data 2 to 3 days after the fact. OpenPanel requests `dataState: all`, so recent days include preliminary numbers that later syncs correct.++If the connect callback fails, OpenPanel redirects to `/login?error=...&correlationId=...` even though you are still signed in. Navigate back to the project and search the API logs for the correlation ID to see the full error.++## Troubleshooting++| Symptom | Likely cause |+|---|---|+| Settings tab says "Google Search Console is not configured on this instance" | The API is missing `GOOGLE_CLIENT_ID` or `GSC_GOOGLE_REDIRECT_URI`, or was not restarted after you added them. |+| Google shows `Error 400: redirect_uri_mismatch` | `GSC_GOOGLE_REDIRECT_URI` differs from the redirect URI registered on the OAuth client. Check `http` vs `https`, the `/api` prefix and trailing slashes. |+| `/login?error=No refresh token returned from Google GSC OAuth` | Google only issues a refresh token on the first consent for a client, and OpenPanel forces re-consent to work around that. If you still hit this, revoke OpenPanel under [myaccount.google.com/permissions](https://myaccount.google.com/permissions) and connect again. |+| `/login?error=Missing GSC OAuth cookies` or `GSC OAuth state mismatch` | The state cookies set before the redirect did not reach the API. The API and dashboard must share a registrable domain. See the cookie notes in the [social login guide](/docs/self-hosting/social-login#before-you-start). |+| Connection shows "Authorization expired" (`token_expired`) | The refresh token was revoked or expired. Most often the consent screen is in Testing mode (7-day limit). Publish the app, then click "Reconnect". |+| Sync status "error" with `Google Search Console API has not been used in project` | The Search Console API is not enabled in the Google Cloud project. Enable it and wait a minute. |+| Sync status "error" with `403` / `User does not have sufficient permission for site` | The connected Google account lost access to the property in Search Console. |+| Worker logs `ENCRYPTION_KEY environment variable is not set` or `must be 32 bytes (64 hex characters)` | `ENCRYPTION_KEY` is missing or malformed on the worker. It must be identical on the API and the worker. |+| Worker logs `GOOGLE_CLIENT_ID or GOOGLE_CLIENT_SECRET is not set in this environment` | The worker has no Google credentials and cannot refresh tokens. Add them to the worker service. |+| "No Search Console properties found for this Google account" | The Google account you signed in with has no properties in Search Console. Add the account as a user on the property (Search Console settings, "Users and permissions") and reconnect. |+| SEO page is empty right after connecting | The backfill runs in the background in 14-day chunks. The settings page shows its status. If it stays on "pending", check that the worker is running and `ENABLED_QUEUES` includes `gsc`. |diff --git a/apps/public/content/docs/self-hosting/meta.json b/apps/public/content/docs/self-hosting/meta.jsonindex e59f271d8..696158758 100644--- a/apps/public/content/docs/self-hosting/meta.json+++ b/apps/public/content/docs/self-hosting/meta.json@@ -9,6 +9,8 @@"[Deploy on Kubernetes](/docs/self-hosting/deploy-kubernetes)","[Reverse proxy setup](/docs/self-hosting/reverse-proxy)","[Environment Variables](/docs/self-hosting/environment-variables)",+ "[Social login (Google & GitHub)](/docs/self-hosting/social-login)",+ "[Google Search Console](/docs/self-hosting/google-search-console)","[High volume setup](/docs/self-hosting/high-volume)","supporter-access-latest-docker-images","changelog"diff --git a/apps/public/content/docs/self-hosting/social-login.mdx b/apps/public/content/docs/self-hosting/social-login.mdxnew file mode 100644index 000000000..52b86c721--- /dev/null+++ b/apps/public/content/docs/self-hosting/social-login.mdx@@ -0,0 +1,168 @@+---+title: Social login (Google & GitHub)+description: Let users sign in to your self-hosted OpenPanel with their Google or GitHub account+---++import { Step, Steps } from 'fumadocs-ui/components/steps';+import { Callout } from 'fumadocs-ui/components/callout';++OpenPanel supports signing in with Google and GitHub in addition to email and password. Both are optional. Email/password login always works, and the social login buttons only appear when the provider is configured.++Enabling a provider takes three steps:++1. Create an OAuth application at the provider and register OpenPanel's callback URL.+2. Add the client ID, client secret and callback URL to your environment.+3. Restart the API.++## Before you start++You need two URLs from your deployment:++| Variable | What it is | Example |+|---|---|---|+| `DASHBOARD_URL` | The public URL users open in the browser | `https://analytics.example.com` |+| `API_URL` | The public URL of the API. With the default Docker Compose / Caddy setup this is the dashboard URL plus `/api` | `https://analytics.example.com/api` |++The OAuth callback (the URL the provider redirects back to) always lives on the API:++| Provider | Callback URL | Environment variable |+|---|---|---|+| Google | `${API_URL}/oauth/google/callback` | `GOOGLE_REDIRECT_URI` |+| GitHub | `${API_URL}/oauth/github/callback` | `GITHUB_REDIRECT_URI` |++With the example above that is `https://analytics.example.com/api/oauth/google/callback` and `https://analytics.example.com/api/oauth/github/callback`.++<Callout>+The callback URL is not derived from `API_URL`. You must set `GOOGLE_REDIRECT_URI` / `GITHUB_REDIRECT_URI` yourself, and the value must be identical to what you register at the provider: same scheme, same host, same `/api` prefix, no trailing slash. If your API is served from its own subdomain such as `https://api.example.com`, drop the `/api` segment.+</Callout>++<Callout type="warn">+The API and the dashboard must share a domain so the session cookie set by the API callback is readable by the dashboard. `analytics.example.com` + `analytics.example.com/api` works, and so does `app.example.com` + `api.example.com`. `example.com` + `example.org` does not. See [`CUSTOM_COOKIE_DOMAIN`](/docs/self-hosting/environment-variables#custom_cookie_domain) and [`COOKIE_TLDS`](/docs/self-hosting/environment-variables#cookie_tlds) if your domain layout is unusual. Use HTTPS in production; session cookies are marked `secure` whenever `DASHBOARD_URL` uses `https://`.+</Callout>+++<Steps>+<Step>+### Create or pick a Google Cloud project++Go to the [Google Cloud Console](https://console.cloud.google.com/) and select an existing project or create a new one. Any project works; it does not need billing enabled.+</Step>++<Step>+### Configure the OAuth consent screen++Open "APIs & Services" and then "OAuth consent screen" (newer consoles call this "Google Auth Platform" and "Branding").++Choose "External" as the user type unless every user is in your Google Workspace organisation. In that case "Internal" is simpler and skips verification entirely. Fill in an app name, support email and developer contact; users see the app name on the consent dialog.++The sign-in flow only uses the `openid`, `email` and `profile` scopes. These are non-sensitive and need no verification.++An External app starts in Testing mode, which limits sign-in to up to 100 Google accounts that you list as test users. That is fine for a private instance. If you want anyone with a Google account to be able to sign in, click "Publish app". Because only non-sensitive scopes are used, publishing does not require a Google review.++<Callout>+If you also plan to enable the [Google Search Console integration](/docs/self-hosting/google-search-console), read the notes there before choosing Testing or Published. The choice affects how long Search Console tokens stay valid.+</Callout>+</Step>++<Step>+### Create OAuth client credentials++Open "APIs & Services", "Credentials", "Create credentials", "OAuth client ID" and fill in:++| Field | Value |+|---|---|+| Application type | Web application |+| Name | Anything, e.g. `OpenPanel` |+| Authorized JavaScript origins | Your `DASHBOARD_URL`, e.g. `https://analytics.example.com` |+| Authorized redirect URIs | `${API_URL}/oauth/google/callback`, e.g. `https://analytics.example.com/api/oauth/google/callback` |++Click "Create" and copy the client ID (ends with `.apps.googleusercontent.com`) and client secret (starts with `GOCSPX-`).+</Step>++<Step>+### Add the environment variables++```bash title=".env"+GOOGLE_CLIENT_ID=123456789012-abcdefghijklmnop.apps.googleusercontent.com+GOOGLE_CLIENT_SECRET=GOCSPX-xxxxxxxxxxxxxxxxxxxxxxxx+GOOGLE_REDIRECT_URI=https://analytics.example.com/api/oauth/google/callback+```+</Step>+</Steps>++## GitHub++<Steps>+<Step>+### Create a GitHub OAuth App++Go to "Settings", "Developer settings", "OAuth Apps", "New OAuth App" on [github.com](https://github.com/settings/developers). You can create it under your personal account or under an organisation (from the organisation's settings page). Both work the same way.++| Field | Value |+|---|---|+| Application name | Anything, e.g. `OpenPanel` |+| Homepage URL | Your `DASHBOARD_URL`, e.g. `https://analytics.example.com` |+| Authorization callback URL | `${API_URL}/oauth/github/callback`, e.g. `https://analytics.example.com/api/oauth/github/callback` |++Leave "Enable Device Flow" unchecked and click "Register application".+</Step>++<Step>+### Generate a client secret++On the app page, copy the client ID, then click "Generate a new client secret" and copy the secret. GitHub only shows it once.+</Step>++<Step>+### Add the environment variables++```bash title=".env"+GITHUB_CLIENT_ID=Iv1.xxxxxxxxxxxxxxxx+GITHUB_CLIENT_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx+GITHUB_REDIRECT_URI=https://analytics.example.com/api/oauth/github/callback+```+</Step>+</Steps>++<Callout>+OpenPanel requests the `user:email` and `user:read` scopes and uses the account's primary, verified email address. Users whose primary GitHub email is unverified will see `GitHub email not found or not verified`.+</Callout>++## Apply the configuration++All six variables belong to the API service. The dashboard and worker do not use them; the dashboard asks the API which providers are configured and renders buttons accordingly. Giving every service the full set is harmless, which is what the Docker Compose setup does.++How you set them depends on how you deployed OpenPanel. With the Docker Compose setup, add them to `self-hosting/.env` (the generated file already contains a commented-out template) and recreate the API container:++```bash+docker compose up -d --force-recreate op-api+```++With Coolify, the bundled template exposes them as `OPENPANEL_GOOGLE_CLIENT_ID`, `OPENPANEL_GOOGLE_CLIENT_SECRET`, `OPENPANEL_GOOGLE_REDIRECT_URI`, `OPENPANEL_GITHUB_CLIENT_ID`, `OPENPANEL_GITHUB_CLIENT_SECRET` and `OPENPANEL_GITHUB_REDIRECT_URI`. For any other setup, add them to the API's environment the same way you set `COOKIE_SECRET` and restart the API.++## Things to know++Registration rules still apply. A social login that would create a new user is subject to [`ALLOW_REGISTRATION`](/docs/self-hosting/environment-variables#allow_registration) and [`ALLOW_INVITATION`](/docs/self-hosting/environment-variables#allow_invitation). The very first user is always allowed. After that, users need an invite link or `ALLOW_REGISTRATION=true`. Existing users can always sign in.++Accounts are not linked automatically. If someone signed up with email/password and later clicks "Sign in with Google" using the same address, they are sent back to the login page with `Please sign in using your original authentication method`. The same applies between Google and GitHub. Users must keep using the method they signed up with.++Each provider is independent. Configure one, the other, or both. The login page only shows buttons for providers the API has a client ID and redirect URI for.++OpenPanel remembers the last provider a browser signed in with (a one-year cookie) and marks that button on the login page with "Used last time".++## Troubleshooting++| Symptom | Likely cause |+|---|---|+| Google shows `Error 400: redirect_uri_mismatch`; GitHub shows "The redirect_uri MUST match the registered callback URL" | `GOOGLE_REDIRECT_URI` / `GITHUB_REDIRECT_URI` differs from the URL registered at the provider. Check `http` vs `https`, the `/api` prefix and trailing slashes. |+| Google shows `Error 401: invalid_client`, or the authorization URL has an empty `client_id` | `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` is not set on the API service, or the API was not restarted after changing `.env`. |+| Redirected to `/login?error=Missing oauth parameters` or `OAuth state mismatch` | The state cookie set before the redirect was not sent back to the API. Usually the API and dashboard are on different registrable domains, `DASHBOARD_URL` is wrong, or the browser blocks cookies. See the cookie callout above. |+| `/login?error=Registrations are not allowed` | New user and `ALLOW_REGISTRATION=false` with no valid invite. Send an invite from the organisation settings or set `ALLOW_REGISTRATION=true`. |+| `/login?error=Please sign in using your original authentication method` | An account with that email already exists via another method. Sign in with that method instead. |+| `/login?error=GitHub email not found or not verified` | The user's primary email on GitHub is not verified. Verify it under GitHub settings, "Emails". |+| `/login?error=Email not verified with Google` | Google reports the email as unverified. This is rare and usually a Workspace account with a pending domain. |+| Google login works for you but others get "Access blocked: This app has not completed the Google verification process" | The consent screen is in Testing and the user is not listed as a test user. Add them, or publish the app. |+| Buttons do not appear on the login page | The API does not have both the client ID and the redirect URI for that provider (`GOOGLE_CLIENT_ID` + `GOOGLE_REDIRECT_URI`, or `GITHUB_CLIENT_ID` + `GITHUB_REDIRECT_URI`), or it was not restarted after you added them. |++Every error redirect includes a `correlationId` query parameter. Search the API logs for it to see the full error.diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.gsc.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.gsc.tsxindex bd8f975ff..e01ae8bed 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.gsc.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.gsc.tsx@@ -6,7 +6,7 @@ import { useState } from 'react';import { toast } from 'sonner';import { Skeleton } from '@/components/skeleton';import { Badge } from '@/components/ui/badge';-import { Button } from '@/components/ui/button';+import { Button, LinkButton } from '@/components/ui/button';import {Select,SelectContent,@@ -23,12 +23,17 @@ export const Route = createFileRoute(component: GscSettings,});+const GSC_SELF_HOSTING_DOCS_URL =+ 'https://openpanel.dev/docs/self-hosting/google-search-console';+function GscSettings() {const { projectId } = useAppParams();const trpc = useTRPC();const queryClient = useQueryClient();const [selectedSite, setSelectedSite] = useState('');+ const providersQuery = useQuery(trpc.auth.providers.queryOptions());+const connectionQuery = useQuery(trpc.gsc.getConnection.queryOptions({ projectId },@@ -81,8 +86,9 @@ function GscSettings() {);const connection = connectionQuery.data;+ const isGscConfigured = providersQuery.data?.gsc ?? false;- if (connectionQuery.isLoading) {+ if (connectionQuery.isLoading || providersQuery.isLoading) {return (<div className="space-y-4"><Skeleton className="h-32 w-full" />@@ -90,6 +96,39 @@ function GscSettings() {);}+ // The API has no Google OAuth client / GSC redirect URI configured.+ // Existing connections are still shown below so data keeps working even if+ // an operator removes the env vars later.+ if (!(connection || isGscConfigured)) {+ return (+ <div className="space-y-6">+ <div>+ <h3 className="font-medium text-lg">Google Search Console</h3>+ <p className="mt-1 text-muted-foreground text-sm">+ Connect your Google Search Console property to import search+ performance data.+ </p>+ </div>+ <div className="flex flex-col gap-4 rounded-lg border p-6">+ <p className="text-muted-foreground text-sm">+ Google Search Console is not configured on this instance. Whoever+ operates it needs to create a Google OAuth client and add it to the+ API and worker environment. The setup guide has the details.+ </p>+ <LinkButton+ className="w-fit"+ href={GSC_SELF_HOSTING_DOCS_URL}+ rel="noopener"+ target="_blank"+ variant="outline"+ >+ Read the setup guide+ </LinkButton>+ </div>+ </div>+ );+ }+// Not connected at allif (!connection) {return (diff --git a/apps/start/src/routes/_login.login.tsx b/apps/start/src/routes/_login.login.tsxindex ef36777ed..c3d65dfba 100644--- a/apps/start/src/routes/_login.login.tsx+++ b/apps/start/src/routes/_login.login.tsx@@ -1,3 +1,4 @@+import { useSuspenseQuery } from '@tanstack/react-query';import { createFileRoute } from '@tanstack/react-router';import { AlertCircle } from 'lucide-react';import { z } from 'zod';@@ -7,6 +8,7 @@ import { SignInGithub } from '@/components/auth/sign-in-github';import { SignInGoogle } from '@/components/auth/sign-in-google';import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';import { useCookieStore } from '@/hooks/use-cookie-store';+import { useTRPC } from '@/integrations/trpc/react';import { createTitle, PAGE_TITLES } from '@/utils/title';export const Route = createFileRoute('/_login/login')({@@ -22,10 +24,20 @@ export const Route = createFileRoute('/_login/login')({correlationId: z.string().optional(),inviteId: z.string().optional(),}),+ loader: async ({ context }) => {+ await context.queryClient.ensureQueryData(+ context.trpc.auth.providers.queryOptions()+ );+ },});function LoginPage() {const { error, correlationId, inviteId } = Route.useSearch();+ const trpc = useTRPC();+ const { data: providers } = useSuspenseQuery(+ trpc.auth.providers.queryOptions()+ );+ const hasOAuthProviders = providers.google || providers.github;const [lastProvider] = useCookieStore<null | string>('last-auth-provider',null@@ -72,20 +84,31 @@ function LoginPage() {</Alert>)}- <div className="space-y-4">- <SignInGoogle- inviteId={inviteId}- isLastUsed={lastProvider === 'google'}- type="sign-in"- />- <SignInGithub- inviteId={inviteId}- isLastUsed={lastProvider === 'github'}- type="sign-in"- />- </div>- <Or />- <SignInEmailForm inviteId={inviteId} isLastUsed={lastProvider === 'email'} />+ {hasOAuthProviders && (+ <>+ <div className="space-y-4">+ {providers.google && (+ <SignInGoogle+ inviteId={inviteId}+ isLastUsed={lastProvider === 'google'}+ type="sign-in"+ />+ )}+ {providers.github && (+ <SignInGithub+ inviteId={inviteId}+ isLastUsed={lastProvider === 'github'}+ type="sign-in"+ />+ )}+ </div>+ <Or />+ </>+ )}+ <SignInEmailForm+ inviteId={inviteId}+ isLastUsed={lastProvider === 'email'}+ /></div>);}diff --git a/apps/start/src/routes/_public.onboarding.tsx b/apps/start/src/routes/_public.onboarding.tsxindex e854db824..0475cd15b 100644--- a/apps/start/src/routes/_public.onboarding.tsx+++ b/apps/start/src/routes/_public.onboarding.tsx@@ -1,4 +1,4 @@-import { useQuery } from '@tanstack/react-query';+import { useQuery, useSuspenseQuery } from '@tanstack/react-query';import { createFileRoute, redirect } from '@tanstack/react-router';import { MailIcon } from 'lucide-react';import { z } from 'zod';@@ -28,6 +28,9 @@ export const Route = createFileRoute('/_public/onboarding')({component: Component,validateSearch,loader: async ({ context, location }) => {+ await context.queryClient.ensureQueryData(+ context.trpc.auth.providers.queryOptions()+ );const search = validateSearch.safeParse(location.search);if (search.success && search.data.inviteId) {await context.queryClient.prefetchQuery(@@ -43,6 +46,11 @@ export const Route = createFileRoute('/_public/onboarding')({function Component() {const { inviteId } = Route.useSearch();const trpc = useTRPC();+ const { data: providers } = useSuspenseQuery(+ trpc.auth.providers.queryOptions()+ );+ const hasOAuthProviders = providers.google || providers.github;+ const hasBothOAuthProviders = providers.google && providers.github;const { data: invite } = useQuery(trpc.organization.getInvite.queryOptions({@@ -119,15 +127,29 @@ function Component() {)}<div className="space-y-6">- <div className="grid grid-cols-1 gap-4 md:grid-cols-2">- <SignInGithub inviteId={inviteId} type="sign-up" />- <SignInGoogle inviteId={inviteId} type="sign-up" />- </div>- <p className="text-center text-muted-foreground text-xs">- No credit card required · Free 30-day trial · Cancel anytime- </p>+ {hasOAuthProviders && (+ <>+ <div+ className={+ hasBothOAuthProviders+ ? 'grid grid-cols-1 gap-4 md:grid-cols-2'+ : 'grid grid-cols-1 gap-4'+ }+ >+ {providers.github && (+ <SignInGithub inviteId={inviteId} type="sign-up" />+ )}+ {providers.google && (+ <SignInGoogle inviteId={inviteId} type="sign-up" />+ )}+ </div>+ <p className="text-center text-muted-foreground text-xs">+ No credit card required · Free 30-day trial · Cancel anytime+ </p>- <Or className="my-6" />+ <Or className="my-6" />+ </>+ )}<div className="mb-4 flex items-center gap-2 font-semibold text-lg"><MailIcon className="size-4" />diff --git a/packages/core/src/modules/auth/auth.rpc.test.ts b/packages/core/src/modules/auth/auth.rpc.test.tsindex cb24b8481..ad8de3950 100644--- a/packages/core/src/modules/auth/auth.rpc.test.ts+++ b/packages/core/src/modules/auth/auth.rpc.test.ts@@ -5,6 +5,7 @@// see auth.rpc.ts's header.import { expect, test } from 'bun:test';+import { testCoreConfig } from '../../../test/config-fixture';import { stubHttpCtx } from '../../../test/rpc-fixtures';import { makeTrpcContext } from '../../rpc/base';import type { CookieOptions } from '../../shared/cookie';@@ -30,6 +31,39 @@ async function anonCaller() {return authRouter.createCaller(trpcCtx);}+test('providers reports which OAuth features are configured, as booleans only', async () => {+ const anon = await anonCaller();+ expect(await anon.providers()).toEqual({+ google: false,+ github: false,+ gsc: false,+ });++ const config = testCoreConfig();+ config.auth.google = {+ clientId: 'google-id',+ clientSecret: 'google-secret',+ redirectUri: 'https://api.example.com/oauth/google/callback',+ };+ config.auth.googleGsc = {+ ...config.auth.google,+ redirectUri: 'https://api.example.com/gsc/callback',+ };+ // A GitHub client id without its redirect URI cannot complete a sign-in.+ config.auth.github = {+ clientId: 'github-id',+ clientSecret: 'github-secret',+ redirectUri: '',+ };+ const { ctx } = stubHttpCtx({ config }, EMPTY_SESSION);+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {+ cookieOptions: COOKIE_OPTIONS,+ });+ const providers = await authRouter.createCaller(trpcCtx).providers();+ expect(providers).toEqual({ google: true, github: false, gsc: true });+ expect(JSON.stringify(providers)).not.toContain('secret');+});+test('totpStatus rejects an unauthenticated caller', async () => {const caller = await anonCaller();await expect(caller.totpStatus()).rejects.toMatchObject({diff --git a/packages/core/src/modules/auth/auth.rpc.ts b/packages/core/src/modules/auth/auth.rpc.tsindex 9d33b6d81..00862661c 100644--- a/packages/core/src/modules/auth/auth.rpc.ts+++ b/packages/core/src/modules/auth/auth.rpc.ts@@ -34,6 +34,7 @@ import {disableTotp,enableTotp,extendSessionCookie,+ getConfiguredProviders,getTotpStatus,regenerateTotpRecoveryCodes,requestPasswordReset,@@ -48,6 +49,16 @@ import {} from './auth.service';export const authRouter = createTRPCRouter({+ /**+ * Which optional OAuth-backed features this instance has credentials for.+ * The dashboard hides the social login buttons and the Search Console+ * settings on a self-hosted instance that has not configured them.+ * Booleans only: the client id/secret never leave the API.+ */+ providers: publicProcedure.query(({ ctx }) =>+ getConfiguredProviders(ctx.config)+ ),+signOut: publicProcedure.mutation(async ({ ctx }) => {await signOutUser(ctx, ctx.setCookie, ctx.session?.session?.id);}),diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.tsindex df221d7d7..c261371cb 100644--- a/packages/core/src/modules/auth/auth.service.ts+++ b/packages/core/src/modules/auth/auth.service.ts@@ -367,6 +367,25 @@ export type StartOAuthSignInResult =| { type: 'github'; url: string }| { type: 'google'; url: string };+export interface ConfiguredProviders {+ google: boolean;+ github: boolean;+ gsc: boolean;+}++/** A provider counts as configured only when a sign-in could complete: the+ * client id AND its redirect URI. The secret is never reported. */+export function getConfiguredProviders(+ config: CoreConfig+): ConfiguredProviders {+ const { google, github, googleGsc } = config.auth;+ return {+ google: Boolean(google.clientId && google.redirectUri),+ github: Boolean(github.clientId && github.redirectUri),+ gsc: Boolean(googleGsc.clientId && googleGsc.redirectUri),+ };+}+/*** No registration check here. At this point we have no identity for the* caller — the IdP hasn't been hit yet — so we cannot tell a returning userdiff --git a/self-hosting/.env.template b/self-hosting/.env.templateindex 615eab83c..67a7c14f4 100644--- a/self-hosting/.env.template+++ b/self-hosting/.env.template@@ -14,6 +14,24 @@ API_URL="$API_URL"COOKIE_SECRET="$COOKIE_SECRET"EMAIL_SENDER="$EMAIL_SENDER"RESEND_API_KEY="$RESEND_API_KEY"+ENCRYPTION_KEY="$ENCRYPTION_KEY"++# Optional: Social login (Google / GitHub)+# Docs: https://openpanel.dev/docs/self-hosting/social-login+# The redirect URIs must match the "Authorized redirect URI" configured at the+# provider exactly. Default layout: <your-domain>/api/oauth/<provider>/callback+# GOOGLE_CLIENT_ID=xxxx.apps.googleusercontent.com+# GOOGLE_CLIENT_SECRET=GOCSPX-xxxx+# GOOGLE_REDIRECT_URI=https://your-domain.com/api/oauth/google/callback+# GITHUB_CLIENT_ID=Iv1.xxxx+# GITHUB_CLIENT_SECRET=xxxx+# GITHUB_REDIRECT_URI=https://your-domain.com/api/oauth/github/callback++# Optional: Google Search Console integration+# Docs: https://openpanel.dev/docs/self-hosting/google-search-console+# Reuses GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET above, plus its own redirect+# URI. Requires ENCRYPTION_KEY (generated by the setup script).+# GSC_GOOGLE_REDIRECT_URI=https://your-domain.com/api/gsc/callback# Events transport (ADR-004). The op-rp service (Redpanda) is a required part# of this stack, not optional infra — see docker-compose.template.yml.diff --git a/self-hosting/coolify.yml b/self-hosting/coolify.ymlindex 74a20bea9..7762ade81 100644--- a/self-hosting/coolify.yml+++ b/self-hosting/coolify.yml@@ -156,10 +156,20 @@ services:- DASHBOARD_URL=$SERVICE_FQDN_OPDASHBOARD# Others- COOKIE_SECRET=${SERVICE_BASE64_COOKIESECRET}+ - ENCRYPTION_KEY=${SERVICE_HEX_64_ENCRYPTIONKEY}- ALLOW_REGISTRATION=${OPENPANEL_ALLOW_REGISTRATION:-false}- ALLOW_INVITATION=${OPENPANEL_ALLOW_INVITATION:-true}- EMAIL_SENDER=${OPENPANEL_EMAIL_SENDER}- RESEND_API_KEY=${RESEND_API_KEY}+ # Optional: social login (https://openpanel.dev/docs/self-hosting/social-login)+ - GOOGLE_CLIENT_ID=${OPENPANEL_GOOGLE_CLIENT_ID}+ - GOOGLE_CLIENT_SECRET=${OPENPANEL_GOOGLE_CLIENT_SECRET}+ - GOOGLE_REDIRECT_URI=${OPENPANEL_GOOGLE_REDIRECT_URI}+ - GITHUB_CLIENT_ID=${OPENPANEL_GITHUB_CLIENT_ID}+ - GITHUB_CLIENT_SECRET=${OPENPANEL_GITHUB_CLIENT_SECRET}+ - GITHUB_REDIRECT_URI=${OPENPANEL_GITHUB_REDIRECT_URI}+ # Optional: Google Search Console (https://openpanel.dev/docs/self-hosting/google-search-console)+ - GSC_GOOGLE_REDIRECT_URI=${OPENPANEL_GSC_GOOGLE_REDIRECT_URI}healthcheck:test: ["CMD-SHELL", "curl -f http://localhost:3000/healthcheck || exit 1"]interval: 10s@@ -214,6 +224,11 @@ services:- CLICKHOUSE_URL=${OPENPANEL_CLICKHOUSE_URL:-http://opch:8123/openpanel}# Set coolify FQDN domain- API_URL=$SERVICE_FQDN_OPAPI+ # Must match the API's key: the worker decrypts GSC tokens during sync+ - ENCRYPTION_KEY=${SERVICE_HEX_64_ENCRYPTIONKEY}+ # Optional: Google Search Console sync needs the Google OAuth client+ - GOOGLE_CLIENT_ID=${OPENPANEL_GOOGLE_CLIENT_ID}+ - GOOGLE_CLIENT_SECRET=${OPENPANEL_GOOGLE_CLIENT_SECRET}healthcheck:test: ["CMD-SHELL", "curl -f http://localhost:3000/healthz/ready || exit 1"]interval: 10sdiff --git a/self-hosting/quiz.ts b/self-hosting/quiz.tsindex 85448e201..f0fa9f2eb 100644--- a/self-hosting/quiz.ts+++ b/self-hosting/quiz.ts@@ -1,3 +1,4 @@+import { randomBytes } from 'node:crypto';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';@@ -20,6 +21,9 @@ let envs = {DATABASE_URL: '',DOMAIN_NAME: '',COOKIE_SECRET: generatePassword(32),+ // AES-256 key for at-rest encryption (GSC tokens, 2FA secrets). Must be+ // exactly 32 bytes / 64 hex chars, so it can't reuse generatePassword.+ ENCRYPTION_KEY: randomBytes(32).toString('hex'),RESEND_API_KEY: '',EMAIL_SENDER: '',KAFKA_EVENTS_TOPIC_PARTITIONS,@@ -48,7 +52,7 @@ function writeCaddyfile(domainName: string, basicAuthPassword: string) {const caddyfileTemplatePath = path.resolve(__dirname,'caddy',- 'Caddyfile.template',+ 'Caddyfile.template');const caddyfilePath = path.resolve(__dirname, 'caddy', 'Caddyfile');fs.writeFileSync(@@ -58,12 +62,12 @@ function writeCaddyfile(domainName: string, basicAuthPassword: string) {.replaceAll('$DOMAIN_NAME', domainName.replace(/https?:\/\//, '')).replaceAll('$BASIC_AUTH_PASSWORD',- bcrypt.hashSync(basicAuthPassword, 10),+ bcrypt.hashSync(basicAuthPassword, 10)).replaceAll('$SSL_CONFIG',- domainName.includes('localhost:443') ? '\n\ttls internal' : '',- ),+ domainName.includes('localhost:443') ? '\n\ttls internal' : ''+ ));}@@ -90,7 +94,7 @@ function searchAndReplaceDockerCompose(replacements: [string, string][]) {const dockerComposeContent = fs.readFileSync(dockerComposePath, 'utf-8');const dockerComposeReplaced = replacements.reduce((acc, [search, replace]) => acc.replaceAll(search, replace),- dockerComposeContent,+ dockerComposeContent);fs.writeFileSync(dockerComposePath, dockerComposeReplaced);@@ -119,7 +123,7 @@ function removeServiceFromDockerCompose(serviceName: string) {if (Array.isArray(serviceConfig.depends_on)) {// Handle legacy array formatserviceConfig.depends_on = serviceConfig.depends_on.filter(- (dep) => dep !== serviceName,+ (dep) => dep !== serviceName);} else {// Handle new object format@@ -155,6 +159,7 @@ function writeEnvFile(envs: EnvVars) {const newEnvFile = envTemplate.replace('$COOKIE_SECRET', envs.COOKIE_SECRET)+ .replace('$ENCRYPTION_KEY', envs.ENCRYPTION_KEY).replace('$CLICKHOUSE_URL', envs.CLICKHOUSE_URL).replace('$REDIS_URL', envs.REDIS_URL).replace('$DATABASE_URL', envs.DATABASE_URL)@@ -163,7 +168,10 @@ function writeEnvFile(envs: EnvVars) {.replace('$API_URL', `${stripTrailingSlash(envs.DOMAIN_NAME)}/api`).replace('$RESEND_API_KEY', envs.RESEND_API_KEY).replace('$EMAIL_SENDER', envs.EMAIL_SENDER)- .replace('$KAFKA_EVENTS_TOPIC_PARTITIONS', envs.KAFKA_EVENTS_TOPIC_PARTITIONS);+ .replace(+ '$KAFKA_EVENTS_TOPIC_PARTITIONS',+ envs.KAFKA_EVENTS_TOPIC_PARTITIONS+ );fs.writeFileSync(envPath,@@ -172,7 +180,7 @@ function writeEnvFile(envs: EnvVars) {.filter((line) => {return !line.includes('=""');})- .join('\n'),+ .join('\n'));}@@ -183,7 +191,7 @@ function writeRedpandaBootstrap(partitions: string) {const templatePath = path.resolve(__dirname,'redpanda',- 'bootstrap.template.yaml',+ 'bootstrap.template.yaml');const bootstrapPath = path.resolve(__dirname, 'redpanda', 'bootstrap.yaml');@@ -191,7 +199,7 @@ function writeRedpandaBootstrap(partitions: string) {bootstrapPath,fs.readFileSync(templatePath, 'utf-8')- .replaceAll('$KAFKA_EVENTS_TOPIC_PARTITIONS', partitions),+ .replaceAll('$KAFKA_EVENTS_TOPIC_PARTITIONS', partitions));}@@ -219,11 +227,11 @@ async function initiateOnboarding() {];console.log(- '******************************************************************************\n',+ '******************************************************************************\n');console.log(message.join('\n'));console.log(- '\n******************************************************************************',+ '\n******************************************************************************');// Domain name@@ -423,7 +431,7 @@ async function initiateOnboarding() {console.log('Updating docker-compose.yml file...\n');fs.copyFileSync(path.resolve(__dirname, 'docker-compose.template.yml'),- path.resolve(__dirname, 'docker-compose.yml'),+ path.resolve(__dirname, 'docker-compose.yml'));if (envs.CLICKHOUSE_URL) {@@ -468,7 +476,7 @@ async function initiateOnboarding() {`Start OpenPanel with "./start" inside the self-hosting directory`,'','',- ].join('\n'),+ ].join('\n'));}