|
| 1 | +/** |
| 2 | + * Copyright 2026 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +import type { APIRequestContext, Locator, Page } from "@playwright/test"; |
| 18 | +import { enUs } from "@firebase-oss/ui-translations"; |
| 19 | +import { expect, test } from "../fixtures/test-harness"; |
| 20 | + |
| 21 | +const AUTH_EMULATOR_BASE_URL = "http://127.0.0.1:9099"; |
| 22 | +const FIREBASE_PROJECT_ID = "demo-test"; |
| 23 | +const RECOVERY_PATH = "/screens/legacy-recovery-demo"; |
| 24 | + |
| 25 | +const projectsUnderTest = ["react", "angular-example"] as const; |
| 26 | + |
| 27 | +type EmulatorUser = { |
| 28 | + localId: string; |
| 29 | + providerUserInfo?: Array<{ providerId: string }>; |
| 30 | +}; |
| 31 | + |
| 32 | +function uniqueEmail(projectName: string, label: string): string { |
| 33 | + return `${projectName}-${label}-${crypto.randomUUID()}@example.test`; |
| 34 | +} |
| 35 | + |
| 36 | +async function clearEmulatorUsers(request: APIRequestContext): Promise<void> { |
| 37 | + const response = await request.delete( |
| 38 | + `${AUTH_EMULATOR_BASE_URL}/emulator/v1/projects/${FIREBASE_PROJECT_ID}/accounts` |
| 39 | + ); |
| 40 | + expect(response.ok(), await response.text()).toBe(true); |
| 41 | +} |
| 42 | + |
| 43 | +async function createGoogleAccount(request: APIRequestContext, email: string): Promise<void> { |
| 44 | + const claims = { |
| 45 | + sub: crypto.randomUUID(), |
| 46 | + name: "Playwright Recovery User", |
| 47 | + email, |
| 48 | + email_verified: true, |
| 49 | + }; |
| 50 | + const requestUri = |
| 51 | + `${AUTH_EMULATOR_BASE_URL}/emulator/auth/handler?providerId=google.com&id_token=` + |
| 52 | + encodeURIComponent(JSON.stringify(claims)); |
| 53 | + const response = await request.post( |
| 54 | + `${AUTH_EMULATOR_BASE_URL}/identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key=fake-api-key`, |
| 55 | + { |
| 56 | + data: { |
| 57 | + requestUri, |
| 58 | + sessionId: "ValueNotUsedByAuthEmulator", |
| 59 | + returnSecureToken: true, |
| 60 | + returnIdpCredential: true, |
| 61 | + }, |
| 62 | + } |
| 63 | + ); |
| 64 | + |
| 65 | + expect(response.ok(), await response.text()).toBe(true); |
| 66 | +} |
| 67 | + |
| 68 | +/** |
| 69 | + * The Auth emulator widget marks every OAuth email as verified. Its backend then silently merges |
| 70 | + * providers with matching emails instead of returning account-exists-with-different-credential. |
| 71 | + * Production providers can return an unverified email, so rewrite only the attempted provider's |
| 72 | + * emulator assertion to exercise Firebase Auth's real conflict response and credential payload. |
| 73 | + */ |
| 74 | +async function forceUnverifiedProviderEmail(page: Page, providerId: string): Promise<void> { |
| 75 | + await page.route("**/accounts:signInWithIdp?*", async (route) => { |
| 76 | + const request = route.request(); |
| 77 | + const body = request.postDataJSON() as { requestUri: string }; |
| 78 | + const requestUri = new URL(body.requestUri); |
| 79 | + |
| 80 | + if (requestUri.searchParams.get("providerId") === providerId) { |
| 81 | + const idToken = requestUri.searchParams.get("id_token"); |
| 82 | + if (idToken) { |
| 83 | + const claims = JSON.parse(idToken) as { email_verified?: boolean }; |
| 84 | + claims.email_verified = false; |
| 85 | + requestUri.searchParams.set("id_token", JSON.stringify(claims)); |
| 86 | + body.requestUri = requestUri.toString(); |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + await route.continue({ postData: JSON.stringify(body) }); |
| 91 | + }); |
| 92 | +} |
| 93 | + |
| 94 | +async function completeNewProviderSignIn( |
| 95 | + page: Page, |
| 96 | + buttonName: string, |
| 97 | + emulatorProviderName: string, |
| 98 | + email: string |
| 99 | +): Promise<void> { |
| 100 | + const popupPromise = page.waitForEvent("popup"); |
| 101 | + await page.getByRole("button", { name: buttonName, exact: true }).click(); |
| 102 | + const popup = await popupPromise; |
| 103 | + |
| 104 | + const addAccountButton = popup.getByRole("button", { name: "Add new account" }); |
| 105 | + await expect(addAccountButton).toBeVisible(); |
| 106 | + const emailInput = popup.locator("#email-input"); |
| 107 | + await expect(async () => { |
| 108 | + await addAccountButton.click(); |
| 109 | + await expect(emailInput).toBeVisible({ timeout: 1_000 }); |
| 110 | + }).toPass({ timeout: 10_000 }); |
| 111 | + |
| 112 | + await emailInput.fill(email); |
| 113 | + await popup.locator("#display-name-input").fill("Playwright Recovery User"); |
| 114 | + await Promise.all([ |
| 115 | + popup.waitForEvent("close"), |
| 116 | + popup.getByRole("button", { name: new RegExp(`Sign in with ${emulatorProviderName}`, "i") }).click(), |
| 117 | + ]); |
| 118 | +} |
| 119 | + |
| 120 | +async function completeExistingGoogleSignIn(page: Page, dialog: Locator, email: string): Promise<void> { |
| 121 | + const popupPromise = page.waitForEvent("popup"); |
| 122 | + await dialog.getByRole("button", { name: enUs.translations.labels.signInWithGoogle }).click(); |
| 123 | + const popup = await popupPromise; |
| 124 | + |
| 125 | + const existingAccount = popup.getByText(email, { exact: true }); |
| 126 | + await expect(existingAccount).toBeVisible(); |
| 127 | + await Promise.all([popup.waitForEvent("close"), existingAccount.click()]); |
| 128 | +} |
| 129 | + |
| 130 | +async function getUsersByEmail(request: APIRequestContext, email: string): Promise<EmulatorUser[]> { |
| 131 | + const response = await request.post( |
| 132 | + `${AUTH_EMULATOR_BASE_URL}/identitytoolkit.googleapis.com/v1/projects/${FIREBASE_PROJECT_ID}/accounts:lookup`, |
| 133 | + { |
| 134 | + headers: { authorization: "Bearer owner" }, |
| 135 | + data: { email: [email] }, |
| 136 | + } |
| 137 | + ); |
| 138 | + expect(response.ok(), await response.text()).toBe(true); |
| 139 | + |
| 140 | + const body = (await response.json()) as { users?: EmulatorUser[] }; |
| 141 | + return body.users ?? []; |
| 142 | +} |
| 143 | + |
| 144 | +for (const projectName of projectsUnderTest) { |
| 145 | + test.describe(`legacy sign-in recovery (${projectName})`, () => { |
| 146 | + test.describe.configure({ timeout: 90_000 }); |
| 147 | + |
| 148 | + test.beforeEach(async ({ request }, testInfo) => { |
| 149 | + test.skip(testInfo.project.name !== projectName, `runs only on the ${projectName} project`); |
| 150 | + await clearEmulatorUsers(request); |
| 151 | + }); |
| 152 | + |
| 153 | + test("shows previous methods and links the pending OAuth credential", async ({ page, request }) => { |
| 154 | + const email = uniqueEmail(projectName, "default"); |
| 155 | + await createGoogleAccount(request, email); |
| 156 | + await forceUnverifiedProviderEmail(page, "github.com"); |
| 157 | + |
| 158 | + await page.goto(RECOVERY_PATH); |
| 159 | + await completeNewProviderSignIn(page, enUs.translations.labels.signInWithGitHub, "GitHub.com", email); |
| 160 | + |
| 161 | + const dialog = page.getByRole("dialog", { |
| 162 | + name: enUs.translations.messages.legacySignInRecoverySelectMethod, |
| 163 | + }); |
| 164 | + await expect(dialog).toBeVisible(); |
| 165 | + await expect(dialog).toContainText(email); |
| 166 | + await expect(dialog.getByRole("button", { name: enUs.translations.labels.signInWithGoogle })).toBeVisible(); |
| 167 | + await expect(page.getByText(enUs.translations.errors.accountExistsWithDifferentCredential)).toBeVisible(); |
| 168 | + // "pendingCred" mirrors PENDING_CREDENTIAL_STORAGE_KEY in packages/core/src/behaviors/legacy-fetch-sign-in-with-email.ts. |
| 169 | + // Left as a literal here since page.evaluate runs in the browser context and can't import from the package. |
| 170 | + expect(await page.evaluate(() => window.sessionStorage.getItem("pendingCred"))).not.toBeNull(); |
| 171 | + |
| 172 | + await completeExistingGoogleSignIn(page, dialog, email); |
| 173 | + |
| 174 | + await expect(dialog).toHaveCount(0); |
| 175 | + await expect.poll(() => page.evaluate(() => window.sessionStorage.getItem("pendingCred"))).toBeNull(); |
| 176 | + |
| 177 | + await expect |
| 178 | + .poll(async () => { |
| 179 | + const users = await getUsersByEmail(request, email); |
| 180 | + return { |
| 181 | + count: users.length, |
| 182 | + providers: users[0]?.providerUserInfo?.map(({ providerId }) => providerId).sort(), |
| 183 | + }; |
| 184 | + }) |
| 185 | + .toEqual({ count: 1, providers: ["github.com", "google.com"] }); |
| 186 | + }); |
| 187 | + |
| 188 | + test("supports custom recovery UI and clears it when dismissed", async ({ page, request }) => { |
| 189 | + const email = uniqueEmail(projectName, "handled"); |
| 190 | + await createGoogleAccount(request, email); |
| 191 | + await forceUnverifiedProviderEmail(page, "github.com"); |
| 192 | + |
| 193 | + await page.goto(`${RECOVERY_PATH}?legacyRecovery=handled`); |
| 194 | + await completeNewProviderSignIn(page, enUs.translations.labels.signInWithGitHub, "GitHub.com", email); |
| 195 | + |
| 196 | + await expect(page.getByRole("dialog")).toHaveCount(0); |
| 197 | + const customRecovery = page.getByTestId("custom-legacy-recovery"); |
| 198 | + await expect(customRecovery).toBeVisible(); |
| 199 | + await expect(page.getByTestId("custom-legacy-recovery-email")).toHaveText(email); |
| 200 | + await expect(page.getByTestId("custom-legacy-recovery-methods")).toContainText("google.com"); |
| 201 | + // "pendingCred" mirrors PENDING_CREDENTIAL_STORAGE_KEY in packages/core/src/behaviors/legacy-fetch-sign-in-with-email.ts. |
| 202 | + // Left as a literal here since page.evaluate runs in the browser context and can't import from the package. |
| 203 | + expect(await page.evaluate(() => window.sessionStorage.getItem("pendingCred"))).not.toBeNull(); |
| 204 | + |
| 205 | + await page.getByRole("button", { name: "Custom dismiss" }).click(); |
| 206 | + await expect(customRecovery).toHaveCount(0); |
| 207 | + // clearLegacySignInRecovery() removes the pending credential synchronously, so no polling |
| 208 | + // is needed here (contrast with the completeExistingGoogleSignIn case above, which clears |
| 209 | + // it via an async sign-in flow). |
| 210 | + expect(await page.evaluate(() => window.sessionStorage.getItem("pendingCred"))).toBeNull(); |
| 211 | + }); |
| 212 | + }); |
| 213 | +} |
0 commit comments