Skip to content

Conversation

@wobsoriano
Copy link
Member

@wobsoriano wobsoriano commented Jul 28, 2025

Description

This PR adds machine scope creation, deletion and machine secret key retrieval to machines BAPI

Resolves USER-2474

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 the ability to create and delete machine scopes, enabling management of authorization between machines.
    • Introduced functionality to retrieve secret keys associated with machines.
    • Enhanced machine creation and update options with additional parameters for scoped machines and token time-to-live.

@changeset-bot
Copy link

changeset-bot bot commented Jul 28, 2025

🦋 Changeset detected

Latest commit: 6b38d86

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 Patch
@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 Jul 28, 2025

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

Name Status Preview Comments Updated (UTC)
clerk-js-sandbox ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 28, 2025 10:08pm

@wobsoriano wobsoriano marked this pull request as ready for review July 28, 2025 21:15
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 28, 2025

📝 Walkthrough

"""

Walkthrough

This change set introduces new functionality to the @clerk/backend package, specifically extending the machine API to support management of machine scopes and retrieval of secret keys. Three new methods are added: createScope, deleteScope, and getSecretKey, each enabling the creation and deletion of machine-to-machine scopes and retrieval of a machine's secret key, respectively. Supporting data types and deserialization logic for MachineScope and MachineSecretKey are implemented, and these new types are exported for use elsewhere in the package. Type definitions for machine creation and update parameters are also expanded.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15–20 minutes

Assessment against linked issues

Objective Addressed Explanation
Add method to create machine scope (USER-2474)
Add method to delete machine scope (USER-2474)
Add method to retrieve machine secret key (USER-2474)
Add parameter descriptions for new/updated methods (USER-2474) Parameter types are updated in code, but no explicit parameter descriptions or documentation updates are included in the changes.

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes were found. All code changes are directly related to the objectives described in the linked issue.
"""


🪧 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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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

🧹 Nitpick comments (1)
packages/backend/src/api/endpoints/MachineApi.ts (1)

114-126: Consider parameter naming consistency.

The method implementation is solid, but there's an inconsistency in parameter naming:

  • createScope uses toMachineId
  • deleteScope uses otherMachineId

For better API consistency, consider using the same parameter name in both methods.

