-
Notifications
You must be signed in to change notification settings - Fork 419
chore(backend): Rename M2M secret -> token
#6536
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
Conversation
🦋 Changeset detectedLatest commit: 64b3cf6 The changes in this PR will be included in the next version bump. This PR includes changesets to release 11 packages
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 |
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
📝 WalkthroughWalkthroughIntroduces 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
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
There was a problem hiding this 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 typePassing 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 typesPackages 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 tokenThe 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 tokenMinor 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 — LGTMBack-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 terminologyThe 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 creationAdding 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 testsSince 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 propertiesPublic 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
📒 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.tspackages/backend/src/api/resources/M2MToken.tspackages/backend/src/tokens/verify.tsintegration/tests/machine-auth/m2m.test.tspackages/backend/src/api/__tests__/M2MTokenApi.test.tspackages/backend/src/api/endpoints/M2MTokenApi.tspackages/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.tspackages/backend/src/api/resources/M2MToken.tspackages/backend/src/tokens/verify.tsintegration/tests/machine-auth/m2m.test.tspackages/backend/src/api/__tests__/M2MTokenApi.test.tspackages/backend/src/api/endpoints/M2MTokenApi.tspackages/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.tspackages/backend/src/api/resources/M2MToken.tspackages/backend/src/tokens/verify.tspackages/backend/src/api/__tests__/M2MTokenApi.test.tspackages/backend/src/api/endpoints/M2MTokenApi.tspackages/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.tspackages/backend/src/api/resources/M2MToken.tspackages/backend/src/tokens/verify.tspackages/backend/src/api/__tests__/M2MTokenApi.test.tspackages/backend/src/api/endpoints/M2MTokenApi.tspackages/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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor 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
Useconst assertionsfor literal types:as const
Usesatisfiesoperator 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 ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor 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.tspackages/backend/src/api/resources/M2MToken.tspackages/backend/src/tokens/verify.tsintegration/tests/machine-auth/m2m.test.tspackages/backend/src/api/__tests__/M2MTokenApi.test.tspackages/backend/src/api/endpoints/M2MTokenApi.tspackages/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.tspackages/backend/src/api/resources/M2MToken.tspackages/backend/src/tokens/verify.tsintegration/tests/machine-auth/m2m.test.tspackages/backend/src/api/__tests__/M2MTokenApi.test.tspackages/backend/src/api/endpoints/M2MTokenApi.tspackages/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.tspackages/backend/src/api/resources/M2MToken.tspackages/backend/src/tokens/verify.tsintegration/tests/machine-auth/m2m.test.tspackages/backend/src/api/__tests__/M2MTokenApi.test.tspackages/backend/src/api/endpoints/M2MTokenApi.tspackages/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.tspackages/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.tspackages/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 appropriateMinor 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 — LGTMTest correctly asserts that per-call machineSecretKey takes precedence via headerParams.Authorization.
356-358: Header selection with useMachineSecretKey=true — LGTMGood coverage for defaulting to client.machineSecretKey when no per-call override is provided.
407-433: Precedence: machineSecretKey over instance secretKey — LGTMClear 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 — LGTMCorrectly exercises the new token property and expected 401.
159-161: Authorized email server with token-based Bearer — LGTMValidates the happy path with the new verifyToken flow.
174-176: Authorized after scoping and fresh token — LGTMGood 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 issueThe 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.
| type VerifyM2MTokenParams = { | ||
| /** | ||
| * Custom machine secret key for authentication. | ||
| */ | ||
| machineSecretKey?: string; | ||
| /** | ||
| * Machine-to-machine token to verify. | ||
| */ | ||
| token: string; | ||
| }; | ||
|
|
There was a problem hiding this comment.
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.
| /** | ||
| * 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( |
There was a problem hiding this comment.
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.
| /** | |
| * 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.
| 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); | ||
| } |
There was a problem hiding this comment.
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.
| 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.
| readonly token?: string, | ||
| readonly secret?: string, | ||
| ) {} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
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.
| export async function verifyMachineAuthToken(token: string, options: VerifyTokenOptions) { | ||
| if (token.startsWith(M2M_TOKEN_PREFIX)) { | ||
| return verifyMachineToken(token, options); | ||
| return verifyM2MToken(token, options); | ||
| } |
There was a problem hiding this comment.
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.
| 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.
Description
clerkClient.m2mTokens.verifySecretin favor of.verifyToken.verifySecretusersSee workers PR for more info
Resolves USER-3147
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
New Features
Deprecations
Chores