Skip to content

Conversation

jacekradko
Copy link
Member

@jacekradko jacekradko commented Sep 11, 2025

Description

When the CHIPS build of clerk-js runs inside an iframe, OAuth sign-in/sign-up flows fail because the backend attempts to validate the client_id against registered OAuth applications. The client_id differs between the iframe context and the parent window context, causing validation failures.

Fixes: USER-3277

Related: https://github.com/clerk/clerk_go/pull/13638

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • New Features

    • Improved authentication when the SDK runs inside embedded iframes for CHIPS builds.
  • Improvements

    • iframe detection now includes clientId in create/update and redirect flows for embedded sign-in/sign-up.
    • Internal router navigation updated to always return a Promise and accept NavigateOptions for more consistent routing.
  • Types

    • Added optional clientId/iframe identification fields to sign-in and sign-up parameter types.
  • Tests

    • New unit tests covering iframe-related create/update and redirect behaviors.
  • Style

    • Clarified an inline comment for a UI action handler.

Copy link

vercel bot commented Sep 11, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Sep 16, 2025 5:38pm

Copy link

changeset-bot bot commented Sep 11, 2025

🦋 Changeset detected

Latest commit: e124825

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 22 packages
Name Type
@clerk/clerk-js Minor
@clerk/types Minor
@clerk/chrome-extension Patch
@clerk/clerk-expo Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/backend Patch
@clerk/elements Patch
@clerk/expo-passkeys Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/localizations Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/clerk-react Patch
@clerk/remix Patch
@clerk/shared Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch
@clerk/themes Patch
@clerk/vue Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link
Contributor

coderabbitai bot commented Sep 11, 2025

Walkthrough

Adds an optional clientId to SignIn/SignUp types and injects it into create/update/sign-in-future payloads when __BUILD_VARIANT_CHIPS__ is true and inIframe() returns true; imports inIframe() in resources, adds tests, updates a changeset, and tightens router internalNavigate typings.

Changes

Cohort / File(s) Summary
SignIn runtime updates
packages/clerk-js/src/core/resources/SignIn.ts
Import inIframe; build createParams in authenticateWithRedirectOrPopup and in SignInFuture.create; when __BUILD_VARIANT_CHIPS__ && inIframe() set clientId (from BaseResource.clerk.client?.id); post createParams.
SignUp runtime updates
packages/clerk-js/src/core/resources/SignUp.ts
Import inIframe; clone incoming params to finalParams in create and update; when __BUILD_VARIANT_CHIPS__ && inIframe() set finalParams.clientId = BaseResource.clerk.client?.id; send finalParams (merged with captcha data) as request body.
Types: signIn / signInFuture / signUp
packages/types/src/signInCommon.ts, packages/types/src/signInFuture.ts, packages/types/src/signUpCommon.ts
Add optional clientId?: string (with @internal JSDoc where present) to relevant SignIn/SignInFuture/SignUp create param types.
Tests: SignIn & SignUp
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts, packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
Add suites mocking inIframe, toggling __BUILD_VARIANT_CHIPS__, and asserting clientId is included only when CHIPS build is enabled and running in an iframe; verify redirect URL construction and SignIn future POST body.
Changeset
.changeset/violet-badgers-change.md
Add changeset noting minor bumps and public API additions (optional clientId to SignIn/SignUp params for CHIPS iframe context).
UI comment-only change
packages/clerk-js/src/ui/elements/Action/ActionTrigger.tsx
Add explanatory comment above a ts-ignore; no runtime change.
Router typing tightening
packages/clerk-js/src/ui/router/BaseRouter.tsx, packages/clerk-js/src/ui/router/PathRouter.tsx, packages/clerk-js/src/ui/router/VirtualRouter.tsx
Tighten internalNavigate to return Promise<any>; update PathRouter to accept/forward a URL object and remove undefined guard; add optional _options?: NavigateOptions to VirtualRouter internalNavigate and return a resolved Promise.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App
  participant Runtime as inIframe()
  participant Resource as SignIn/SignUp
  participant Base as BaseResource.clerk
  participant Backend as API

  App->>Resource: create()/update()/authenticateWithRedirectOrPopup(params)
  Resource->>Runtime: inIframe()
  Runtime-->>Resource: true/false
  alt __BUILD_VARIANT_CHIPS__ && inIframe() == true
    rect #EBF8FF
      Resource->>Base: read client?.id
      Resource->>Resource: clone params -> createParams/finalParams
      Resource->>Resource: set createParams.clientId = client.id
    end
  end
  Resource->>Backend: POST/PATCH with body (maybe includes clientId)
  Backend-->>Resource: response
  Resource-->>App: result / redirect
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

A rabbit hops in with a tiny new id,
slips it through frames where OAuths hid.
CHIPS lights the way inside the iframe,
payloads whisper the client name.
Hop, test, and ship — carrot-coded fame! 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Out of Scope Changes Check ⚠️ Warning The PR contains unrelated edits beyond the CHIPS/client_id fix, most notably signature/return-type changes to internalNavigate in BaseRouter.tsx, PathRouter.tsx, and VirtualRouter.tsx and a comment-only change in ActionTrigger.tsx; these router/type adjustments are not required to implement the CHIPS iframe clientId behavior and could affect unrelated callers or consumers. Because these router API/type changes are outside the linked issue scope and may introduce breaking/type churn, they are considered out-of-scope for this bugfix PR. Split the router signature/type changes and any other unrelated edits into a separate PR (or provide a clear justification and test coverage here), run full type-checks and consumer integration tests, and keep this PR focused on the CHIPS/client_id behavior to minimize review scope and risk.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "fix(clerk-js): Send client_id in CHIPS build" is concise and accurately describes the primary change: adding/sending the client identifier when running the CHIPS build in an iframe. It clearly communicates the main intent and is concise enough for history scanning. The phrasing is focused and appropriate for the change set described.
Linked Issues Check ✅ Passed The PR implements conditional inclusion of clientId in SignIn/SignUp/SignInFuture request bodies when BUILD_VARIANT_CHIPS && inIframe(), updates types to include clientId, and adds unit tests that assert the clientId is sent in CHIPS+iframe scenarios; these code changes directly address USER-3277's coding objective to communicate the client identifier from iframe contexts so the backend can validate OAuth requests. The provided summaries show the runtime, type, and test coverage necessary to satisfy the linked issue's requirements. Based on the provided information, the coding changes satisfy the issue's objectives.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch jr.fix/signal-iframe-in-chips

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

