Line data Source code
1 : /**
2 : * Tells, from facts rather than a timer, whether a popup sign-in was
3 : * abandoned. Firebase itself cannot: after the window closes it waits a
4 : * hardcoded 8s (on a 2s poll) before rejecting with `popup-closed-by-user`,
5 : * because a closed window alone does not say whether the sign-in result had
6 : * already been handed over.
7 : *
8 : * The result is handed over through the resolver's event manager, and
9 : * Firebase's hosted handler page waits for the page to acknowledge it before
10 : * closing the popup. So "window closed and no result for this operation" means
11 : * the visitor gave up, and "result received" means the sign-in is completing,
12 : * however long the token exchange then takes.
13 : *
14 : * This subclasses the SDK's public `browserPopupRedirectResolver` and reads two
15 : * of its internals: the event manager `_initialize` resolves to, and the
16 : * provider, event id and window `_openPopup` works with
17 : * (popupWatchSdkContract.test.ts pins them). When they are not what this
18 : * expects, nothing is watched and sign-in keeps Firebase's own timing.
19 : */
20 : import type { PopupRedirectResolver } from 'firebase/auth'
21 : import { browserPopupRedirectResolver } from 'firebase/auth'
22 :
23 : export interface PopupWatchCallbacks {
24 : /** The popup closed before any sign-in result reached the page: the visitor gave up. */
25 : readonly onAbandoned?: () => void
26 : /** A result arrived after `onAbandoned` and was kept: the sign-in completes after all. */
27 : readonly onResumed?: () => void
28 : /**
29 : * Asked when a result arrives after `onAbandoned`. True discards it before
30 : * Firebase exchanges it, so no account is signed in or created.
31 : */
32 : readonly discardLateResult?: () => boolean
33 : }
34 :
35 : /** Frequent enough to feel immediate; one `closed` read per tick. */
36 2356 : const CLOSED_POLL_MS = 100
37 :
38 : interface AuthEventLike {
39 : readonly type?: unknown
40 : readonly eventId?: unknown
41 : readonly error?: unknown
42 : }
43 :
44 : interface AuthEventManagerLike {
45 : onEvent: (event: AuthEventLike) => boolean
46 : }
47 :
48 : interface ResolverInternals {
49 : _initialize(auth: unknown): Promise<unknown>
50 : _openPopup(
51 : auth: unknown,
52 : provider: unknown,
53 : authType: unknown,
54 : eventId?: string
55 : ): Promise<unknown>
56 : }
57 :
58 : type ResolverClass = new () => ResolverInternals
59 :
60 : interface WatchedAttempt {
61 : readonly callbacks: PopupWatchCallbacks
62 : abandoned: boolean
63 : eventId?: string
64 : poll?: ReturnType<typeof setInterval>
65 : }
66 :
67 : // Keyed by the provider object each sign-in hands to `signInWithPopup`, which
68 : // Firebase passes on to `_openPopup`, so a popup Firebase still opens for an
69 : // operation it already cancelled is never taken for a newer one.
70 2356 : const attemptsByProvider = new WeakMap<object, WatchedAttempt>()
71 2356 : const attemptsByEventId = new Map<string, WatchedAttempt>()
72 2356 : const wrappedManagers = new WeakSet<object>()
73 : // Only an Auth whose event manager is wrapped has results this can see.
74 2356 : const observedAuths = new WeakSet<object>()
75 :
76 0 : function isObject(value: unknown): value is object {
77 0 : return typeof value === 'object' && value !== null
78 : }
79 :
80 2356 : function isResolverClass(value: unknown): value is ResolverClass {
81 2356 : if (typeof value !== 'function') return false
82 2356 : const prototype: unknown = value.prototype
83 2356 : return (
84 : typeof prototype === 'object' &&
85 : prototype !== null &&
86 : '_initialize' in prototype &&
87 : '_openPopup' in prototype
88 : )
89 : }
90 :
91 0 : function isEventManager(value: unknown): value is AuthEventManagerLike {
92 0 : return (
93 : typeof value === 'object' &&
94 : value !== null &&
95 : 'onEvent' in value &&
96 : typeof value.onEvent === 'function'
97 : )
98 : }
99 :
100 : interface PopupWindowLike {
101 : readonly closed: unknown
102 : }
103 :
104 0 : function popupWindowOf(popup: unknown): PopupWindowLike | undefined {
105 0 : if (typeof popup !== 'object' || popup === null || !('window' in popup))
106 0 : return undefined
107 0 : const { window } = popup
108 0 : return typeof window === 'object' && window !== null && 'closed' in window
109 : ? window
110 : : undefined
111 : }
112 :
113 0 : function stopPolling(attempt: WatchedAttempt): void {
114 0 : clearInterval(attempt.poll)
115 0 : attempt.poll = undefined
116 : }
117 :
118 0 : function deliver(
119 : original: AuthEventManagerLike['onEvent'],
120 : event: AuthEventLike
121 : ): boolean {
122 0 : const attempt =
123 : event.type === 'signInViaPopup' && typeof event.eventId === 'string'
124 : ? attemptsByEventId.get(event.eventId)
125 : : undefined
126 0 : if (!attempt) return original(event)
127 0 : stopPolling(attempt)
128 : // A late failure is Firebase's to report; the host already heard the close.
129 0 : if (!attempt.abandoned || event.error) return original(event)
130 : // Acknowledged so the handler page stops, never handed to Firebase.
131 0 : if (shouldDiscard(attempt)) return true
132 0 : attempt.abandoned = false
133 0 : try {
134 0 : attempt.callbacks.onResumed?.()
135 : } catch {
136 : // The result is kept either way; a host bug must not stall Firebase.
137 : }
138 0 : return original(event)
139 : }
140 :
141 0 : function shouldDiscard(attempt: WatchedAttempt): boolean {
142 0 : try {
143 0 : return attempt.callbacks.discardLateResult?.() ?? false
144 : } catch {
145 0 : return true
146 : }
147 : }
148 :
149 : /** Ties the attempt to its latest popup, dropping any earlier one's watch. */
150 0 : function watchWindow(
151 : attempt: WatchedAttempt,
152 : eventId: string,
153 : popup: PopupWindowLike
154 : ): void {
155 0 : stopPolling(attempt)
156 0 : if (attempt.eventId) attemptsByEventId.delete(attempt.eventId)
157 0 : attempt.eventId = eventId
158 0 : attemptsByEventId.set(eventId, attempt)
159 0 : attempt.poll = setInterval(() => {
160 0 : if (popup.closed !== true) return
161 0 : stopPolling(attempt)
162 0 : attempt.abandoned = true
163 0 : attempt.callbacks.onAbandoned?.()
164 : }, CLOSED_POLL_MS)
165 : }
166 :
167 2356 : function watchingResolver(Base: ResolverClass): ResolverClass {
168 2356 : return class WatchingPopupRedirectResolver extends Base {
169 : override async _initialize(auth: unknown): Promise<unknown> {
170 0 : const manager = await super._initialize(auth)
171 0 : if (!isEventManager(manager)) return manager
172 0 : if (!wrappedManagers.has(manager)) {
173 0 : const original = manager.onEvent.bind(manager)
174 0 : manager.onEvent = (event) => deliver(original, event)
175 0 : wrappedManagers.add(manager)
176 : }
177 0 : if (isObject(auth)) observedAuths.add(auth)
178 0 : return manager
179 : }
180 :
181 : override async _openPopup(
182 : auth: unknown,
183 : provider: unknown,
184 : authType: unknown,
185 : eventId?: string
186 : ): Promise<unknown> {
187 0 : const popup = await super._openPopup(auth, provider, authType, eventId)
188 0 : const attempt = isObject(provider)
189 : ? attemptsByProvider.get(provider)
190 : : undefined
191 0 : const popupWindow = popupWindowOf(popup)
192 : // Without results to compare against, a closed window proves nothing.
193 0 : const observed = isObject(auth) && observedAuths.has(auth)
194 0 : if (attempt && observed && eventId && popupWindow)
195 0 : watchWindow(attempt, eventId, popupWindow)
196 0 : return popup
197 : }
198 : }
199 : }
200 :
201 : /**
202 : * The resolver a watched identity's Auth is created with. One for the whole
203 : * page, so Auth created again for the same app is handed the same resolver.
204 : * Firebase's own when its resolver cannot be extended.
205 : */
206 2356 : export const watchedPopupRedirectResolver: PopupRedirectResolver =
207 : isResolverClass(browserPopupRedirectResolver)
208 : ? watchingResolver(browserPopupRedirectResolver)
209 : : browserPopupRedirectResolver
210 :
211 : /**
212 : * Runs one popup sign-in for `provider`, the object passed to
213 : * `signInWithPopup`, reporting through `callbacks` while it is pending.
214 : */
215 0 : export async function runWatchedPopup<T>(
216 : provider: object,
217 : signIn: () => Promise<T>,
218 : callbacks: PopupWatchCallbacks
219 : ): Promise<T> {
220 0 : const attempt: WatchedAttempt = { callbacks, abandoned: false }
221 0 : attemptsByProvider.set(provider, attempt)
222 0 : try {
223 0 : return await signIn()
224 : } finally {
225 0 : stopPolling(attempt)
226 0 : attemptsByProvider.delete(provider)
227 0 : if (attempt.eventId) attemptsByEventId.delete(attempt.eventId)
228 : }
229 : }
|