Skip to content

Conversation

@wobsoriano
Copy link
Member

@wobsoriano wobsoriano commented Aug 14, 2025

Description

Please see this notion doc for the updated namespace.

Rename M2M namespace from m2mTokens to m2m in Backend API client

Before:

clerkClient.m2mTokens.create()

clerkClient.m2mTokens.revoke()

clerkClient.m2mTokens.verifySecret({ secret: 'ak_xxx' })

After:

clerkClient.m2m.createToken()

clerkClient.m2m.revokeToken()

clerkClient.m2m.verifyToken({ token: 'ak_xxx' })

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

  • Refactor
    • Renamed the M2M API namespace from m2mTokens to m2m.
    • Renamed methods: create → createToken, revoke → revokeToken; verifyToken now accessed via m2m.
    • Removed deprecated verifySecret flow and its associated deprecated route.
  • Tests
    • Updated tests to use m2m.createToken, m2m.revokeToken, and m2m.verifyToken.
    • Adjusted test authorization flows to align with the new API surface.

@changeset-bot
Copy link

changeset-bot bot commented Aug 14, 2025

🦋 Changeset detected

Latest commit: 6e76cf7

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

This PR includes changesets to release 11 packages
Name Type
@clerk/backend Minor
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing 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

@vercel
Copy link

vercel bot commented Aug 14, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Preview Comment Aug 14, 2025 1:49am

@pkg-pr-new
Copy link

pkg-pr-new bot commented Aug 14, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 6e76cf7

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 14, 2025

📝 Walkthrough

Walkthrough

Public API namespace renamed from m2mTokens to m2m across backend client, endpoints, and tests. Method names changed: create → createToken, revoke → revokeToken; verifyToken moved to the new namespace and continues to accept a token (and optional machineSecretKey). The deprecated verifySecret method and its related endpoint/route were removed. Factory now exports m2m instead of m2mTokens. Tests and internal verification callers were updated to the new method names and paths. No other behavioral changes.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 1

🔭 Outside diff range comments (3)
packages/backend/src/api/factory.ts (1)

75-82: Keep the m2mTokens alias for backward-compatibility

We found m2mTokens referenced in several packages’ CHANGELOG.md files, so adding a deprecated alias will avoid breaking downstream users:

• File to update: packages/backend/src/api/factory.ts
• Add a single shared instance for both keys and alias it:

@@ createBackendApiClient(options) {
-  m2m: new M2MTokenApi(
-    buildRequest({
-      ...options,
-      skipApiVersionInUrl: true,
-      requireSecretKey: false,
-      useMachineSecretKey: true,
-    }),
-  ),
+  // primary export
+  m2m: m2mApi,
+  /** @deprecated Use `m2m` instead. Will be removed in a future major release. */
+  m2mTokens: m2mApi,
}

@@ before return
-    m2m: new M2MTokenApi(
-      buildRequest({ ...options, skipApiVersionInUrl: true, requireSecretKey: false, useMachineSecretKey: true }),
-    ),
+  const m2mApi = new M2MTokenApi(
+    buildRequest({ ...options, skipApiVersionInUrl: true, requireSecretKey: false, useMachineSecretKey: true }),
+  );

This preserves existing clerkClient.m2mTokens.* calls while steering users toward the new m2m key.

packages/backend/src/api/endpoints/M2MTokenApi.ts (2)

60-76: Add explicit return type and JSDoc for the public API method createToken

Per the repo’s TS guidelines, public APIs should have explicit return types and JSDoc. Also consider exporting the input type so users can import it.

-  async createToken(params?: CreateM2MTokenParams) {
+  /**
+   * Create a new M2M token.
+   */
+  async createToken(params?: CreateM2MTokenParams): Promise<M2MToken> {
     const { claims = null, machineSecretKey, secondsUntilExpiration = null } = params || {};

Optional (outside this hunk):

  • Export input types for consumers:
export type CreateM2MTokenParams = { /* ... */ }
  • Ensure barrel re-exports if applicable (e.g., from './endpoints').

78-95: Add explicit return type and harden header merging in revokeToken

Return type should be explicit. Additionally, while not in this hunk, #createRequestOptions spreads options.headerParams which can be undefined; guard with nullish coalescing to avoid runtime TypeErrors.

-  async revokeToken(params: RevokeM2MTokenParams) {
+  async revokeToken(params: RevokeM2MTokenParams): Promise<M2MToken> {
     const { m2mTokenId, revocationReason = null, machineSecretKey } = params;

Outside this hunk (reference Lines 50-53):

-        headerParams: {
-          ...options.headerParams,
-          Authorization: `Bearer ${machineSecretKey}`,
-        },
+        headerParams: {
+          ...(options.headerParams ?? {}),
+          Authorization: `Bearer ${machineSecretKey}`,
+        },

Also consider adding JSDoc for this public method for consistency with the guidelines.

♻️ Duplicate comments (1)
integration/tests/machine-auth/m2m.test.ts (1)

83-86: Duplicate of prior suggestion on DRYing expiration value

Same note as above regarding extracting a constant for 30 minutes.

🧹 Nitpick comments (4)
packages/backend/src/api/__tests__/M2MTokenApi.test.ts (1)

68-71: LGTM: createToken with explicit machineSecretKey

Covers per-call auth; consider adding a test that passes claims to ensure they’re forwarded to bodyParams.

integration/tests/machine-auth/m2m.test.ts (3)

73-76: Switched to client.m2m.createToken — OK; consider DRYing expiration

Change aligns with the new API. Minor nit: reuse a constant for 30 minutes to avoid duplication across the file.

You could define once near the top:

const THIRTY_MINUTES_IN_SECONDS = 60 * 30 as const;

Then use:

-  secondsUntilExpiration: 60 * 30,
+  secondsUntilExpiration: THIRTY_MINUTES_IN_SECONDS,

94-99: Make token revocation best-effort to avoid teardown flakiness

Tokens may already be expired/revoked by the time afterAll runs. Using Promise.allSettled prevents unnecessary failures during teardown.

Apply this diff:

-    await client.m2m.revokeToken({
-      m2mTokenId: emailServerM2MToken.id,
-    });
-    await client.m2m.revokeToken({
-      m2mTokenId: analyticsServerM2MToken.id,
-    });
+    await Promise.allSettled([
+      client.m2m.revokeToken({ m2mTokenId: emailServerM2MToken.id }),
+      client.m2m.revokeToken({ m2mTokenId: analyticsServerM2MToken.id }),
+    ]);

168-170: Add an assertion that revoked tokens are rejected

Verifies behavior post-revocation and guards against regressions.

Apply this diff:

     await u.services.clerk.m2m.revokeToken({
       m2mTokenId: m2mToken.id,
     });
+    // Verify the revoked token is no longer accepted
+    const res3 = await u.page.request.get(app.serverUrl + '/api/protected', {
+      headers: {
+        Authorization: `Bearer ${m2mToken.token}`,
+      },
+    });
+    expect(res3.status()).toBe(401);
+    expect(await res3.text()).toBe('Unauthorized');
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d400782 and e987b33.

📒 Files selected for processing (6)
  • integration/tests/machine-auth/m2m.test.ts (6 hunks)
  • packages/backend/src/api/__tests__/M2MTokenApi.test.ts (9 hunks)
  • packages/backend/src/api/__tests__/factory.test.ts (3 hunks)
  • packages/backend/src/api/endpoints/M2MTokenApi.ts (2 hunks)
  • packages/backend/src/api/factory.ts (1 hunks)
  • packages/backend/src/tokens/verify.ts (1 hunks)
🧰 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/backend/src/tokens/verify.ts
  • packages/backend/src/api/factory.ts
  • integration/tests/machine-auth/m2m.test.ts
  • packages/backend/src/api/__tests__/factory.test.ts
  • packages/backend/src/api/__tests__/M2MTokenApi.test.ts
  • packages/backend/src/api/endpoints/M2MTokenApi.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/backend/src/tokens/verify.ts
  • packages/backend/src/api/factory.ts
  • integration/tests/machine-auth/m2m.test.ts
  • packages/backend/src/api/__tests__/factory.test.ts
  • packages/backend/src/api/__tests__/M2MTokenApi.test.ts
  • packages/backend/src/api/endpoints/M2MTokenApi.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/backend/src/tokens/verify.ts
  • packages/backend/src/api/factory.ts
  • packages/backend/src/api/__tests__/factory.test.ts
  • packages/backend/src/api/__tests__/M2MTokenApi.test.ts
  • packages/backend/src/api/endpoints/M2MTokenApi.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/backend/src/tokens/verify.ts
  • packages/backend/src/api/factory.ts
  • packages/backend/src/api/__tests__/factory.test.ts
  • packages/backend/src/api/__tests__/M2MTokenApi.test.ts
  • packages/backend/src/api/endpoints/M2MTokenApi.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/backend/src/tokens/verify.ts
  • packages/backend/src/api/factory.ts
  • integration/tests/machine-auth/m2m.test.ts
  • packages/backend/src/api/__tests__/factory.test.ts
  • packages/backend/src/api/__tests__/M2MTokenApi.test.ts
  • packages/backend/src/api/endpoints/M2MTokenApi.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/backend/src/tokens/verify.ts
  • packages/backend/src/api/factory.ts
  • integration/tests/machine-auth/m2m.test.ts
  • packages/backend/src/api/__tests__/factory.test.ts
  • packages/backend/src/api/__tests__/M2MTokenApi.test.ts
  • packages/backend/src/api/endpoints/M2MTokenApi.ts
**/*

⚙️ CodeRabbit Configuration File

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

Files:

  • packages/backend/src/tokens/verify.ts
  • packages/backend/src/api/factory.ts
  • integration/tests/machine-auth/m2m.test.ts
  • packages/backend/src/api/__tests__/factory.test.ts
  • packages/backend/src/api/__tests__/M2MTokenApi.test.ts
  • packages/backend/src/api/endpoints/M2MTokenApi.ts
integration/**

📄 CodeRabbit Inference Engine (.cursor/rules/global.mdc)

Framework integration templates and E2E tests should be placed under the integration/ directory

Files:

  • integration/tests/machine-auth/m2m.test.ts
integration/**/*

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

End-to-end tests and integration templates must be located in the 'integration/' directory.

Files:

  • integration/tests/machine-auth/m2m.test.ts
integration/**/*.{test,spec}.{js,ts}

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Integration tests should use Playwright.

Files:

  • integration/tests/machine-auth/m2m.test.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/backend/src/api/__tests__/factory.test.ts
  • packages/backend/src/api/__tests__/M2MTokenApi.test.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/backend/src/api/__tests__/factory.test.ts
  • packages/backend/src/api/__tests__/M2MTokenApi.test.ts
🧬 Code Graph Analysis (1)
packages/backend/src/api/factory.ts (1)
packages/backend/src/api/endpoints/M2MTokenApi.ts (1)
  • M2MTokenApi (45-111)
⏰ 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). (5)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (14)
packages/backend/src/api/__tests__/factory.test.ts (3)

328-333: LGTM: test updated to new m2m namespace and validates per-call Authorization override

Test accurately reflects the renaming and the header override semantics.


356-360: LGTM: verifies fallback to machineSecretKey via client config

Correct assertion for the Authorization header when useMachineSecretKey is enabled on the client.


428-432: LGTM: prioritization of machineSecretKey over instance secret is covered

Good coverage of precedence rules.

packages/backend/src/api/__tests__/M2MTokenApi.test.ts (8)

43-51: LGTM: createToken under m2m namespace

Renamed method name and namespace are correctly exercised.


105-106: LGTM: negative case for invalid auth on createToken

Asserts proper 401 path.


146-149: LGTM: revokeToken with machine secret

Updated naming validated.


174-177: LGTM: revokeToken with instance secret

Covers both auth paths.


198-203: LGTM: missing auth error case for revokeToken

Good negative test coverage.


226-229: LGTM: verifyToken with machine secret

Namespace and method rename validated.


252-255: LGTM: verifyToken with instance secret

Covers alternate auth path.


276-281: LGTM: missing auth error case for verifyToken

Negative path remains correct post-rename.

integration/tests/machine-auth/m2m.test.ts (3)

46-47: Rename to clerkClient.m2m.verifyToken looks correct

Matches the new namespace and method. No issues spotted in the embedded server handler.


156-159: u.services.clerk.m2m.createToken usage is correct

New namespace and method name look consistent with the rest of the changes.


1-173: No deprecated M2M methods detected

The repo-wide ripgrep scan returned zero matches for both the old m2mTokens/verifySecret patterns and the legacy m2m.create or m2m.revoke calls—no further cleanup is needed.

Comment on lines +209 to 210
const verifiedToken = await client.m2m.verifyToken({ token });
return { data: verifiedToken, tokenType: TokenType.M2MToken, errors: undefined };
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Pass per-call machineSecretKey and align the exported API type

The low-level API supports a per-call machineSecretKey, but it’s not forwarded here. Also, verifyMachineAuthToken’s options type currently excludes machineSecretKey, preventing consumers from passing it even though verifyM2MToken supports it.

Forward the per-call secret:

-    const verifiedToken = await client.m2m.verifyToken({ token });
+    const verifiedToken = await client.m2m.verifyToken({ token, machineSecretKey: options.machineSecretKey });

And update the exported function type (outside this hunk; Lines 248-249) to accept the machine secret:

-export async function verifyMachineAuthToken(token: string, options: VerifyTokenOptions) {
+export async function verifyMachineAuthToken(
+  token: string,
+  options: VerifyTokenOptions & { machineSecretKey?: string },
+) {

This preserves generic usage while allowing proper auth for M2M verification without requiring an instance secret.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const verifiedToken = await client.m2m.verifyToken({ token });
return { data: verifiedToken, tokenType: TokenType.M2MToken, errors: undefined };
// … around line 209 …
- const verifiedToken = await client.m2m.verifyToken({ token });
+ const verifiedToken = await client.m2m.verifyToken({
+ token,
+ machineSecretKey: options.machineSecretKey,
+ });
return { data: verifiedToken, tokenType: TokenType.M2MToken, errors: undefined };
// …
Suggested change
const verifiedToken = await client.m2m.verifyToken({ token });
return { data: verifiedToken, tokenType: TokenType.M2MToken, errors: undefined };
// … around lines 248–249 …
-export async function verifyMachineAuthToken(token: string, options: VerifyTokenOptions) {
+export async function verifyMachineAuthToken(
+ token: string,
+ options: VerifyTokenOptions & { machineSecretKey?: string },
+) {
// function body…
}
🤖 Prompt for AI Agents
In packages/backend/src/tokens/verify.ts around lines 209 to 210, the per-call
machineSecretKey supported by the low-level client isn't being forwarded to
client.m2m.verifyToken and the exported verifyMachineAuthToken options type
(around lines 248-249) currently excludes machineSecretKey; update the call to
pass through the machineSecretKey from options into client.m2m.verifyToken and
modify the exported function/options type to include machineSecretKey (while
preserving existing generics and other fields) so callers can provide a per-call
secret for M2M verification without requiring an instance secret.

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 (1)
.changeset/serious-chicken-report.md (1)

5-27: Add a short migration guide to ease adoption.

The examples are helpful. Consider adding a concise mapping to make the breaking changes explicit for users scanning the Changeset.

Proposed addition at the end of the body:

 The `verifySecret()` method is removed. Please use `.verifyToken()` instead.
+
+## Migration guide
+- `clerkClient.m2mTokens.create()` → `clerkClient.m2m.createToken()`
+- `clerkClient.m2mTokens.revoke()` → `clerkClient.m2m.revokeToken()`
+- `clerkClient.m2mTokens.verifySecret({ secret })` → `clerkClient.m2m.verifyToken({ token })`
+
+See the package CHANGELOG for more details and examples.

If you’d like, I can expand this with common call-site patterns and type changes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e987b33 and 6e76cf7.

📒 Files selected for processing (1)
  • .changeset/serious-chicken-report.md (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
.changeset/**

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/serious-chicken-report.md
🪛 LanguageTool
.changeset/serious-chicken-report.md

[grammar] ~4-~4: There might be a mistake here.
Context: --- "@clerk/backend": minor --- Rename M2M namespace from m2mTokens to m2m...

(QB_NEW_EN)

⏰ 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). (5)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (generic, chrome)

@@ -0,0 +1,27 @@
---
"@clerk/backend": minor
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Semantic version should be major, not minor (breaking public API).

This rename removes/renames public methods (namespace rename, create→createToken, revoke→revokeToken, verifySecret removed). That’s a breaking change for consumers and warrants a major bump for @clerk/backend.

Apply this diff:

-"@clerk/backend": minor
+"@clerk/backend": major
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"@clerk/backend": minor
"@clerk/backend": major
🤖 Prompt for AI Agents
In .changeset/serious-chicken-report.md around line 2, the changeset incorrectly
marks "@clerk/backend" as "minor" even though the rename is a breaking API
change; update the changeset to mark "@clerk/backend" as "major" (replace
"minor" with "major") so the release tooling will generate a major version bump
for that package.

Comment on lines +5 to +25
Rename M2M namespace from `m2mTokens` to `m2m` in Backend API client

Before:

```ts
clerkClient.m2mTokens.create()

clerkClient.m2mTokens.revoke()

clerkClient.m2mTokens.verifySecret({ secret: 'ak_xxx' })
```

After:

```ts
clerkClient.m2m.createToken()

clerkClient.m2m.revokeToken()

clerkClient.m2m.verifyToken({ token: 'ak_xxx' })
```
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Double-check repo-wide references to old namespace before merging.

Ensure there are no lingering references to m2mTokens or verifySecret in code, docs, or examples beyond the updated tests.


🏁 Script executed:

#!/bin/bash
# From repo root: find lingering references in source, tests, and docs (excluding node_modules, dist, build)
rg -n --hidden --glob '!**/node_modules/**' --glob '!**/dist/**' --glob '!**/build/**' $'\\bm2mTokens\\b|\\bverifySecret\\b' -S

Length of output: 2060


Update all lingering m2mTokens and verifySecret references before merging

A global search turned up several remaining instances that need to be renamed or removed:

• packages/backend/src/tokens/verify.ts:235
• packages/backend/src/api/endpoints/APIKeysApi.ts:68
• CHANGELOGs in:
– packages/astro/CHANGELOG.md (line 34)
– packages/tanstack-react-start/CHANGELOG.md (34)
– packages/remix/CHANGELOG.md (34)
– packages/react-router/CHANGELOG.md (34)
– packages/nuxt/CHANGELOG.md (32)
– packages/fastify/CHANGELOG.md (30)
– packages/express/CHANGELOG.md (32)
– packages/nextjs/CHANGELOG.md (42)
– packages/backend/CHANGELOG.md (42, 56, 65, 78, 86)
• Other changesets under .changeset:
– serious-chicken-report.md (lines 5,10,12,14,27)
– small-adults-crash.md (5)
– chatty-kings-raise.md (10, 18)

Please replace all clerkClient.m2mTokens.*() calls with the new clerkClient.m2m.*() variants and update verifySecret(…)verifyToken(…) in these files.

🤖 Prompt for AI Agents
In .changeset/serious-chicken-report.md around lines 5 to 25, there are
lingering references to the old M2M API naming; update all occurrences listed
(packages/backend/src/tokens/verify.ts:235,
packages/backend/src/api/endpoints/APIKeysApi.ts:68, the various CHANGELOGs and
other changesets called out) by replacing clerkClient.m2mTokens.*() with
clerkClient.m2m.*() and rename verifySecret(...) to verifyToken(...), ensuring
any method-name changes follow the new mapping (e.g., create() → createToken(),
revoke() → revokeToken(), verifySecret → verifyToken) and update the text in
changelogs/changesets accordingly.

Comment on lines +20 to +25
clerkClient.m2m.createToken()

clerkClient.m2m.revokeToken()

clerkClient.m2m.verifyToken({ token: 'ak_xxx' })
```
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Confirm and document any additional verifyToken parameters (if applicable).

If verifyToken supports optional parameters (e.g., machineSecretKey) in this release, it’s worth including a second example here to prevent confusion.

Run this script to locate the source and confirm the signature, then update the example accordingly:


🏁 Script executed:

#!/bin/bash
# Verify verifyToken signature and usages across the repo
rg -n -A2 -B2 $'verifyToken\\s*\\('
rg -n $'verifySecret\\s*\\('

Length of output: 13802


Document optional machineSecretKey in m2m.verifyToken

The M2M verifyToken call accepts an optional machineSecretKey alongside token. Update the example in .changeset/serious-chicken-report.md to show both usages:

 clerkClient.m2m.createToken()

 clerkClient.m2m.revokeToken()

- clerkClient.m2m.verifyToken({ token: 'mt_xxx' })
+ // Verify with the default API key configured on the client
+ clerkClient.m2m.verifyToken({ token: 'mt_xxx' })
+
+ // Verify using an explicit machineSecretKey
+ clerkClient.m2m.verifyToken({
+   token: 'mt_xxx',
+   machineSecretKey: 'sk_test_machine_secret'
+ })

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In .changeset/serious-chicken-report.md around lines 20 to 25, the example for
m2m.verifyToken only shows passing token; update the example to document the
optional machineSecretKey parameter by providing two usages: one calling
clerkClient.m2m.verifyToken({ token: 'ak_xxx' }) and another calling
clerkClient.m2m.verifyToken({ token: 'ak_xxx', machineSecretKey: 'sk_xxx' });
ensure surrounding backticks/formatting remain valid and the examples are
adjacent to the existing createToken and revokeToken lines.

@wobsoriano wobsoriano merged commit 307dc3f into main Aug 14, 2025
41 checks passed
@wobsoriano wobsoriano deleted the rob/rename-m2m-namespace branch August 14, 2025 03:22
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.

4 participants