- async deleteScope(machineId: string, otherMachineId: string) {
+ async deleteScope(machineId: string, toMachineId: string) {
   this.requireId(machineId);
   return this.request<MachineScope>({
     method: 'DELETE',
-    path: joinPaths(basePath, machineId, 'scopes', otherMachineId),
+    path: joinPaths(basePath, machineId, 'scopes', toMachineId),
   });
 }

Also update the JSDoc parameter name:

- * @param otherMachineId - The ID of the machine that is being accessed.
+ * @param toMachineId - The ID of the machine that is being accessed.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f1d9d34 and 50512c9.

📒 Files selected for processing (7)
  • .changeset/five-jokes-clap.md (1 hunks)
  • packages/backend/src/api/endpoints/MachineApi.ts (2 hunks)
  • packages/backend/src/api/resources/Deserializer.ts (2 hunks)
  • packages/backend/src/api/resources/JSON.ts (2 hunks)
  • packages/backend/src/api/resources/MachineScope.ts (1 hunks)
  • packages/backend/src/api/resources/MachineSecretKey.ts (1 hunks)
  • packages/backend/src/api/resources/index.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/backend/src/api/resources/Deserializer.ts
  • packages/backend/src/api/resources/index.ts
  • packages/backend/src/api/resources/MachineSecretKey.ts
  • packages/backend/src/api/resources/MachineScope.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/backend/src/api/endpoints/MachineApi.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/Deserializer.ts
  • packages/backend/src/api/resources/index.ts
  • packages/backend/src/api/resources/MachineSecretKey.ts
  • packages/backend/src/api/resources/MachineScope.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/backend/src/api/endpoints/MachineApi.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/backend/src/api/resources/Deserializer.ts
  • packages/backend/src/api/resources/index.ts
  • packages/backend/src/api/resources/MachineSecretKey.ts
  • packages/backend/src/api/resources/MachineScope.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/backend/src/api/endpoints/MachineApi.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/Deserializer.ts
  • packages/backend/src/api/resources/index.ts
  • packages/backend/src/api/resources/MachineSecretKey.ts
  • packages/backend/src/api/resources/MachineScope.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/backend/src/api/endpoints/MachineApi.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/Deserializer.ts
  • packages/backend/src/api/resources/index.ts
  • packages/backend/src/api/resources/MachineSecretKey.ts
  • packages/backend/src/api/resources/MachineScope.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/backend/src/api/endpoints/MachineApi.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/Deserializer.ts
  • packages/backend/src/api/resources/index.ts
  • packages/backend/src/api/resources/MachineSecretKey.ts
  • packages/backend/src/api/resources/MachineScope.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/backend/src/api/endpoints/MachineApi.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.

Whenever reviewing a pull request, if there are any changes that could impact security, always tag @clerk/security in the PR.

Security-impacting changes include, but are not limited to:

  • Changes to authentication logic or mechanisms (e.g. login, session handling, token issuance)
  • Any modification to access control, authorization checks, or role-based permissions
  • Introduction or modification of hashing algorithms, signature verification, or cryptographic primitives
  • Handling of sensitive data (e.g. passwords, tokens, secrets, PII)
  • Integration with external identity providers (e.g. SSO, OAuth, OpenID Connect)
  • Modifications to security headers, cookie flags, CORS policies, or CSRF protections
  • Bypass mechanisms (e.g. feature flags, testing overrides) that could weaken protections
  • Changes to rate limiting, abuse prevention, or input validation

If you're unsure whether a change is security-relevant, err on the side of caution and tag @clerk/security.

Any time that you tag @clerk/security, please do so explicitly in a code comment, rather than within a collapsed section in a coderabbit comment, such as the "recent review details" section. If you do use the team name in any thinking or non-direct-code-comment content, it can be referred to as "clerk security team" to avoid accidentally printing the tag which sends a notification to the team.

Files:

  • packages/backend/src/api/resources/Deserializer.ts
  • packages/backend/src/api/resources/index.ts
  • packages/backend/src/api/resources/MachineSecretKey.ts
  • packages/backend/src/api/resources/MachineScope.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/backend/src/api/endpoints/MachineApi.ts
packages/**/index.{js,ts}

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

Use tree-shaking friendly exports

Files:

  • packages/backend/src/api/resources/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/api/resources/index.ts
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/five-jokes-clap.md
🧬 Code Graph Analysis (4)
packages/backend/src/api/resources/Deserializer.ts (3)
packages/backend/src/api/resources/JSON.ts (2)
  • ObjectType (19-72)
  • ObjectType (74-74)
packages/backend/src/api/resources/MachineScope.ts (1)
  • MachineScope (3-14)
packages/backend/src/api/resources/MachineSecretKey.ts (1)
  • MachineSecretKey (3-9)
packages/backend/src/api/resources/MachineSecretKey.ts (1)
packages/backend/src/api/resources/JSON.ts (1)
  • MachineSecretKeyJSON (725-728)
packages/backend/src/api/resources/MachineScope.ts (1)
packages/backend/src/api/resources/JSON.ts (1)
  • MachineScopeJSON (717-723)
packages/backend/src/api/endpoints/MachineApi.ts (2)
packages/backend/src/api/resources/MachineSecretKey.ts (1)
  • MachineSecretKey (3-9)
packages/backend/src/api/resources/MachineScope.ts (1)
  • MachineScope (3-14)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: pr-title-lint
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep/ci
🔇 Additional comments (15)
packages/backend/src/api/resources/MachineSecretKey.ts (2)

3-9: LGTM! Proper resource class structure with security considerations.

The MachineSecretKey class follows the established pattern with readonly properties and static fromJSON deserialization. Since this class handles sensitive secret key data, please ensure proper security measures are in place upstream.

Security Review Required: This change introduces handling of machine secret keys, which is security-sensitive functionality. @clerk/security should review this implementation to ensure proper security controls are in place for secret key handling, storage, and transmission.


1-1: Fix the import statement.

The import should be MachineSecretKeyJSON instead of MachineScopeJSON based on the usage in the fromJSON method.

-import type { MachineSecretKeyJSON } from './JSON';
+import type { MachineSecretKeyJSON } from './JSON';

Wait, let me check this again. The import statement shows MachineSecretKeyJSON which is correct. This appears to be a display issue in my analysis.

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

34-35: LGTM! Proper export additions.

The new exports for MachineScope and MachineSecretKey are correctly placed and follow the established alphabetical ordering pattern.

packages/backend/src/api/resources/Deserializer.ts (2)

19-20: LGTM! Proper import additions.

The new imports for MachineScope and MachineSecretKey are correctly placed in alphabetical order.


140-143: LGTM! Consistent deserialization pattern.

The new switch cases for MachineScope and MachineSecretKey follow the established pattern by calling their respective fromJSON static methods.

packages/backend/src/api/resources/MachineScope.ts (1)

3-14: LGTM! Well-structured resource class.

The MachineScope class follows established patterns with:

  • Readonly properties in the constructor
  • Proper TypeScript typing with optional parameters
  • Consistent snake_case to camelCase mapping in fromJSON
  • Clean separation of concerns

This properly represents machine-to-machine authorization scopes.

.changeset/five-jokes-clap.md (1)

1-16: LGTM! Clear changeset documentation.

The changeset properly documents the new machine scope and secret key functionality with clear examples. The patch-level version bump is appropriate for these new methods.

Consider adding tests: Since these changes introduce new API methods for managing machine scopes and secret keys, please ensure comprehensive test coverage is added to verify the functionality works as expected and handles edge cases properly.

packages/backend/src/api/resources/JSON.ts (3)

38-39: LGTM: New ObjectType constants follow established patterns.

The addition of MachineScope and MachineSecretKey object types is consistent with the existing naming convention and structure.


717-723: Well-structured interface for machine scope relationships.

The MachineScopeJSON interface appropriately represents the machine-to-machine relationship with clear field names and optional timestamp/deletion flags.


725-728: Ensure secure handling of MachineSecretKey.secret across the codebase

Our grep did not find any direct console.log or logger calls that emit the raw secret field, and the integration cleanup script appropriately masks secrets before logging. However, we did locate one serialization site:

  • packages/nextjs/src/app-router/keyless-actions.ts
    • JSON.stringify({ claimUrl, publishableKey, secretKey })

Please verify that:

  1. The secretKey in that JSON payload is only ever used in server-side code (never sent to client logs or browser console)
  2. All transport channels (HTTP requests, cookies) are secured (TLS, HttpOnly/Secure flags)
  3. This payload is not inadvertently logged, cached, or exposed in error/debug traces
  4. Endpoints returning or consuming MachineSecretKey enforce strict access controls

After confirming these points, tag @clerk/security for a final review.

packages/backend/src/api/endpoints/MachineApi.ts (5)

4-5: LGTM: Proper type imports added.

The new imports for MachineScope and MachineSecretKey types are correctly structured and follow the existing import pattern.


10-23: Well-documented parameter extensions.

The additions to CreateMachineParams are properly documented with JSDoc and follow TypeScript best practices. The optional fields provide good flexibility for machine configuration.


25-38: Good parameter design for updates.

Making name optional in UpdateMachineParams makes sense for PATCH operations, and the new defaultTokenTtl parameter is well-documented.


89-95: Secure secret retrieval implementation.

The getSecretKey method follows the established API pattern with proper ID validation. The endpoint path is appropriate for this sensitive operation.


97-112: Well-documented scope creation method.

The JSDoc documentation clearly explains the purpose and parameters. The implementation follows established patterns with proper validation.

Comment on lines +89 to +126
async getSecretKey(machineId: string) {
this.requireId(machineId);
return this.request<MachineSecretKey>({
method: 'GET',
path: joinPaths(basePath, machineId, 'secret_key'),
});
}

/**
* Creates a new machine scope, allowing the specified machine to access another machine.
*
* @param machineId - The ID of the machine that will have access to another machine.
* @param toMachineId - The ID of the machine that will be scoped to the current machine.
*/
async createScope(machineId: string, toMachineId: string) {
this.requireId(machineId);
return this.request<MachineScope>({
method: 'POST',
path: joinPaths(basePath, machineId, 'scopes'),
bodyParams: {
toMachineId,
},
});
}

/**
* Deletes a machine scope, removing access from one machine to another.
*
* @param machineId - The ID of the machine that has access to another machine.
* @param otherMachineId - The ID of the machine that is being accessed.
*/
async deleteScope(machineId: string, otherMachineId: string) {
this.requireId(machineId);
return this.request<MachineScope>({
method: 'DELETE',
path: joinPaths(basePath, machineId, 'scopes', otherMachineId),
});
}
Copy link
Contributor

@coderabbitai coderabbitai bot Jul 28, 2025

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Missing test coverage for new API methods.

According to the coding guidelines, tests should be added to cover new functionality. Please ensure that unit tests are added for:

  1. getSecretKey method
  2. createScope method
  3. deleteScope method

Tests should cover both success cases and error scenarios (e.g., invalid machine IDs).


🏁 Script executed:

#!/bin/bash
# Description: Check for existing test files and patterns for MachineApi

echo "=== Looking for existing MachineApi test files ==="
fd -e spec.ts -e test.ts | rg -i machine

echo -e "\n=== Checking test patterns in the codebase ==="
fd -e spec.ts -e test.ts | head -5 | xargs grep -l "describe\|it\|test" 

echo -e "\n=== Checking if there are existing API endpoint tests ==="
rg -l "class.*Api.*extends.*AbstractAPI" --type ts | head -3

Length of output: 1583


Add unit tests for MachineApi’s new methods

There are currently no tests covering MachineApi.getSecretKey, createScope, or deleteScope. Please add a new spec under packages/backend/src/api/endpoints/__tests__/MachineApi.test.ts (or similar) that includes:

  • Success cases for:
    • getSecretKey(machineId)
    • createScope(machineId, toMachineId)
    • deleteScope(machineId, otherMachineId)
  • Error scenarios (e.g., calling with invalid or empty IDs)
  • Mocking/stubbing of this.request to verify the correct HTTP method, path, and bodyParams

This will ensure all new functionality is exercised and adheres to our coverage guidelines.

🤖 Prompt for AI Agents
In packages/backend/src/api/endpoints/__tests__/MachineApi.test.ts, add unit
tests for the new MachineApi methods getSecretKey, createScope, and deleteScope.
Write success case tests that mock this.request to verify the correct HTTP
method, path, and bodyParams are used for each method. Also include error
scenario tests that check behavior when invalid or empty IDs are passed,
ensuring requireId validation triggers errors. Use stubs or mocks for
this.request to isolate the tests from actual HTTP calls and confirm the methods
behave as expected.

Copy link
Member Author

Choose a reason for hiding this comment

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

This will be tested in a follow up PR here

Copy link
Contributor

Choose a reason for hiding this comment

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

@wobsoriano Thank you for the clarification! That's a perfectly reasonable approach to handle test coverage in a follow-up PR. I appreciate you providing the link to PR #6229 where the tests will be added.

Having the core functionality implemented first and then comprehensive testing in a dedicated follow-up PR helps keep each PR focused and manageable.

ଘ(੭ˊᵕˋ)੭

Copy link
Member Author

Choose a reason for hiding this comment

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

coderobert

Copy link
Contributor

Choose a reason for hiding this comment

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

@wobsoriano Hello! 👋 I think you meant "CodeRabbit" but "coderobert" works too! 😊

Is there anything specific you'd like me to help you with regarding this PR or any other code review needs?

ଘ(੭ˊᵕˋ)੭♡

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

🧹 Nitpick comments (4)
packages/backend/src/api/resources/Machine.ts (2)

10-11: Add JSDoc documentation for new properties.

The new scopedMachines and defaultTokenTtl properties lack JSDoc documentation. Per coding guidelines, all public APIs must be documented with JSDoc.

Add documentation above the constructor:

export class Machine {
+  /**
+   * @param id - Unique identifier for the machine
+   * @param name - Display name of the machine
+   * @param instanceId - Instance identifier
+   * @param createdAt - Creation timestamp
+   * @param updatedAt - Last update timestamp
+   * @param scopedMachines - Array of machines that this machine has access to
+   * @param defaultTokenTtl - Default token time-to-live in seconds
+   */
  constructor(
    readonly id: string,
    readonly name: string,
    readonly instanceId: string,
    readonly createdAt: number,
    readonly updatedAt: number,
    readonly scopedMachines: Machine[],
    readonly defaultTokenTtl: number,
  ) {}

29-29: Improve the inline comment.

The comment could be more descriptive about why nested machines don't have scoped_machines.

-            [], // Nested machines don't have scoped_machines
+            [], // Prevent infinite recursion - nested machines don't contain their own scoped_machines
packages/backend/src/api/__tests__/MachineApi.test.ts (2)

156-169: Good test coverage for secret key retrieval.

The test correctly validates the getSecretKey method with proper URL construction and response handling.

Consider adding edge case tests for the secret key functionality:

it('handles invalid machine ID for secret key', async () => {
  server.use(
    http.get(
      `https://api.clerk.test/v1/machines/invalid_id/secret_key`,
      validateHeaders(() => {
        return HttpResponse.json({ error: 'Machine not found' }, { status: 404 });
      }),
    ),
  );

  await expect(apiClient.machines.getSecretKey('invalid_id')).rejects.toThrow();
});

91-116: Verify scoped machines property access in test.

The test asserts response.scopedMachines properties but doesn't verify that the Machine class properly deserializes the nested scoped machines. Consider adding an assertion to verify the defaultTokenTtl property as well.

    expect(response.id).toBe(machineId);
    expect(response.name).toBe('Test Machine');
    expect(response.scopedMachines).toHaveLength(1);
    expect(response.scopedMachines[0].id).toBe(otherMachineId);
    expect(response.scopedMachines[0].name).toBe('Second Machine');
+   expect(response.defaultTokenTtl).toBe(7200);
+   expect(response.scopedMachines[0].defaultTokenTtl).toBeDefined();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 50512c9 and 6b38d86.

📒 Files selected for processing (3)
  • packages/backend/src/api/__tests__/MachineApi.test.ts (1 hunks)
  • packages/backend/src/api/resources/JSON.ts (2 hunks)
  • packages/backend/src/api/resources/Machine.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/backend/src/api/resources/JSON.ts
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/backend/src/api/resources/Machine.ts
  • packages/backend/src/api/__tests__/MachineApi.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/Machine.ts
  • packages/backend/src/api/__tests__/MachineApi.test.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/backend/src/api/resources/Machine.ts
  • packages/backend/src/api/__tests__/MachineApi.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/Machine.ts
  • packages/backend/src/api/__tests__/MachineApi.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/Machine.ts
  • packages/backend/src/api/__tests__/MachineApi.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/Machine.ts
  • packages/backend/src/api/__tests__/MachineApi.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.

Whenever reviewing a pull request, if there are any changes that could impact security, always tag @clerk/security in the PR.

Security-impacting changes include, but are not limited to:

  • Changes to authentication logic or mechanisms (e.g. login, session handling, token issuance)
  • Any modification to access control, authorization checks, or role-based permissions
  • Introduction or modification of hashing algorithms, signature verification, or cryptographic primitives
  • Handling of sensitive data (e.g. passwords, tokens, secrets, PII)
  • Integration with external identity providers (e.g. SSO, OAuth, OpenID Connect)
  • Modifications to security headers, cookie flags, CORS policies, or CSRF protections
  • Bypass mechanisms (e.g. feature flags, testing overrides) that could weaken protections
  • Changes to rate limiting, abuse prevention, or input validation

If you're unsure whether a change is security-relevant, err on the side of caution and tag @clerk/security.

Any time that you tag @clerk/security, please do so explicitly in a code comment, rather than within a collapsed section in a coderabbit comment, such as the "recent review details" section. If you do use the team name in any thinking or non-direct-code-comment content, it can be referred to as "clerk security team" to avoid accidentally printing the tag which sends a notification to the team.

Files:

  • packages/backend/src/api/resources/Machine.ts
  • packages/backend/src/api/__tests__/MachineApi.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__/MachineApi.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__/MachineApi.test.ts
🧬 Code Graph Analysis (1)
packages/backend/src/api/resources/Machine.ts (1)
packages/backend/src/api/resources/JSON.ts (1)
  • MachineJSON (708-717)
⏰ 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). (3)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (5)
packages/backend/src/api/resources/Machine.ts (1)

15-34: Well-implemented recursive deserialization.

The fromJSON method correctly handles the new properties and prevents infinite recursion by providing empty arrays for nested machines' scoped_machines. The implementation properly converts snake_case JSON properties to camelCase TypeScript properties.

packages/backend/src/api/__tests__/MachineApi.test.ts (4)

51-154: Comprehensive CRUD test coverage.

The basic CRUD operations are well-tested with proper request validation, response mocking, and assertion coverage. The tests correctly validate HTTP methods, URLs, headers, request bodies, and query parameters.


171-203: Excellent test coverage for scope management.

The createScope and deleteScope tests are well-implemented with:

  • Correct HTTP methods and URL construction
  • Proper request body validation for createScope
  • Response mapping validation for both operations
  • Clear test assertions

These tests effectively validate the new scope management functionality outlined in the PR objectives.


1-204: Add error‐handling and edge‐case tests for MachineAPI

The existing tests in packages/backend/src/api/tests/MachineApi.test.ts only cover happy‐path responses. To ensure robustness—especially around security‐sensitive operations like secret‐key retrieval and scope management—please add tests for:

  • 404 Not Found (invalid machine IDs)
  • 401/403 Unauthorized or Forbidden responses
  • Network failures/timeouts (e.g., simulate fetch rejecting)
  • Malformed or unexpected response bodies
  • Validation of invalid parameters (e.g., missing required fields)

Locations to update:

  • packages/backend/src/api/tests/MachineApi.test.ts (add new it(…) blocks)

Example snippets:

it('throws on 404 when fetching secret key', async () => {
  server.use(
    http.get(
      `https://api.clerk.test/v1/machines/nonexistent/secret_key`,
      validateHeaders(() =>
        HttpResponse.json({ message: 'Not found' }, { status: 404 }),
      ),
    ),
  );
  await expect(apiClient.machines.getSecretKey('nonexistent'))
    .rejects.toThrow('Not found');
});

it('throws on 401 unauthorized when creating scope', async () => {
  server.use(
    http.post(
      `https://api.clerk.test/v1/machines/${machineId}/scopes`,
      validateHeaders(() =>
        HttpResponse.json({ message: 'Unauthorized' }, { status: 401 }),
      ),
    ),
  );
  await expect(
    apiClient.machines.createScope(machineId, otherMachineId),
  ).rejects.toThrow('Unauthorized');
});

Also tag @clerk/security for a focused review of the authentication/authorization flows.


16-33: Ensure mock data consistency.

The mockSecondMachine object is missing the default_token_ttl property that's present in mockMachine. This inconsistency could cause test failures when the Machine constructor expects all properties.

  const mockSecondMachine = {
    object: 'machine',
    id: otherMachineId,
    name: 'Second Machine',
    instance_id: 'inst_456',
    created_at: 1640995200,
    updated_at: 1640995200,
+   default_token_ttl: 3600,
+   scoped_machines: [],
  };

Also add the missing properties to mockMachine:

  const mockMachine = {
    object: 'machine',
    id: machineId,
    name: 'Test Machine',
    instance_id: 'inst_123',
    created_at: 1640995200,
    updated_at: 1640995200,
+   default_token_ttl: 7200,
    scoped_machines: [mockSecondMachine],
  };

Likely an incorrect or invalid review comment.

Comment on lines +21 to +32
data.scoped_machines.map(
m =>
new Machine(
m.id,
m.name,
m.instance_id,
m.created_at,
m.updated_at,
[], // Nested machines don't have scoped_machines
m.default_token_ttl,
),
),
Copy link
Contributor

@coderabbitai coderabbitai bot Jul 28, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add null safety for scoped_machines array.

The mapping of data.scoped_machines assumes it's always an array, but the API might return null or undefined. Consider adding a null safety check.

-      data.scoped_machines.map(
+      (data.scoped_machines || []).map(
        m =>
          new Machine(
            m.id,
            m.name,
            m.instance_id,
            m.created_at,
            m.updated_at,
            [], // Nested machines don't have scoped_machines
            m.default_token_ttl,
          ),
      ),
📝 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
data.scoped_machines.map(
m =>
new Machine(
m.id,
m.name,
m.instance_id,
m.created_at,
m.updated_at,
[], // Nested machines don't have scoped_machines
m.default_token_ttl,
),
),
(data.scoped_machines || []).map(
m =>
new Machine(
m.id,
m.name,
m.instance_id,
m.created_at,
m.updated_at,
[], // Nested machines don't have scoped_machines
m.default_token_ttl,
),
),
🤖 Prompt for AI Agents
In packages/backend/src/api/resources/Machine.ts around lines 21 to 32, the code
maps over data.scoped_machines without checking if it is null or undefined,
which can cause runtime errors. Add a null safety check by verifying that
data.scoped_machines is an array before mapping, for example by using a
conditional or defaulting to an empty array, to ensure safe iteration.

Copy link
Member Author

Choose a reason for hiding this comment

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

the root scoped_machines will always be an array

Copy link
Contributor

Choose a reason for hiding this comment

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

@wobsoriano Thank you for the clarification! I understand that the API contract guarantees scoped_machines will always be an array, so the null safety check is indeed unnecessary.


✏️ Learnings added
Learnt from: wobsoriano
PR: clerk/javascript#6417
File: packages/backend/src/api/resources/Machine.ts:21-32
Timestamp: 2025-07-28T22:19:42.397Z
Learning: In the Machine API, the `scoped_machines` field in the JSON response is guaranteed to always be an array, so null safety checks are not needed when mapping over this field.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@wobsoriano wobsoriano enabled auto-merge (squash) July 28, 2025 22:19
@pkg-pr-new
Copy link

pkg-pr-new bot commented Jul 28, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 6b38d86

@wobsoriano wobsoriano merged commit 0bdd0df into main Jul 28, 2025
42 of 45 checks passed
@wobsoriano wobsoriano deleted the rob/user-2474-machines-endpoints branch July 28, 2025 22:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants