Skip to content

Commit 8a9990c

Browse files
committed
fix(js): omit Device Intelligence loaders from no-RHC builds
1 parent b5803ea commit 8a9990c

6 files changed

Lines changed: 131 additions & 3 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
'@clerk/clerk-js': patch
3+
'@clerk/chrome-extension': patch
4+
---
5+
6+
Prevent Chrome extensions from loading Device Intelligence scripts from remote URLs.
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import { copyFile, mkdtemp, rm, writeFile } from 'node:fs/promises';
2+
import { tmpdir } from 'node:os';
3+
import * as path from 'node:path';
4+
5+
import { chromium, expect, test } from '@playwright/test';
6+
7+
import { createBaseEnvironmentJSON } from '../../../packages/clerk-js/src/test/fixtures';
8+
9+
for (const environmentType of ['development', 'production'] as const) {
10+
test(`no-RHC runtime ignores configured script loaders (${environmentType}) @chrome-extension`, async () => {
11+
const extensionPath = await mkdtemp(path.join(tmpdir(), 'clerk-no-rhc-'));
12+
await Promise.all([
13+
copyFile(
14+
path.resolve(import.meta.dirname, '../../../packages/clerk-js/dist/clerk.no-rhc.mjs'),
15+
path.join(extensionPath, 'clerk.mjs'),
16+
),
17+
writeFile(
18+
path.join(extensionPath, 'manifest.json'),
19+
JSON.stringify({
20+
manifest_version: 3,
21+
name: 'Clerk no-RHC regression',
22+
version: '1.0.0',
23+
background: { service_worker: 'background.js' },
24+
host_permissions: ['https://clerk.example.com/*'],
25+
content_security_policy: { extension_pages: "script-src 'self'; object-src 'self'" },
26+
}),
27+
),
28+
writeFile(path.join(extensionPath, 'background.js'), 'chrome.runtime.onInstalled.addListener(() => {});'),
29+
writeFile(path.join(extensionPath, 'popup.html'), '<body><script type="module" src="popup.js"></script></body>'),
30+
writeFile(
31+
path.join(extensionPath, 'popup.js'),
32+
`import { Clerk } from './clerk.mjs';
33+
const clerk = new Clerk('${environmentType === 'production' ? 'pk_live_' : 'pk_test_'}' + btoa('clerk.example.com$'));
34+
await clerk.load({ standardBrowser: false, telemetry: false });
35+
document.body.dataset.loaded = String(clerk.loaded);
36+
`,
37+
),
38+
]);
39+
40+
const context = await chromium.launchPersistentContext('', {
41+
headless: false,
42+
bypassCSP: false,
43+
args: ['--headless=new', `--disable-extensions-except=${extensionPath}`, `--load-extension=${extensionPath}`],
44+
});
45+
46+
try {
47+
const environment = createBaseEnvironmentJSON();
48+
environment.display_config.instance_environment_type = environmentType;
49+
environment.protect_config = {
50+
id: 'protect_config_test',
51+
object: 'protect_config',
52+
loaders: [
53+
{ type: 'script', attributes: { src: 'https://example.com/device-intelligence.js' } },
54+
{ type: 'script', text_content: 'window.remoteLoaderExecuted = true;' },
55+
],
56+
};
57+
58+
let environmentRequests = 0;
59+
await context.route('https://clerk.example.com/**', async route => {
60+
const isEnvironment = new URL(route.request().url()).pathname === '/v1/environment';
61+
if (isEnvironment) {
62+
environmentRequests++;
63+
}
64+
await route.fulfill({
65+
json: {
66+
response: isEnvironment ? environment : { object: 'client', id: 'client_test', sessions: [] },
67+
},
68+
});
69+
});
70+
71+
const background = context.serviceWorkers()[0] || (await context.waitForEvent('serviceworker'));
72+
const extensionId = new URL(background.url()).host;
73+
const page = await context.newPage();
74+
const remoteScripts: string[] = [];
75+
const errors: string[] = [];
76+
page.on('request', request => {
77+
if (request.resourceType() === 'script' && request.url().startsWith('https://')) {
78+
remoteScripts.push(request.url());
79+
}
80+
});
81+
page.on('console', message => {
82+
if (message.type() === 'error') {
83+
errors.push(message.text());
84+
}
85+
});
86+
page.on('pageerror', error => errors.push(error.message));
87+
88+
await page.goto(`chrome-extension://${extensionId}/popup.html`);
89+
await expect(page.locator('body')).toHaveAttribute('data-loaded', 'true');
90+
expect(environmentRequests).toBeGreaterThan(0);
91+
await expect(page.locator('script[src^="https://"], script:not([src])')).toHaveCount(0);
92+
expect(remoteScripts).toEqual([]);
93+
expect(errors).toEqual([]);
94+
} finally {
95+
await context.close();
96+
await rm(extensionPath, { recursive: true, force: true });
97+
}
98+
});
99+
}

‎packages/clerk-js/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
],
6060
"scripts": {
6161
"build": "pnpm build:bundle && pnpm build:declarations",
62+
"postbuild": "node ../../scripts/search-for-rhc.mjs file dist/clerk.no-rhc.mjs && node ../../scripts/search-for-rhc.mjs file dist/clerk.no-rhc.js",
6263
"build:analyze": "rspack build --config rspack.config.mjs --env production --env variant=\"clerk.browser\" --env analysis",
6364
"build:bundle": "pnpm clean && rspack build --config rspack.config.mjs --env production",
6465
"build:declarations": "tsc -p tsconfig.declarations.json",
@@ -76,7 +77,6 @@
7677
"lint": "eslint src",
7778
"lint:attw": "attw --pack . --profile node16 --ignore-rules named-exports --ignore-rules false-cjs",
7879
"lint:publint": "publint || true",
79-
"postbuild:disabled": "node ../../scripts/search-for-rhc.mjs file dist/clerk.no-rhc.mjs",
8080
"test": "vitest --watch=false",
8181
"test:sandbox:integration": "playwright test",
8282
"test:sandbox:integration:ui": "playwright test --ui",

‎packages/clerk-js/src/core/__tests__/clerk.protect-params.test.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { ProtectAssertion } from '@clerk/shared/types';
2-
import { beforeEach, describe, expect, it, vi } from 'vitest';
2+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
33

44
import { Clerk } from '../clerk';
55

@@ -53,6 +53,10 @@ describe('Clerk getProtectParams', () => {
5353
capturedOptions.current = undefined;
5454
});
5555

56+
afterEach(() => {
57+
vi.unstubAllGlobals();
58+
});
59+
5660
it('is wired into the FAPI client', () => {
5761
expect(hookFor()).toBeTypeOf('function');
5862
});
@@ -75,6 +79,22 @@ describe('Clerk getProtectParams', () => {
7579
await expect(hookFor('token-abc')()).resolves.toEqual(assertionParams);
7680
});
7781

82+
it('does not acquire remote loader params in no-RHC builds', async () => {
83+
vi.stubGlobal('__BUILD_DISABLE_RHC__', true);
84+
getRequestParams.mockResolvedValue(sessionParams);
85+
86+
await expect(hookFor()()).resolves.toBeUndefined();
87+
expect(getRequestParams).not.toHaveBeenCalled();
88+
});
89+
90+
it('sends application assertions in no-RHC builds', async () => {
91+
vi.stubGlobal('__BUILD_DISABLE_RHC__', true);
92+
getRequestParams.mockResolvedValue(sessionParams);
93+
94+
await expect(hookFor('token-abc')()).resolves.toEqual(assertionParams);
95+
expect(getRequestParams).not.toHaveBeenCalled();
96+
});
97+
7898
// Returning `{}` would make every sign-in body differ from what it was before the feature existed.
7999
it('resolves to undefined when neither contributes anything', async () => {
80100
getRequestParams.mockResolvedValue(undefined);

‎packages/clerk-js/src/core/clerk.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -598,7 +598,9 @@ export class Clerk implements ClerkInterface {
598598

599599
// This line is used for the piggy-backing mechanism
600600
BaseResource.clerk = this;
601-
this.#protect = new Protect();
601+
if (!__BUILD_DISABLE_RHC__) {
602+
this.#protect = new Protect();
603+
}
602604
}
603605

604606
public getFapiClient = (): FapiClient => this.#fapiClient;

‎scripts/search-for-rhc.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ await Promise.allSettled([
2929
asyncSearchRHC('clerk-js Hotloading', '/npm/@clerk/clerk-js'),
3030
asyncSearchRHC('clerk-ui Hotloading', '/npm/@clerk/ui'),
3131
asyncSearchRHC('Google One Tap', 'accounts.google.com/gsi/client'),
32+
asyncSearchRHC('Protect loader', '[protect] loader'),
3233
asyncSearchRHC('Coinbase', 'coinbase.com'),
3334
asyncSearchRHC('Coinbase Wallet import', 'import\s*"@coinbase/wallet-sdk', true), // eslint-disable-line no-useless-escape
3435
asyncSearchRHC('Stripe', 'js.stripe.com'),

0 commit comments

Comments
 (0)