pkg-pr-new bot commented Sep 11, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@6758

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@6758

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@6758

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@6758

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@6758

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@6758

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@6758

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@6758

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@6758

@clerk/express

npm i https://pkg.pr.new/@clerk/express@6758

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@6758

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@6758

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@6758

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@6758

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@6758

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@6758

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@6758

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@6758

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@6758

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@6758

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@6758

@clerk/types

npm i https://pkg.pr.new/@clerk/types@6758

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@6758

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@6758

commit: e124825

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
packages/types/src/signUpCommon.ts (1)

103-106: Make the property optional for readability (already optional via Partial)

The field is inside a Partial<…>, so it’s effectively optional. For consistency with SignIn types, consider adding ?.

Apply:

-    iframeContext: boolean;
+    iframeContext?: boolean;
packages/clerk-js/src/core/resources/SignUp.ts (2)

146-149: Correctly signaling iframe context on create

Gated by BUILD_VARIANT_CHIPS and inIframe(), which matches the PR goal.

Avoid overriding a pre-set value (even if internal) by only setting when undefined:

-    if (__BUILD_VARIANT_CHIPS__ && inIframe()) {
-      finalParams.iframeContext = true;
-    }
+    if (__BUILD_VARIANT_CHIPS__ && inIframe() && finalParams.iframeContext === undefined) {
+      finalParams.iframeContext = true;
+    }

Please confirm normalizeUnsafeMetadata preserves unknown top-level keys like iframeContext.


434-442: Propagating iframe context on update as well — good coverage

Mirrors create() behavior so both create/update payloads carry the signal.

Extract a small helper to DRY this logic across create/update:

+const withIframeContext = <T extends Record<string, unknown>>(params: T): T =>
+  (__BUILD_VARIANT_CHIPS__ && inIframe() && params.iframeContext === undefined
+    ? ({ ...params, iframeContext: true } as T)
+    : params);
...
-  const finalParams = { ...params };
-  if (__BUILD_VARIANT_CHIPS__ && inIframe()) {
-    finalParams.iframeContext = true;
-  }
+  const finalParams = withIframeContext({ ...params });

Do we also need this flag when using the SignUpFuture API paths (create/sso) in CHIPS? If so, consider similar handling there.

packages/clerk-js/src/core/resources/SignIn.ts (1)

302-314: Adds iframeContext during create for OAuth flows — correct, but consider centralizing

This fixes the affected flow. To prevent future misses, consider doing this in SignIn.create() with a safe guard.

Apply:

   create = (params: SignInCreateParams): Promise<SignInResource> => {
     debugLogger.debug('SignIn.create', { id: this.id, strategy: 'strategy' in params ? params.strategy : undefined });
-    return this._basePost({
-      path: this.pathRoot,
-      body: params,
-    });
+    const body =
+      __BUILD_VARIANT_CHIPS__ &&
+      inIframe() &&
+      'strategy' in params &&
+      (params.strategy === 'saml' || params.strategy === 'enterprise_sso' || typeof params.strategy === 'string')
+        ? ({ ...params, iframeContext: true } as SignInCreateParams)
+        : params;
+    return this._basePost({ path: this.pathRoot, body });
   };

This keeps the flag constrained to strategy-based creates and avoids touching identifier-only creates.

If you prefer not to centralize, audit other create paths (e.g., web3, email_code bootstrap) to ensure the flag isn’t required there.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 54b4b5a and cb5a23f.

📒 Files selected for processing (5)
  • packages/clerk-js/src/core/resources/SignIn.ts (3 hunks)
  • packages/clerk-js/src/core/resources/SignUp.ts (3 hunks)
  • packages/types/src/signInCommon.ts (1 hunks)
  • packages/types/src/signInFuture.ts (1 hunks)
  • packages/types/src/signUpCommon.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/types/src/signInFuture.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/types/src/signUpCommon.ts
  • packages/types/src/signInCommon.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/types/src/signInFuture.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/types/src/signUpCommon.ts
  • packages/types/src/signInCommon.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/types/src/signInFuture.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/types/src/signUpCommon.ts
  • packages/types/src/signInCommon.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/types/src/signInFuture.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/types/src/signUpCommon.ts
  • packages/types/src/signInCommon.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/types/src/signInFuture.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/types/src/signUpCommon.ts
  • packages/types/src/signInCommon.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/types/src/signInFuture.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/types/src/signUpCommon.ts
  • packages/types/src/signInCommon.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
🧬 Code graph analysis (2)
packages/clerk-js/src/core/resources/SignUp.ts (1)
packages/clerk-js/src/utils/runtime.ts (1)
  • inIframe (9-19)
packages/clerk-js/src/core/resources/SignIn.ts (3)
packages/types/src/signInCommon.ts (1)
  • SignInCreateParams (123-168)
packages/clerk-js/src/utils/runtime.ts (1)
  • inIframe (9-19)
packages/types/src/signInFuture.ts (1)
  • SignInFutureCreateParams (6-16)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (5)
packages/types/src/signInFuture.ts (1)

12-15: iframeContext type surface addition looks good

Optional flag aligns with runtime usage in SignInFuture.create. Keep it marked @internal to avoid leaking in public docs.

If you generate API docs, ensure @internal is excluded by your Typedoc config so this field doesn’t appear publicly.

packages/clerk-js/src/core/resources/SignUp.ts (1)

56-56: New inIframe import — OK

Import location and usage are consistent with utils/runtime.

packages/types/src/signInCommon.ts (1)

131-135: Targeted addition for OAuth/SAML/Enterprise SSO variant — OK

Field is scoped to the variant that’s relevant for OAuth/SSO flows. Looks correct.

Double-check all call sites that construct this variant (e.g., authenticateWithRedirect/Popup) so none miss the flag.

packages/clerk-js/src/core/resources/SignIn.ts (2)

57-57: inIframe import — OK

Consistent with utils usage elsewhere.


637-646: SignInFuture.create includes iframeContext — good

Covers the programmatic future API. No further issues.

Ensure SignInFuture.sso indeed routes through this.create so the flag propagates (it does in the current code).

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (9)
.changeset/violet-badgers-change.md (1)

1-6: Tighten release note; call out CHIPS gating and linked issue

Clarify optionality and gating to reduce ambiguity in release notes and generated changelog.

Apply:

-Adding iframeContext to SignIn and SignUp params when a CHIPS build is running in an iframe context
+CHIPS: Signal iframe context for OAuth flows.
+
+- Adds optional `iframeContext` to `SignInCreateParams` and `SignUpCreateParams`.
+- Only sent when `__BUILD_VARIANT_CHIPS__` is true and `inIframe()` returns true.
+- Backwards compatible (no-op for non-CHIPS builds).
+- Fixes USER-3277.
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (4)

