Repository navigation
fix(chrome-extension): avoid remote loaders and initialize production auth #10565
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
8a9990c
fix(js): omit Device Intelligence loaders from no-RHC builds
mwickett 045c301
test(chrome-extension): cover development and production auth flows
mwickett 1ae7c8a
fix(chrome-extension): initialize native API mode on the first produc…
mwickett 243e3c2
test(chrome-extension): use reserved verification addresses for produ…
mwickett 0baee80
test(chrome-extension): await verification preparation before enterin…
mwickett 58cef15
test(chrome-extension): stop racing on the shared production fixture
mwickett 03175fe
test(chrome-extension): expect development sign-up to fail for now
mwickett a3641ed
test(chrome-extension): assert the known development sign-up rejection
mwickett dae1f31
Merge remote-tracking branch 'origin/main' into fix/chrome-extension-…
mwickett 0af8faf
test(chrome-extension): rely on the signed-in state instead of the OT…
mwickett File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| --- | ||
| '@clerk/clerk-js': patch | ||
| '@clerk/chrome-extension': patch | ||
| --- | ||
|
|
||
| Prevent Chrome extensions from loading Device Intelligence scripts from remote URLs. | ||
|
|
||
| Initialize production Chrome extension authentication without requiring a previously stored client token. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| import type { ClerkClient } from '@clerk/backend'; | ||
| import { parsePublishableKey } from '@clerk/shared/keys'; | ||
| import { createPageObjects } from '@clerk/testing/playwright/unstable'; | ||
|
|
||
| import { appConfigs } from '../../presets'; | ||
| import { createTestUtils } from '../../testUtils'; | ||
| import type { FakeUser, UserService } from '../../testUtils/usersService'; | ||
| import { expect, test as extensionTest } from './fixtures'; | ||
|
|
||
| for (const environmentType of ['development', 'production'] as const) { | ||
| const test = extensionTest.extend({ | ||
| extensionEnv: [ | ||
| environmentType === 'production' ? appConfigs.envs.sessionsProd1 : appConfigs.envs.withEmailCodes, | ||
| { scope: 'worker' }, | ||
| ], | ||
| extensionTestingToken: [false, { scope: 'worker' }], | ||
| }); | ||
|
|
||
| test.describe(`chrome extension ${environmentType} auth @chrome-extension`, () => { | ||
| test.describe.configure({ mode: 'default', timeout: 90_000 }); | ||
|
|
||
| let services: { clerk: ClerkClient; users: UserService }; | ||
| let user: FakeUser; | ||
|
|
||
| test.beforeAll(async ({ extensionApp }) => { | ||
| const publishableKey = extensionApp.env.publicVariables.get('CLERK_PUBLISHABLE_KEY'); | ||
| expect(publishableKey?.startsWith(environmentType === 'production' ? 'pk_live_' : 'pk_test_')).toBe(true); | ||
| ({ services } = await createTestUtils({ app: extensionApp })); | ||
|
|
||
| if (environmentType === 'production') { | ||
| const { frontendApi } = parsePublishableKey(publishableKey, { fatal: true }); | ||
| const readTestMode = async () => { | ||
| const response = await fetch(`https://${frontendApi}/v1/environment?_is_native=1`); | ||
| return response.ok ? (await response.json()).auth_config?.test_mode : undefined; | ||
| }; | ||
|
|
||
| if ((await readTestMode()) !== true) { | ||
| await services.clerk.instance.update({ testMode: true }); | ||
| await expect.poll(readTestMode, { timeout: 60_000, intervals: [1_000, 2_000, 5_000] }).toBe(true); | ||
| } | ||
| } | ||
| }); | ||
|
|
||
| test.beforeEach(async ({ extensionId }) => { | ||
| user = services.users.createFakeUser(test, { fictionalEmail: true }); | ||
|
|
||
| if (environmentType === 'production') { | ||
| const origin = `chrome-extension://${extensionId}`; | ||
| const instance = await services.clerk.instance.get(); | ||
| if (!instance.allowedOrigins?.includes(origin)) { | ||
| await services.clerk.instance.update({ allowedOrigins: [...(instance.allowedOrigins || []), origin] }); | ||
| } | ||
| } | ||
| }); | ||
|
|
||
| test.afterEach(async () => { | ||
| await user?.deleteIfExists(); | ||
| }); | ||
|
|
||
| test('signs in with email and password without a Testing Token', async ({ extensionPage }) => { | ||
| await services.users.createBapiUser(user); | ||
| const { signIn } = createPageObjects({ page: extensionPage, useTestingToken: false }); | ||
| await signIn.waitForMounted(); | ||
| await signIn.setIdentifier(user.email!); | ||
| await signIn.continue(); | ||
| await signIn.getPasswordInput().fill(user.password); | ||
| await signIn.continue(); | ||
| await expect(extensionPage.getByTestId('user-id')).toHaveText(/^user_/, { timeout: 30_000 }); | ||
| await expect(extensionPage.getByTestId('session-id')).toHaveText(/^sess_/); | ||
| }); | ||
|
|
||
| test('signs up with email and password without a Testing Token', async ({ extensionPage }) => { | ||
| await extensionPage.getByRole('button', { name: 'Create account', exact: true }).click(); | ||
| const { signUp } = createPageObjects({ page: extensionPage, useTestingToken: false }); | ||
| await signUp.waitForMounted(); | ||
| const preparation = extensionPage | ||
| .waitForResponse( | ||
| response => | ||
| response.request().method() === 'POST' && | ||
| new URL(response.url()).pathname.startsWith('/v1/client/sign_ups/') && | ||
| new URL(response.url()).pathname.endsWith('/prepare_verification'), | ||
| ) | ||
| .catch(() => undefined); | ||
| const [response] = await Promise.all([ | ||
| extensionPage.waitForResponse( | ||
| response => | ||
| response.request().method() === 'POST' && new URL(response.url()).pathname === '/v1/client/sign_ups', | ||
| ), | ||
| signUp.signUpWithEmailAndPassword({ email: user.email, password: user.password }), | ||
| ]); | ||
|
|
||
| if (environmentType === 'development') { | ||
| expect(response.status()).toBe(403); | ||
| expect((await response.json()).errors?.[0]?.code).toBe('action_blocked'); | ||
| return; | ||
| } | ||
|
|
||
| expect(response.ok()).toBe(true); | ||
| expect((await preparation)?.ok()).toBe(true); | ||
| await signUp.enterTestOtpCode({ awaitPrepare: false, awaitAttempt: false }); | ||
|
|
||
| await expect(extensionPage.getByTestId('user-id')).toHaveText(/^user_/, { timeout: 30_000 }); | ||
| await expect(extensionPage.getByTestId('session-id')).toHaveText(/^sess_/); | ||
| }); | ||
| }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| import { copyFile, mkdtemp, rm, writeFile } from 'node:fs/promises'; | ||
| import { tmpdir } from 'node:os'; | ||
| import * as path from 'node:path'; | ||
|
|
||
| import { chromium, expect, test } from '@playwright/test'; | ||
|
|
||
| import { createBaseEnvironmentJSON } from '../../../packages/clerk-js/src/test/fixtures'; | ||
|
|
||
| for (const environmentType of ['development', 'production'] as const) { | ||
| test(`no-RHC runtime ignores configured script loaders (${environmentType}) @chrome-extension`, async () => { | ||
| const extensionPath = await mkdtemp(path.join(tmpdir(), 'clerk-no-rhc-')); | ||
| await Promise.all([ | ||
| copyFile( | ||
| path.resolve(import.meta.dirname, '../../../packages/clerk-js/dist/clerk.no-rhc.mjs'), | ||
| path.join(extensionPath, 'clerk.mjs'), | ||
| ), | ||
| writeFile( | ||
| path.join(extensionPath, 'manifest.json'), | ||
| JSON.stringify({ | ||
| manifest_version: 3, | ||
| name: 'Clerk no-RHC regression', | ||
| version: '1.0.0', | ||
| background: { service_worker: 'background.js' }, | ||
| host_permissions: ['https://clerk.example.com/*'], | ||
| content_security_policy: { extension_pages: "script-src 'self'; object-src 'self'" }, | ||
| }), | ||
| ), | ||
| writeFile(path.join(extensionPath, 'background.js'), 'chrome.runtime.onInstalled.addListener(() => {});'), | ||
| writeFile(path.join(extensionPath, 'popup.html'), '<body><script type="module" src="popup.js"></script></body>'), | ||
| writeFile( | ||
| path.join(extensionPath, 'popup.js'), | ||
| `import { Clerk } from './clerk.mjs'; | ||
| const clerk = new Clerk('${environmentType === 'production' ? 'pk_live_' : 'pk_test_'}' + btoa('clerk.example.com$')); | ||
| await clerk.load({ standardBrowser: false, telemetry: false }); | ||
| document.body.dataset.loaded = String(clerk.loaded); | ||
| `, | ||
| ), | ||
| ]); | ||
|
|
||
| const context = await chromium.launchPersistentContext('', { | ||
| headless: false, | ||
| bypassCSP: false, | ||
| args: ['--headless=new', `--disable-extensions-except=${extensionPath}`, `--load-extension=${extensionPath}`], | ||
| }); | ||
|
|
||
| try { | ||
| const environment = createBaseEnvironmentJSON(); | ||
| environment.display_config.instance_environment_type = environmentType; | ||
| environment.protect_config = { | ||
| id: 'protect_config_test', | ||
| object: 'protect_config', | ||
| loaders: [ | ||
| { type: 'script', target: 'body', attributes: { src: 'https://example.com/device-intelligence.js' } }, | ||
| { type: 'script', target: 'body', text_content: 'window.remoteLoaderExecuted = true;' }, | ||
| ], | ||
| }; | ||
|
|
||
| let environmentRequests = 0; | ||
| await context.route('https://clerk.example.com/**', async route => { | ||
| const isEnvironment = new URL(route.request().url()).pathname === '/v1/environment'; | ||
| if (isEnvironment) { | ||
| environmentRequests++; | ||
| } | ||
| await route.fulfill({ | ||
| json: { | ||
| response: isEnvironment ? environment : { object: 'client', id: 'client_test', sessions: [] }, | ||
| }, | ||
| }); | ||
| }); | ||
|
|
||
| const background = context.serviceWorkers()[0] || (await context.waitForEvent('serviceworker')); | ||
| const extensionId = new URL(background.url()).host; | ||
| const page = await context.newPage(); | ||
| const remoteScripts: string[] = []; | ||
| const errors: string[] = []; | ||
| page.on('request', request => { | ||
| if (request.resourceType() === 'script' && request.url().startsWith('https://')) { | ||
| remoteScripts.push(request.url()); | ||
| } | ||
| }); | ||
| page.on('console', message => { | ||
| if (message.type() === 'error') { | ||
| errors.push(message.text()); | ||
| } | ||
| }); | ||
| page.on('pageerror', error => errors.push(error.message)); | ||
|
|
||
| await page.goto(`chrome-extension://${extensionId}/popup.html`); | ||
| await expect(page.locator('body')).toHaveAttribute('data-loaded', 'true'); | ||
| expect(environmentRequests).toBeGreaterThan(0); | ||
| await expect(page.locator('script[src^="https://"], script:not([src])')).toHaveCount(0); | ||
| expect(remoteScripts).toEqual([]); | ||
| expect(errors).toEqual([]); | ||
| } finally { | ||
| await context.close(); | ||
| await rm(extensionPath, { recursive: true, force: true }); | ||
| } | ||
| }); | ||
| } |
32 changes: 32 additions & 0 deletions
32
packages/chrome-extension/src/internal/utils/__tests__/request-handler.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| import { describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| import type { JWTHandler } from '../jwt-handler'; | ||
| import { requestHandler } from '../request-handler'; | ||
|
|
||
| describe('requestHandler', () => { | ||
| it.each([ | ||
| { isProd: true, jwt: undefined }, | ||
| { isProd: true, jwt: 'client-jwt' }, | ||
| { isProd: false, jwt: undefined }, | ||
| { isProd: false, jwt: 'development-jwt' }, | ||
| ])('sets request credentials for isProd=$isProd and jwt=$jwt', async ({ isProd, jwt }) => { | ||
| const jwtHandler: JWTHandler = { | ||
| get: vi.fn().mockResolvedValue(jwt), | ||
| set: vi.fn(), | ||
| remove: vi.fn(), | ||
| listener: vi.fn(), | ||
| }; | ||
| const request = { | ||
| url: new URL('https://example.com/v1/client'), | ||
| headers: new Headers(), | ||
| credentials: 'include' as RequestCredentials, | ||
| }; | ||
|
|
||
| await requestHandler(jwtHandler, { isProd })(request); | ||
|
|
||
| expect(request.credentials).toBe('omit'); | ||
| expect(request.url.searchParams.getAll('_is_native')).toEqual(isProd ? ['1'] : []); | ||
| expect(request.url.searchParams.get('__clerk_db_jwt')).toBe(!isProd && jwt ? jwt : null); | ||
| expect(request.headers.get('Authorization')).toBe(isProd && jwt ? `Bearer ${jwt}` : null); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.