Skip to content

chore(repo,backend): Add machine-to-machine integration tests #6500

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 24 commits into from
Aug 12, 2025

Conversation

wobsoriano
Copy link
Member

@wobsoriano wobsoriano commented Aug 9, 2025

Description

This PR adds E2E tests for the machine-to-machine SDK support

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 a long‑running app preset for machine‑auth scenarios.
    • Public API now exposes Machine and M2MToken resources.
    • Added an option to set M2M token expiration when issuing tokens.
  • Tests

    • Added integration tests for machine‑to‑machine auth covering invalid tokens, scoped access, dynamic scope grants, and cleanup.
  • Chores

    • Added a dedicated integration test script, CI matrix entry, pipeline task, and a patch changeset.

Copy link

vercel bot commented Aug 9, 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 12, 2025 2:28pm

Base automatically changed from rob/express-e2e-refactor to main August 11, 2025 15:14
Copy link

changeset-bot bot commented Aug 11, 2025

🦋 Changeset detected

Latest commit: 53a9eb8

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

@wobsoriano wobsoriano changed the title chore(express,repo): M2M E2E tests chore(express,repo): Add machine-to-machine integration tests Aug 11, 2025
@wobsoriano wobsoriano marked this pull request as ready for review August 11, 2025 15:52
@wobsoriano wobsoriano changed the title chore(express,repo): Add machine-to-machine integration tests WIP: Add machine-to-machine integration tests Aug 11, 2025
Copy link

pkg-pr-new bot commented Aug 11, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 53a9eb8

Copy link
Contributor

coderabbitai bot commented Aug 11, 2025

📝 Walkthrough

Walkthrough

Adds a new long-running app preset id "withMachine.express.vite". Introduces an integration test suite for machine-to-machine (M2M) auth that creates machines, issues/revokes M2M tokens, validates token handling and dynamic scope grants, and performs setup/teardown. Exports two new public types/resources (Machine, M2MToken) from @clerk/backend and adds a CreateM2MTokenParams field secondsUntilExpiration?: number | null. Adds package.json script test:integration:machine, a turbo.json task //#test:integration:machine, a CI matrix entry for the "machine" integration test, and a changeset publishing the backend exports.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b628254 and 53a9eb8.

📒 Files selected for processing (1)
  • .changeset/nasty-colts-travel.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • .changeset/nasty-colts-travel.md
⏰ 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: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan

🪧 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: 0

🧹 Nitpick comments (3)
integration/presets/longRunningApps.ts (1)

50-55: Consider implementing the TODO and organizing machine auth apps together.

The TODO comment suggests grouping machine auth apps together. Since you're adding this section now, consider:

  1. Moving the existing API keys app (line 34: next.appRouter.withAPIKeys) to this new section
  2. Creating a clearer separation for machine auth apps

This would improve code organization and make it easier to find related configurations.

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

49-57: Use explicit return statement for clarity.

While the current code works, using an explicit return statement improves code clarity.

  app.get('/api/protected', (req, res) => {
    const { machineId } = getAuth(req, { acceptsToken: 'm2m_token' });
    if (!machineId) {
-     res.status(401).send('Unauthorized');
-     return;
+     return res.status(401).send('Unauthorized');
    }

-   res.send('Protected response');
+   return res.send('Protected response');
  });

19-94: Consider adding error handling for setup operations.

While the current implementation will fail tests if setup fails, adding try-catch blocks would make debugging easier when setup operations fail.

  test.beforeAll(async () => {
+   try {
      const fakeCompanyName = faker.company.name();
      
      // ... rest of the setup code ...
      
+   } catch (error) {
+     console.error('Failed to set up M2M test environment:', error);
+     throw error;
+   }
  });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 773bf7f and b52c3b9.

