Skip to content

Conversation

@wobsoriano
Copy link
Member

@wobsoriano wobsoriano commented Aug 13, 2025

Description

  • Deprecate clerkClient.m2mTokens.verifySecret in favor of .verifyToken.
  • Backwards compatible with verifySecret users

See workers PR for more info

Resolves USER-3147

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

    • Added token-based verification for M2M tokens via verifyToken.
    • M2M token responses may now include a token field alongside the legacy secret.
  • Deprecations

    • verifySecret is deprecated; use verifyToken({ token }) instead.
    • The secret field on M2M tokens is deprecated in favor of token.
    • Deprecation warnings are emitted when using the old method/field.
  • Chores

    • Added a changeset entry for a minor release of @clerk/backend.

@changeset-bot
Copy link

changeset-bot bot commented Aug 13, 2025

🦋 Changeset detected

Latest commit: 64b3cf6

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 13, 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 13, 2025 5:58pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 13, 2025

📝 Walkthrough

Walkthrough

Introduces a new m2mTokens.verifyToken({ token }) method and deprecates m2mTokens.verifySecret({ secret }) across backend API, resources, and internal verification flow. Adds token to M2MToken and M2MTokenJSON, updates constructors and fromJSON mapping. Adjusts tests to use verifyToken, adds coverage for deprecated verifySecret, and updates integration tests and routes to authenticate via Bearer token with verifyToken while preserving a deprecated path. Adds deprecation warning in verifySecret and a changeset entry for a minor release of @clerk/backend.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Rename M2M verification methods from token to secret (USER-3147) Code renames secret to token, adds verifyToken and deprecates verifySecret, contrary to the stated direction.

🪧 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.

@pkg-pr-new
Copy link

pkg-pr-new bot commented Aug 13, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 64b3cf6

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

🔭 Outside diff range comments (2)
packages/backend/src/tokens/verify.ts (1)

203-214: Forward machineSecretKey and surface it in options type

Passing machineSecretKey through ensures callers can override the Authorization header for M2M verification. Also expose machineSecretKey on VerifyTokenOptions so callers don’t hit excess property checks.

Apply this diff to forward the param:

 async function verifyM2MToken(
   token: string,
   options: VerifyTokenOptions & { machineSecretKey?: string },
 ): Promise<MachineTokenReturnType<M2MToken, MachineTokenVerificationError>> {
   try {
     const client = createBackendApiClient(options);
-    const verifiedToken = await client.m2mTokens.verifyToken({ token });
+    const verifiedToken = await client.m2mTokens.verifyToken({
+      token,
+      // allow per-call override when provided
+      machineSecretKey: options.machineSecretKey,
+    });
     return { data: verifiedToken, tokenType: TokenType.M2MToken, errors: undefined };
   } catch (err: any) {
     return handleClerkAPIError(TokenType.M2MToken, err, 'Machine token not found');
   }
 }

And add machineSecretKey to VerifyTokenOptions (outside this hunk):

// In this file, extend the options type:
export type VerifyTokenOptions = Omit<VerifyJwtOptions, 'key'> &
  Omit<LoadClerkJWKFromRemoteOptions, 'kid'> & {
    /**
     * Used to verify the session token in a networkless manner. Supply the PEM public key...
     */
    jwtKey?: string;
    /**
     * When verifying M2M tokens, use this secret to authenticate with the Backend API.
     * If omitted, falls back to `secretKey` depending on client configuration.
     */
    machineSecretKey?: string;
  };
packages/backend/src/api/endpoints/M2MTokenApi.ts (1)

36-46: Export newly introduced public types

Packages should export TypeScript types alongside runtime code. Export VerifyM2MTokenParamsDeprecated so SDK users can type variables and params externally.

-type VerifyM2MTokenParamsDeprecated = {
+export type VerifyM2MTokenParamsDeprecated = {
   /**
    * Custom machine secret key for authentication.
    */
   machineSecretKey?: string;
   /**
    * Machine-to-machine token secret to verify.
    */
   secret: string;
 };
🧹 Nitpick comments (8)
.changeset/small-adults-crash.md (1)

5-6: Fix grammar and stray character in changeset note

  • “in favor or” → “in favor of”
  • Remove the dangling “6” line.

Apply this diff:

-Deprecates `clerkClient.m2mTokens.verifySecret({ secret: 'mt_xxx' })` in favor or `clerkClient.m2mTokens.verifyToken({ token: 'mt_xxx' })`
-6
+Deprecates `clerkClient.m2mTokens.verifySecret({ secret: 'mt_xxx' })` in favor of `clerkClient.m2mTokens.verifyToken({ token: 'mt_xxx' })`
packages/backend/src/api/resources/JSON.ts (1)

737-742: M2MTokenJSON: deprecate secret, add token — LGTM; consider adding brief JSDoc for token

The deprecation on secret with a pointer to token is good. Consider adding a short JSDoc explaining token to aid Typedoc output.

Apply this diff to document token:

 export interface M2MTokenJSON extends ClerkResourceJSON {
   object: typeof ObjectType.M2MToken;
   /**
    * @deprecated Use {@link token} instead.
    */
   secret?: string;
+  /**
+   * The raw machine-to-machine token string to be used as a Bearer credential.
+   */
   token?: string;
   subject: string;
   scopes: string[];
   claims: Record<string, any> | null;
integration/tests/machine-auth/m2m.test.ts (2)

43-51: Short-circuit on missing Authorization token

Minor guard to avoid calling the SDK with an undefined token, and to return 401 faster.

Apply this diff:

 app.get('/api/protected', async (req, res) => {
-  const token = req.get('Authorization')?.split(' ')[1];
-  
-  try {
+  const token = req.get('Authorization')?.split(' ')[1];
+  if (!token) {
+    return res.status(401).send('Unauthorized');
+  }
+  try {
     const m2mToken = await clerkClient.m2mTokens.verifyToken({ token });
     res.send('Protected response ' + m2mToken.id);
   } catch {
     res.status(401).send('Unauthorized');
   }
 });

184-195: Deprecated path coverage — LGTM

Back-compat route exercising verifySecret is valuable; ensures smooth migration.

Optional: consider adding an assertion that a deprecation warning is logged (if the SDK surfaces one) to make sure consumers notice the migration path.

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

17-20: Align mock naming with new API terminology

The mock assigns the same value to both secret and token. To reduce confusion now that token is the preferred field, consider renaming m2mSecret to m2mToken (or adding a separate const) and favoring token in assertions going forward.


51-51: Good: Asserting the new token field on creation

Adding an assertion for response.token ensures the model exposes the new property. Consider adding a similar assertion in the second create test for consistency.


212-287: Prefer asserting token over secret in verifyToken tests

Since verifyToken is the new API, assertions should prioritize response.token. Keeping a legacy assertion for response.secret is fine temporarily, but it should be phased out.

Suggested update:

@@
-      expect(response.id).toBe(m2mId);
-      expect(response.secret).toBe(m2mSecret);
+      expect(response.id).toBe(m2mId);
+      expect(response.token).toBe(m2mSecret);
+      // Back-compat assertion; consider removing in a future cleanup
+      expect(response.secret).toBe(m2mSecret);
@@
-      expect(response.id).toBe(m2mId);
-      expect(response.secret).toBe(m2mSecret);
+      expect(response.id).toBe(m2mId);
+      expect(response.token).toBe(m2mSecret);
+      // Back-compat assertion; consider removing in a future cleanup
+      expect(response.secret).toBe(m2mSecret);
packages/backend/src/api/resources/M2MToken.ts (1)

15-17: Add JSDoc and deprecation notice for class properties

Public APIs should be documented. Add JSDoc for token and mark secret as deprecated to guide users.

Would you like me to open a follow-up PR to add property-level JSDoc on M2MToken (and mark secret as @deprecated)?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8b52d7a and 64b3cf6.

📒 Files selected for processing (8)
  • .changeset/small-adults-crash.md (1 hunks)
  • integration/tests/machine-auth/m2m.test.ts (5 hunks)
  • packages/backend/src/api/__tests__/M2MTokenApi.test.ts (3 hunks)
  • packages/backend/src/api/__tests__/factory.test.ts (4 hunks)
  • packages/backend/src/api/endpoints/M2MTokenApi.ts (5 hunks)
  • packages/backend/src/api/resources/JSON.ts (1 hunks)
  • packages/backend/src/api/resources/M2MToken.ts (2 hunks)
  • packages/backend/src/tokens/verify.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/small-adults-crash.md
**/*.{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/api/resources/JSON.ts
  • packages/backend/src/api/resources/M2MToken.ts
  • packages/backend/src/tokens/verify.ts
  • integration/tests/machine-auth/m2m.test.ts
  • packages/backend/src/api/__tests__/M2MTokenApi.test.ts
  • packages/backend/src/api/endpoints/M2MTokenApi.ts
  • packages/backend/src/api/__tests__/factory.test.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/api/resources/JSON.ts
  • packages/backend/src/api/resources/M2MToken.ts
  • packages/backend/src/tokens/verify.ts
  • integration/tests/machine-auth/m2m.test.ts
  • packages/backend/src/api/__tests__/M2MTokenApi.test.ts
  • packages/backend/src/api/endpoints/M2MTokenApi.ts
  • packages/backend/src/api/__tests__/factory.test.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/backend/src/api/resources/JSON.ts
  • packages/backend/src/api/resources/M2MToken.ts
  • packages/backend/src/tokens/verify.ts
  • packages/backend/src/api/__tests__/M2MTokenApi.test.ts
  • packages/backend/src/api/endpoints/M2MTokenApi.ts
  • packages/backend/src/api/__tests__/factory.test.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/api/resources/JSON.ts
  • packages/backend/src/api/resources/M2MToken.ts
  • packages/backend/src/tokens/verify.ts
  • packages/backend/src/api/__tests__/M2MTokenApi.test.ts
  • packages/backend/src/api/endpoints/M2MTokenApi.ts
  • packages/backend/src/api/__tests__/factory.test.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/api/resources/JSON.ts
  • packages/backend/src/api/resources/M2MToken.ts
  • packages/backend/src/tokens/verify.ts
  • integration/tests/machine-auth/m2m.test.ts
  • packages/backend/src/api/__tests__/M2MTokenApi.test.ts
  • packages/backend/src/api/endpoints/M2MTokenApi.ts
  • packages/backend/src/api/__tests__/factory.test.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/api/resources/JSON.ts
  • packages/backend/src/api/resources/M2MToken.ts
  • packages/backend/src/tokens/verify.ts
  • integration/tests/machine-auth/m2m.test.ts
  • packages/backend/src/api/__tests__/M2MTokenApi.test.ts
  • packages/backend/src/api/endpoints/M2MTokenApi.ts
  • packages/backend/src/api/__tests__/factory.test.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/api/resources/JSON.ts
  • packages/backend/src/api/resources/M2MToken.ts
  • packages/backend/src/tokens/verify.ts
  • integration/tests/machine-auth/m2m.test.ts
  • packages/backend/src/api/__tests__/M2MTokenApi.test.ts
  • packages/backend/src/api/endpoints/M2MTokenApi.ts
  • packages/backend/src/api/__tests__/factory.test.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__/M2MTokenApi.test.ts
  • packages/backend/src/api/__tests__/factory.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__/M2MTokenApi.test.ts
  • packages/backend/src/api/__tests__/factory.test.ts
🧬 Code Graph Analysis (3)
packages/backend/src/tokens/verify.ts (6)
packages/backend/src/api/endpoints/M2MTokenApi.ts (1)
  • options (59-71)
packages/backend/src/index.ts (2)
  • VerifyTokenOptions (52-52)
  • M2MToken (130-130)
packages/backend/src/jwt/types.ts (1)
  • MachineTokenReturnType (13-23)
packages/backend/src/api/resources/M2MToken.ts (1)
  • M2MToken (3-35)
packages/backend/src/errors.ts (1)
  • MachineTokenVerificationError (82-98)
packages/backend/src/api/factory.ts (1)
  • createBackendApiClient (39-97)
packages/backend/src/api/__tests__/M2MTokenApi.test.ts (1)
packages/backend/src/api/factory.ts (1)
  • createBackendApiClient (39-97)
packages/backend/src/api/endpoints/M2MTokenApi.ts (2)
packages/backend/src/api/resources/M2MToken.ts (1)
  • M2MToken (3-35)
packages/backend/src/index.ts (1)
  • M2MToken (130-130)
⏰ 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). (23)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Static analysis
  • GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (8)
.changeset/small-adults-crash.md (1)

1-3: Changeset scope and bump look appropriate

Minor bump for @clerk/backend fits deprecating old API and introducing a new one.

Note: The linked issue title says “rename … from token to secret,” while this PR (and the changeset) deprecates verifySecret in favor of verifyToken (secret -> token). Please confirm the linked issue title is inverted or adjust the changeset/message to avoid confusion in release notes.

packages/backend/src/api/__tests__/factory.test.ts (3)

328-331: Switch to verifyToken with machineSecretKey override — LGTM

Test correctly asserts that per-call machineSecretKey takes precedence via headerParams.Authorization.


356-358: Header selection with useMachineSecretKey=true — LGTM

Good coverage for defaulting to client.machineSecretKey when no per-call override is provided.


407-433: Precedence: machineSecretKey over instance secretKey — LGTM

Clear assertion that machine secret key is prioritized when both are present and useMachineSecretKey is true.

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

143-145: Uses token-based Bearer for unauthorized analytics server — LGTM

Correctly exercises the new token property and expected 401.


159-161: Authorized email server with token-based Bearer — LGTM

Validates the happy path with the new verifyToken flow.


174-176: Authorized after scoping and fresh token — LGTM

Good coverage for dynamic scoping and subsequent authorization using token.

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

1-1: Confirm objective consistency between PR and linked issue

The PR title/changes implement “secret -> token” for M2M verification, while the linked issue title says “rename ... from token to secret.” Please confirm which direction is the source of truth to avoid misalignment in release notes and docs.

Comment on lines +47 to +57
type VerifyM2MTokenParams = {
/**
* Custom machine secret key for authentication.
*/
machineSecretKey?: string;
/**
* Machine-to-machine token to verify.
*/
token: string;
};

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

Export the new VerifyM2MTokenParams type

Same rationale as above: export the public-facing type.

-type VerifyM2MTokenParams = {
+export type VerifyM2MTokenParams = {
   /**
    * Custom machine secret key for authentication.
    */
   machineSecretKey?: string;
   /**
    * Machine-to-machine token to verify.
    */
   token: string;
 };
🤖 Prompt for AI Agents
In packages/backend/src/api/endpoints/M2MTokenApi.ts around lines 47 to 57, the
VerifyM2MTokenParams type is declared but not exported; change its declaration
to export the type (i.e., export type VerifyM2MTokenParams = { ... }) so it
becomes part of the public API, and update any files that should import it to
import the exported type rather than relying on local duplication.

Comment on lines +110 to 120
/**
* Verify a machine-to-machine token.
*
* @deprecated Use {@link verifyToken} instead.
*/
async verifySecret(params: VerifyM2MTokenParamsDeprecated) {
const { secret, machineSecretKey } = params;

deprecated('verifySecret', 'Use `verifyToken({ token: mt_xxx })` instead');

const requestOptions = this.#createRequestOptions(
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

Add explicit return type and explicit access modifier to public API

Per guidelines, public APIs should declare explicit return types and use explicit access modifiers. Also, consider including a removal timeline in the deprecation message to set expectations.

-  async verifySecret(params: VerifyM2MTokenParamsDeprecated) {
+  public async verifySecret(params: VerifyM2MTokenParamsDeprecated): Promise<M2MToken> {
     const { secret, machineSecretKey } = params;

-    deprecated('verifySecret', 'Use `verifyToken({ token: mt_xxx })` instead');
+    deprecated('verifySecret', 'Use `verifyToken({ token: mt_xxx })` instead');
📝 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
/**
* Verify a machine-to-machine token.
*
* @deprecated Use {@link verifyToken} instead.
*/
async verifySecret(params: VerifyM2MTokenParamsDeprecated) {
const { secret, machineSecretKey } = params;
deprecated('verifySecret', 'Use `verifyToken({ token: mt_xxx })` instead');
const requestOptions = this.#createRequestOptions(
/**
* Verify a machine-to-machine token.
*
* @deprecated Use {@link verifyToken} instead.
*/
public async verifySecret(params: VerifyM2MTokenParamsDeprecated): Promise<M2MToken> {
const { secret, machineSecretKey } = params;
deprecated('verifySecret', 'Use `verifyToken({ token: mt_xxx })` instead');
const requestOptions = this.#createRequestOptions(
// …
);
// …
}
🤖 Prompt for AI Agents
In packages/backend/src/api/endpoints/M2MTokenApi.ts around lines 110 to 120,
the public deprecated method verifySecret lacks an explicit access modifier and
an explicit return type and its deprecation message doesn't include a removal
timeline; update the method signature to include an explicit access modifier
(public) and an explicit return type matching the actual resolved promise type
(e.g., Promise<VerifyTokenResult> or the correct interface used elsewhere), and
update the deprecated(...) call text to include a clear removal timeline (for
example: "deprecated: remove in vX.Y - use `verifyToken({ token: mt_xxx })`
instead") so the API surface is explicit and users know when it will be removed.

Comment on lines +132 to +145
async verifyToken(params: VerifyM2MTokenParams) {
const { token, machineSecretKey } = params;

const requestOptions = this.#createRequestOptions(
{
method: 'POST',
path: joinPaths(basePath, 'verify'),
bodyParams: { token },
},
machineSecretKey,
);

return this.request<M2MToken>(requestOptions);
}
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

Document verifyToken and add explicit return type with access modifier

Add JSDoc for the new public method and specify the return type. This improves DX and aligns with the project’s TypeScript/JSDoc guidelines.

-  async verifyToken(params: VerifyM2MTokenParams) {
+  /**
+   * Verify a machine-to-machine token.
+   *
+   * Verifies the provided M2M token against the Clerk API.
+   * By default, the client uses the configured Machine Secret Key.
+   * You can override it per-call by passing `machineSecretKey`.
+   *
+   * @param params - The verification parameters.
+   * @returns The verified M2MToken resource.
+   */
+  public async verifyToken(params: VerifyM2MTokenParams): Promise<M2MToken> {
     const { token, machineSecretKey } = params;
📝 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
async verifyToken(params: VerifyM2MTokenParams) {
const { token, machineSecretKey } = params;
const requestOptions = this.#createRequestOptions(
{
method: 'POST',
path: joinPaths(basePath, 'verify'),
bodyParams: { token },
},
machineSecretKey,
);
return this.request<M2MToken>(requestOptions);
}
/**
* Verify a machine-to-machine token.
*
* Verifies the provided M2M token against the Clerk API.
* By default, the client uses the configured Machine Secret Key.
* You can override it per-call by passing `machineSecretKey`.
*
* @param params - The verification parameters.
* @returns The verified M2MToken resource.
*/
public async verifyToken(params: VerifyM2MTokenParams): Promise<M2MToken> {
const { token, machineSecretKey } = params;
const requestOptions = this.#createRequestOptions(
{
method: 'POST',
path: joinPaths(basePath, 'verify'),
bodyParams: { token },
},
machineSecretKey,
);
return this.request<M2MToken>(requestOptions);
}
🤖 Prompt for AI Agents
In packages/backend/src/api/endpoints/M2MTokenApi.ts around lines 132 to 145,
the new verifyToken method is missing JSDoc and an explicit public return type;
add a JSDoc block describing the method, its parameters, and the returned
M2MToken, and change the signature to include the access modifier and explicit
return type (e.g., public async verifyToken(params: VerifyM2MTokenParams):
Promise<M2MToken>) so the method is documented and types are explicit.

Comment on lines +15 to 17
readonly token?: string,
readonly secret?: string,
) {}
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

Avoid a silent breaking change in the constructor parameter order

Inserting token before secret changes the positional index of secret. Any direct instantiation like new M2MToken(..., updatedAt, secret) will now set token instead of secret, leaving secret undefined. This can cause subtle bugs without type errors.

To preserve backward compatibility, keep secret in its original position and add token after it. Update fromJSON accordingly.

-    readonly updatedAt: number,
-    readonly token?: string,
-    readonly secret?: string,
+    readonly updatedAt: number,
+    readonly secret?: string,
+    readonly token?: string,
@@
-      data.updated_at,
-      data.token,
-      data.secret,
+      data.updated_at,
+      data.secret,
+      data.token,

Also applies to: 31-33

🤖 Prompt for AI Agents
In packages/backend/src/api/resources/M2MToken.ts around lines 15-17 (and
similarly adjust lines 31-33), the constructor parameter order was changed to
place token before secret which breaks positional instantiation; restore the
original parameter order so secret remains before token (e.g., ..., updatedAt,
secret, token) and update the fromJSON factory to map JSON.secret to the secret
parameter and JSON.token to the token parameter in that same order to preserve
backward compatibility.

Comment on lines 248 to 251
export async function verifyMachineAuthToken(token: string, options: VerifyTokenOptions) {
if (token.startsWith(M2M_TOKEN_PREFIX)) {
return verifyMachineToken(token, options);
return verifyM2MToken(token, options);
}
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

Add explicit return type to the public API

Public APIs should declare explicit return types. Make verifyMachineAuthToken’s return type a union over supported token data.

Apply this diff:

-export async function verifyMachineAuthToken(token: string, options: VerifyTokenOptions) {
+export async function verifyMachineAuthToken(
+  token: string,
+  options: VerifyTokenOptions,
+): Promise<MachineTokenReturnType<M2MToken | IdPOAuthAccessToken | APIKey, MachineTokenVerificationError>> {
   if (token.startsWith(M2M_TOKEN_PREFIX)) {
     return verifyM2MToken(token, options);
📝 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
export async function verifyMachineAuthToken(token: string, options: VerifyTokenOptions) {
if (token.startsWith(M2M_TOKEN_PREFIX)) {
return verifyMachineToken(token, options);
return verifyM2MToken(token, options);
}
export async function verifyMachineAuthToken(
token: string,
options: VerifyTokenOptions,
): Promise<
MachineTokenReturnType<
M2MToken | IdPOAuthAccessToken | APIKey,
MachineTokenVerificationError
>
> {
if (token.startsWith(M2M_TOKEN_PREFIX)) {
return verifyM2MToken(token, options);
}
// ...rest of implementation...
}
🤖 Prompt for AI Agents
In packages/backend/src/tokens/verify.ts around lines 248 to 251, the exported
function verifyMachineAuthToken lacks an explicit return type; update its
signature to declare a Promise returning an explicit union of all supported
token data types (for example Promise<M2MTokenData | UserTokenData | null> or
whatever concrete types the underlying verify functions return), import or
reference those types at the top of the file, and update the function signature
to use that union so the public API has a concrete, exported return type.

@wobsoriano wobsoriano merged commit 2db7431 into main Aug 13, 2025
39 checks passed
@wobsoriano wobsoriano deleted the rob/user-3147-token-to-secret branch August 13, 2025 20:42
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