Skip to content

Commit d56a33d

Browse files
chrisbliss18Chris Jean
andauthored
SEO: Support host-provided Google verification (#54920)
Co-authored-by: Chris Jean <chris.jean@automattic.com>
1 parent a6d2f9a commit d56a33d

8 files changed

Lines changed: 118 additions & 54 deletions

File tree

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,19 @@
1-
// Google site-verification state.
2-
//
3-
// The bootstrap (keyring connect URL + whether the current user is connected) is
4-
// injected onto `window.JetpackScriptData.seo.google_verify` by
5-
// `Dashboard_Data::get_google_verify_data()`. The live verified status is fetched
6-
// client-side from `/jetpack/v4/verify-site/google` (a wpcom round-trip).
7-
81
export interface GoogleVerifyBootstrap {
92
/** WordPress.com keyring OAuth URL that opens the auto-verify popup. */
103
connect_url: string;
11-
/** Whether the current user is connected to WordPress.com (keyring available). */
4+
/** Whether the current user has a Jetpack user connection. */
125
is_connected: boolean;
6+
/** Whether the host supplies an automatic verification transport. */
7+
can_auto_verify?: boolean;
8+
/** Host-local REST path; older hosts use the existing Jetpack route. */
9+
api_path?: string;
1310
}
1411

15-
/** Shape returned by GET/POST `/jetpack/v4/verify-site/google`. */
12+
/** Shared response from the host's Google verification endpoints. */
1613
export interface GoogleVerifyStatus {
1714
verified: boolean;
1815
is_owner: boolean;
19-
google_search_console_url: string;
20-
/**
21-
* The verification token Google expects to find on the site. It must be saved to
22-
* `verification_services_codes.google` (so the `google-site-verification` meta tag
23-
* is emitted) BEFORE asking Google to verify, or verification fails with
24-
* "the necessary verification token could not be found on your site".
25-
*/
16+
google_search_console_url?: string;
17+
/** Save this to verification_services_codes.google before requesting verification. */
2618
token?: string;
2719
}

‎projects/packages/seo/_inc/data/test/use-google-verify.test.ts‎

Lines changed: 71 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,21 @@
11
import { jest } from '@jest/globals';
22
import { act, renderHook, waitFor } from '@testing-library/react';
3+
import type { GoogleVerifyBootstrap } from '../google-verify-types';
34

45
type Request = { path: string; method?: string };
56

67
const mockApiFetch = jest.fn< ( options: Request ) => Promise< unknown > >();
78
const saveCode = jest.fn< ( code: string ) => Promise< void > >();
9+
const popup =
10+
jest.fn< ( url: string, callback: ( result: { keyring_id?: number } ) => void ) => void >();
811

912
jest.unstable_mockModule( '@wordpress/api-fetch', () => ( { default: mockApiFetch } ) );
1013
jest.unstable_mockModule( '@automattic/request-external-access', () => ( {
11-
default: ( _url: string, callback: ( result: { keyring_id: number } ) => void ) =>
12-
callback( { keyring_id: 7 } ),
14+
default: popup,
1315
} ) );
16+
let bootstrap: GoogleVerifyBootstrap;
1417
jest.unstable_mockModule( '@automattic/jetpack-script-data', () => ( {
15-
getScriptData: () => ( {
16-
seo: { google_verify: { connect_url: 'https://example.com/connect', is_connected: true } },
17-
} ),
18+
getScriptData: () => ( { seo: { google_verify: bootstrap } } ),
1819
} ) );
1920
jest.unstable_mockModule( '@wordpress/notices', () => ( { store: 'core/notices' } ) );
2021
const createErrorNotice = jest.fn();
@@ -68,6 +69,8 @@ async function mountHook() {
6869
describe( 'useGoogleVerify', () => {
6970
beforeEach( () => {
7071
jest.clearAllMocks();
72+
bootstrap = { connect_url: 'https://example.com/connect', is_connected: true };
73+
popup.mockImplementation( ( _url, callback ) => callback( { keyring_id: 7 } ) );
7174
saveCode.mockResolvedValue( undefined );
7275
} );
7376

@@ -119,4 +122,67 @@ describe( 'useGoogleVerify', () => {
119122
expect( mockApiFetch ).not.toHaveBeenCalledWith( VERIFY_POST );
120123
expect( createErrorNotice ).toHaveBeenCalledWith( 'Nope.', expect.anything() );
121124
} );
125+
it( 'uses a native host transport without a Jetpack user connection', async () => {
126+
bootstrap = {
127+
connect_url: 'https://example.com/native-connect',
128+
is_connected: false,
129+
can_auto_verify: true,
130+
api_path: '/wpcom/v2/seo/google-verify',
131+
};
132+
respond();
133+
const { result } = await mountHook();
134+
expect( result.current.canAutoVerify ).toBe( true );
135+
act( () => result.current.autoVerify() );
136+
await waitFor( () => expect( result.current.isVerifying ).toBe( false ) );
137+
expect(
138+
mockApiFetch.mock.calls.map( ( [ request ] ) => [ request.path, request.method ?? 'GET' ] )
139+
).toEqual( [
140+
[ '/wpcom/v2/seo/google-verify', 'GET' ],
141+
[ '/wpcom/v2/seo/google-verify/7', 'GET' ],
142+
[ '/wpcom/v2/seo/google-verify', 'POST' ],
143+
[ '/wpcom/v2/seo/google-verify/7', 'GET' ],
144+
] );
145+
expect( saveCode ).toHaveBeenCalledWith( 'tok' );
146+
expect( popup ).toHaveBeenCalledWith( bootstrap.connect_url, expect.any( Function ) );
147+
} );
148+
149+
it.each( [
150+
[ 'disconnected user', { is_connected: false } ],
151+
[ 'missing popup URL', { connect_url: '' } ],
152+
[ 'host disables automatic verification', { can_auto_verify: false } ],
153+
] )( 'keeps manual entry for %s', async ( _label, overrides ) => {
154+
bootstrap = { ...bootstrap, ...overrides };
155+
const { result } = await mountHook();
156+
expect( result.current.canAutoVerify ).toBe( false );
157+
expect( result.current.state ).toBe( 'unavailable' );
158+
act( () => result.current.autoVerify() );
159+
expect( mockApiFetch ).not.toHaveBeenCalled();
160+
} );
161+
162+
it.each( [ 'forbidden', 'rest_forbidden', 'rest_no_route' ] )(
163+
'keeps manual entry after %s',
164+
async code => {
165+
mockApiFetch.mockRejectedValue( { code } );
166+
const { result } = await mountHook();
167+
expect( result.current.state ).toBe( 'unavailable' );
168+
act( () => result.current.autoVerify() );
169+
expect( mockApiFetch ).toHaveBeenCalledTimes( 1 );
170+
expect( saveCode ).not.toHaveBeenCalled();
171+
expect( popup ).not.toHaveBeenCalled();
172+
}
173+
);
174+
175+
it( 'allows another attempt after the connection popup is canceled', async () => {
176+
popup.mockImplementation( ( _url, callback ) => callback( {} ) );
177+
respond();
178+
const { result } = await mountHook();
179+
act( () => result.current.autoVerify() );
180+
expect( result.current.isVerifying ).toBe( false );
181+
expect( result.current.isConfirming ).toBe( false );
182+
expect( saveCode ).not.toHaveBeenCalled();
183+
popup.mockImplementation( ( _url, callback ) => callback( { keyring_id: 7 } ) );
184+
act( () => result.current.autoVerify() );
185+
await waitFor( () => expect( result.current.isVerifying ).toBe( false ) );
186+
expect( saveCode ).toHaveBeenCalledWith( 'tok' );
187+
} );
122188
} );

‎projects/packages/seo/_inc/data/use-google-verify.ts‎

Lines changed: 25 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ export type GoogleVerifyState = 'loading' | 'verified' | 'unverified' | 'unavail
3737

3838
export interface GoogleVerify {
3939
state: GoogleVerifyState;
40-
isConnected: boolean;
40+
canAutoVerify: boolean;
4141
isOwner: boolean;
4242
searchConsoleUrl: string;
4343
isVerifying: boolean;
@@ -48,15 +48,10 @@ export interface GoogleVerify {
4848
}
4949

5050
/**
51-
* Owns the Google auto-verify flow. On a connected site it fetches the live verified
52-
* status on mount, and `autoVerify()` opens the keyring OAuth popup and POSTs the
53-
* returned keyring id to verify the site — both via the existing
54-
* `/jetpack/v4/verify-site/google` endpoint. On a disconnected site there's no keyring,
55-
* so it reports `unavailable` and the UI falls back to manual code entry.
51+
* Verify through the host's transport, retaining manual entry when unavailable.
5652
*
5753
* @param options - Hook options.
58-
* @param options.saveCode - Saves the verification code through the settings form,
59-
* which records it and keeps the form in sync.
54+
* @param options.saveCode - Persist the token before asking Google to verify.
6055
* @return The Google-verification controller.
6156
*/
6257
export function useGoogleVerify( {
@@ -65,11 +60,13 @@ export function useGoogleVerify( {
6560
saveCode: ( code: string ) => Promise< void >;
6661
} ): GoogleVerify {
6762
const bootstrap = useMemo( () => getGoogleVerifyBootstrap(), [] );
68-
const isConnected = bootstrap?.is_connected ?? false;
6963
const connectUrl = bootstrap?.connect_url ?? '';
64+
const endpoint = bootstrap?.api_path ?? ENDPOINT;
65+
const canAutoVerify =
66+
( bootstrap?.can_auto_verify ?? bootstrap?.is_connected ?? false ) && !! connectUrl;
7067

7168
const [ state, setState ] = useState< GoogleVerifyState >(
72-
isConnected ? 'loading' : 'unavailable'
69+
canAutoVerify ? 'loading' : 'unavailable'
7370
);
7471
const [ isOwner, setIsOwner ] = useState( false );
7572
const [ searchConsoleUrl, setSearchConsoleUrl ] = useState( '' );
@@ -83,13 +80,13 @@ export function useGoogleVerify( {
8380
setSearchConsoleUrl( status.google_search_console_url ?? '' );
8481
}, [] );
8582

86-
// Fetch the live verified status once, on a connected site.
83+
// Read status only when the host supplies a usable verification flow.
8784
useEffect( () => {
88-
if ( ! isConnected ) {
85+
if ( ! canAutoVerify ) {
8986
return undefined;
9087
}
9188
let cancelled = false;
92-
apiFetch< GoogleVerifyStatus >( { path: ENDPOINT } )
89+
apiFetch< GoogleVerifyStatus >( { path: endpoint } )
9390
.then( status => {
9491
if ( ! cancelled ) {
9592
applyStatus( status );
@@ -99,19 +96,21 @@ export function useGoogleVerify( {
9996
if ( cancelled ) {
10097
return;
10198
}
102-
// A `forbidden` status (e.g. the site is under construction) means
103-
// auto-verify is blocked, so fall back to manual entry only. Any other
104-
// failure leaves the verify button and manual fallback available.
99+
// A missing route during deployment or forbidden access keeps manual entry available.
105100
const code = ( error as { code?: string } )?.code;
106-
setState( code === 'forbidden' ? 'unavailable' : 'unverified' );
101+
setState(
102+
[ 'forbidden', 'rest_forbidden', 'rest_no_route' ].includes( code ?? '' )
103+
? 'unavailable'
104+
: 'unverified'
105+
);
107106
} );
108107
return () => {
109108
cancelled = true;
110109
};
111-
}, [ isConnected, applyStatus ] );
110+
}, [ canAutoVerify, endpoint, applyStatus ] );
112111

113112
const autoVerify = useCallback( () => {
114-
if ( ! connectUrl || isVerifying ) {
113+
if ( ! canAutoVerify || state === 'unavailable' || isVerifying ) {
115114
return;
116115
}
117116
// Mark the flow in progress *before* opening the popup. The Verify button is
@@ -141,7 +140,7 @@ export function useGoogleVerify( {
141140
// `google-site-verification` meta tag, (3) ask Google to verify (it fetches the
142141
// tag), (4) re-read the authoritative status. Skipping step 2 fails with
143142
// "the necessary verification token could not be found on your site".
144-
apiFetch< GoogleVerifyStatus >( { path: `${ ENDPOINT }/${ keyringId }` } )
143+
apiFetch< GoogleVerifyStatus >( { path: `${ endpoint }/${ keyringId }` } )
145144
.then( status => {
146145
if ( status.verified ) {
147146
// Already verified: report it and skip the save/verify round-trips.
@@ -166,12 +165,12 @@ export function useGoogleVerify( {
166165
} )
167166
.then( () =>
168167
apiFetch( {
169-
path: ENDPOINT,
168+
path: endpoint,
170169
method: 'POST',
171170
data: { keyring_id: keyringId },
172171
} )
173172
)
174-
.then( () => apiFetch< GoogleVerifyStatus >( { path: `${ ENDPOINT }/${ keyringId }` } ) )
173+
.then( () => apiFetch< GoogleVerifyStatus >( { path: `${ endpoint }/${ keyringId }` } ) )
175174
.then( status => {
176175
applyStatus( status );
177176
if ( status.verified ) {
@@ -209,6 +208,9 @@ export function useGoogleVerify( {
209208
} );
210209
}, [
211210
connectUrl,
211+
endpoint,
212+
canAutoVerify,
213+
state,
212214
isVerifying,
213215
applyStatus,
214216
saveCode,
@@ -219,7 +221,7 @@ export function useGoogleVerify( {
219221

220222
return {
221223
state,
222-
isConnected,
224+
canAutoVerify,
223225
isOwner,
224226
searchConsoleUrl,
225227
isVerifying,

‎projects/packages/seo/_inc/screens/settings/google-verification-field.tsx‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,7 @@ const manualHelp = __(
3131
);
3232

3333
/**
34-
* Google verification: a WordPress.com keyring auto-verify flow on connected sites,
35-
* with manual meta-tag entry as a fallback (and the only option when disconnected).
36-
* The other services stay simple code fields in the parent card.
34+
* Offer the host's Google verification flow with manual code entry as a fallback.
3735
*
3836
* @param props - Component props.
3937
* @param props.value - The manual Google verification code.
@@ -50,7 +48,7 @@ const GoogleVerificationField: FC< Props > = ( {
5048
onCommit,
5149
disabled,
5250
} ) => {
53-
const { state, isConnected, isOwner, searchConsoleUrl, isVerifying, isConfirming, autoVerify } =
51+
const { state, canAutoVerify, isOwner, searchConsoleUrl, isVerifying, isConfirming, autoVerify } =
5452
useGoogleVerify( { saveCode } );
5553
const [ manualOpen, setManualOpen ] = useState( false );
5654
const manualVisible = manualOpen || !! value;
@@ -78,10 +76,8 @@ const GoogleVerificationField: FC< Props > = ( {
7876
/>
7977
);
8078

81-
// Manual entry only when there is no keyring auto-verify path: a disconnected
82-
// self-hosted site (no popup), or a site where the status check came back
83-
// `unavailable` (e.g. a `forbidden` response on an under-construction site).
84-
if ( ! isConnected || state === 'unavailable' ) {
79+
// Keep manual entry available when the host lacks or forbids automatic verification.
80+
if ( ! canAutoVerify || state === 'unavailable' ) {
8581
return (
8682
<TextControl
8783
label={ __( 'Google', 'jetpack-seo' ) }

‎projects/packages/seo/_inc/screens/settings/test/google-verification-field.test.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ const { default: GoogleVerificationField } = await import( '../google-verificati
1212

1313
const googleVerifyDefaults = {
1414
state: 'unverified',
15-
isConnected: true,
15+
canAutoVerify: true,
1616
isOwner: false,
1717
searchConsoleUrl: '',
1818
isVerifying: false,

‎projects/packages/seo/_inc/screens/settings/test/verification-card.test.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ describe( 'VerificationCard', () => {
1616
beforeEach( () => {
1717
mockUseGoogleVerify.mockReturnValue( {
1818
state: 'unverified',
19-
isConnected: true,
19+
canAutoVerify: true,
2020
isOwner: false,
2121
searchConsoleUrl: '',
2222
isVerifying: false,
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Significance: patch
2+
Type: fixed
3+
4+
Support automatic Google verification through the hosting platform when available.
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Significance: patch
2+
Type: bugfix
3+
4+
SEO: Support automatic Google verification through the hosting platform when available.

0 commit comments

Comments
 (0)