import { useCallback, useEffect, useRef, useState } from 'react'; import { weSAccountAvailable, weSAccountPost, weSErrorMessage, weSSentryPost, } from '../data/ajax'; /** * Whether a `connect/login` or `connect/start` body carries a URL to open * @param body * @param body.url */ function weSHasUrl( body: { url?: unknown } ): boolean { return typeof body.url === 'string' && body.url !== ''; } /** * The ajax client lives in `data/ajax.ts` so every tab shares it (Redmine * #25049); these two are re-exported for the callers that imported them from * here. */ export { weSAccountAvailable, weSErrorMessage }; /** * The connect button's states. * * `loading` is the mount-time status request; `pending` is a connect tab open * somewhere in the browser. Both are disabled states. * * `activate` is sentry's own addition, with no counterpart in we-graph: the * site holds an account token but `products` does not include `sentry` — the * account was connected by another product, or sentry was deprovisioned by its * deactivation hook while the token survived. No consent round trip is needed * to leave it, only the plugin's own `sentrysetup` route. */ export type WeSConnectState = | 'loading' | 'idle' | 'pending' | 'activate' | 'connected'; /** The product name this plugin connects as — `Account::activeProducts()`'s */ const WE_CONNECT_PRODUCT = 'sentry'; /** The channel the callback page announces itself on, shared with `Account::renderConnectOutcome()` */ const WE_CONNECT_CHANNEL = 'we360cloud-connect'; /** `connect/status` is answered from options and a transient, so polling it is cheap */ const WE_CONNECT_POLL_MS = 2500; /** How long a connect may stay pending before the button is handed back */ const WE_CONNECT_TIMEOUT_MS = 10 * 60 * 1000; /** * How long after the tab is seen closed to keep polling. * * The callback page closes itself *immediately* after signalling, and on a slow * machine the option write can still be in flight, so a closed tab is not * evidence the user cancelled until one more poll has come back empty. */ const WE_CONNECT_CLOSED_GRACE_MS = 5000; /** `route=connect/start` — the consent URL to open, and the state it is bound to */ type WeSConnectStartResponse = { success: true; url: string; state: string; expires_in: number; }; /** `route=connect/status` — everything the button needs, from options only */ type WeSConnectStatusResponse = { success: true; connected: boolean; pending: boolean; products: string[]; dash_url: string; email: string; }; /** * `route=user/login` — where the "My account" and "Manage in cloud" clicks * go. * * `url` is a single-use cloud handoff URL when `handoff` is true, and the plain * dashboard URL when anything prevented one (no token yet, an older cloud, an * outage) — either way it is simply opened. * * An optional `target` field says which cloud page the handoff should land on. * The account layer forwards it as sent; the cloud owns the list of targets it * knows and lands an unrecognised one on the dashboard rather than failing. */ type WeSConnectLoginResponse = { success: true; url: string; handoff: boolean; }; /** * `route=user/status` — the current WordPress user's own cloud sign-in * (Redmine #26390). `not_member` is set when the account they signed in with * is not in the site's team. */ type WeSUserStatusResponse = { success: true; signed_in: boolean; not_member: { email: string; ownerName: string } | null; }; /** What the callback page broadcasts just before it closes itself */ type WeSConnectSignal = { type: 'we360cloud-connect'; status: 'connected' | 'signed-in' | 'not-member' | 'cancelled' | 'error'; }; /** * What to tell a user whose cloud account is not in the site's team * @param notMember * @param notMember.email * @param notMember.ownerName */ function weSNotMemberMessage( notMember: { email: string; ownerName: string; } ): string { const who = notMember.ownerName ? `the site's administrator (${ notMember.ownerName })` : "the site's administrator"; return `Your Web-Engine cloud account ${ notMember.email } is not in the team for this site. Ask ${ who } to add ${ notMember.email } to their team, then sign in again.`; } /** * Whether a value is the callback page's completion signal * @param data */ function weSIsConnectSignal( data: unknown ): data is WeSConnectSignal { return ( !! data && typeof data === 'object' && ( data as { type?: unknown } ).type === 'we360cloud-connect' ); } /** * The connect button's state machine. * * Connecting the site to the Web-Engine cloud happens in a browser tab of its * own — the cloud's consent page, then an `admin-post.php` callback that * exchanges the code and closes itself. Nothing about that round trip comes * back through this page's JavaScript, so the completion signal * (`BroadcastChannel` plus a same-origin `postMessage`) is only ever a *hint* * that it is worth asking again: **`connect/status` is the source of truth**, * and a signal that says `connected` is confirmed by a status request before * the button moves. The poll is what makes the flow survive a signal that never * arrives (a tab restored into another process, a browser without * `BroadcastChannel`, a user who completes the flow and never returns). * * @param onError - shown to the user; called with an already-readable message * @param accountTarget - the cloud page "My account" lands on; omitted leaves * it to the cloud, which means the dashboard */ export function useWe360Connect( onError?: ( message: string ) => void, accountTarget?: string ): { state: WeSConnectState; email: string; products: string[]; onClick: () => void; openCloud: ( target?: string ) => void; onActivate: () => void; refresh: () => void; } { const [ state, setState ] = useState< WeSConnectState >( 'loading' ); /** The registered account email, from the last status response; '' until known */ const [ email, setEmail ] = useState< string >( '' ); /** Every product active on this domain — the disconnect warning names the others */ const [ products, setProducts ] = useState< string[] >( [] ); /** The dashboard link, from the last status response `connected` was read from */ const dashUrl = useRef< string >( '' ); /** The tab `connect/start` was opened into; null when the browser blocked it */ const connectWindow = useRef< Window | null >( null ); /** * Held in a ref so the watcher effect does not re-run — and tear down a * live poll — every time the parent re-renders with a new callback identity. */ const errorSink = useRef< ( ( message: string ) => void ) | undefined >( onError ); useEffect( () => { errorSink.current = onError; } ); const report = useCallback( ( reason: unknown ) => { if ( errorSink.current ) { errorSink.current( weSErrorMessage( reason ) ); } }, [] ); /** * Read the server's view of the connection and settle the state on it. * * The one place `connected`, `activate` and `idle` are ever decided. */ const readStatus = useCallback( (): Promise< WeSConnectStatusResponse > => weSAccountPost< WeSConnectStatusResponse >( 'connect/status', {}, ( status ) => typeof status.connected === 'boolean' && Array.isArray( status.products ) ).then( ( status ) => { dashUrl.current = status.dash_url; setProducts( status.products ); if ( status.connected ) { // Only a connected status carries the REGISTERED address // — otherwise `email` is just the WP user's, which would // wrongly claim a registration. setEmail( status.email ); } else { setEmail( '' ); } return status; } ), [] ); /** * Which state a status response means, once no connect is in flight. * * @param status - a `connect/status` response */ const settle = useCallback( ( status: WeSConnectStatusResponse ) => { if ( status.connected ) { setState( status.products.includes( WE_CONNECT_PRODUCT ) ? 'connected' : 'activate' ); return; } setState( 'idle' ); }, [] ); /** Re-read the server's view — after a disconnect, or on demand */ const refresh = useCallback( () => { if ( ! weSAccountAvailable ) { return; } setState( 'loading' ); readStatus().then( settle, () => setState( 'idle' ) ); }, [ readStatus, settle ] ); /** * The mount-time status request. * * A failure here is *not* surfaced: the account layer being unreachable * must not put an error banner over the settings the user came for. The * button falls back to "Connect", and the failure surfaces on the click. */ useEffect( () => { if ( ! weSAccountAvailable ) { return; } let mounted = true; readStatus().then( ( status ) => { if ( ! mounted ) { return; } // A pending transient means a connect tab may still be open // somewhere (this page was reloaded mid-flow). Resume into // 'pending' so its completion is still picked up — there is no // window handle, but the poll and the 10-minute timeout carry // the flow exactly as they would for a blocked signal. if ( ! status.connected && status.pending ) { setState( 'pending' ); return; } settle( status ); }, () => { if ( ! mounted ) { return; } setState( 'idle' ); } ); return () => { mounted = false; }; }, [ readStatus, settle ] ); /** * The watchers, for as long as a connect is pending. * * `done` guards the resolution rather than the state, because several of * these can fire in the same tick — the broadcast, the `message` and the * poll all describe the same event — and only the first should count. */ useEffect( () => { if ( state !== 'pending' ) { return; } let done = false; /** When the tab was first seen closed; 0 while it is still open */ let closedSince = 0; const finish = ( next: WeSConnectState, message?: string ) => { if ( done ) { return; } done = true; if ( message ) { report( message ); } setState( next ); }; /** * Ask the server. This is both the poll and the confirmation a signal * gets. */ const check = () => { readStatus().then( ( status ) => { if ( done ) { return; } if ( status.connected ) { finish( status.products.includes( WE_CONNECT_PRODUCT ) ? 'connected' : 'activate' ); return; } // The tab is gone and the server still has nothing. Give the // callback's own write time to land, then hand the button back. const win = connectWindow.current; if ( win && win.closed ) { if ( closedSince === 0 ) { closedSince = Date.now(); } else if ( Date.now() - closedSince >= WE_CONNECT_CLOSED_GRACE_MS ) { finish( 'idle' ); } } else { closedSince = 0; } }, () => { // A single failed poll says nothing — the next one is 2.5s away. } ); }; const onSignal = ( signal: WeSConnectSignal ) => { if ( done ) { return; } if ( signal.status === 'cancelled' ) { finish( 'idle' ); return; } if ( signal.status === 'error' ) { finish( 'idle', 'The connection could not be completed. Please try again.' ); return; } // 'connected' — a hint, not the answer. Confirm with the server. check(); }; const onMessage = ( event: MessageEvent ) => { if ( event.origin !== window.location.origin ) { return; } if ( ! weSIsConnectSignal( event.data ) ) { return; } onSignal( event.data ); }; // Not universal (and absent in some embedded webviews), hence the guard // — the poll alone completes the flow where it is missing. let channel: BroadcastChannel | null = null; try { channel = new BroadcastChannel( WE_CONNECT_CHANNEL ); channel.onmessage = ( event: MessageEvent ) => { if ( weSIsConnectSignal( event.data ) ) { onSignal( event.data ); } }; } catch { channel = null; } window.addEventListener( 'message', onMessage ); const pollId = window.setInterval( check, WE_CONNECT_POLL_MS ); const timeoutId = window.setTimeout( () => finish( 'idle' ), WE_CONNECT_TIMEOUT_MS ); return () => { done = true; window.clearInterval( pollId ); window.clearTimeout( timeoutId ); window.removeEventListener( 'message', onMessage ); if ( channel ) { channel.onmessage = null; channel.close(); } }; }, [ readStatus, report, state ] ); /** * A sign-in from "My account" whose account is not in the site's team. * * The callback page closes itself, so its sentence would be lost; the * signal is the cue to read `user/status` and say it here. Listens for as * long as the page is open, since the sign-in tab can be finished at any * time and is not a pending state of the button. */ useEffect( () => { if ( ! weSAccountAvailable ) { return; } const onSignal = ( signal: WeSConnectSignal ) => { if ( signal.status !== 'not-member' ) { return; } weSAccountPost< WeSUserStatusResponse >( 'user/status' ).then( ( status ) => { if ( status.not_member ) { report( weSNotMemberMessage( status.not_member ) ); } }, report ); }; const onMessage = ( event: MessageEvent ) => { if ( event.origin === window.location.origin && weSIsConnectSignal( event.data ) ) { onSignal( event.data ); } }; let channel: BroadcastChannel | null = null; try { channel = new BroadcastChannel( WE_CONNECT_CHANNEL ); channel.onmessage = ( event: MessageEvent ) => { if ( weSIsConnectSignal( event.data ) ) { onSignal( event.data ); } }; } catch { channel = null; } window.addEventListener( 'message', onMessage ); return () => { window.removeEventListener( 'message', onMessage ); if ( channel ) { channel.onmessage = null; channel.close(); } }; }, [ report ] ); /** * Enable sentry on an already-connected site. * * No consent tab: the site already holds an account token, so this is only * sentry's own `sentrysetup` route (`Captcha::provision()`) followed by a * re-read of the status that decides whether it worked. */ const onActivate = useCallback( () => { if ( state !== 'activate' ) { return; } setState( 'loading' ); weSSentryPost< { success: boolean } >( 'sentrysetup' ).then( () => readStatus().then( settle, () => setState( 'activate' ) ), ( reason ) => { report( reason ); // A rejected account token is cleared server-side by the // failed setup call, so re-read rather than offer the same // button again: it settles on Connect when the token has gone // (Redmine #25466). readStatus().then( settle, () => setState( 'activate' ) ); } ); }, [ readStatus, report, settle, state ] ); /** * Open the cloud in a tab of its own, on a single-use handoff where one * can be minted and the plain dashboard URL where it cannot. * * Shared by "My account" and "Manage in cloud"; the two differ only in the * `target` they ask the cloud to land on. Must be called straight from a * click handler, for the reason given inside. * * The handoff is the clicking user's own (Redmine #26390): a user signed * in to the cloud lands in their account through `user/login`, and one who * is not is sent through the cloud's sign-in instead (`user/start`), never * into the account of whoever connected the site. The click after a * sign-in opens the account. * * @param target - the cloud page to land on; omitted leaves it to the cloud */ const openCloud = useCallback( ( target?: string ) => { // The tab is opened SYNCHRONOUSLY, inside the click's user // activation — Safari refuses a window.open that arrives after an // await. The handoff URL then steers it once the server answers. // Minted fresh on every click, never cached: handoffs are // single-use. const win = window.open( '', '_blank' ); weSAccountPost< WeSUserStatusResponse >( 'user/status', {}, ( status ) => typeof status.signed_in === 'boolean' ) .then( ( status ): Promise< { url: string } > => status.signed_in ? weSAccountPost< WeSConnectLoginResponse >( 'user/login', undefined === target ? {} : { target }, weSHasUrl ) : weSAccountPost< WeSConnectStartResponse >( 'user/start', { product: WE_CONNECT_PRODUCT }, weSHasUrl ) ) .then( ( result ) => { if ( win ) { win.location.href = result.url; } else { // The synchronous open was blocked; this may be too, // but it is the only move left. window.open( result.url, '_blank' ); } }, ( reason ) => { // Never strand an about:blank tab — the dashboard link is // the answer the pre-handoff button would have given. if ( win && dashUrl.current ) { win.location.href = dashUrl.current; } else if ( win ) { win.close(); report( reason ); } else { report( reason ); } } ); }, [ report ] ); const onClick = useCallback( () => { if ( ! weSAccountAvailable ) { return; } if ( state === 'connected' || state === 'activate' ) { openCloud( accountTarget ); return; } // 'idle' starts the flow; 'pending' RESTARTS it — the escape hatch for a // lost tab (closed unnoticed, page reloaded, or a stale transient from an // earlier attempt). connect/start overwrites the pending state server-side, // so the old tab's copy is invalidated by design. Only 'loading' declines. if ( state !== 'idle' && state !== 'pending' ) { return; } weSAccountPost< WeSConnectStartResponse >( 'connect/start', { product: WE_CONNECT_PRODUCT }, weSHasUrl ).then( ( start ) => { // A tab, not a popup: no features string, because how the cloud's // consent page is presented is the user's decision, not ours. connectWindow.current = window.open( start.url, '_blank' ); setState( 'pending' ); }, ( reason ) => { report( reason ); } ); }, [ accountTarget, openCloud, report, state ] ); return { state, email, products, onClick, openCloud, onActivate, refresh }; }