10-12: Avoid module-scope mutation of global build flag

Setting global.__BUILD_VARIANT_CHIPS__ at import time can leak across suites. Prefer per-test or per-beforeEach setup.

Apply:

-const originalBuildVariant = global.__BUILD_VARIANT_CHIPS__;
-global.__BUILD_VARIANT_CHIPS__ = true;
+const originalBuildVariant = global.__BUILD_VARIANT_CHIPS__;

And initialize a known default in beforeEach:

   beforeEach(() => {
     vi.clearAllMocks();
+    global.__BUILD_VARIANT_CHIPS__ = false;
   });

Finally, make CHIPS-enabled tests explicit (example for the first test):

   it('should set iframeContext to true when CHIPS build and in iframe', async () => {
+    global.__BUILD_VARIANT_CHIPS__ = true;
     vi.mocked(inIframe).mockReturnValue(true);

31-35: Use a getter spy for fapiClient to auto-restore

Object.defineProperty won’t be reset by vi.clearAllMocks(), risking leakage. Spy on the getter and restore in afterEach.

Apply:

-    Object.defineProperty(SignIn, 'fapiClient', {
-      get: () => mockFapiClient,
-      configurable: true,
-    });
+    vi.spyOn(SignIn as any, 'fapiClient', 'get').mockReturnValue(mockFapiClient);

Also restore spies:

   afterEach(() => {
     global.__BUILD_VARIANT_CHIPS__ = originalBuildVariant;
+    vi.restoreAllMocks();
   });

21-24: Remove redundant reassignment of buildUrlWithAuth

You already set buildUrlWithAuth on mockClerk. Reassigning it again is unnecessary.

Apply:

-    mockBuildUrlWithAuth = vi.fn((url: string) => `https://clerk.example.com${url}`);
-    SignIn.clerk.buildUrlWithAuth = mockBuildUrlWithAuth;
+    mockBuildUrlWithAuth = mockClerk.buildUrlWithAuth;

Also applies to: 48-50


78-85: Avoid asserting undefined properties; use partial match

Asserting keys with undefined makes tests brittle if the implementation omits the key. Prefer expect.objectContaining.

Apply:

-      expect(mockCreate).toHaveBeenCalledWith({
-        strategy: 'oauth_google',
-        identifier: '[email protected]',
-        redirectUrl: 'https://clerk.example.com/callback',
-        actionCompleteRedirectUrl: undefined,
-        iframeContext: true,
-      });
+      expect(mockCreate).toHaveBeenCalledWith(
+        expect.objectContaining({
+          strategy: 'oauth_google',
+          identifier: '[email protected]',
+          redirectUrl: 'https://clerk.example.com/callback',
+          iframeContext: true,
+        }),
+      );

Replicate this pattern for similar assertions in this file.

packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts (4)

10-12: Avoid module-scope mutation of global build flag

Match the SignIn.spec.ts pattern: don’t set CHIPS at import time; set a default in beforeEach, toggle per test.

Apply:

-const originalBuildVariant = global.__BUILD_VARIANT_CHIPS__;
-global.__BUILD_VARIANT_CHIPS__ = true;
+const originalBuildVariant = global.__BUILD_VARIANT_CHIPS__;

And in beforeEach:

   beforeEach(() => {
     vi.clearAllMocks();
+    global.__BUILD_VARIANT_CHIPS__ = false;
   });

42-46: Spy on fapiClient getter instead of redefining property

Ensures clean teardown with vi.restoreAllMocks().

Apply:

-    Object.defineProperty(SignUp, 'fapiClient', {
-      get: () => mockFapiClient,
-      configurable: true,
-    });
+    vi.spyOn(SignUp as any, 'fapiClient', 'get').mockReturnValue(mockFapiClient);

Also restore spies and static replacements:

   afterEach(() => {
     global.__BUILD_VARIANT_CHIPS__ = originalBuildVariant;
+    vi.restoreAllMocks();
   });

40-41: Restore SignUp.clerk after tests

Static assignment can leak across suites. Save original and restore in afterEach.

Apply:

-    SignUp.clerk = mockClerk as any;
+    const originalClerk = SignUp.clerk;
+    SignUp.clerk = mockClerk as any;

And:

   afterEach(() => {
     global.__BUILD_VARIANT_CHIPS__ = originalBuildVariant;
+    // Restore static
+    // @ts-expect-error test-only restoration
+    SignUp.clerk = originalClerk;
+    vi.restoreAllMocks();
   });

Also applies to: 81-83


238-250: Avoid asserting undefined properties; use partial match

Prefer partial matches over explicit undefined keys to reduce brittleness.

Apply:

-      expect(mockCreate).toHaveBeenCalledWith({
-        path: '/client/sign_ups',
-        body: {
-          strategy: 'oauth_google',
-          redirectUrl: 'https://clerk.example.com/callback',
-          actionCompleteRedirectUrl: undefined,
-          unsafeMetadata: undefined,
-          emailAddress: undefined,
-          legalAccepted: undefined,
-          oidcPrompt: undefined,
-          iframeContext: true,
-        },
-      });
+      expect(mockCreate).toHaveBeenCalledWith({
+        path: '/client/sign_ups',
+        body: expect.objectContaining({
+          strategy: 'oauth_google',
+          redirectUrl: 'https://clerk.example.com/callback',
+          iframeContext: true,
+        }),
+      });

Replicate for the update flow below.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between cb5a23f and f59c43e.

📒 Files selected for processing (3)
  • .changeset/violet-badgers-change.md (1 hunks)
  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (1 hunks)
  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
packages/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Unit tests should use Jest or Vitest as the test runner.

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Visual regression testing should be performed for UI components.

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
**/__tests__/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)

**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
.changeset/**

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/violet-badgers-change.md
🧬 Code graph analysis (2)
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts (1)
packages/clerk-js/src/utils/runtime.ts (1)
  • inIframe (9-19)
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (1)
packages/clerk-js/src/utils/runtime.ts (1)
  • inIframe (9-19)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (25)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
  • GitHub Check: Static analysis
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (11)
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (11)

10-12: Avoid module-scoped mutation of BUILD_VARIANT_CHIPS (order-dependent tests).

Setting the flag at module load makes test outcomes depend on execution order. Prefer per-test or per-suite setup.

Apply this diff to stop setting it at module scope:

- (globalThis as any).__BUILD_VARIANT_CHIPS__ = true;
+ // Set __BUILD_VARIANT_CHIPS__ explicitly in beforeEach or per test

18-20: Set the CHIPS flag in beforeEach for deterministic defaults.

Ensure every test starts from the same baseline; tests that need a different value can override locally.

   beforeEach(() => {
     vi.clearAllMocks();
+    (globalThis as any).__BUILD_VARIANT_CHIPS__ = true;
   });

14-17: Prevent static leakage: capture originals to restore after the suite.

Stubbing SignIn.clerk and the fapiClient getter without restoring can leak across suites.

   let signIn: SignIn;
   let mockCreate: any;
-  let mockBuildUrlWithAuth: any;
+  let mockBuildUrlWithAuth: any;
+
+  // Capture originals to restore after the suite
+  const originalClerk = SignIn.clerk;
+  const originalFapiDescriptor = Object.getOwnPropertyDescriptor(SignIn, 'fapiClient');

52-55: Restore globals and statics after the suite.

Complements the per-test setup and avoids cross-file interference.

   afterEach(() => {
     (globalThis as any).__BUILD_VARIANT_CHIPS__ = originalBuildVariant;
   });
+
+  afterAll(() => {
+    // Restore SignIn statics
+    SignIn.clerk = originalClerk as any;
+    if (originalFapiDescriptor) {
+      Object.defineProperty(SignIn, 'fapiClient', originalFapiDescriptor);
+    } else {
+      // Ensure we don't leave a test-only getter behind
+      // eslint-disable-next-line @typescript-eslint/no-explicit-any
+      delete (SignIn as any).fapiClient;
+    }
+  });

21-35: Minor: prefer vi.stubGlobal for globals, and vi.restoreAllMocks for spies.

Not mandatory, but vi.stubGlobal/vi.unstubAllGlobals provide cleaner lifecycle for globals, and restoreAllMocks reverts spy replacements (beyond clearAllMocks).


48-50: Drop redundant reassignment of buildUrlWithAuth.

You already set SignIn.clerk in beforeEach; reassigning buildUrlWithAuth here is unnecessary and can trip ESLint (unused variable).

-  mockBuildUrlWithAuth = vi.fn((url: string) => `https://clerk.example.com${url}`);
-  SignIn.clerk.buildUrlWithAuth = mockBuildUrlWithAuth;
+  // buildUrlWithAuth already mocked via mockClerk above

56-85: Make the expectation resilient; avoid asserting undefined keys.

Asserting actionCompleteRedirectUrl: undefined is brittle if the implementation omits undefined fields. Use objectContaining and assert iframeContext specifically.

-      expect(mockCreate).toHaveBeenCalledWith({
-        strategy: 'oauth_google',
-        identifier: '[email protected]',
-        redirectUrl: 'https://clerk.example.com/callback',
-        actionCompleteRedirectUrl: undefined,
-        iframeContext: true,
-      });
+      expect(mockCreate).toHaveBeenCalledWith(
+        expect.objectContaining({
+          strategy: 'oauth_google',
+          identifier: '[email protected]',
+          redirectUrl: 'https://clerk.example.com/callback',
+          iframeContext: true,
+        }),
+      );
+      // Optional: assert navigation target if applicable in this path
+      // expect(mockNavigate).toHaveBeenCalledWith('https://oauth.provider.com/auth');

87-116: Clarify test intent and reduce false positives.

Explicitly set CHIPS=true so this test validates the “not in iframe” condition rather than passing because CHIPS might be falsy from a prior test. Also avoid asserting undefined keys.

     it('should not set iframeContext when not in iframe', async () => {
-      vi.mocked(inIframe).mockReturnValue(false);
+      vi.mocked(inIframe).mockReturnValue(false);
+      (globalThis as any).__BUILD_VARIANT_CHIPS__ = true;
@@
-      expect(mockCreate).toHaveBeenCalledWith({
-        strategy: 'oauth_google',
-        identifier: '[email protected]',
-        redirectUrl: 'https://clerk.example.com/callback',
-        actionCompleteRedirectUrl: undefined,
-      });
+      expect(mockCreate).toHaveBeenCalledWith(
+        expect.objectContaining({
+          strategy: 'oauth_google',
+          identifier: '[email protected]',
+          redirectUrl: 'https://clerk.example.com/callback',
+        }),
+      );
       expect(mockCreate).toHaveBeenCalledWith(expect.not.objectContaining({ iframeContext: true }));

117-141: Optional: also assert redirectUrl building under non-CHIPS.

Verifies we still use Clerk’s URL builder regardless of CHIPS.

       await signIn.authenticateWithRedirectOrPopup(params, mockNavigate);
 
       expect(mockCreate).toHaveBeenCalledWith(expect.not.objectContaining({ iframeContext: true }));
+      expect(mockCreate).toHaveBeenCalledWith(
+        expect.objectContaining({ redirectUrl: 'https://clerk.example.com/callback' }),
+      );

143-167: Strengthen “continueSignIn” behavior check.

Also assert that navigation occurs to the provider URL, since create is skipped.

       await signIn.authenticateWithRedirectOrPopup(params, mockNavigate);
 
       expect(mockCreate).not.toHaveBeenCalled();
+      expect(mockNavigate).toHaveBeenCalledWith('https://oauth.provider.com/auth');

198-223: Clarify test baseline for Future path (set CHIPS).

Not required for correctness here, but setting CHIPS=true removes any ambiguity about why iframeContext is omitted.

     it('should not set iframeContext when not in iframe', async () => {
-      vi.mocked(inIframe).mockReturnValue(false);
+      vi.mocked(inIframe).mockReturnValue(false);
+      (globalThis as any).__BUILD_VARIANT_CHIPS__ = true;
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f59c43e and ff88ba4.

📒 Files selected for processing (2)
  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (1 hunks)
  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/clerk-js/src/core/resources/tests/SignUp.spec.ts
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
packages/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Unit tests should use Jest or Vitest as the test runner.

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Visual regression testing should be performed for UI components.

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
**/__tests__/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)

