Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

GSC connection issues fixes

Blue Mousebce33f5da1c4
diff --git a/backend/.env.example b/backend/.env.example
index 99a3bb636..fb06c8629 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -58,10 +58,14 @@ CDN_ACCESS_TOKEN=SOME_SECRET_TOKEN
# Captcha API
CAPTCHA_SALT=
-# Google SSO & GSC integration
+# Google SSO
GOOGLE_OAUTH2_CLIENT_ID=
GOOGLE_OAUTH2_CLIENT_SECRET=
+# Google GSC Integration Client
+GOOGLE_GSC_CLIENT_ID=
+GOOGLE_GSC_CLIENT_SECRET=
+
# Github SSO
GITHUB_OAUTH2_CLIENT_ID=
GITHUB_OAUTH2_CLIENT_SECRET=
diff --git a/backend/apps/cloud/src/common/utils.ts b/backend/apps/cloud/src/common/utils.ts
index 2550460a1..0fee9de63 100644
--- a/backend/apps/cloud/src/common/utils.ts
+++ b/backend/apps/cloud/src/common/utils.ts
@@ -31,7 +31,7 @@ export const hash = (content: string): string => {
* Derives a key from the SECRET_KEY_BASE environment variable using the HKDF algorithm.
*/
export const deriveKey = (
- purpose: 'refresh-token' | 'access-token',
+ purpose: 'refresh-token' | 'access-token' | 'gsc-token',
length = 32,
) => {
const base = Buffer.from(process.env.SECRET_KEY_BASE || '', 'utf8')
diff --git a/backend/apps/cloud/src/project/gsc.controller.ts b/backend/apps/cloud/src/project/gsc.controller.ts
index a5f0fbab0..6d749e3c2 100644
--- a/backend/apps/cloud/src/project/gsc.controller.ts
+++ b/backend/apps/cloud/src/project/gsc.controller.ts
@@ -5,11 +5,9 @@ import {
Delete,
Param,
Body,
- Query,
UseGuards,
BadRequestException,
HttpCode,
- Response,
} from '@nestjs/common'
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'
@@ -21,15 +19,25 @@ import { ProjectService } from './project.service'
@ApiTags('Project - Google Search Console')
@UseGuards(AuthenticationGuard)
-@Controller({ path: 'project', version: '1' })
+@Controller({ path: 'project/gsc', version: '1' })
export class GSCController {
constructor(
private readonly gscService: GSCService,
private readonly projectService: ProjectService,
) {}
+ @Post('process-token')
+ async processGSCToken(@Body() body: { code: string; state: string }) {
+ const { code, state } = body
+ if (!code || !state) {
+ throw new BadRequestException('Invalid GSC token parameters')
+ }
+ const { pid } = await this.gscService.handleOAuthCallback(code, state)
+ return { pid }
+ }
+
@ApiBearerAuth()
- @Post(':pid/gsc/connect')
+ @Post(':pid/connect')
@Auth()
async connect(@Param('pid') pid: string, @CurrentUserId() uid: string) {
// ensure user can manage project
@@ -38,22 +46,8 @@ export class GSCController {
return this.gscService.generateConnectURL(uid, pid)
}
- // OAuth2 callback endpoint
- @Get('gsc/callback')
- async oauthCallback(
- @Query('code') code: string,
- @Query('state') state: string,
- @Response() res: any,
- ) {
- if (!code || !state) {
- throw new BadRequestException('Invalid OAuth callback parameters')
- }
- const { pid } = await this.gscService.handleOAuthCallback(code, state)
- res.redirect(`/project/${pid}/settings?gsc=connected`)
- }
-
@ApiBearerAuth()
- @Get(':pid/gsc/status')
+ @Get(':pid/status')
@Auth()
async status(@Param('pid') pid: string, @CurrentUserId() uid: string) {
const project = await this.projectService.getRedisProject(pid)
@@ -63,7 +57,7 @@ export class GSCController {
}
@ApiBearerAuth()
- @Get(':pid/gsc/properties')
+ @Get(':pid/properties')
@Auth()
async properties(@Param('pid') pid: string, @CurrentUserId() uid: string) {
const project = await this.projectService.getRedisProject(pid)
@@ -72,7 +66,7 @@ export class GSCController {
}
@ApiBearerAuth()
- @Post(':pid/gsc/property')
+ @Post(':pid/property')
@Auth()
async setProperty(
@Param('pid') pid: string,
@@ -86,7 +80,7 @@ export class GSCController {
}
@ApiBearerAuth()
- @Delete(':pid/gsc')
+ @Delete(':pid/disconnect')
@Auth()
@HttpCode(204)
async disconnect(@Param('pid') pid: string, @CurrentUserId() uid: string) {
diff --git a/backend/apps/cloud/src/project/gsc.service.ts b/backend/apps/cloud/src/project/gsc.service.ts
index 774844a94..c4a566997 100644
--- a/backend/apps/cloud/src/project/gsc.service.ts
+++ b/backend/apps/cloud/src/project/gsc.service.ts
@@ -9,8 +9,9 @@ import { ConfigService } from '@nestjs/config'
import { google } from 'googleapis'
import CryptoJS from 'crypto-js'
-import { EMAIL_ACTION_ENCRYPTION_KEY, redis } from '../common/constants'
+import { isDevelopment, PRODUCTION_ORIGIN, redis } from '../common/constants'
import { ProjectService } from './project.service'
+import { deriveKey } from '../common/utils'
type StoredTokens = {
access_token?: string
@@ -21,7 +22,12 @@ type StoredTokens = {
}
const REDIS_STATE_PREFIX = 'gsc:state:'
-// tokens are stored in DB; Redis is used only for short-lived OAuth state
+
+const GSC_REDIRECT_URL = isDevelopment
+ ? 'http://localhost:3000/gsc-connected'
+ : `${PRODUCTION_ORIGIN}/gsc-connected`
+
+const ENCRYPTION_KEY = deriveKey('gsc-token')
@Injectable()
export class GSCService {
@@ -30,30 +36,19 @@ export class GSCService {
private readonly projectService: ProjectService,
) {}
- private getRedirectUri(): string {
- const override = this.configService.get<string>(
- 'GOOGLE_OAUTH2_GSC_REDIRECT_URL',
- )
- if (override) return override
-
- const origin =
- this.configService.get<string>('PRODUCTION_ORIGIN') ||
- 'http://localhost:5005'
- // Nest versioned path - /v1/project/gsc/callback
- return `${origin.replace(/\/$/, '')}/v1/project/gsc/callback`
- }
-
private getOAuthClient() {
- const clientId = this.configService.get<string>('GOOGLE_OAUTH2_CLIENT_ID')
+ const clientId = this.configService.get<string>('GOOGLE_GSC_CLIENT_ID')
const clientSecret = this.configService.get<string>(
- 'GOOGLE_OAUTH2_CLIENT_SECRET',
+ 'GOOGLE_GSC_CLIENT_SECRET',
)
if (!clientId || !clientSecret) {
- throw new InternalServerErrorException('Google OAuth2 is not configured')
+ throw new InternalServerErrorException(
+ 'Google GSC Client is not configured',
+ )
}
- return new google.auth.OAuth2(clientId, clientSecret, this.getRedirectUri())
+ return new google.auth.OAuth2(clientId, clientSecret, GSC_REDIRECT_URL)
}
async generateConnectURL(uid: string, pid: string): Promise<{ url: string }> {
@@ -122,7 +117,7 @@ export class GSCService {
const decrypt = (val?: string | null) => {
if (!val) return undefined
try {
- const bytes = CryptoJS.Rabbit.decrypt(val, EMAIL_ACTION_ENCRYPTION_KEY)
+ const bytes = CryptoJS.Rabbit.decrypt(val, ENCRYPTION_KEY)
return bytes.toString(CryptoJS.enc.Utf8) || undefined
} catch {
return undefined
@@ -144,9 +139,7 @@ export class GSCService {
private async setStoredTokens(pid: string, tokens: StoredTokens) {
const encrypt = (val?: string) =>
- val
- ? CryptoJS.Rabbit.encrypt(val, EMAIL_ACTION_ENCRYPTION_KEY).toString()
- : null
+ val ? CryptoJS.Rabbit.encrypt(val, ENCRYPTION_KEY).toString() : null
await this.projectService.update({ id: pid }, {
gscAccessTokenEnc: encrypt(tokens.access_token),
@@ -228,7 +221,9 @@ export class GSCService {
'Search Console is not connected for this project',
)
}
- await this.setStoredTokens(pid, { ...tokens, property_uri: propertyUri })
+ await this.projectService.update({ id: pid }, {
+ gscPropertyUri: propertyUri ?? null,
+ } as any)
}
async getKeywords(
diff --git a/web/app/api/index.ts b/web/app/api/index.ts
index e7b8b5374..1ab6a451f 100644
--- a/web/app/api/index.ts
+++ b/web/app/api/index.ts
@@ -1518,7 +1518,7 @@ export const completeOnboarding = () =>
// Google Search Console integration
export const generateGSCAuthURL = (pid: string) =>
api
- .post(`v1/project/${pid}/gsc/connect`)
+ .post(`v1/project/gsc/${pid}/connect`)
.then((response): { url: string } => response.data)
.catch((error) => {
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
@@ -1526,15 +1526,23 @@ export const generateGSCAuthURL = (pid: string) =>
export const getGSCStatus = (pid: string) =>
api
- .get(`v1/project/${pid}/gsc/status`)
+ .get(`v1/project/gsc/${pid}/status`)
.then((response): { connected: boolean } => response.data)
.catch((error) => {
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
})
+export const processGSCToken = (code: string, state: string) =>
+ api
+ .post(`v1/project/gsc/process-token`, { code, state })
+ .then((response): { pid: string } => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
+ })
+
export const getGSCProperties = (pid: string) =>
api
- .get(`v1/project/${pid}/gsc/properties`)
+ .get(`v1/project/gsc/${pid}/properties`)
.then((response): { siteUrl: string; permissionLevel?: string }[] => response.data)
.catch((error) => {
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
@@ -1542,7 +1550,7 @@ export const getGSCProperties = (pid: string) =>
export const setGSCProperty = (pid: string, propertyUri: string) =>
api
- .post(`v1/project/${pid}/gsc/property`, { propertyUri })
+ .post(`v1/project/gsc/${pid}/property`, { propertyUri })
.then((response) => response.data)
.catch((error) => {
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
@@ -1550,7 +1558,7 @@ export const setGSCProperty = (pid: string, propertyUri: string) =>
export const disconnectGSC = (pid: string) =>
api
- .delete(`v1/project/${pid}/gsc`)
+ .delete(`v1/project/gsc/${pid}/disconnect`)
.then((response) => response.data)
.catch((error) => {
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.ts
index 59d806f3b..7a1b9a004 100644
--- a/web/app/lib/models/Project.ts
+++ b/web/app/lib/models/Project.ts
@@ -149,6 +149,7 @@ export interface Project {
isErrorDataExists: boolean
botsProtectionLevel: 'off' | 'basic'
role?: Role
+ gscPropertyUri?: string | null
}
export interface CaptchaProject extends Project {
diff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsx
index 2819d4e2c..e6c3a73c6 100644
--- a/web/app/pages/Project/Settings/ProjectSettings.tsx
+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx
@@ -288,6 +288,7 @@ const ProjectSettings = () => {
origins: null,
ipBlacklist: null,
botsProtectionLevel: 'basic',
+ gscPropertyUri: null,
})
const [validated, setValidated] = useState(false)
const [errors, setErrors] = useState<{
@@ -329,7 +330,6 @@ const ProjectSettings = () => {
// Google Search Console integration state
const [gscConnected, setGscConnected] = useState<boolean | null>(null)
const [gscProperties, setGscProperties] = useState<{ siteUrl: string; permissionLevel?: string }[]>([])
- const [gscProperty, setGscProperty] = useState<string>('')
// for reset data via filters
const [activeFilter, setActiveFilter] = useState<string[]>([])
@@ -850,18 +850,27 @@ const ProjectSettings = () => {
items={_map(gscProperties, (p) => ({ key: p.siteUrl, label: p.siteUrl }))}
keyExtractor={(item) => item.key}
labelExtractor={(item) => item.label}
- onSelect={(item: { key: string; label: string }) => setGscProperty(item.key)}
- title={gscProperty || t('project.settings.gsc.selectProperty')}
- selectedItem={gscProperty ? { key: gscProperty, label: gscProperty } : undefined}
+ onSelect={(item: { key: string; label: string }) => {
+ setForm((prevForm) => ({
+ ...prevForm,
+ gscPropertyUri: item.key,
+ }))
+ }}
+ title={form.gscPropertyUri || t('project.settings.gsc.selectProperty')}
+ selectedItem={
+ form.gscPropertyUri
+ ? { key: form.gscPropertyUri, label: form.gscPropertyUri }
+ : undefined
+ }
/>
</div>
<Button
type='button'
onClick={async () => {
- if (!gscProperty) return
+ if (!form.gscPropertyUri) return
try {
- await setGSCProperty(id, gscProperty)
- toast.success(t('project.settings.gsc.connected'))
+ await setGSCProperty(id, form.gscPropertyUri)
+ toast.success(t('project.settings.gsc.propertyConnected'))
} catch (reason: any) {
toast.error(
typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'),
@@ -883,7 +892,10 @@ const ProjectSettings = () => {
await disconnectGSC(id)
setGscConnected(false)
setGscProperties([])
- setGscProperty('')
+ setForm((prevForm) => ({
+ ...prevForm,
+ gscPropertyUri: null,
+ }))
toast.success(t('project.settings.gsc.disconnected'))
} catch (reason: any) {
toast.error(
diff --git a/web/app/routes/gsc-connected.tsx b/web/app/routes/gsc-connected.tsx
new file mode 100644
index 000000000..d1f80e67c
--- /dev/null
+++ b/web/app/routes/gsc-connected.tsx
@@ -0,0 +1,109 @@
+import { XCircleIcon } from '@heroicons/react/24/solid'
+import _replace from 'lodash/replace'
+import { useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Link, redirect, useNavigate } from 'react-router'
+import type { SitemapFunction } from 'remix-sitemap'
+
+import { processGSCToken } from '~/api'
+import { isSelfhosted } from '~/lib/constants'
+import Loader from '~/ui/Loader'
+import routes from '~/utils/routes'
+
+export async function loader() {
+ if (isSelfhosted) {
+ return redirect('/login', 302)
+ }
+
+ return null
+}
+
+export const sitemap: SitemapFunction = () => ({
+ exclude: true,
+})
+
+export default function GscConnected() {
+ const { t } = useTranslation('common')
+ const navigate = useNavigate()
+ const [loading, setLoading] = useState(true)
+ const [isError, setIsError] = useState(false)
+
+ useEffect(() => {
+ // For some reason, Google redirects to a hash URL, let's fix it
+ const _location = _replace(window.location.href, `${routes.gsc_connected}#`, `${routes.gsc_connected}?`)
+
+ const { searchParams } = new URL(_location)
+ const state = searchParams.get('state')
+ const code = searchParams.get('code')
+
+ // Prevent duplicate callback processing in React 18 StrictMode (dev) or other double-invocation scenarios
+ const processedKey = state ? `gsc_processed:${state}` : null
+ if (processedKey && sessionStorage.getItem(processedKey) === '1') {
+ setLoading(false)
+ return
+ }
+
+ const processCode = async () => {
+ if (!state || !code) {
+ setIsError(true)
+ return
+ }
+
+ try {
+ const { pid } = await processGSCToken(code, state)
+ navigate({
+ pathname: _replace(routes.project_settings, ':id', pid),
+ search: new URLSearchParams({ tab: 'integrations', gsc: 'connected' }).toString(),
+ })
+ } catch (reason) {
+ setIsError(true)
+ setLoading(false)
+ console.error(`[ERROR] Error while processing GSC integration: ${reason}`)
+ }
+ }
+
+ setLoading(true)
+
+ processCode()
+ }, [navigate])
+
+ if (loading) {
+ return (
+ <div className='min-h-page bg-gray-50 dark:bg-slate-900'>
+ <Loader />
+ </div>
+ )
+ }
+
+ if (isError) {
+ return (
+ <div className='min-h-page bg-gray-50 px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8 dark:bg-slate-900'>
+ <div className='mx-auto max-w-max'>
+ <main className='sm:flex'>
+ <XCircleIcon className='h-12 w-12 text-red-400' aria-hidden='true' />
+ <div className='sm:ml-6'>
+ <div className='max-w-prose sm:border-l sm:border-gray-200 sm:pl-6'>
+ <h1 className='text-4xl font-extrabold text-gray-900 sm:text-5xl dark:text-gray-50'>
+ {t('gsc.failed')}
+ </h1>
+ <p className='mt-1 max-w-prose text-base whitespace-pre-line text-gray-700 dark:text-gray-300'>
+ {t('gsc.failedDesc')}
+ </p>
+ </div>
+ <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>
+ <Link
+ to={routes.contact}
+ className='inline-flex items-center rounded-md border border-transparent bg-indigo-100 px-4 py-2 text-sm font-medium text-indigo-700 hover:bg-indigo-200 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:outline-hidden dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700 dark:focus:ring-gray-50'
+ >
+ {t('notFoundPage.support')}
+ </Link>
+ </div>
+ </div>
+ </main>
+ </div>
+ </div>
+ )
+ }
+
+ return null
+}
diff --git a/web/app/utils/routes.ts b/web/app/utils/routes.ts
index e44ca3b34..0af556433 100644
--- a/web/app/utils/routes.ts
+++ b/web/app/utils/routes.ts
@@ -30,6 +30,7 @@ const routes = Object.freeze({
transfer_confirm: '/project/transfer/confirm',
transfer_reject: '/project/transfer/cancel',
socialised: '/socialised',
+ gsc_connected: '/gsc-connected',
project_protected_password: '/projects/:pid/password',
open: '/open',
ref: '/ref/:id',
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 8b4ba1daf..0aa1fe3f8 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -513,6 +513,10 @@
"unsubscribe": {
"success": "You've unsubscribed from analytics email reports"
},
+ "gsc": {
+ "failed": "Connection failed",
+ "failedDesc": "An error has occurred while connecting to your Google Search Console, please try again or contact support."
+ },
"auth": {
"recovery": {
"title": "Account recovery",
@@ -1134,7 +1138,8 @@
"connected": "The project has been connected to your Google Search Console account.",
"disconnected": "The project has been disconnected from your Google Search Console account.",
"selectProperty": "Select a property",
- "connectDisclamer": "For the integration to work, make sure you have set up your website on the <url>Google Search Console</url> first."
+ "connectDisclamer": "For the integration to work, make sure you have set up your website on the <url>Google Search Console</url> first.",
+ "propertyConnected": "Selected property saved to your project"
},
"tabs": {
"general": "General",