From f9bbe7b66c1abc4d47dce2a2f5c7d5b48046886e Mon Sep 17 00:00:00 2001 From: Ademola Fadumo <48495111+demolaf@users.noreply.github.com> Date: Wed, 4 Nov 2026 16:20:00 +0100 Subject: [PATCH 1/6] fix(auth): keep the continue URL's query parameters on email sign-in links The action-code builder replaced the continue URL's query items with ui_auid alone, dropping parameters the app put on it. Keep them and drop only the items the library writes, since the configured settings object is reused for every link. --- .../Sources/Services/AuthService.swift | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift index 548bf37363..757513b508 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift @@ -1141,6 +1141,9 @@ private extension AuthService { return actionCodeSettings } + /// The continue-URL query items the library writes on email sign-in links. + static let emailLinkQueryItemNames: Set = ["ui_auid", "ui_sid", "ui_sd"] + private func updateActionCodeSettings() throws -> ActionCodeSettings { let actionCodeSettings = try safeActionCodeSettings() guard var urlComponents = URLComponents(string: actionCodeSettings.url!.absoluteString) else { @@ -1150,7 +1153,11 @@ private extension AuthService { ) } - var queryItems: [URLQueryItem] = [] + // Keep the app's own query items. The configured settings object is reused for every + // link, so drop the items an earlier link added before adding this link's. + var queryItems = (urlComponents.queryItems ?? []).filter { + !Self.emailLinkQueryItemNames.contains($0.name) + } if shouldHandleAnonymousUpgrade { if let currentUser = currentUser { @@ -1160,7 +1167,7 @@ private extension AuthService { } } - urlComponents.queryItems = queryItems + urlComponents.queryItems = queryItems.isEmpty ? nil : queryItems if let finalURL = urlComponents.url { actionCodeSettings.url = finalURL } From 94c9228025b7666243e5693619a1e781856da14c Mon Sep 17 00:00:00 2001 From: Ademola Fadumo <48495111+demolaf@users.noreply.github.com> Date: Wed, 4 Nov 2026 16:41:23 +0100 Subject: [PATCH 2/6] feat(auth): confirm the email when a sign-in link opens on another device Restores the FirebaseUI-iOS v15 cross-device email-link flow. Links carry ui_sid and ui_sd; a link opened without this device's session asks the user to confirm their email through EmailLinkContentState.needsEmailConfirmation and confirmEmail, or is rejected when withEmailLinkSignIn(forceSameDevice: true) is set. AuthPickerView now opens the email-link screen for a link received while that screen isn't showing, and the continue URL is read before the link's second decode, which dropped every continue-URL parameter after the first. --- .../Sources/Services/AuthService.swift | 257 +++++++++++------- .../Sources/Strings/Localizable.xcstrings | 24 ++ .../Sources/Utils/StringUtils.swift | 22 ++ .../Sources/Views/AuthPickerContent.swift | 3 + .../Views/DefaultEmailLinkContent.swift | 35 ++- .../Sources/Views/EmailLinkScreen.swift | 78 ++++-- .../ContentStateDefaultsTests.swift | 2 +- FirebaseSwiftUI/README.md | 13 + .../EmailLinkDeviceTests.swift | 137 ++++++++++ 9 files changed, 450 insertions(+), 121 deletions(-) create mode 100644 e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift index 757513b508..f36c59f99d 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift @@ -206,8 +206,10 @@ public final class AuthService { @ObservationIgnored @AppStorage("is-email-link") private var isEmailLinkSignIn: Bool = false // Storage for email link reauthentication (separate from sign-in) @ObservationIgnored @AppStorage("email-link-reauth") private var emailLinkReauth: String? - @ObservationIgnored @AppStorage("is-reauthenticating") private var isReauthenticating: Bool = - false + @ObservationIgnored @AppStorage("is-reauthenticating") private(set) var isReauthenticating: + Bool = false + /// Identifies the last sign-in link this device sent, written on the link as `ui_sid`. + @ObservationIgnored @AppStorage("email-link-session-id") private var emailLinkSessionID: String? private var currentMFAResolver: MultiFactorResolver? private var listenerManager: AuthListenerManager? @@ -232,6 +234,15 @@ public final class AuthService { /// library. public private(set) var allowNewEmailAccounts = true public var emailLinkSignInEnabled = false + /// Whether a sign-in link only works on the device that requested it. Set with + /// ``withEmailLinkSignIn(forceSameDevice:)``. + public private(set) var emailLinkForceSameDevice = false + /// A sign-in link opened on a device that didn't request it, waiting for + /// ``confirmEmailLinkSignIn(email:)``. + public private(set) var pendingEmailLink: URL? + /// A sign-in link the app opened while ``EmailLinkScreen`` wasn't showing, handed to it + /// when it appears. + var incomingEmailLink: URL? public var legacySignInRecovery: LegacySignInRecoveryContext? public var suggestedEmailAddress: String? /// How many in-place email forms (an ``EmailAuthScreen`` without a fixed flow) exist on the @@ -621,16 +632,27 @@ public extension AuthService { // MARK: - Email Link Sign In public extension AuthService { - /// Enable email link sign-in with default behavior (navigates to email link view) - func withEmailLinkSignIn() -> AuthService { - return withEmailLinkSignIn { [weak self] in + /// Enables email-link sign-in. Its button pushes ``AuthView/emailLink``. + /// + /// - Parameter forceSameDevice: Whether a link only works on the device that requested it. + /// When `false`, a link opened on another device asks the user to confirm their email + /// first. Defaults to `false`. + func withEmailLinkSignIn(forceSameDevice: Bool = false) -> AuthService { + return withEmailLinkSignIn(forceSameDevice: forceSameDevice) { [weak self] in self?.navigator.push(.emailLink) } } - /// Enable email link sign-in with custom callback - func withEmailLinkSignIn(onTap: @escaping () -> Void) -> AuthService { + /// Enables email-link sign-in with a custom action for its button. + /// + /// - Parameters: + /// - forceSameDevice: Whether a link only works on the device that requested it. Defaults + /// to `false`. + /// - onTap: Runs when the email-link button is tapped. + func withEmailLinkSignIn(forceSameDevice: Bool = false, + onTap: @escaping () -> Void) -> AuthService { emailLinkSignInEnabled = true + emailLinkForceSameDevice = forceSameDevice emailLinkSignInCallback = onTap return self } @@ -640,7 +662,8 @@ public extension AuthService { /// - email: Email address to send link to /// - isReauth: Whether this is for reauthentication (default: false) func sendEmailSignInLink(email: String, isReauth: Bool = false) async throws { - let actionCodeSettings = try updateActionCodeSettings() + let sessionID = isReauth ? nil : String(Int.random(in: 0 ... 999_999_999)) + let actionCodeSettings = try updateActionCodeSettings(sessionID: sessionID) try await auth.sendSignInLink( toEmail: email, actionCodeSettings: actionCodeSettings @@ -650,104 +673,150 @@ public extension AuthService { if isReauth { emailLinkReauth = email isReauthenticating = true + } else { + emailLink = email + emailLinkSessionID = sessionID + pendingEmailLink = nil } } + /// Signs in with a sign-in link the app opened, or reauthenticates when + /// ``sendEmailSignInLink(email:isReauth:)`` sent it for reauthentication. + /// + /// A link opened on a device that didn't request it sets ``pendingEmailLink`` instead, for + /// ``confirmEmailLinkSignIn(email:)``. With + /// ``withEmailLinkSignIn(forceSameDevice:)`` set, it throws + /// ``AuthServiceError/invalidEmailLink(_:)``. func handleSignInLink(url: URL) async throws { - do { - // Check which flow we're in based on the flag - let email: String - let isReauth = isReauthenticating - - if isReauth { - guard let reauthEmail = emailLinkReauth else { - throw AuthServiceError - .invalidEmailLink("Email address is missing for reauthentication") - } - email = reauthEmail - } else { - guard let signInEmail = emailLink else { - throw AuthServiceError - .invalidEmailLink("email address is missing from app storage. Is this the same device?") - } - email = signInEmail - } + if isReauthenticating { + try await handleEmailLinkReauthentication(url: url) + return + } - let urlString = url.absoluteString + let link = try Self.emailSignInLink(from: url) + guard auth.isSignIn(withEmailLink: link) else { return } - guard let originalLink = CommonUtils.getQueryParamValue(from: urlString, paramName: "link") - else { - throw AuthServiceError - .invalidEmailLink("'link' parameter is missing from the email link URL") - } + guard let continueURL = try Self.continueURL(from: url) else { + throw AuthServiceError + .invalidEmailLink("`continueUrl` parameter is missing from the email link URL") + } + let parameter = { CommonUtils.getQueryParamValue(from: continueURL, paramName: $0) } - guard let link = originalLink.removingPercentEncoding else { - throw AuthServiceError - .invalidEmailLink("Failed to decode Link URL") + // Links sent before `ui_sid` existed count as this device's when an email is stored. + let linkSessionID = parameter("ui_sid") + guard let email = emailLink, linkSessionID == nil || linkSessionID == emailLinkSessionID else { + if parameter("ui_sd") == "1" { + throw AuthServiceError.invalidEmailLink(string.emailLinkDifferentDeviceMessage) } + pendingEmailLink = url + return + } - if auth.isSignIn(withEmailLink: link) { - let credential = EmailAuthProvider.credential(withEmail: email, link: link) + try await signInWithEmailLink(email: email, link: link, anonymousUserID: parameter("ui_auid")) + } - if isReauth { - // Reauthentication flow - try await reauthenticate(with: credential) - // Clean up reauth state - emailLinkReauth = nil - isReauthenticating = false - } else { - // Sign-in flow - guard let continueUrl = CommonUtils.getQueryParamValue( - from: link, - paramName: "continueUrl" - ) - else { - throw AuthServiceError - .invalidEmailLink("`continueUrl` parameter is missing from the email link URL") - } + /// Finishes signing in with ``pendingEmailLink`` once the user confirms the email address the + /// link was sent to. Never upgrades an anonymous user, since that user is on another device. + func confirmEmailLinkSignIn(email: String) async throws { + guard let url = pendingEmailLink else { + throw AuthServiceError.invalidEmailLink("No sign-in link is waiting for confirmation") + } + let link = try Self.emailSignInLink(from: url) + try await signInWithEmailLink(email: email, link: link, anonymousUserID: nil) + } - let anonymousUserID = CommonUtils.getQueryParamValue( - from: continueUrl, - paramName: "ui_auid" - ) - if shouldHandleAnonymousUpgrade, anonymousUserID == currentUser?.uid { - _ = try await handleAutoUpgradeAnonymousUser(credentials: credential) - } else { - _ = try await auth.signIn(withEmail: email, link: link) - } - updateAuthenticationState() - // Track that user signed in with email link - isEmailLinkSignIn = true - emailLink = nil - } + /// Hands a sign-in link the app opened to ``EmailLinkScreen``, presenting the sheet and pushing + /// ``AuthView/emailLink`` when that screen isn't already showing to handle it itself. + internal func presentEmailLinkScreen(for url: URL) { + guard emailLinkSignInEnabled, !isReauthenticating, + authenticationState != .authenticated, + !(isPresented && authView == .emailLink), + let link = try? Self.emailSignInLink(from: url), + auth.isSignIn(withEmailLink: link) else { return } + + incomingEmailLink = url + isPresented = true + navigator.push(.emailLink) + } + + private func signInWithEmailLink(email: String, + link: String, + anonymousUserID: String?) async throws { + let credential = EmailAuthProvider.credential(withEmail: email, link: link) + do { + if let anonymousUserID, shouldHandleAnonymousUpgrade, + anonymousUserID == currentUser?.uid { + _ = try await handleAutoUpgradeAnonymousUser(credentials: credential) + } else { + _ = try await auth.signIn(withEmail: email, link: link) } } catch { - // Determine which email to use for error handling - let email = isReauthenticating ? emailLinkReauth : emailLink - let link = url.absoluteString + // Possible conflicts from auth.signIn(withEmail:link:): + // - accountExistsWithDifferentCredential: account exists with different provider + // - credentialAlreadyInUse: credential is already linked to another account + try handleErrorWithConflictCheck(error: error, credential: credential) + } + updateAuthenticationState() + // Track that user signed in with email link + isEmailLinkSignIn = true + emailLink = nil + emailLinkSessionID = nil + pendingEmailLink = nil + } - guard let email = email else { - throw AuthServiceError - .invalidEmailLink("email address is missing from app storage") - } - let credential = EmailAuthProvider.credential(withEmail: email, link: link) - - // Only handle conflicts for sign-in flow, not reauth - if !isReauthenticating { - // Possible conflicts from auth.signIn(withEmail:link:): - // - accountExistsWithDifferentCredential: account exists with different provider - // - credentialAlreadyInUse: credential is already linked to another account - try handleErrorWithConflictCheck(error: error, credential: credential) - } else { - // For reauth, just rethrow. The link is consumed even when a second factor is still - // required, so clean up reauth state in that case. - if case AuthServiceError.multiFactorReauthenticationRequired = error { - emailLinkReauth = nil - isReauthenticating = false - } - throw error + private func handleEmailLinkReauthentication(url: URL) async throws { + guard let email = emailLinkReauth else { + throw AuthServiceError.invalidEmailLink("Email address is missing for reauthentication") + } + let link = try Self.emailSignInLink(from: url) + guard auth.isSignIn(withEmailLink: link) else { return } + + do { + try await reauthenticate(with: EmailAuthProvider.credential(withEmail: email, link: link)) + } catch { + // The link is consumed even when a second factor is still required, so clean up + // reauth state in that case. + if case AuthServiceError.multiFactorReauthenticationRequired = error { + emailLinkReauth = nil + isReauthenticating = false } + throw error + } + emailLinkReauth = nil + isReauthenticating = false + } + + /// The continue URL of the sign-in link inside a URL the app opened. Read before + /// ``emailSignInLink(from:)`` decodes the link a second time, which would split the continue + /// URL's own query items off onto the link. + private static func continueURL(from url: URL) throws -> String? { + guard let originalLink = CommonUtils.getQueryParamValue( + from: url.absoluteString, + paramName: "link" + ) else { + throw AuthServiceError + .invalidEmailLink("'link' parameter is missing from the email link URL") } + return CommonUtils.getQueryParamValue(from: originalLink, paramName: "continueUrl") + ?? CommonUtils.getQueryParamValue( + from: originalLink.removingPercentEncoding ?? originalLink, + paramName: "continueUrl" + ) + } + + /// The Firebase sign-in link inside the `link` query parameter of a URL the app opened. + private static func emailSignInLink(from url: URL) throws -> String { + guard let originalLink = CommonUtils.getQueryParamValue( + from: url.absoluteString, + paramName: "link" + ) else { + throw AuthServiceError + .invalidEmailLink("'link' parameter is missing from the email link URL") + } + guard let link = originalLink.removingPercentEncoding else { + throw AuthServiceError.invalidEmailLink("Failed to decode Link URL") + } + return link } } @@ -1144,7 +1213,7 @@ private extension AuthService { /// The continue-URL query items the library writes on email sign-in links. static let emailLinkQueryItemNames: Set = ["ui_auid", "ui_sid", "ui_sd"] - private func updateActionCodeSettings() throws -> ActionCodeSettings { + private func updateActionCodeSettings(sessionID: String?) throws -> ActionCodeSettings { let actionCodeSettings = try safeActionCodeSettings() guard var urlComponents = URLComponents(string: actionCodeSettings.url!.absoluteString) else { throw AuthServiceError @@ -1167,6 +1236,12 @@ private extension AuthService { } } + // Lets the device that opens the link tell whether it sent it, as the UIKit library did. + if let sessionID { + queryItems.append(URLQueryItem(name: "ui_sid", value: sessionID)) + queryItems.append(URLQueryItem(name: "ui_sd", value: emailLinkForceSameDevice ? "1" : "0")) + } + urlComponents.queryItems = queryItems.isEmpty ? nil : queryItems if let finalURL = urlComponents.url { actionCodeSettings.url = finalURL diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Strings/Localizable.xcstrings b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Strings/Localizable.xcstrings index b8b9e159d7..c63c11a519 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Strings/Localizable.xcstrings +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Strings/Localizable.xcstrings @@ -8862,6 +8862,18 @@ } } }, + "ConfirmEmailLinkMessage" : { + "comment" : "Shown when an email sign-in link is opened on a device that didn't request it.", + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "You opened this sign-in link on a different device or browser. Enter the email address it was sent to." + } + } + } + }, "ConfirmPasswordInputLabel" : { "comment" : "Input label for confirming password when signing up", "extractionState" : "manual", @@ -12466,6 +12478,18 @@ } } }, + "EmailLinkDifferentDeviceMessage" : { + "comment" : "Error when an email sign-in link that must stay on one device is opened on another.", + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Open this sign-in link on the device where you requested it." + } + } + } + }, "EmailsDontMatch" : { "comment" : "Error message displayed when after re-authorization current user's email and re-authorized user's email doesn't match. Use short/abbreviated translation for 'email' which is less than 15 chars.", "extractionState" : "manual", diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Utils/StringUtils.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Utils/StringUtils.swift index 3975619d98..5e86324063 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Utils/StringUtils.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Utils/StringUtils.swift @@ -1079,9 +1079,31 @@ public class StringUtils { return String(format: localizedString(for: "Email: %@"), email) } + /// Confirm email title + /// found in: + /// - DefaultEmailLinkContent + public var confirmEmailTitle: String { + return localizedString(for: "ConfirmEmail") + } + + /// Message asking to confirm the email address of a sign-in link opened on another device + /// found in: + /// - DefaultEmailLinkContent + public var confirmEmailLinkMessage: String { + return localizedString(for: "ConfirmEmailLinkMessage") + } + + /// Error for a same-device sign-in link opened on another device + /// found in: + /// - AuthService + public var emailLinkDifferentDeviceMessage: String { + return localizedString(for: "EmailLinkDifferentDeviceMessage") + } + /// Confirm button label /// found in: /// - EmailReauthView + /// - DefaultEmailLinkContent public var confirmButtonLabel: String { return localizedString(for: "Confirm") } diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/AuthPickerContent.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/AuthPickerContent.swift index b05b732c30..a2ff5d292f 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/AuthPickerContent.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/AuthPickerContent.swift @@ -58,6 +58,9 @@ public struct AuthPickerContent< public var body: some View { @Bindable var authService = authService content() + // A sign-in link opened while the email-link screen isn't showing, for example on + // another device or after a cold launch, opens that screen to finish signing in. + .onOpenURL { authService.presentEmailLinkScreen(for: $0) } // Reopening the sheet starts from the first screen, not a half-finished pushed one. .sheet(isPresented: $authService.isPresented, onDismiss: authService.navigator.clear) { @Bindable var navigator = authService.navigator diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/DefaultEmailLinkContent.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/DefaultEmailLinkContent.swift index da5046691f..57420acafc 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/DefaultEmailLinkContent.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/DefaultEmailLinkContent.swift @@ -27,9 +27,17 @@ public struct DefaultEmailLinkContent: View { public var body: some View { VStack(spacing: 24) { + if state.needsEmailConfirmation { + Text(authService.string.confirmEmailLinkMessage) + .authCustomFont(.body) + .frame(maxWidth: .infinity, alignment: .leading) + .accessibilityIdentifier("email-link-confirm-message") + } AuthTextField( text: state.email, - label: authService.string.signInLinkEmailFieldLabel, + label: state.needsEmailConfirmation + ? authService.string.emailFieldLabel + : authService.string.signInLinkEmailFieldLabel, prompt: authService.string.emailInputLabel, keyboardType: .emailAddress, contentType: .emailAddress, @@ -41,18 +49,33 @@ public struct DefaultEmailLinkContent: View { } ) .accessibilityIdentifier("email-link-email-field") - Button(action: state.sendSignInLink) { - Text(authService.string.sendEmailLinkButtonLabel) - .padding(.vertical, 8) - .frame(maxWidth: .infinity) + Button { + if state.needsEmailConfirmation { + state.confirmEmail() + } else { + state.sendSignInLink() + } + } label: { + Text( + state.needsEmailConfirmation + ? authService.string.confirmButtonLabel + : authService.string.sendEmailLinkButtonLabel + ) + .padding(.vertical, 8) + .frame(maxWidth: .infinity) } .authCTAButtonStyle() + .accessibilityIdentifier("email-link-send-button") .disabled(!state.isValid || state.isLoading) .padding([.top, .bottom], 8) .frame(maxWidth: .infinity) } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) - .navigationTitle(authService.string.signInWithEmailLinkViewTitle) + .navigationTitle( + state.needsEmailConfirmation + ? authService.string.confirmEmailTitle + : authService.string.signInWithEmailLinkViewTitle + ) .safeAreaPadding() .errorMessageAlert( state.errorMessage, diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift index 6fb7ca0d79..c4be92a76f 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift @@ -28,6 +28,16 @@ public struct EmailLinkContentState { /// Clears ``didSend``. public let dismissAlert: @MainActor () -> Void + /// Signs in with the link waiting for confirmation, using ``email`` as the address it was + /// sent to. Does nothing unless ``needsEmailConfirmation`` and ``isValid`` are `true` and + /// ``isLoading`` is `false`. + public let confirmEmail: @MainActor () -> Void + + /// Whether a sign-in link was opened on a device that didn't request it, so the user must + /// enter the email address it was sent to and call ``confirmEmail``. Turned off with + /// ``AuthService/withEmailLinkSignIn(forceSameDevice:)``. + public let needsEmailConfirmation: Bool + /// Whether a sign-in link was sent and ``dismissAlert`` hasn't been called since. public let didSend: Bool @@ -51,6 +61,8 @@ public struct EmailLinkContentState { public init(email: Binding = .constant(""), sendSignInLink: @escaping @MainActor () -> Void = {}, dismissAlert: @escaping @MainActor () -> Void = {}, + confirmEmail: @escaping @MainActor () -> Void = {}, + needsEmailConfirmation: Bool = false, didSend: Bool = false, isValid: Bool = false, isLoading: Bool = false, @@ -59,6 +71,8 @@ public struct EmailLinkContentState { self.email = email self.sendSignInLink = sendSignInLink self.dismissAlert = dismissAlert + self.confirmEmail = confirmEmail + self.needsEmailConfirmation = needsEmailConfirmation self.didSend = didSend self.isValid = isValid self.isLoading = isLoading @@ -69,8 +83,9 @@ public struct EmailLinkContentState { /// The email-link screen, with its content drawn by you. /// -/// The screen sends the link, signs in when the app opens it, and routes account conflicts and -/// errors. Your content only draws the UI from the ``EmailLinkContentState`` it receives. Wrap +/// The screen sends the link, signs in when the app opens it, asks for the email address when +/// the link was opened on another device, and routes account conflicts and errors. Your content +/// only draws the UI from the ``EmailLinkContentState`` it receives. Wrap /// ``DefaultEmailLinkContent`` to keep the stock markup. /// /// Example: @@ -116,6 +131,8 @@ public struct EmailLinkScreen: View { email: $email, sendSignInLink: sendSignInLink, dismissAlert: { didSend = false }, + confirmEmail: confirmEmail, + needsEmailConfirmation: authService.pendingEmailLink != nil, didSend: didSend, isValid: isValid, isLoading: isLoading, @@ -125,26 +142,13 @@ public struct EmailLinkScreen: View { } .onChange(of: email) { errorMessage = nil } .onOpenURL { url in - // A sign-in link is one-time, so ignore another while one is being handled. - guard !isHandlingLink else { return } - isHandlingLink = true - errorMessage = nil - Task { - defer { isHandlingLink = false } - do { - try await authService.handleSignInLink(url: url) - } catch { - if case let AuthServiceError.accountConflict(ctx) = error, - let onConflict = accountConflictHandler { - onConflict(ctx) - return - } - - if shouldShowErrorAlert(for: error) { - errorMessage = authService.string.localizedErrorMessage(for: error) - } - } - } + handleLink { try await authService.handleSignInLink(url: url) } + } + // A link the app opened before this screen was showing. + .onChange(of: authService.incomingEmailLink, initial: true) { _, url in + guard let url else { return } + authService.incomingEmailLink = nil + handleLink { try await authService.handleSignInLink(url: url) } } .onAppear { if let suggestedEmailAddress = authService.suggestedEmailAddress { @@ -166,6 +170,35 @@ public struct EmailLinkScreen: View { isWorking || isHandlingLink || authService.authenticationState == .authenticating } + private func confirmEmail() { + guard authService.pendingEmailLink != nil, isValid, !isLoading else { return } + let email = self.email + handleLink { try await authService.confirmEmailLinkSignIn(email: email) } + } + + private func handleLink(_ attempt: @escaping @MainActor () async throws -> Void) { + // A sign-in link is one-time, so ignore another while one is being handled. + guard !isHandlingLink else { return } + isHandlingLink = true + errorMessage = nil + Task { + defer { isHandlingLink = false } + do { + try await attempt() + } catch { + if case let AuthServiceError.accountConflict(ctx) = error, + let onConflict = accountConflictHandler { + onConflict(ctx) + return + } + + if shouldShowErrorAlert(for: error) { + errorMessage = authService.string.localizedErrorMessage(for: error) + } + } + } + } + private func sendSignInLink() { guard isValid, !isLoading else { return } let email = self.email @@ -176,7 +209,6 @@ public struct EmailLinkScreen: View { do { try await authService.sendEmailSignInLink(email: email) didSend = true - authService.emailLink = email } catch { if shouldShowErrorAlert(for: error) { errorMessage = authService.string.localizedErrorMessage(for: error) diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Tests/FirebaseAuthSwiftUITests/ContentStateDefaultsTests.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Tests/FirebaseAuthSwiftUITests/ContentStateDefaultsTests.swift index 81d661fdcd..1c663fbe0d 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Tests/FirebaseAuthSwiftUITests/ContentStateDefaultsTests.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Tests/FirebaseAuthSwiftUITests/ContentStateDefaultsTests.swift @@ -91,7 +91,7 @@ struct ContentStateDefaultsTests { func emailLinkContentState() { let state = EmailLinkContentState() #expect(state.email.wrappedValue.isEmpty) - #expect(!state.didSend) + #expect(!state.didSend && !state.needsEmailConfirmation) #expect(!state.isValid && !state.isLoading && state.errorMessage == nil) } diff --git a/FirebaseSwiftUI/README.md b/FirebaseSwiftUI/README.md index 306676dac1..4a9057b590 100644 --- a/FirebaseSwiftUI/README.md +++ b/FirebaseSwiftUI/README.md @@ -244,6 +244,7 @@ When email link sign-in is configured: - Handles deep link navigation from email - Manages the complete email verification flow - Supports anonymous user upgrades via email link +- Asks for the email address when a link is opened on another device, unless `withEmailLinkSignIn(forceSameDevice: true)` limits links to the device that requested them #### 5. **Anonymous User Auto-Upgrade** @@ -1275,6 +1276,18 @@ Handles the email link flow when the user taps the link. Automatically routes to **Note:** This method handles both initial sign-in and reauthentication flows automatically. The behavior is determined by whether `sendEmailSignInLink(email:isReauth:)` was called with `isReauth: true`. +A link opened on a device that didn't request it sets `pendingEmailLink` instead of signing in. Finish with `confirmEmailLinkSignIn(email:)`, passing the address the link was sent to. With `withEmailLinkSignIn(forceSameDevice: true)`, such a link throws `AuthServiceError.invalidEmailLink`. `AuthPickerView` handles links itself, opening the email-link screen when needed. + +--- + +##### Confirm Email Link Sign-In + +```swift +public func confirmEmailLinkSignIn(email: String) async throws +``` + +Signs in with `pendingEmailLink`, a link opened on another device, once the user confirms the email address it was sent to. + --- #### Phone Authentication diff --git a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift new file mode 100644 index 0000000000..1c2952cfd8 --- /dev/null +++ b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift @@ -0,0 +1,137 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import FirebaseAuth +@testable import FirebaseAuthSwiftUI +import Foundation +import Testing + +/// Email-link sign-in when the link is opened on the device that sent it or on another one. +@Suite(.serialized) +@MainActor +struct EmailLinkDeviceTests { + private func makeService(continueURL: String = "https://flutterfire-e2e-tests.firebaseapp.com", + forceSameDevice: Bool = false) async throws -> AuthService { + configureFirebaseIfNeeded() + try await clearAuthEmulatorState() + let settings = makeEmailLinkActionCodeSettings() + settings.url = URL(string: continueURL) + return AuthService( + configuration: AuthConfiguration(emailLinkSignInActionCodeSettings: settings) + ) + .withEmailLinkSignIn(forceSameDevice: forceSameDevice) + } + + private func continueURLItems(of url: URL) throws -> [URLQueryItem] { + let link = try #require( + URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems? + .first { $0.name == "link" }?.value + ) + let continueURL = try #require( + URLComponents(string: link)?.queryItems?.first { $0.name == "continueUrl" }?.value + ) + return URLComponents(string: continueURL)?.queryItems ?? [] + } + + @Test + func continueURLKeepsAppQueryItems() async throws { + let service = try await makeService( + continueURL: "https://flutterfire-e2e-tests.firebaseapp.com/?app=1" + ) + let email = createEmail() + + // The configured settings are reused, so a second link must not repeat the first's items. + try await service.sendEmailSignInLink(email: createEmail()) + try await service.sendEmailSignInLink(email: email) + + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + let items = try continueURLItems(of: link) + #expect(items.filter { $0.name == "app" }.map(\.value) == ["1"]) + #expect(items.filter { $0.name == "ui_sid" }.count == 1) + #expect(items.first { $0.name == "ui_sd" }?.value == "0") + } + + @Test + func linkFromAnotherDeviceWaitsForEmailConfirmation() async throws { + let service = try await makeService() + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + + // Another device has no stored email for the link. + service.emailLink = nil + try await service.handleSignInLink(url: link) + // Waits instead of signing in. Other tests share `Auth`, so its state isn't checked here. + #expect(service.pendingEmailLink == link) + + try await service.confirmEmailLinkSignIn(email: email) + try await waitForStateChange { + service.currentUser?.email?.caseInsensitiveCompare(email) == .orderedSame + } + #expect(service.pendingEmailLink == nil) + try await service.signOut() + } + + @Test + func forcedSameDeviceRejectsLinkFromAnotherDevice() async throws { + let service = try await makeService(forceSameDevice: true) + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + #expect(try continueURLItems(of: link).first { $0.name == "ui_sd" }?.value == "1") + + service.emailLink = nil + await #expect(throws: AuthServiceError.self) { + try await service.handleSignInLink(url: link) + } + #expect(service.pendingEmailLink == nil) + } + + @Test + func openedLinkPresentsEmailLinkScreen() throws { + configureFirebaseIfNeeded() + let service = AuthService().withEmailLinkSignIn() + var link = try #require(URLComponents(string: "https://example.com/")) + link.queryItems = [URLQueryItem( + name: "link", + value: "https://flutterfire-e2e-tests.firebaseapp.com/__/auth/action?apiKey=key" + + "&mode=signIn&oobCode=code&continueUrl=https://example.com" + )] + let url = try #require(link.url) + + service.presentEmailLinkScreen(for: url) + + #expect(service.isPresented) + #expect(service.authView == .emailLink) + #expect(service.incomingEmailLink == url) + + // Already showing: the screen's own handler takes the link. + service.incomingEmailLink = nil + service.presentEmailLinkScreen(for: url) + #expect(service.incomingEmailLink == nil) + #expect(service.navigator.routes == [.emailLink]) + } + + @Test + func openedLinkIsIgnoredWithoutEmailLinkSignIn() throws { + configureFirebaseIfNeeded() + let service = AuthService() + let url = try #require(URL(string: "https://example.com/?link=https://example.com")) + + service.presentEmailLinkScreen(for: url) + + #expect(!service.isPresented) + #expect(service.navigator.routes.isEmpty) + } +} From 95964218ae336c1c03ad252a29083b00dd5ebca1 Mon Sep 17 00:00:00 2001 From: Ademola Fadumo <48495111+demolaf@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:15:44 +0100 Subject: [PATCH 3/6] fix(auth): let users leave the email confirmation step A link waiting for email confirmation stayed pending after sign-out, a closed sheet or a used link, so the email-link screen kept asking for an email and never offered to send a new link. Clear it in those cases and add cancelEmailLinkConfirmation with a cancelConfirmation action on EmailLinkContentState. Also leave opened links to an app's own email-link screen, and stop treating a link without ui_sid as this device's once a newer link was sent. --- .../Sources/Services/AuthService.swift | 43 +++++++++++++--- .../Sources/Views/AuthPickerContent.swift | 5 +- .../Views/DefaultEmailLinkContent.swift | 9 +++- .../Sources/Views/EmailLinkScreen.swift | 7 +++ FirebaseSwiftUI/README.md | 2 + .../EmailLinkDeviceTests.swift | 51 +++++++++++++++++++ 6 files changed, 109 insertions(+), 8 deletions(-) diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift index f36c59f99d..41c2a0570d 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift @@ -214,6 +214,9 @@ public final class AuthService { private var currentMFAResolver: MultiFactorResolver? private var listenerManager: AuthListenerManager? private var emailLinkSignInCallback: (() -> Void)? + /// Whether the email-link button pushes the library's ``AuthView/emailLink`` screen rather + /// than running an app's own `onTap`. + private var emailLinkUsesLibraryScreen = false private var providers: [AuthProviderUI] = [] private let emailLinkSignInMethod = "emailLink" @@ -334,6 +337,7 @@ public final class AuthService { try auth.signOut() // Cannot wait for auth listener to change, feedback needs to be immediate currentUser = nil + clearEmailLinkHandoff() // Clear email link sign-in flag isEmailLinkSignIn = false // Clear email link reauth state @@ -638,9 +642,11 @@ public extension AuthService { /// When `false`, a link opened on another device asks the user to confirm their email /// first. Defaults to `false`. func withEmailLinkSignIn(forceSameDevice: Bool = false) -> AuthService { - return withEmailLinkSignIn(forceSameDevice: forceSameDevice) { [weak self] in + _ = withEmailLinkSignIn(forceSameDevice: forceSameDevice) { [weak self] in self?.navigator.push(.emailLink) } + emailLinkUsesLibraryScreen = true + return self } /// Enables email-link sign-in with a custom action for its button. @@ -654,6 +660,7 @@ public extension AuthService { emailLinkSignInEnabled = true emailLinkForceSameDevice = forceSameDevice emailLinkSignInCallback = onTap + emailLinkUsesLibraryScreen = false return self } @@ -702,9 +709,10 @@ public extension AuthService { } let parameter = { CommonUtils.getQueryParamValue(from: continueURL, paramName: $0) } - // Links sent before `ui_sid` existed count as this device's when an email is stored. + // A link without `ui_sid`, sent before it existed, counts as this device's only when this + // device hasn't sent a link since. let linkSessionID = parameter("ui_sid") - guard let email = emailLink, linkSessionID == nil || linkSessionID == emailLinkSessionID else { + guard let email = emailLink, linkSessionID == emailLinkSessionID else { if parameter("ui_sd") == "1" { throw AuthServiceError.invalidEmailLink(string.emailLinkDifferentDeviceMessage) } @@ -722,13 +730,36 @@ public extension AuthService { throw AuthServiceError.invalidEmailLink("No sign-in link is waiting for confirmation") } let link = try Self.emailSignInLink(from: url) - try await signInWithEmailLink(email: email, link: link, anonymousUserID: nil) + do { + try await signInWithEmailLink(email: email, link: link, anonymousUserID: nil) + } catch { + // A used or expired link can't succeed with any email, so stop asking for one. + let code = AuthErrorCode(rawValue: (error as NSError).code) + if code == .invalidActionCode || code == .expiredActionCode { + pendingEmailLink = nil + } + throw error + } + } + + /// Drops ``pendingEmailLink`` so the email-link screen offers to send a new link instead of + /// asking to confirm the email. + func cancelEmailLinkConfirmation() { + pendingEmailLink = nil + } + + /// Forgets links waiting for the email-link screen, when the sheet closes or the user signs + /// out. + internal func clearEmailLinkHandoff() { + pendingEmailLink = nil + incomingEmailLink = nil } /// Hands a sign-in link the app opened to ``EmailLinkScreen``, presenting the sheet and pushing - /// ``AuthView/emailLink`` when that screen isn't already showing to handle it itself. + /// ``AuthView/emailLink`` when that screen isn't already showing to handle it itself. An app + /// that shows its own screen through `withEmailLinkSignIn(onTap:)` handles links there. internal func presentEmailLinkScreen(for url: URL) { - guard emailLinkSignInEnabled, !isReauthenticating, + guard emailLinkSignInEnabled, emailLinkUsesLibraryScreen, !isReauthenticating, authenticationState != .authenticated, !(isPresented && authView == .emailLink), let link = try? Self.emailSignInLink(from: url), diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/AuthPickerContent.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/AuthPickerContent.swift index a2ff5d292f..c5b06fa37d 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/AuthPickerContent.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/AuthPickerContent.swift @@ -62,7 +62,10 @@ public struct AuthPickerContent< // another device or after a cold launch, opens that screen to finish signing in. .onOpenURL { authService.presentEmailLinkScreen(for: $0) } // Reopening the sheet starts from the first screen, not a half-finished pushed one. - .sheet(isPresented: $authService.isPresented, onDismiss: authService.navigator.clear) { + .sheet(isPresented: $authService.isPresented, onDismiss: { + authService.navigator.clear() + authService.clearEmailLinkHandoff() + }) { @Bindable var navigator = authService.navigator NavigationStack(path: $navigator.routes) { root diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/DefaultEmailLinkContent.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/DefaultEmailLinkContent.swift index 57420acafc..1af0860845 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/DefaultEmailLinkContent.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/DefaultEmailLinkContent.swift @@ -65,10 +65,17 @@ public struct DefaultEmailLinkContent: View { .frame(maxWidth: .infinity) } .authCTAButtonStyle() - .accessibilityIdentifier("email-link-send-button") + .accessibilityIdentifier( + state.needsEmailConfirmation ? "email-link-confirm-button" : "email-link-send-button" + ) .disabled(!state.isValid || state.isLoading) .padding([.top, .bottom], 8) .frame(maxWidth: .infinity) + if state.needsEmailConfirmation { + Button(authService.string.cancelButtonLabel, action: state.cancelConfirmation) + .disabled(state.isLoading) + .accessibilityIdentifier("email-link-cancel-confirmation-button") + } } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) .navigationTitle( diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift index c4be92a76f..4d57ea3cdd 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift @@ -33,6 +33,10 @@ public struct EmailLinkContentState { /// ``isLoading`` is `false`. public let confirmEmail: @MainActor () -> Void + /// Drops the link waiting for confirmation, so ``needsEmailConfirmation`` turns `false` and + /// the user can send a new link. + public let cancelConfirmation: @MainActor () -> Void + /// Whether a sign-in link was opened on a device that didn't request it, so the user must /// enter the email address it was sent to and call ``confirmEmail``. Turned off with /// ``AuthService/withEmailLinkSignIn(forceSameDevice:)``. @@ -62,6 +66,7 @@ public struct EmailLinkContentState { sendSignInLink: @escaping @MainActor () -> Void = {}, dismissAlert: @escaping @MainActor () -> Void = {}, confirmEmail: @escaping @MainActor () -> Void = {}, + cancelConfirmation: @escaping @MainActor () -> Void = {}, needsEmailConfirmation: Bool = false, didSend: Bool = false, isValid: Bool = false, @@ -72,6 +77,7 @@ public struct EmailLinkContentState { self.sendSignInLink = sendSignInLink self.dismissAlert = dismissAlert self.confirmEmail = confirmEmail + self.cancelConfirmation = cancelConfirmation self.needsEmailConfirmation = needsEmailConfirmation self.didSend = didSend self.isValid = isValid @@ -132,6 +138,7 @@ public struct EmailLinkScreen: View { sendSignInLink: sendSignInLink, dismissAlert: { didSend = false }, confirmEmail: confirmEmail, + cancelConfirmation: { authService.cancelEmailLinkConfirmation() }, needsEmailConfirmation: authService.pendingEmailLink != nil, didSend: didSend, isValid: isValid, diff --git a/FirebaseSwiftUI/README.md b/FirebaseSwiftUI/README.md index 4a9057b590..7c3e168e8f 100644 --- a/FirebaseSwiftUI/README.md +++ b/FirebaseSwiftUI/README.md @@ -1288,6 +1288,8 @@ public func confirmEmailLinkSignIn(email: String) async throws Signs in with `pendingEmailLink`, a link opened on another device, once the user confirms the email address it was sent to. +A used or expired link clears `pendingEmailLink`. Call `cancelEmailLinkConfirmation()` to drop it yourself, for example when the user wants a new link; signing out or closing the sheet also drops it. An app that shows its own email-link screen through `withEmailLinkSignIn(onTap:)` handles opened links on that screen. + --- #### Phone Authentication diff --git a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift index 1c2952cfd8..f4cd4e5c6f 100644 --- a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift +++ b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift @@ -83,6 +83,39 @@ struct EmailLinkDeviceTests { try await service.signOut() } + @Test + func linkFromAnotherSessionWaitsAndCanBeCancelled() async throws { + let service = try await makeService() + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + + // This device sent a newer link since, so the stored email may not be this link's. + try await service.sendEmailSignInLink(email: createEmail()) + service.emailLink = email + try await service.handleSignInLink(url: link) + #expect(service.pendingEmailLink == link) + + service.cancelEmailLinkConfirmation() + #expect(service.pendingEmailLink == nil) + } + + @Test + func signingOutForgetsPendingLink() async throws { + let service = try await makeService() + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + service.emailLink = nil + try await service.handleSignInLink(url: link) + #expect(service.pendingEmailLink == link) + + try await service.signOut() + + #expect(service.pendingEmailLink == nil) + #expect(service.incomingEmailLink == nil) + } + @Test func forcedSameDeviceRejectsLinkFromAnotherDevice() async throws { let service = try await makeService(forceSameDevice: true) @@ -123,6 +156,24 @@ struct EmailLinkDeviceTests { #expect(service.navigator.routes == [.emailLink]) } + @Test + func openedLinkIsLeftToAppsOwnEmailLinkScreen() throws { + configureFirebaseIfNeeded() + let service = AuthService().withEmailLinkSignIn(onTap: {}) + var link = try #require(URLComponents(string: "https://example.com/")) + link.queryItems = [URLQueryItem( + name: "link", + value: "https://flutterfire-e2e-tests.firebaseapp.com/__/auth/action?apiKey=key" + + "&mode=signIn&oobCode=code&continueUrl=https://example.com" + )] + + let url = try #require(link.url) + service.presentEmailLinkScreen(for: url) + + #expect(!service.isPresented) + #expect(service.incomingEmailLink == nil) + } + @Test func openedLinkIsIgnoredWithoutEmailLinkSignIn() throws { configureFirebaseIfNeeded() From 6fb751928ec495333c03d8ebecc84952fee0e32c Mon Sep 17 00:00:00 2001 From: Ademola Fadumo <48495111+demolaf@users.noreply.github.com> Date: Wed, 4 Nov 2026 20:14:36 +0100 Subject: [PATCH 4/6] fix(auth): keep handleSignInLink compatible and use each link once A link opened on another device threw before this change, and apps may rely on that, so keep throwing invalidEmailLink while also setting pendingEmailLink; the stock screen shows the confirm step instead of the error. Ignore a link that is already being handled or already signed in, so AuthPickerView and an app's own onOpenURL handler don't both use the same one-time link. --- .../Sources/Services/AuthService.swift | 21 +++++++++--- .../Sources/Views/EmailLinkScreen.swift | 4 +++ FirebaseSwiftUI/README.md | 2 +- .../EmailLinkDeviceTests.swift | 32 +++++++++++++++++-- 4 files changed, 50 insertions(+), 9 deletions(-) diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift index 41c2a0570d..24d9e0d6fc 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift @@ -217,6 +217,10 @@ public final class AuthService { /// Whether the email-link button pushes the library's ``AuthView/emailLink`` screen rather /// than running an app's own `onTap`. private var emailLinkUsesLibraryScreen = false + /// The sign-in link being handled, and the last one that signed in, so a link delivered to + /// several `onOpenURL` handlers is only used once. + @ObservationIgnored private var emailLinkInFlight: URL? + @ObservationIgnored private var lastSignedInEmailLink: URL? private var providers: [AuthProviderUI] = [] private let emailLinkSignInMethod = "emailLink" @@ -690,16 +694,20 @@ public extension AuthService { /// Signs in with a sign-in link the app opened, or reauthenticates when /// ``sendEmailSignInLink(email:isReauth:)`` sent it for reauthentication. /// - /// A link opened on a device that didn't request it sets ``pendingEmailLink`` instead, for - /// ``confirmEmailLinkSignIn(email:)``. With - /// ``withEmailLinkSignIn(forceSameDevice:)`` set, it throws - /// ``AuthServiceError/invalidEmailLink(_:)``. + /// A link opened on a device that didn't request it throws + /// ``AuthServiceError/invalidEmailLink(_:)`` as before, and also sets ``pendingEmailLink`` for + /// ``confirmEmailLinkSignIn(email:)`` unless ``withEmailLinkSignIn(forceSameDevice:)`` is + /// set. A link that is already being handled, or already signed in, is ignored. func handleSignInLink(url: URL) async throws { if isReauthenticating { try await handleEmailLinkReauthentication(url: url) return } + guard url != emailLinkInFlight, url != lastSignedInEmailLink else { return } + emailLinkInFlight = url + defer { emailLinkInFlight = nil } + let link = try Self.emailSignInLink(from: url) guard auth.isSignIn(withEmailLink: link) else { return } @@ -717,10 +725,12 @@ public extension AuthService { throw AuthServiceError.invalidEmailLink(string.emailLinkDifferentDeviceMessage) } pendingEmailLink = url - return + throw AuthServiceError + .invalidEmailLink("email address is missing from app storage. Is this the same device?") } try await signInWithEmailLink(email: email, link: link, anonymousUserID: parameter("ui_auid")) + lastSignedInEmailLink = url } /// Finishes signing in with ``pendingEmailLink`` once the user confirms the email address the @@ -732,6 +742,7 @@ public extension AuthService { let link = try Self.emailSignInLink(from: url) do { try await signInWithEmailLink(email: email, link: link, anonymousUserID: nil) + lastSignedInEmailLink = url } catch { // A used or expired link can't succeed with any email, so stop asking for one. let code = AuthErrorCode(rawValue: (error as NSError).code) diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift index 4d57ea3cdd..c9df83b3b4 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift @@ -198,6 +198,10 @@ public struct EmailLinkScreen: View { onConflict(ctx) return } + // The link was opened on another device; the content asks for the email instead. + if case AuthServiceError.invalidEmailLink = error, authService.pendingEmailLink != nil { + return + } if shouldShowErrorAlert(for: error) { errorMessage = authService.string.localizedErrorMessage(for: error) diff --git a/FirebaseSwiftUI/README.md b/FirebaseSwiftUI/README.md index 7c3e168e8f..877ce88869 100644 --- a/FirebaseSwiftUI/README.md +++ b/FirebaseSwiftUI/README.md @@ -1276,7 +1276,7 @@ Handles the email link flow when the user taps the link. Automatically routes to **Note:** This method handles both initial sign-in and reauthentication flows automatically. The behavior is determined by whether `sendEmailSignInLink(email:isReauth:)` was called with `isReauth: true`. -A link opened on a device that didn't request it sets `pendingEmailLink` instead of signing in. Finish with `confirmEmailLinkSignIn(email:)`, passing the address the link was sent to. With `withEmailLinkSignIn(forceSameDevice: true)`, such a link throws `AuthServiceError.invalidEmailLink`. `AuthPickerView` handles links itself, opening the email-link screen when needed. +A link opened on a device that didn't request it throws `AuthServiceError.invalidEmailLink` as before, and also sets `pendingEmailLink` unless `withEmailLinkSignIn(forceSameDevice: true)` is set. Finish with `confirmEmailLinkSignIn(email:)`, passing the address the link was sent to. `AuthPickerView` handles links itself, opening the email-link screen when needed, and a link already being handled or already used is ignored, so your own `onOpenURL` handler can stay. --- diff --git a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift index f4cd4e5c6f..5e4762860f 100644 --- a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift +++ b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift @@ -71,7 +71,9 @@ struct EmailLinkDeviceTests { // Another device has no stored email for the link. service.emailLink = nil - try await service.handleSignInLink(url: link) + await #expect(throws: AuthServiceError.self) { + try await service.handleSignInLink(url: link) + } // Waits instead of signing in. Other tests share `Auth`, so its state isn't checked here. #expect(service.pendingEmailLink == link) @@ -93,7 +95,10 @@ struct EmailLinkDeviceTests { // This device sent a newer link since, so the stored email may not be this link's. try await service.sendEmailSignInLink(email: createEmail()) service.emailLink = email - try await service.handleSignInLink(url: link) + // Throws as before, and keeps the link for confirmation. + await #expect(throws: AuthServiceError.self) { + try await service.handleSignInLink(url: link) + } #expect(service.pendingEmailLink == link) service.cancelEmailLinkConfirmation() @@ -107,7 +112,10 @@ struct EmailLinkDeviceTests { try await service.sendEmailSignInLink(email: email) let link = try await fetchEmailSignInLinkFromEmulator(email: email) service.emailLink = nil - try await service.handleSignInLink(url: link) + // Throws as before, and keeps the link for confirmation. + await #expect(throws: AuthServiceError.self) { + try await service.handleSignInLink(url: link) + } #expect(service.pendingEmailLink == link) try await service.signOut() @@ -116,6 +124,24 @@ struct EmailLinkDeviceTests { #expect(service.incomingEmailLink == nil) } + @Test + func linkIsOnlyUsedOnce() async throws { + let service = try await makeService() + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + + // Both `AuthPickerView` and an app's own `onOpenURL` may pass the same link. + try await service.handleSignInLink(url: link) + try await service.handleSignInLink(url: link) + + try await waitForStateChange { + service.currentUser?.email?.caseInsensitiveCompare(email) == .orderedSame + } + #expect(service.pendingEmailLink == nil) + try await service.signOut() + } + @Test func forcedSameDeviceRejectsLinkFromAnotherDevice() async throws { let service = try await makeService(forceSameDevice: true) From ec1591ded7c2de2cb7b89a1fe0c7b74e93c932aa Mon Sep 17 00:00:00 2001 From: Ademola Fadumo <48495111+demolaf@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:43:25 +0100 Subject: [PATCH 5/6] fix(auth): give every caller of a sign-in link the same outcome A second handleSignInLink call with a link already being handled returned at once, so an app's own onOpenURL could treat a failed sign-in as done. It now waits for the first attempt and gets its result. EmailLinkScreen hides the cross-device error only for the link that set pendingEmailLink, and signing out forgets the last used link so tapping it again reports that it expired. --- .../Sources/Services/AuthService.swift | 27 +++++++++-- .../Sources/Views/EmailLinkScreen.swift | 14 +++--- FirebaseSwiftUI/README.md | 2 +- .../EmailLinkDeviceTests.swift | 48 +++++++++++++++++++ 4 files changed, 79 insertions(+), 12 deletions(-) diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift index 24d9e0d6fc..069f97b4d8 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift @@ -219,7 +219,7 @@ public final class AuthService { private var emailLinkUsesLibraryScreen = false /// The sign-in link being handled, and the last one that signed in, so a link delivered to /// several `onOpenURL` handlers is only used once. - @ObservationIgnored private var emailLinkInFlight: URL? + @ObservationIgnored private var emailLinkInFlight: (url: URL, task: Task)? @ObservationIgnored private var lastSignedInEmailLink: URL? private var providers: [AuthProviderUI] = [] private let emailLinkSignInMethod = "emailLink" @@ -342,6 +342,8 @@ public final class AuthService { // Cannot wait for auth listener to change, feedback needs to be immediate currentUser = nil clearEmailLinkHandoff() + // A link that signed in before is expired now; let it fail again rather than do nothing. + lastSignedInEmailLink = nil // Clear email link sign-in flag isEmailLinkSignIn = false // Clear email link reauth state @@ -697,17 +699,32 @@ public extension AuthService { /// A link opened on a device that didn't request it throws /// ``AuthServiceError/invalidEmailLink(_:)`` as before, and also sets ``pendingEmailLink`` for /// ``confirmEmailLinkSignIn(email:)`` unless ``withEmailLinkSignIn(forceSameDevice:)`` is - /// set. A link that is already being handled, or already signed in, is ignored. + /// set. A link that is already being handled waits for that attempt and gets its outcome, and + /// a link that already signed in is ignored until sign-out. func handleSignInLink(url: URL) async throws { if isReauthenticating { try await handleEmailLinkReauthentication(url: url) return } - guard url != emailLinkInFlight, url != lastSignedInEmailLink else { return } - emailLinkInFlight = url - defer { emailLinkInFlight = nil } + // A second caller with the same link waits for the first and gets the same outcome. + if let inFlight = emailLinkInFlight, inFlight.url == url { + try await inFlight.task.value + return + } + guard url != lastSignedInEmailLink else { return } + + let task = Task { try await self.signInWithOpenedLink(url: url) } + emailLinkInFlight = (url, task) + defer { + if emailLinkInFlight?.url == url { + emailLinkInFlight = nil + } + } + try await task.value + } + private func signInWithOpenedLink(url: URL) async throws { let link = try Self.emailSignInLink(from: url) guard auth.isSignIn(withEmailLink: link) else { return } diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift index c9df83b3b4..0930751290 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift @@ -149,13 +149,13 @@ public struct EmailLinkScreen: View { } .onChange(of: email) { errorMessage = nil } .onOpenURL { url in - handleLink { try await authService.handleSignInLink(url: url) } + handleLink(url) { try await authService.handleSignInLink(url: url) } } // A link the app opened before this screen was showing. .onChange(of: authService.incomingEmailLink, initial: true) { _, url in guard let url else { return } authService.incomingEmailLink = nil - handleLink { try await authService.handleSignInLink(url: url) } + handleLink(url) { try await authService.handleSignInLink(url: url) } } .onAppear { if let suggestedEmailAddress = authService.suggestedEmailAddress { @@ -180,10 +180,11 @@ public struct EmailLinkScreen: View { private func confirmEmail() { guard authService.pendingEmailLink != nil, isValid, !isLoading else { return } let email = self.email - handleLink { try await authService.confirmEmailLinkSignIn(email: email) } + handleLink(nil) { try await authService.confirmEmailLinkSignIn(email: email) } } - private func handleLink(_ attempt: @escaping @MainActor () async throws -> Void) { + private func handleLink(_ url: URL?, + _ attempt: @escaping @MainActor () async throws -> Void) { // A sign-in link is one-time, so ignore another while one is being handled. guard !isHandlingLink else { return } isHandlingLink = true @@ -198,8 +199,9 @@ public struct EmailLinkScreen: View { onConflict(ctx) return } - // The link was opened on another device; the content asks for the email instead. - if case AuthServiceError.invalidEmailLink = error, authService.pendingEmailLink != nil { + // This link was opened on another device; the content asks for the email instead. + if case AuthServiceError.invalidEmailLink = error, let url, + authService.pendingEmailLink == url { return } diff --git a/FirebaseSwiftUI/README.md b/FirebaseSwiftUI/README.md index 877ce88869..ad6fb8aaac 100644 --- a/FirebaseSwiftUI/README.md +++ b/FirebaseSwiftUI/README.md @@ -1276,7 +1276,7 @@ Handles the email link flow when the user taps the link. Automatically routes to **Note:** This method handles both initial sign-in and reauthentication flows automatically. The behavior is determined by whether `sendEmailSignInLink(email:isReauth:)` was called with `isReauth: true`. -A link opened on a device that didn't request it throws `AuthServiceError.invalidEmailLink` as before, and also sets `pendingEmailLink` unless `withEmailLinkSignIn(forceSameDevice: true)` is set. Finish with `confirmEmailLinkSignIn(email:)`, passing the address the link was sent to. `AuthPickerView` handles links itself, opening the email-link screen when needed, and a link already being handled or already used is ignored, so your own `onOpenURL` handler can stay. +A link opened on a device that didn't request it throws `AuthServiceError.invalidEmailLink` as before, and also sets `pendingEmailLink` unless `withEmailLinkSignIn(forceSameDevice: true)` is set. Finish with `confirmEmailLinkSignIn(email:)`, passing the address the link was sent to. `AuthPickerView` handles links itself, opening the email-link screen when needed, so your own `onOpenURL` handler can stay: a call with a link already being handled waits for that attempt and gets its result, and a link that already signed in is ignored until sign-out. --- diff --git a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift index 5e4762860f..08851ffc9f 100644 --- a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift +++ b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift @@ -142,6 +142,54 @@ struct EmailLinkDeviceTests { try await service.signOut() } + @Test + func concurrentCallsShareOneAttempt() async throws { + let service = try await makeService() + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + + let first = Task { try await service.handleSignInLink(url: link) } + let second = Task { try await service.handleSignInLink(url: link) } + try await first.value + try await second.value + + try await waitForStateChange { + service.currentUser?.email?.caseInsensitiveCompare(email) == .orderedSame + } + try await service.signOut() + } + + @Test + func concurrentCallsShareAFailure() async throws { + let service = try await makeService() + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + // Another device: the first attempt fails, and the second must not report success. + service.emailLink = nil + + let first = Task { try await service.handleSignInLink(url: link) } + let second = Task { try await service.handleSignInLink(url: link) } + await #expect(throws: AuthServiceError.self) { try await first.value } + await #expect(throws: AuthServiceError.self) { try await second.value } + } + + @Test + func signingOutLetsAUsedLinkFailAgain() async throws { + let service = try await makeService() + let email = createEmail() + try await service.sendEmailSignInLink(email: email) + let link = try await fetchEmailSignInLinkFromEmulator(email: email) + try await service.handleSignInLink(url: link) + try await service.signOut() + + // The link is used up; after sign-out it reports that instead of doing nothing. + await #expect(throws: (any Error).self) { + try await service.handleSignInLink(url: link) + } + } + @Test func forcedSameDeviceRejectsLinkFromAnotherDevice() async throws { let service = try await makeService(forceSameDevice: true) From 49ec541068d33eb8c35547326423d3242be8192e Mon Sep 17 00:00:00 2001 From: Ademola Fadumo <48495111+demolaf@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:49:06 +0100 Subject: [PATCH 6/6] fix(auth): leave other deep links alone on the email-link screens EmailLinkScreen and EmailLinkReauthScreen handled every URL the app opened, so an unrelated deep link opened while either showed an error. They now handle only Firebase email sign-in links. Leaving EmailLinkScreen also drops a link waiting for email confirmation, so returning to it offers to send a new link. --- .../Sources/Services/AuthService.swift | 10 ++++++++-- .../Sources/Views/EmailLinkReauthScreen.swift | 2 ++ .../Sources/Views/EmailLinkScreen.swift | 5 +++++ .../EmailLinkDeviceTests.swift | 19 +++++++++++++++++++ 4 files changed, 34 insertions(+), 2 deletions(-) diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift index 069f97b4d8..b866b6ea06 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Services/AuthService.swift @@ -783,6 +783,13 @@ public extension AuthService { incomingEmailLink = nil } + /// Whether a URL the app opened carries a Firebase email sign-in link, so screens can leave + /// the app's other deep links alone. + internal func isEmailSignInLink(_ url: URL) -> Bool { + guard let link = try? Self.emailSignInLink(from: url) else { return false } + return auth.isSignIn(withEmailLink: link) + } + /// Hands a sign-in link the app opened to ``EmailLinkScreen``, presenting the sheet and pushing /// ``AuthView/emailLink`` when that screen isn't already showing to handle it itself. An app /// that shows its own screen through `withEmailLinkSignIn(onTap:)` handles links there. @@ -790,8 +797,7 @@ public extension AuthService { guard emailLinkSignInEnabled, emailLinkUsesLibraryScreen, !isReauthenticating, authenticationState != .authenticated, !(isPresented && authView == .emailLink), - let link = try? Self.emailSignInLink(from: url), - auth.isSignIn(withEmailLink: link) else { return } + isEmailSignInLink(url) else { return } incomingEmailLink = url isPresented = true diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift index e005200aa0..4b2c68f865 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkReauthScreen.swift @@ -107,6 +107,8 @@ public struct EmailLinkReauthScreen: View { )) } .onOpenURL { url in + // The app's other deep links reach this handler too; they aren't errors here. + guard authService.isEmailSignInLink(url) else { return } handleReauthURL(url) } .task { diff --git a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift index 0930751290..d0c55ff972 100644 --- a/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift +++ b/FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/Views/EmailLinkScreen.swift @@ -149,6 +149,8 @@ public struct EmailLinkScreen: View { } .onChange(of: email) { errorMessage = nil } .onOpenURL { url in + // The app's other deep links reach this handler too; they aren't errors here. + guard authService.isEmailSignInLink(url) else { return } handleLink(url) { try await authService.handleSignInLink(url: url) } } // A link the app opened before this screen was showing. @@ -162,6 +164,9 @@ public struct EmailLinkScreen: View { email = suggestedEmailAddress } } + // Leaving the screen abandons the link waiting for confirmation, so coming back offers to + // send a new one. + .onDisappear { authService.cancelEmailLinkConfirmation() } .onChange(of: authService.suggestedEmailAddress) { _, suggestedEmailAddress in if let suggestedEmailAddress { email = suggestedEmailAddress diff --git a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift index 08851ffc9f..dcfb6e22f4 100644 --- a/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift +++ b/e2eTest/FirebaseSwiftUIExample/FirebaseSwiftUIExampleTests/EmailLinkDeviceTests.swift @@ -248,6 +248,25 @@ struct EmailLinkDeviceTests { #expect(service.incomingEmailLink == nil) } + @Test + func onlyFirebaseSignInLinksCountAsEmailSignInLinks() throws { + configureFirebaseIfNeeded() + let service = AuthService().withEmailLinkSignIn() + var link = try #require(URLComponents(string: "https://example.com/")) + link.queryItems = [URLQueryItem( + name: "link", + value: "https://flutterfire-e2e-tests.firebaseapp.com/__/auth/action?apiKey=key" + + "&mode=signIn&oobCode=code&continueUrl=https://example.com" + )] + + #expect(try service.isEmailSignInLink(#require(link.url))) + // Another deep link, or a link to some other Firebase action, is left to the app. + #expect(try !service.isEmailSignInLink(#require(URL(string: "myapp://settings")))) + #expect(try !service.isEmailSignInLink( + #require(URL(string: "https://example.com/?link=https://example.com/?mode=resetPassword")) + )) + } + @Test func openedLinkIsIgnoredWithoutEmailLinkSignIn() throws { configureFirebaseIfNeeded()