**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
🧬 Code graph analysis (1)
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (1)
packages/clerk-js/src/utils/runtime.ts (1)
  • inIframe (9-19)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (2)

6-8: Mocking inIframe is clean and focused.

Good isolation of the runtime check; keeps tests deterministic.


169-196: LGTM: Future path sets iframeContext correctly under CHIPS+iframe.

Good coverage of the internal basePost payload.

Comment on lines 309 to 311
if (__BUILD_VARIANT_CHIPS__ && inIframe()) {
createParams.iframeContext = true;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the core change. When in CHIPS build and running in an iframe we want to send extra params to FAPI that indicate we are using partitioned cookies in an iframe. FAPI will skip validating the client_id in this scenario

Comment on lines 639 to 641
if (__BUILD_VARIANT_CHIPS__ && inIframe()) {
createParams.iframeContext = true;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above, this is the core logical change

Comment on lines 146 to 148
if (__BUILD_VARIANT_CHIPS__ && inIframe()) {
finalParams.iframeContext = true;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as the SignIn change

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
packages/types/src/signInCommon.ts (1)

131-134: Confirm scope: sessionId only on SSO/OAuth branch by design

If backend needs iframe context only for OAuth/SAML/EnterpriseSSO, this is fine. If other strategies may also flow through the same validation, consider broadening. At minimum, make the intent explicit in docs.

Doc tweak (optional):

       /**
-       * @internal Used to identify the session making the request in iframe context.
+       * @internal Used to identify the session making the request in iframe context.
+       * Set internally by the CHIPS build; intentionally exposed only on SSO/OAuth-like strategies.
        */
       sessionId?: string;
packages/types/src/signUpCommon.ts (1)

103-106: Mirror internal-only wording; discourage manual setting

Align doc text with SignIn to reduce accidental external usage.

Apply:

     /**
-     * @internal Used to identify the session making the request in iframe context.
+     * @internal Used to identify the session making the request in iframe context.
+     * Do not set manually—this is set by the CHIPS build when embedded in an iframe.
      */
     sessionId?: string;
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 5158344 and a4feabd.

📒 Files selected for processing (7)
  • packages/clerk-js/src/core/resources/SignIn.ts (3 hunks)
  • packages/clerk-js/src/core/resources/SignUp.ts (3 hunks)
  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (1 hunks)
  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts (1 hunks)
  • packages/types/src/signInCommon.ts (1 hunks)
  • packages/types/src/signInFuture.ts (1 hunks)
  • packages/types/src/signUpCommon.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/clerk-js/src/core/resources/tests/SignIn.spec.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/clerk-js/src/core/resources/tests/SignUp.spec.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/types/src/signUpCommon.ts
  • packages/types/src/signInCommon.ts
  • packages/types/src/signInFuture.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/types/src/signUpCommon.ts
  • packages/types/src/signInCommon.ts
  • packages/types/src/signInFuture.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/types/src/signUpCommon.ts
  • packages/types/src/signInCommon.ts
  • packages/types/src/signInFuture.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/types/src/signUpCommon.ts
  • packages/types/src/signInCommon.ts
  • packages/types/src/signInFuture.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/types/src/signUpCommon.ts
  • packages/types/src/signInCommon.ts
  • packages/types/src/signInFuture.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/types/src/signUpCommon.ts
  • packages/types/src/signInCommon.ts
  • packages/types/src/signInFuture.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
packages/types/src/signInFuture.ts (1)

12-15: Make internal-only intent explicit

Doc tweak below; runtime verified — sessionId is overridden from BaseResource.clerk.session?.id only when BUILD_VARIANT_CHIPS && inIframe(), and caller-provided values are ignored otherwise.

   /**
-  * @internal Used to identify the session making the request in iframe context.
+  * @internal Used to identify the session making the request in iframe context.
+  * Do not set manually—this is set by the CHIPS build when embedded in an iframe.
   */
  sessionId?: string;

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (7)
packages/clerk-js/src/core/resources/SignIn.ts (1)

302-314: Avoid scattering iframe clientId injection; centralize in SignIn.create

Right now, clientId is injected here and in SignInFuture.create, but not in SignIn.create. A direct OAuth call to signIn.create(...) outside this path would miss the signal. Centralize the injection inside SignIn.create to cover all paths and remove duplication.

Apply:

   create = (params: SignInCreateParams): Promise<SignInResource> => {
     debugLogger.debug('SignIn.create', { id: this.id, strategy: 'strategy' in params ? params.strategy : undefined });
-    return this._basePost({
-      path: this.pathRoot,
-      body: params,
-    });
+    const finalParams =
+      __BUILD_VARIANT_CHIPS__ && inIframe()
+        ? { ...params, clientId: BaseResource.clerk.client?.id }
+        : params;
+    return this._basePost({
+      path: this.pathRoot,
+      body: finalParams,
+    });
   };

Optionally, extract a tiny helper withIframeClientId(params) to DRY this and the SignInFuture.create site.

packages/clerk-js/src/core/resources/SignUp.ts (3)

146-149: Only set clientId when present to avoid sending undefined

Minor: guard assignment to avoid clientId: undefined landing in the serialized body (even if JSON.stringify drops it, best to avoid).

-    if (__BUILD_VARIANT_CHIPS__ && inIframe()) {
-      finalParams.clientId = BaseResource.clerk.client?.id;
-    }
+    if (__BUILD_VARIANT_CHIPS__ && inIframe()) {
+      const cid = BaseResource.clerk.client?.id;
+      if (cid) finalParams.clientId = cid;
+    }

433-442: Mirror the same guard in update

Apply the same defined‑value check when augmenting finalParams in update().

-    if (__BUILD_VARIANT_CHIPS__ && inIframe()) {
-      finalParams.clientId = BaseResource.clerk.client?.id;
-    }
+    if (__BUILD_VARIANT_CHIPS__ && inIframe()) {
+      const cid = BaseResource.clerk.client?.id;
+      if (cid) finalParams.clientId = cid;
+    }

684-697: SignUpFuture.sso path also needs iframe client signal

The future SSO flow posts directly and currently omits clientId. Add it under CHIPS+iframe for parity with create/update and to cover OAuth in future flows.

       await this.resource.__internal_basePost({
         path: this.resource.pathRoot,
-        body: {
+        body: {
           strategy,
           redirectUrl: SignUp.clerk.buildUrlWithAuth(redirectCallbackUrl),
           redirectUrlComplete: redirectUrl,
           captchaToken,
           captchaWidgetType,
           captchaError,
-        },
+          ...( __BUILD_VARIANT_CHIPS__ && inIframe()
+              ? { clientId: BaseResource.clerk.client?.id }
+              : {} ),
+        },
       });

Add unit tests for this path mirroring the create/update expectations.

packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts (3)

222-304: Add coverage for SignUpFuture.sso

Future SSO posts bypass create/update. Add tests to assert clientId presence under CHIPS+iframe and absence otherwise.

I can draft the vitest cases if helpful.


20-53: Prevent global leakage of mocked statics

We mutate SignUp.clerk and BaseResource.clerk but don’t restore them. Capture previous values in beforeEach and restore in afterEach to avoid cross‑test contamination.

   beforeEach(() => {
     vi.clearAllMocks();
+    prevSignUpClerk = SignUp.clerk;
+    prevBaseClerk = BaseResource.clerk;
@@
     SignUp.clerk = mockClerk as any;
     // Mock BaseResource.clerk for client ID access
     BaseResource.clerk = mockClerk as any;
   });
 
   afterEach(() => {
     global.__BUILD_VARIANT_CHIPS__ = originalBuildVariant;
+    SignUp.clerk = prevSignUpClerk as any;
+    BaseResource.clerk = prevBaseClerk as any;
   });

Declare at top:

let prevSignUpClerk: unknown;
let prevBaseClerk: unknown;

14-114: Nit: test names say “set clientId to true”

They actually assert specific id value. Consider renaming to “includes clientId when CHIPS build and in iframe”.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a4feabd and 44e5eaa.

📒 Files selected for processing (9)
  • packages/clerk-js/src/core/resources/SignIn.ts (3 hunks)
  • packages/clerk-js/src/core/resources/SignUp.ts (3 hunks)
  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (1 hunks)
  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts (1 hunks)
  • packages/clerk-js/src/ui/elements/Action/ActionTrigger.tsx (1 hunks)
  • packages/clerk-js/src/ui/router/BaseRouter.tsx (1 hunks)
  • packages/types/src/signInCommon.ts (1 hunks)
  • packages/types/src/signInFuture.ts (1 hunks)
  • packages/types/src/signUpCommon.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/clerk-js/src/ui/elements/Action/ActionTrigger.tsx
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/types/src/signInCommon.ts
  • packages/types/src/signUpCommon.ts
  • packages/clerk-js/src/core/resources/tests/SignIn.spec.ts
🧰 Additional context used
📓 Path-based instructions (12)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/types/src/signInFuture.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/clerk-js/src/ui/router/BaseRouter.tsx
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/types/src/signInFuture.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/clerk-js/src/ui/router/BaseRouter.tsx
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/types/src/signInFuture.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/clerk-js/src/ui/router/BaseRouter.tsx
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/types/src/signInFuture.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/clerk-js/src/ui/router/BaseRouter.tsx
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/types/src/signInFuture.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/clerk-js/src/ui/router/BaseRouter.tsx
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/types/src/signInFuture.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/clerk-js/src/ui/router/BaseRouter.tsx
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
packages/clerk-js/src/ui/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/clerk-js-ui.mdc)

packages/clerk-js/src/ui/**/*.{ts,tsx}: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure

Files:

  • packages/clerk-js/src/ui/router/BaseRouter.tsx
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/clerk-js/src/ui/router/BaseRouter.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/react.mdc)

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/clerk-js/src/ui/router/BaseRouter.tsx
packages/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Unit tests should use Jest or Vitest as the test runner.

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Visual regression testing should be performed for UI components.

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
**/__tests__/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)

**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
🧬 Code graph analysis (3)
packages/clerk-js/src/core/resources/SignUp.ts (1)
packages/clerk-js/src/utils/runtime.ts (1)
  • inIframe (9-21)
packages/clerk-js/src/ui/router/BaseRouter.tsx (1)
packages/types/src/clerk.ts (1)
  • NavigateOptions (1107-1110)
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts (2)
packages/clerk-js/src/core/resources/SignUp.ts (1)
  • SignUp (72-541)
packages/clerk-js/src/utils/runtime.ts (1)
  • inIframe (9-21)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (8)
packages/clerk-js/src/ui/router/BaseRouter.tsx (2)

118-121: Confirm RouterMetadata shape

We pass { metadata: { navigationType: 'internal' } }. Ensure RouterMetadata allows navigationType or adjust to the canonical keys.


17-17: Type narrowing: ensure all internalNavigate providers are async

BaseRouter.internalNavigate now returns a Promise (packages/clerk-js/src/ui/router/BaseRouter.tsx:17). Repository search for JSX props and object providers returned no hits — verify all BaseRouter instantiations, factories, adapters and platform-specific forks and update any sync providers to return a Promise (mark async or wrap with Promise.resolve()).

packages/types/src/signInFuture.ts (1)

12-16: Addition of clientId?: string looks good

Matches the CHIPS+iframe requirement and is marked @internal. Keep docs consistent with corresponding SignIn/SignUp params.

Confirm the same optional field exists on:

  • SignInCreateParams
  • SignUpCreateParams
packages/clerk-js/src/core/resources/SignIn.ts (2)

57-58: Runtime guard import is appropriate

Using inIframe() gated by __BUILD_VARIANT_CHIPS__ is the right boundary for CHIPS behavior.


637-646: LGTM on SignInFuture.create augmentation

Cloning and conditionally attaching clientId is correct and side‑effect free.

packages/clerk-js/src/core/resources/SignUp.ts (1)

39-40: Import is correct

Using inIframe here aligns SignUp with SignIn behavior.

packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts (2)

92-156: Create-path tests: assertions look solid

Positive and negative cases correctly check body.clientId. Good coverage for CHIPS/inIframe toggles.


158-220: Update-path tests: assertions look solid

Mirrors create-path checks; nice.

@jacekradko jacekradko changed the title fix(clerk-js): Signal iframe context in CHIPS build fix(clerk-js): Send client_id in CHIPS build Sep 16, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
packages/clerk-js/src/ui/router/PathRouter.tsx (2)

24-27: Signature alignment looks good; prefer stable callback and a narrower return type if possible.

  • Wrap with useCallback so internalNavigate identity is stable.
  • If BaseRouter accepts it, prefer Promise<void> over Promise<any> to avoid any.
-  const internalNavigate = async (toURL: URL, options?: NavigateOptions): Promise<any> => {
-    // Only send the path
-    return navigate(stripOrigin(toURL), options);
-  };
+  const internalNavigate = React.useCallback(
+    async (toURL: URL, options?: NavigateOptions): Promise<any> => {
+      // Only send the path
+      return navigate(stripOrigin(toURL), options);
+    },
+    [navigate],
+  );

37-46: Avoid window.location.hash in deps; either run once on mount or subscribe to hashchange.

Including window.location.hash in the deps array doesn’t react to hash changes (no render is triggered) and can upset SSR. Either:

  • Minimal: run once on mount (matches current behavior) and silence the linter, or
  • Robust: add a hashchange listener and call convertHashToPath on change.

Minimal change:

-  React.useEffect(() => {
+  React.useEffect(() => {
     const convertHashToPath = async () => {
       if (hasUrlInFragment(window.location.hash)) {
         const url = mergeFragmentIntoUrl(new URL(window.location.href));
         await internalNavigate(url, { replace: true });
         setStripped(true);
       }
     };
     void convertHashToPath();
-  }, [setStripped, navigate, window.location.hash]);
+    // We only need to strip once on mount
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, []);

Robust alternative (if you want to handle hash mutations after mount):

-  React.useEffect(() => {
-    const convertHashToPath = async () => {
-      if (hasUrlInFragment(window.location.hash)) {
-        const url = mergeFragmentIntoUrl(new URL(window.location.href));
-        await internalNavigate(url, { replace: true });
-        setStripped(true);
-      }
-    };
-    void convertHashToPath();
-  }, [setStripped, navigate, window.location.hash]);
+  React.useEffect(() => {
+    const convertHashToPath = async () => {
+      if (hasUrlInFragment(window.location.hash)) {
+        const url = mergeFragmentIntoUrl(new URL(window.location.href));
+        await internalNavigate(url, { replace: true });
+        setStripped(true);
+      }
+    };
+    const onHashChange = () => void convertHashToPath();
+    window.addEventListener('hashchange', onHashChange);
+    void convertHashToPath();
+    return () => window.removeEventListener('hashchange', onHashChange);
+  }, [internalNavigate, setStripped]);
packages/clerk-js/src/core/resources/SignIn.ts (2)

680-689: Mirror the clientId guard in Future.create

Same concern: don’t include an undefined clientId; align on SignIn.clerk accessor.

Apply this diff:

-      if (__BUILD_VARIANT_CHIPS__ && inIframe()) {
-        createParams.clientId = BaseResource.clerk.client?.id;
-      }
+      if (__BUILD_VARIANT_CHIPS__ && inIframe()) {
+        const clientId = SignIn.clerk.client?.id;
+        if (clientId) {
+          createParams.clientId = clientId;
+        }
+      }

Optional follow‑up: extract a small helper (e.g., attachIframeClientId<T extends { clientId?: string }>(p: T): T) and reuse in both sites (and SignUp) to avoid drift.


313-325: Only attach clientId when defined; use SignIn.clerk

Avoid sending clientId: undefined and prefer SignIn.clerk for consistency. Apply the same change at the other occurrence in SignIn.ts.

-      if (__BUILD_VARIANT_CHIPS__ && inIframe()) {
-        createParams.clientId = BaseResource.clerk.client?.id;
-      }
+      if (__BUILD_VARIANT_CHIPS__ && inIframe()) {
+        const clientId = SignIn.clerk.client?.id;
+        if (clientId) {
+          createParams.clientId = clientId;
+        }
+      }

Locations: packages/clerk-js/src/core/resources/SignIn.ts (around lines ~320 and ~683). Verified: BUILD_VARIANT_CHIPS declared in packages/clerk-js/global.d.ts and set in vitest.config.mts / rspack.config.js / jest.config.js (tests also toggle it).

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 44e5eaa and 9cef617.

📒 Files selected for processing (5)
  • packages/clerk-js/src/core/resources/SignIn.ts (3 hunks)
  • packages/clerk-js/src/core/resources/SignUp.ts (3 hunks)
  • packages/clerk-js/src/ui/router/PathRouter.tsx (2 hunks)
  • packages/clerk-js/src/ui/router/VirtualRouter.tsx (2 hunks)
  • packages/types/src/signInFuture.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/types/src/signInFuture.ts
🧰 Additional context used
📓 Path-based instructions (9)
packages/clerk-js/src/ui/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/clerk-js-ui.mdc)

packages/clerk-js/src/ui/**/*.{ts,tsx}: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure

Files:

  • packages/clerk-js/src/ui/router/VirtualRouter.tsx
  • packages/clerk-js/src/ui/router/PathRouter.tsx
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/clerk-js/src/ui/router/VirtualRouter.tsx
  • packages/clerk-js/src/ui/router/PathRouter.tsx
  • packages/clerk-js/src/core/resources/SignIn.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/ui/router/VirtualRouter.tsx
  • packages/clerk-js/src/ui/router/PathRouter.tsx
  • packages/clerk-js/src/core/resources/SignIn.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/router/VirtualRouter.tsx
  • packages/clerk-js/src/ui/router/PathRouter.tsx
  • packages/clerk-js/src/core/resources/SignIn.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/ui/router/VirtualRouter.tsx
  • packages/clerk-js/src/ui/router/PathRouter.tsx
  • packages/clerk-js/src/core/resources/SignIn.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/clerk-js/src/ui/router/VirtualRouter.tsx
  • packages/clerk-js/src/ui/router/PathRouter.tsx
  • packages/clerk-js/src/core/resources/SignIn.ts
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/clerk-js/src/ui/router/VirtualRouter.tsx
  • packages/clerk-js/src/ui/router/PathRouter.tsx
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/ui/router/VirtualRouter.tsx
  • packages/clerk-js/src/ui/router/PathRouter.tsx
  • packages/clerk-js/src/core/resources/SignIn.ts
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/react.mdc)

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/clerk-js/src/ui/router/VirtualRouter.tsx
  • packages/clerk-js/src/ui/router/PathRouter.tsx
🧬 Code graph analysis (3)
packages/clerk-js/src/ui/router/VirtualRouter.tsx (1)
packages/types/src/clerk.ts (1)
  • NavigateOptions (1107-1110)
packages/clerk-js/src/ui/router/PathRouter.tsx (1)
packages/types/src/clerk.ts (1)
  • NavigateOptions (1107-1110)
packages/clerk-js/src/core/resources/SignIn.ts (3)
packages/types/src/signInCommon.ts (1)
  • SignInCreateParams (123-168)
packages/clerk-js/src/utils/runtime.ts (1)
  • inIframe (9-21)
packages/types/src/signInFuture.ts (1)
  • SignInFutureCreateParams (7-17)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (3)
packages/clerk-js/src/ui/router/VirtualRouter.tsx (2)

2-2: Type‑only import is correct and keeps bundles lean.

Using import type avoids runtime code and aligns with TS best practices.


44-47: Stabilize internalNavigate with useCallback and align its return type with BaseRouter

  • Wrap the handler in React.useCallback and drop the redundant Promise.resolve(); keep the function body as a plain async (or return nothing) to avoid extra allocations.
  • BaseRouter currently types internalNavigate as (toURL: URL, options?: NavigateOptions) => Promise — packages/clerk-js/src/ui/router/BaseRouter.tsx:17. Either keep Promise on VirtualRouter to match, or update BaseRouter (and any implementations) before changing the signature to Promise.
  • If ESLint flags the unused _options, silence it with void _options; or rely on the leading underscore.