📒 Files selected for processing (5)
  • integration/presets/longRunningApps.ts (1 hunks)
  • integration/tests/machine-auth/m2m.test.ts (1 hunks)
  • package.json (1 hunks)
  • packages/backend/src/index.ts (1 hunks)
  • turbo.json (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:

  • integration/presets/longRunningApps.ts
  • packages/backend/src/index.ts
  • integration/tests/machine-auth/m2m.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:

  • integration/presets/longRunningApps.ts
  • packages/backend/src/index.ts
  • package.json
  • integration/tests/machine-auth/m2m.test.ts
  • turbo.json
**/*.{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:

  • integration/presets/longRunningApps.ts
  • packages/backend/src/index.ts
  • integration/tests/machine-auth/m2m.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/presets/longRunningApps.ts
  • 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/presets/longRunningApps.ts
  • integration/tests/machine-auth/m2m.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:

  • integration/presets/longRunningApps.ts
  • packages/backend/src/index.ts
  • integration/tests/machine-auth/m2m.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:

  • integration/presets/longRunningApps.ts
  • packages/backend/src/index.ts
  • package.json
  • integration/tests/machine-auth/m2m.test.ts
  • turbo.json
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/backend/src/index.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/index.ts
packages/**/index.{js,ts}

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

Use tree-shaking friendly exports

Files:

  • packages/backend/src/index.ts
**/index.ts

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

Use index.ts files for clean imports but avoid deep barrel exports

Avoid barrel files (index.ts re-exports) as they can cause circular dependencies

Files:

  • packages/backend/src/index.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
🔇 Additional comments (6)
package.json (1)

45-45: LGTM! Script follows established patterns.

The new integration test script correctly follows the naming convention and structure of other integration test scripts in the file.

packages/backend/src/index.ts (1)

129-130: Exports Verified: Machine and M2MToken definitions exist

Machine and M2MToken are implemented as classes in the resources module and match the new exports.

• packages/backend/src/api/resources/Machine.ts → export class Machine
• packages/backend/src/api/resources/M2MToken.ts → export class M2MToken

turbo.json (1)

348-359: LGTM! Turbo task configuration is consistent.

The new integration test task follows the established pattern and includes all necessary dependencies for the M2M tests.

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

1-18: LGTM! Test structure and imports are well organized.

Good use of parallel mode for test performance and proper tagging with @machine for test filtering.


96-110: Excellent cleanup implementation.

The cleanup properly revokes tokens before deleting machines and ensures all resources are cleaned up in the correct order.


112-177: Comprehensive test coverage for M2M authentication scenarios.

The tests properly cover:

  • Invalid token rejection
  • Access control based on machine scopes
  • Dynamic scope grants

Good practice cleaning up the temporary token in the authorized access test.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b52c3b9 and 45a490d.

📒 Files selected for processing (1)
  • .github/workflows/ci.yml (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
.github/workflows/*.yml

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

CI/CD must be configured with GitHub Actions.

Files:

  • .github/workflows/ci.yml
⏰ 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, 14)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (express, 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)
  • GitHub Check: semgrep-cloud-platform/scan

@wobsoriano wobsoriano changed the title WIP: Add machine-to-machine integration tests chore(repo,backend): Add machine-to-machine integration tests Aug 11, 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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 268c92b and b628254.

📒 Files selected for processing (3)
  • .changeset/nasty-colts-travel.md (1 hunks)
  • integration/tests/machine-auth/m2m.test.ts (1 hunks)
  • packages/backend/src/api/endpoints/M2MTokenApi.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/backend/src/api/endpoints/M2MTokenApi.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • integration/tests/machine-auth/m2m.test.ts
🧰 Additional context used
📓 Path-based instructions (1)
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/nasty-colts-travel.md
🔇 Additional comments (1)
.changeset/nasty-colts-travel.md (1)

1-3: Changeset frontmatter looks valid

Package name and release type are correctly specified and properly quoted.

"@clerk/backend": patch
---

Exports `Machine` and `M2MToken` resource classes
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

Clarify wording and verify “classes” vs “types”; double-check semver level

The body currently says “resource classes,” while the PR summary mentions exporting “types.” Ensure the note matches the actual exports (classes vs types). Also, adding new public exports is often considered a minor release per SemVer, not a patch—confirm if “patch” is intended.

If the intent is generic and accurate regardless of implementation detail, you can update the copy to avoid ambiguity:

-Exports `Machine` and `M2MToken` resource classes
+Expose `Machine` and `M2MToken` as public exports.

Optionally, if this is a minor release:

-"@clerk/backend": patch
+"@clerk/backend": minor

Run this script to verify the nature of the exports and ensure the wording is accurate:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Checking export statements in packages/backend/src/index.ts..."
rg -n -A2 -B2 'export .* (Machine|M2MToken)' packages/backend/src/index.ts || true

echo
echo "Searching for declarations to determine if they are classes or types..."
rg -n -A2 -B2 'export (class|type|interface) (Machine|M2MToken)' packages/backend/src || true

Length of output: 6239


Update semver to minor for new exports

The term “resource classes” is accurate—both Machine and M2MToken are declared as export class in packages/backend/src/api/resources. However, exposing new public API requires a minor bump, not a patch.

  • .changeset/nasty-colts-travel.md
--- a/.changeset/nasty-colts-travel.md
- "@clerk/backend": patch
+ "@clerk/backend": minor
📝 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
Exports `Machine` and `M2MToken` resource classes
---
"@clerk/backend": minor
---
Exports `Machine` and `M2MToken` resource classes
🤖 Prompt for AI Agents
In .changeset/nasty-colts-travel.md around line 5, the changeset currently marks
the package bump as a patch despite adding new exported resource classes; edit
the changeset to change the version bump from "patch" to "minor" (i.e., update
the bump level in the file header or package entry to "minor"), save and commit
the updated changeset so the release tooling will perform a minor version bump.

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

🔭 Outside diff range comments (3)
packages/backend/src/api/endpoints/M2MTokenApi.ts (3)

60-76: Validate secondsUntilExpiration at the SDK boundary and add explicit return type

Per guidelines, validate inputs and provide explicit return types for public APIs. Guarding here avoids cryptic backend 4xxs and gives developers actionable messages.

Apply:

-  async create(params?: CreateM2MTokenParams) {
+  async create(params?: CreateM2MTokenParams): Promise<M2MToken> {
     const { claims = null, machineSecretKey, secondsUntilExpiration = null } = params || {};
+    if (secondsUntilExpiration != null) {
+      if (!Number.isInteger(secondsUntilExpiration) || secondsUntilExpiration <= 0) {
+        throw new TypeError('secondsUntilExpiration must be a positive integer (seconds).');
+      }
+    }
 
     const requestOptions = this.#createRequestOptions(
       {
         method: 'POST',
         path: basePath,
         bodyParams: {
           secondsUntilExpiration,
           claims,
         },
       },
       machineSecretKey,
     );
 
     return this.request<M2MToken>(requestOptions);
   }

78-95: Add explicit return type to revoke()

Aligns with “explicit return types for public APIs”.

-  async revoke(params: RevokeM2MTokenParams) {
+  async revoke(params: RevokeM2MTokenParams): Promise<M2MToken> {

97-110: Add explicit return type to verifySecret()

Aligns with “explicit return types for public APIs”.

-  async verifySecret(params: VerifyM2MTokenParams) {
+  async verifySecret(params: VerifyM2MTokenParams): Promise<M2MToken> {
🧹 Nitpick comments (4)
.changeset/nasty-colts-travel.md (1)

5-5: Expand the changeset description for clarity

Briefly call out that you’re adding new public resource classes (runtime exports), and reference any relevant files (e.g., packages/backend/src/index.ts) to aid changelog readers.

Here’s a clearer description you can use:

Exports the Machine and M2MToken resource classes from @clerk/backend (public API). No breaking changes.
packages/backend/src/api/endpoints/M2MTokenApi.ts (3)

13-17: Clarify TTL semantics in JSDoc (positive integer and null behavior)

Specify that the value must be a positive integer in seconds and that null means "no expiration".

Apply this doc tweak:

   /**
-   * Number of seconds until the token expires.
-   *
-   * @default null - Token does not expire
+   * Number of seconds until the token expires.
+   * Must be a positive integer (seconds). Use `null` for non-expiring tokens.
+   * @default null
    */

45-58: Add explicit return type to private helper for stronger typing

Improves readability and type safety.

-  #createRequestOptions(options: ClerkBackendApiRequestOptions, machineSecretKey?: string) {
+  #createRequestOptions(
+    options: ClerkBackendApiRequestOptions,
+    machineSecretKey?: string,
+  ): ClerkBackendApiRequestOptions {

60-76: Consider adding an integration test for token expiration (TTL)

New TTL input is not obviously covered by the added tests. Add an integration test that issues a short-lived token via secondsUntilExpiration, verifies it works immediately, then verifies it fails after expiry.

I can draft a test that:

  • Issues a token with secondsUntilExpiration: 1
  • Verifies access succeeds right away
  • Sleeps ~2s
  • Verifies the same token is now rejected (expired)

Want me to prepare the test scaffold under integration/tests/machine-auth?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 268c92b and b628254.

📒 Files selected for processing (3)
  • .changeset/nasty-colts-travel.md (1 hunks)
  • integration/tests/machine-auth/m2m.test.ts (1 hunks)
  • packages/backend/src/api/endpoints/M2MTokenApi.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • integration/tests/machine-auth/m2m.test.ts
🧰 Additional context used
📓 Path-based instructions (8)
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/nasty-colts-travel.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/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/api/endpoints/M2MTokenApi.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • 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/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/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/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/api/endpoints/M2MTokenApi.ts
🔇 Additional comments (1)
.changeset/nasty-colts-travel.md (1)

2-2: Bump level should be minor, not patch, for new public exports

Exporting new public resource classes is a feature addition to the public API surface and warrants a minor version bump per semver.

Apply this diff:

-"@clerk/backend": patch
+"@clerk/backend": minor

If this export is intentionally treated as a patch under your release policy, please confirm.

@@ -293,6 +293,7 @@ jobs:
'nuxt',
'react-router',
'billing',
'machine'
Copy link
Member

Choose a reason for hiding this comment

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

🙃

Suggested change
'machine'
'm2m'

Copy link
Member Author

Choose a reason for hiding this comment

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

So there's a follow up PR for this that will group all "machine" related tests (api keys, m2m)

"@clerk/testing#build",
"@clerk/clerk-js#build",
"@clerk/backend#build",
"@clerk/nextjs#build",
Copy link
Member

Choose a reason for hiding this comment

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

We are testing against nextjs, right ?

Copy link
Member Author

Choose a reason for hiding this comment

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

Related to my comment above, the api keys test needs nextjs

@wobsoriano wobsoriano merged commit df63e76 into main Aug 12, 2025
39 checks passed
@wobsoriano wobsoriano deleted the rob/m2m-e2e branch August 12, 2025 14:51
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.

3 participants