packages/clerk-js/src/core/resources/SignIn.ts (1)

59-59: SSR‑safe iframe detection import — LGTM

Importing inIframe from the runtime utilities is appropriate and remains SSR‑safe due to the internal inBrowser() guard.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (9)
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (9)

11-13: Avoid module-scope mutation of the CHIPS flag

Setting __BUILD_VARIANT_CHIPS__ at import time can leak state across test files. Move this into beforeEach and restore it in afterEach.

-const originalBuildVariant = (globalThis as any).__BUILD_VARIANT_CHIPS__;
-(globalThis as any).__BUILD_VARIANT_CHIPS__ = true;
+let originalBuildVariant: unknown;

And update lifecycle hooks:

   beforeEach(() => {
-    vi.clearAllMocks();
+    vi.clearAllMocks();
+    originalBuildVariant = (globalThis as any).__BUILD_VARIANT_CHIPS__;
+    (globalThis as any).__BUILD_VARIANT_CHIPS__ = true;
   });
 
   afterEach(() => {
-    (globalThis as any).__BUILD_VARIANT_CHIPS__ = originalBuildVariant;
+    (globalThis as any).__BUILD_VARIANT_CHIPS__ = originalBuildVariant;
   });

20-21: Reset mocked implementation, not only calls

vi.clearAllMocks() clears calls but preserves return values. Add a reset for inIframe to prevent leakage between tests.

   beforeEach(() => {
     vi.clearAllMocks();
+    vi.mocked(inIframe).mockReset();
   });

33-41: Restore patched statics to avoid cross-test pollution

You patch SignIn.clerk, BaseResource.clerk, and redefine SignIn.fapiClient but never restore them. Capture originals and restore in afterEach.

+let originalSignInClerk: unknown;
+let originalBaseResourceClerk: unknown;
+const originalFapiDescriptor = Object.getOwnPropertyDescriptor(SignIn, 'fapiClient');
+
   beforeEach(() => {
     vi.clearAllMocks();
+    originalSignInClerk = SignIn.clerk;
+    originalBaseResourceClerk = BaseResource.clerk;
     ...
     SignIn.clerk = mockClerk as any;
     // Mock BaseResource.clerk for client ID access
     BaseResource.clerk = mockClerk as any;
     Object.defineProperty(SignIn, 'fapiClient', {
       get: () => mockFapiClient,
       configurable: true,
     });
   });
 
   afterEach(() => {
     (globalThis as any).__BUILD_VARIANT_CHIPS__ = originalBuildVariant;
+    SignIn.clerk = originalSignInClerk as any;
+    BaseResource.clerk = originalBaseResourceClerk as any;
+    if (originalFapiDescriptor) {
+      Object.defineProperty(SignIn, 'fapiClient', originalFapiDescriptor);
+    }
   });

Also applies to: 59-61


64-64: Clarify test name

It’s setting clientId to the Clerk client id, not “to true”.

-it('should set clientId to true when CHIPS build and in iframe', async () => {
+it('should include clientId when CHIPS build and in an iframe', async () => {

85-91: Make expectation resilient to omitted undefined fields

Matching actionCompleteRedirectUrl: undefined is brittle if the implementation omits the key. Use objectContaining and drop the undefined field.

-      expect(mockCreate).toHaveBeenCalledWith({
-        strategy: 'oauth_google',
-        identifier: '[email protected]',
-        redirectUrl: 'https://clerk.example.com/callback',
-        actionCompleteRedirectUrl: undefined,
-        clientId: 'test-client-id',
-      });
+      expect(mockCreate).toHaveBeenCalledWith(
+        expect.objectContaining({
+          strategy: 'oauth_google',
+          identifier: '[email protected]',
+          redirectUrl: 'https://clerk.example.com/callback',
+          clientId: 'test-client-id',
+        }),
+      );

83-84: Also assert navigation to the provider URL

Verifies the primary side effect when verification is unverified.

       await signIn.authenticateWithRedirectOrPopup(params, mockNavigate);
 
+      expect(mockNavigate).toHaveBeenCalledWith('https://oauth.provider.com/auth');

115-121: Same resilience for the non-iframe case

Avoid asserting on an explicitly undefined field.

-      expect(mockCreate).toHaveBeenCalledWith({
-        strategy: 'oauth_google',
-        identifier: '[email protected]',
-        redirectUrl: 'https://clerk.example.com/callback',
-        actionCompleteRedirectUrl: undefined,
-      });
+      expect(mockCreate).toHaveBeenCalledWith(
+        expect.objectContaining({
+          strategy: 'oauth_google',
+          identifier: '[email protected]',
+          redirectUrl: 'https://clerk.example.com/callback',
+        }),
+      );

177-177: Clarify test name

Same wording nit as above.

-it('should set clientId to true when CHIPS build and in iframe', async () => {
+it('should include clientId when CHIPS build and in an iframe', async () => {

52-57: Prefer spying over method reassignment

vi.spyOn(signIn, 'create') preserves prototype behavior and is easier to restore.

-    mockCreate = vi.fn().mockResolvedValue({});
-    signIn.create = mockCreate;
+    mockCreate = vi.spyOn(signIn as any, 'create').mockResolvedValue({});
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9cef617 and e124825.

📒 Files selected for processing (2)
  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (1 hunks)
  • packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/clerk-js/src/core/resources/tests/SignUp.spec.ts
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
packages/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Unit tests should use Jest or Vitest as the test runner.

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Visual regression testing should be performed for UI components.

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
**/__tests__/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)

**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces

Files:

  • packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
🧬 Code graph analysis (1)
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (2)
packages/clerk-js/src/core/resources/SignIn.ts (1)
  • SignIn (93-552)
packages/clerk-js/src/utils/runtime.ts (1)
  • inIframe (9-21)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (1)

1-231: Overall: solid coverage and correct assertions for CHIPS + iframe behavior

The tests capture the clientId propagation paths for both authenticateWithRedirectOrPopup and SignInFuture.create and validate redirect URL building. With the small robustness and hygiene tweaks above, this looks good.

@jacekradko jacekradko marked this pull request as draft September 16, 2025 21:10
@jacekradko
Copy link
Member Author

Converted this back to draft as I don't think this can be securely implemented from the client-facing SDKs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants