Skip to content

feat: add licenses.validate endpoint to preview a license before applying#40858

Open
rodrigok wants to merge 3 commits into
developfrom
worktree-majestic-wibbling-jellyfish
Open

feat: add licenses.validate endpoint to preview a license before applying#40858
rodrigok wants to merge 3 commits into
developfrom
worktree-majestic-wibbling-jellyfish

Conversation

@rodrigok

@rodrigok rodrigok commented Jun 9, 2026

Copy link
Copy Markdown
Member

Adds a new POST /api/v1/licenses.validate REST endpoint that validates a Rocket.Chat license (V2 or V3 JWT) against the current workspace's validation structure without applying it, so the result can be previewed from the UI before the license is committed.

  • core-typings: new LicenseValidationResult type
  • license: LicenseManager.validateLicenseForPreview() runs the same validation pipeline used on apply (URL, periods, limits) without mutating state or emitting events; the shared licenseValidationBehaviors constant is reused by both the apply and preview paths to avoid duplication
  • rest-typings: isLicensesValidateProps schema + endpoint typing
  • meteor: licenses.validate route (edit-privileged-setting)

Proposed changes (including videos or screenshots)

Issue(s)

Steps to test or reproduce

Further comments

CORE-2104

Summary by CodeRabbit

  • New Features

    • Added a license validation preview option before applying a license.
    • The new check returns clear validation results so users can confirm whether a license is acceptable.
  • Bug Fixes

    • Improved validation feedback for invalid licenses and workspace mismatches.
    • Ensured preview validation does not change the current license or workspace state.

…ying

Adds a new `POST /api/v1/licenses.validate` REST endpoint that validates a
Rocket.Chat license (V2 or V3 JWT) against the current workspace's validation
structure without applying it, so the result can be previewed from the UI
before the license is committed.

- core-typings: new `LicenseValidationResult` type
- license: `LicenseManager.validateLicenseForPreview()` runs the same
  validation pipeline used on apply (URL, periods, limits) without mutating
  state or emitting events; the shared `licenseValidationBehaviors` constant
  is reused by both the apply and preview paths to avoid duplication
- rest-typings: `isLicensesValidateProps` schema + endpoint typing
- meteor: `licenses.validate` route (edit-privileged-setting)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@dionisio-bot

dionisio-bot Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Looks like this PR is not ready to merge, because of the following issues:

  • This PR is missing the 'stat: QA assured' label
  • This PR is targeting the wrong base branch. It should target 8.7.0, but it targets 8.6.0

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@coderabbitai

coderabbitai Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

This PR adds a new licenses.validate REST endpoint that performs dry-run validation of a Rocket.Chat license JWT against the current workspace without applying it. It introduces request typings, a validateLicenseForPreview method on LicenseManager, an authenticated route handler, accompanying tests, and changeset documentation.

Changes

License Preview Validation

Layer / File(s) Summary
REST endpoint type contract
packages/rest-typings/src/v1/licenses.ts
Adds licensesValidateProps schema and isLicensesValidateProps validator, and extends LicensesEndpoints with the new POST /v1/licenses.validate signature.
License preview validation implementation
ee/packages/license/src/license.ts
Extracts a shared licenseValidationBehaviors array used by validateLicense, adds validateLicenseForPreview to decrypt/normalize/validate a license without persisting state, and simplifies shouldPreventActionResultsMap cache logic.
License preview validation tests
ee/packages/license/src/validateLicenseForPreview.spec.ts
Adds tests for invalid format, not-ready validation, valid license preview, re-preview of active licenses, URL mismatch, expired invalidation periods, and expired disable_modules periods.
HTTP API endpoint handler
apps/meteor/ee/server/api/licenses.ts
Adds authenticated licenses.validate POST route gated by permission, returning failure with reasons or success based on preview validation.
Release documentation
.changeset/license-validate-preview.md
Bumps affected package versions and documents the new endpoint.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant LicensesRoute as licenses.validate route
  participant License as License.validateLicenseForPreview
  participant Validation as runValidation

  Client->>LicensesRoute: POST license string
  LicensesRoute->>License: validateLicenseForPreview(license)
  License->>License: decrypt and normalize to ILicenseV3
  License->>Validation: run with licenseValidationBehaviors
  Validation-->>License: validation reasons
  License-->>LicensesRoute: filtered invalidate/prevent reasons
  LicensesRoute-->>Client: success() or failure(license-invalid, reasons)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • ggazzo
  • cardoso
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: a new licenses.validate endpoint for previewing a license before applying it.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • CORE-2104: Request failed with status code 401

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@changeset-bot

changeset-bot Bot commented Jun 9, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 6463727

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

This PR includes changesets to release 4 packages
Name Type
@rocket.chat/license Minor
@rocket.chat/rest-typings Minor
@rocket.chat/meteor Minor
@rocket.chat/core-typings Minor

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

@codecov

codecov Bot commented Jun 9, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.00000% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.91%. Comparing base (021f169) to head (6463727).
⚠️ Report is 189 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #40858      +/-   ##
===========================================
- Coverage    70.17%   69.91%   -0.26%     
===========================================
  Files         3341     3381      +40     
  Lines       123645   130413    +6768     
  Branches     22050    22761     +711     
===========================================
+ Hits         86765    91178    +4413     
- Misses       33539    35940    +2401     
+ Partials      3341     3295      -46     
Flag Coverage Δ
unit 69.94% <80.00%> (-1.06%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@dougfabris dougfabris added this to the 8.6.0 milestone Jun 10, 2026
@rodrigok rodrigok marked this pull request as ready for review June 12, 2026 16:44
@rodrigok rodrigok requested review from a team as code owners June 12, 2026 16:44
@coderabbitai coderabbitai Bot added the type: feature Pull requests that introduces new feature label Jun 12, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (2)
ee/packages/license/src/validateLicenseForPreview.spec.ts (1)

3-95: ⚡ Quick win

Add a case that proves preview surfaces exceeded limits.

The implementation now appends 'prevent_action' to the preview behaviors, but this suite never drives a limit over its licensed max and asserts that validationErrors contains a prevent_action entry while isValid stays true. That is the main preview-only branch in ee/packages/license/src/license.ts, so it should have explicit coverage.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ee/packages/license/src/validateLicenseForPreview.spec.ts` around lines 3 -
95, Add a new test in the validateLicenseForPreview suite that builds a license
via MockedLicenseBuilder which sets a max limit lower than the usage so the
preview logic will produce a 'prevent_action' behavior; call
licenseManager.validateLicenseForPreview(...) with that license and assert
result.isFormatValid is true, result.isValid remains true, and
result.validationErrors contains an object with behavior: 'prevent_action' (and
appropriate reason), and ensure grantedModules still reflect allowed modules;
use validateLicenseForPreview, MockedLicenseBuilder, and licenseManager to
locate where to add this case.
ee/packages/license/src/license.ts (1)

337-341: ⚡ Quick win

Avoid decrypting the preview payload twice.

validateFormat() already verifies/decrypts the license, and this branch immediately calls decrypt() again before parsing. That doubles the crypto work for every preview request.

Suggested fix
 	let license: ILicenseV3;
 	try {
-		await validateFormat(encryptedLicense);
-
 		const decrypted = JSON.parse(await decrypt(encryptedLicense));
 		license = encryptedLicense.startsWith('RCV3_') ? decrypted : convertToV3(decrypted);
 	} catch (err) {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ee/packages/license/src/license.ts` around lines 337 - 341, The code decrypts
the preview payload twice: validateFormat(encryptedLicense) already
returns/produces the decrypted payload, but the branch still calls
decrypt(encryptedLicense) again; change validateFormat to return the decrypted
string/object (or have it return both a boolean and decrypted payload), then
replace the second decrypt call with the decrypted value from validateFormat
(e.g., const decryptedRaw = await validateFormat(encryptedLicense); const
decrypted = JSON.parse(decryptedRaw); license =
encryptedLicense.startsWith('RCV3_') ? decrypted : convertToV3(decrypted)),
updating function signatures/types for validateFormat if needed.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@ee/packages/license/src/license.ts`:
- Around line 333-361: validateLicenseForPreview currently skips the readiness
guard and calls runValidation on partial workspace state; add the same readiness
check used in setLicense/validateLicense by calling
isReadyForValidation.call(this) before invoking runValidation and, if it returns
false, short-circuit and return a LicenseValidationResult matching the other
guards (e.g., isFormatValid: true/false per existing logic, isValid: false,
workspaceUrl, empty grantedModules and validationErrors) so the preview mirrors
the apply-path readiness behavior; reference validateLicenseForPreview,
isReadyForValidation, runValidation, setLicense and validateLicense when making
the change.

---

Nitpick comments:
In `@ee/packages/license/src/license.ts`:
- Around line 337-341: The code decrypts the preview payload twice:
validateFormat(encryptedLicense) already returns/produces the decrypted payload,
but the branch still calls decrypt(encryptedLicense) again; change
validateFormat to return the decrypted string/object (or have it return both a
boolean and decrypted payload), then replace the second decrypt call with the
decrypted value from validateFormat (e.g., const decryptedRaw = await
validateFormat(encryptedLicense); const decrypted = JSON.parse(decryptedRaw);
license = encryptedLicense.startsWith('RCV3_') ? decrypted :
convertToV3(decrypted)), updating function signatures/types for validateFormat
if needed.

In `@ee/packages/license/src/validateLicenseForPreview.spec.ts`:
- Around line 3-95: Add a new test in the validateLicenseForPreview suite that
builds a license via MockedLicenseBuilder which sets a max limit lower than the
usage so the preview logic will produce a 'prevent_action' behavior; call
licenseManager.validateLicenseForPreview(...) with that license and assert
result.isFormatValid is true, result.isValid remains true, and
result.validationErrors contains an object with behavior: 'prevent_action' (and
appropriate reason), and ensure grantedModules still reflect allowed modules;
use validateLicenseForPreview, MockedLicenseBuilder, and licenseManager to
locate where to add this case.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 99090ac8-bcb3-43ec-88be-d20e32821295

📥 Commits

Reviewing files that changed from the base of the PR and between 1b88937 and 93bc1b7.

📒 Files selected for processing (7)
  • .changeset/license-validate-preview.md
  • apps/meteor/ee/server/api/licenses.ts
  • ee/packages/license/src/license.ts
  • ee/packages/license/src/validateLicenseForPreview.spec.ts
  • packages/core-typings/src/license/LicenseValidationResult.ts
  • packages/core-typings/src/license/index.ts
  • packages/rest-typings/src/v1/licenses.ts
📜 Review details
⏰ 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). (2)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Hacktron Security Check
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation

Files:

  • packages/core-typings/src/license/LicenseValidationResult.ts
  • packages/core-typings/src/license/index.ts
  • apps/meteor/ee/server/api/licenses.ts
  • packages/rest-typings/src/v1/licenses.ts
  • ee/packages/license/src/license.ts
  • ee/packages/license/src/validateLicenseForPreview.spec.ts
**/*.spec.ts

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.spec.ts: Use descriptive test names that clearly communicate expected behavior in Playwright tests
Use .spec.ts extension for test files (e.g., login.spec.ts)

Files:

  • ee/packages/license/src/validateLicenseForPreview.spec.ts
🧠 Learnings (8)
📚 Learning: 2026-03-16T21:50:37.589Z
Learnt from: amitb0ra
Repo: RocketChat/Rocket.Chat PR: 39676
File: .changeset/migrate-users-register-openapi.md:3-3
Timestamp: 2026-03-16T21:50:37.589Z
Learning: For changes related to OpenAPI migrations in Rocket.Chat/OpenAPI, when removing endpoint types and validators from rocket.chat/rest-typings (e.g., UserRegisterParamsPOST, /v1/users.register) document this as a minor changeset (not breaking) per RocketChat/Rocket.Chat-Open-API#150 Rule 7. Note that the endpoint type is re-exposed via a module augmentation .d.ts in the consuming package (e.g., packages/web-ui-registration/src/users-register.d.ts). In reviews, ensure the changeset clearly states: this is a non-breaking change, the major version should not be bumped, and the changeset reflects a minor version bump. Do not treat this as a breaking change during OpenAPI migrations.

Applied to files:

  • .changeset/license-validate-preview.md
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.

Applied to files:

  • packages/core-typings/src/license/LicenseValidationResult.ts
  • packages/core-typings/src/license/index.ts
  • apps/meteor/ee/server/api/licenses.ts
  • packages/rest-typings/src/v1/licenses.ts
  • ee/packages/license/src/license.ts
  • ee/packages/license/src/validateLicenseForPreview.spec.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.

Applied to files:

  • packages/core-typings/src/license/LicenseValidationResult.ts
  • packages/core-typings/src/license/index.ts
  • apps/meteor/ee/server/api/licenses.ts
  • packages/rest-typings/src/v1/licenses.ts
  • ee/packages/license/src/license.ts
  • ee/packages/license/src/validateLicenseForPreview.spec.ts
📚 Learning: 2026-05-06T12:21:44.083Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 40256
File: apps/meteor/client/components/CreateDiscussion/CreateDiscussion.tsx:121-149
Timestamp: 2026-05-06T12:21:44.083Z
Learning: Field wrappers in rocket.chat/fuselage-forms (Field, FieldLabel, FieldRow, FieldError, FieldHint) auto-create htmlFor/id associations, aria-describedby, and role="alert" for errors. Do not manually set htmlFor, id, aria-describedby, or role attributes when using these wrappers. This automatic wiring does not apply to plain rocket.chat/fuselage components, which require explicit ID wiring per the accessibility docs. In code reviews, prefer using fuselage-forms wrappers for form fields and verify there is no unnecessary manual ID/aria wiring in files that use these wrappers. If a component uses plain fuselage components, ensure proper id wiring as per docs.

Applied to files:

  • packages/core-typings/src/license/LicenseValidationResult.ts
  • packages/core-typings/src/license/index.ts
  • apps/meteor/ee/server/api/licenses.ts
  • packages/rest-typings/src/v1/licenses.ts
  • ee/packages/license/src/license.ts
  • ee/packages/license/src/validateLicenseForPreview.spec.ts
📚 Learning: 2026-05-11T23:14:59.316Z
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 40469
File: packages/rest-typings/src/v1/users.ts:337-337
Timestamp: 2026-05-11T23:14:59.316Z
Learning: In Rocket.Chat REST endpoint typings (e.g., packages/rest-typings/src/v1/users.ts and other rest-typings files), keep the established convention of deriving field types from the domain model (e.g., use IUser indexed access like IUser['statusExpiresAt']) rather than swapping individual fields to serialized primitives (like string) in an ad-hoc way. If a truly different “serialized” representation is needed, perform the refactor consistently across the codebase (not just a single endpoint/field) and ensure all related REST typings stay aligned with the shared serialization types.

Applied to files:

  • packages/rest-typings/src/v1/licenses.ts
📚 Learning: 2025-12-10T21:00:43.645Z
Learnt from: KevLehman
Repo: RocketChat/Rocket.Chat PR: 37091
File: ee/packages/abac/jest.config.ts:4-7
Timestamp: 2025-12-10T21:00:43.645Z
Learning: Adopt the monorepo-wide Jest testMatch pattern: <rootDir>/src/**/*.spec.{ts,js,mjs} (represented here as '**/src/**/*.spec.{ts,js,mjs}') to ensure spec files under any package's src directory are picked up consistently across all packages in the Rocket.Chat monorepo. Apply this pattern in jest.config.ts for all relevant packages to maintain uniform test discovery.

Applied to files:

  • ee/packages/license/src/validateLicenseForPreview.spec.ts
📚 Learning: 2026-02-24T19:22:48.358Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 38493
File: apps/meteor/tests/e2e/omnichannel/omnichannel-send-pdf-transcript.spec.ts:66-67
Timestamp: 2026-02-24T19:22:48.358Z
Learning: In Playwright end-to-end tests (e.g., under apps/meteor/tests/e2e/...), prefer locating elements by translated text (getByText) and ARIA roles (getByRole) over data-qa attributes. If translation values change, update the corresponding test locators accordingly. Never use data-qa locators. This guideline applies to all Playwright e2e test specs in the repository and helps keep tests robust to UI text changes and accessible semantics.

Applied to files:

  • ee/packages/license/src/validateLicenseForPreview.spec.ts
📚 Learning: 2026-03-06T18:10:15.268Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/code/CodeBlock.spec.tsx:47-68
Timestamp: 2026-03-06T18:10:15.268Z
Learning: In tests (especially those using testing-library/dom/jsdom) for Rocket.Chat components, the HTML <code> element has an implicit ARIA role of 'code'. Therefore, screen.getByRole('code') or screen.findByRole('code') will locate <code> elements even without a role attribute. Do not flag findByRole('code') as invalid in reviews; prefer using the implicit role instead of adding role="code" unless necessary for accessibility.

Applied to files:

  • ee/packages/license/src/validateLicenseForPreview.spec.ts
🔇 Additional comments (4)
.changeset/license-validate-preview.md (1)

1-8: LGTM!

packages/core-typings/src/license/LicenseValidationResult.ts (1)

1-33: LGTM!

packages/core-typings/src/license/index.ts (1)

11-11: LGTM!

packages/rest-typings/src/v1/licenses.ts (1)

1-1: LGTM!

Also applies to: 39-55, 66-68

Comment thread ee/packages/license/src/license.ts Outdated

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

1 issue found across 7 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="ee/packages/license/src/license.ts">

<violation number="1" location="ee/packages/license/src/license.ts:357">
P2: Missing `isReadyForValidation` guard before calling `runValidation`. Both `validateLicense()` and `setLicense()` check `isReadyForValidation.call(this)` and throw `NotReadyForValidation` when the workspace isn't fully configured (e.g., workspace URL not yet set). Without the same guard here, the preview endpoint can validate against incomplete state and return misleading results. Add the readiness check (returning an appropriate error in the result) before running validation.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread ee/packages/license/src/license.ts
Reworks the licenses.validate endpoint so a valid license responds with a
plain success and an invalid one responds with the validation behaviors that
rejected it, instead of always returning a full validation result object.

- license: validateLicenseForPreview now returns the invalidating
  BehaviorWithContext[] (empty means accepted), guards with
  isReadyForValidation, and throws InvalidLicenseError on a malformed string,
  mirroring the apply path and reusing licenseValidationBehaviors/runValidation
- meteor: route returns API.v1.success() when valid, API.v1.failure() with the
  reasons when not
- rest-typings: licenses.validate POST now returns void
- core-typings: drop the now-unused LicenseValidationResult type

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
ee/packages/license/src/validateLicenseForPreview.spec.ts (1)

1-85: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Solid coverage of the new contract.

Tests correctly assert InvalidLicenseError/NotReadyForValidation rejections, the reasons array shape, and that previewing never applies the license (lines 29-31). One gap: there's no test asserting a prevent_installation reason is surfaced, even though validateLicenseForPreview explicitly filters for it (license.ts filterBehaviorsResult(..., ['invalidate_license', 'prevent_installation'])). Consider adding one for completeness.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ee/packages/license/src/validateLicenseForPreview.spec.ts` around lines 1 -
85, Add coverage for the missing preview contract case where
validateLicenseForPreview should surface a prevent_installation reason. Extend
the tests in validateLicenseForPreview.spec.ts with a scenario that builds a
license triggering that behavior and assert the returned reasons include
prevent_installation, alongside the existing invalidate_license checks. Use the
same helpers already present, especially MockedLicenseBuilder and
getReadyLicenseManager, to keep the test aligned with validateLicenseForPreview
in LicenseImp.
ee/packages/license/src/license.ts (1)

336-359: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Avoid decrypting/verifying the license twice.

validateFormat(encryptedLicense) already calls decrypt(encryptedLicense) internally to confirm the format is valid, then this method calls decrypt(encryptedLicense) again right after. For V3 licenses, decrypt performs JWT signature verification, so this redundantly runs the crypto verification step twice per preview call.

♻️ Proposed fix to decrypt only once
 public async validateLicenseForPreview(encryptedLicense: string): Promise<BehaviorWithContext[]> {
 	if (!isReadyForValidation.call(this)) {
 		throw new NotReadyForValidation();
 	}

-	await validateFormat(encryptedLicense);
+	if (!encryptedLicense || String(encryptedLicense).trim() === '') {
+		throw new InvalidLicenseError('Empty license');
+	}

 	let license: ILicenseV3;
 	try {
 		const decrypted = JSON.parse(await decrypt(encryptedLicense));
 		license = encryptedLicense.startsWith('RCV3_') ? decrypted : convertToV3(decrypted);
 	} catch (err) {
 		logger.error({ msg: 'Invalid raw license provided for validation preview', err });
 		throw new InvalidLicenseError();
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ee/packages/license/src/license.ts` around lines 336 - 359,
validateLicenseForPreview currently decrypts the same license twice because
validateFormat(encryptedLicense) already performs decryption/verification before
the method decrypts again in its try block. Refactor validateLicenseForPreview
in license.ts so the decrypted payload from the existing format-validation path
is reused (or returned) instead of calling decrypt(encryptedLicense) a second
time, while preserving the current RCV3_ / convertToV3 handling and error flow
with InvalidLicenseError.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@ee/packages/license/src/license.ts`:
- Around line 336-359: validateLicenseForPreview currently decrypts the same
license twice because validateFormat(encryptedLicense) already performs
decryption/verification before the method decrypts again in its try block.
Refactor validateLicenseForPreview in license.ts so the decrypted payload from
the existing format-validation path is reused (or returned) instead of calling
decrypt(encryptedLicense) a second time, while preserving the current RCV3_ /
convertToV3 handling and error flow with InvalidLicenseError.

In `@ee/packages/license/src/validateLicenseForPreview.spec.ts`:
- Around line 1-85: Add coverage for the missing preview contract case where
validateLicenseForPreview should surface a prevent_installation reason. Extend
the tests in validateLicenseForPreview.spec.ts with a scenario that builds a
license triggering that behavior and assert the returned reasons include
prevent_installation, alongside the existing invalidate_license checks. Use the
same helpers already present, especially MockedLicenseBuilder and
getReadyLicenseManager, to keep the test aligned with validateLicenseForPreview
in LicenseImp.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 896a2682-82a2-4e20-bb70-b3a00d9bb664

📥 Commits

Reviewing files that changed from the base of the PR and between 93bc1b7 and 6463727.

📒 Files selected for processing (5)
  • .changeset/license-validate-preview.md
  • apps/meteor/ee/server/api/licenses.ts
  • ee/packages/license/src/license.ts
  • ee/packages/license/src/validateLicenseForPreview.spec.ts
  • packages/rest-typings/src/v1/licenses.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (5)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: CodeQL-Build
  • GitHub Check: Hacktron Security Check
  • GitHub Check: CodeQL-Build
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation

Files:

  • packages/rest-typings/src/v1/licenses.ts
  • apps/meteor/ee/server/api/licenses.ts
  • ee/packages/license/src/validateLicenseForPreview.spec.ts
  • ee/packages/license/src/license.ts
**/*.spec.ts

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.spec.ts: Use descriptive test names that clearly communicate expected behavior in Playwright tests
Use .spec.ts extension for test files (e.g., login.spec.ts)

Files:

  • ee/packages/license/src/validateLicenseForPreview.spec.ts
🧠 Learnings (8)
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.

Applied to files:

  • packages/rest-typings/src/v1/licenses.ts
  • apps/meteor/ee/server/api/licenses.ts
  • ee/packages/license/src/validateLicenseForPreview.spec.ts
  • ee/packages/license/src/license.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.

Applied to files:

  • packages/rest-typings/src/v1/licenses.ts
  • apps/meteor/ee/server/api/licenses.ts
  • ee/packages/license/src/validateLicenseForPreview.spec.ts
  • ee/packages/license/src/license.ts
📚 Learning: 2026-05-06T12:21:44.083Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 40256
File: apps/meteor/client/components/CreateDiscussion/CreateDiscussion.tsx:121-149
Timestamp: 2026-05-06T12:21:44.083Z
Learning: Field wrappers in rocket.chat/fuselage-forms (Field, FieldLabel, FieldRow, FieldError, FieldHint) auto-create htmlFor/id associations, aria-describedby, and role="alert" for errors. Do not manually set htmlFor, id, aria-describedby, or role attributes when using these wrappers. This automatic wiring does not apply to plain rocket.chat/fuselage components, which require explicit ID wiring per the accessibility docs. In code reviews, prefer using fuselage-forms wrappers for form fields and verify there is no unnecessary manual ID/aria wiring in files that use these wrappers. If a component uses plain fuselage components, ensure proper id wiring as per docs.

Applied to files:

  • packages/rest-typings/src/v1/licenses.ts
  • apps/meteor/ee/server/api/licenses.ts
  • ee/packages/license/src/validateLicenseForPreview.spec.ts
  • ee/packages/license/src/license.ts
📚 Learning: 2026-05-11T23:14:59.316Z
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 40469
File: packages/rest-typings/src/v1/users.ts:337-337
Timestamp: 2026-05-11T23:14:59.316Z
Learning: In Rocket.Chat REST endpoint typings (e.g., packages/rest-typings/src/v1/users.ts and other rest-typings files), keep the established convention of deriving field types from the domain model (e.g., use IUser indexed access like IUser['statusExpiresAt']) rather than swapping individual fields to serialized primitives (like string) in an ad-hoc way. If a truly different “serialized” representation is needed, perform the refactor consistently across the codebase (not just a single endpoint/field) and ensure all related REST typings stay aligned with the shared serialization types.

Applied to files:

  • packages/rest-typings/src/v1/licenses.ts
📚 Learning: 2025-12-10T21:00:43.645Z
Learnt from: KevLehman
Repo: RocketChat/Rocket.Chat PR: 37091
File: ee/packages/abac/jest.config.ts:4-7
Timestamp: 2025-12-10T21:00:43.645Z
Learning: Adopt the monorepo-wide Jest testMatch pattern: <rootDir>/src/**/*.spec.{ts,js,mjs} (represented here as '**/src/**/*.spec.{ts,js,mjs}') to ensure spec files under any package's src directory are picked up consistently across all packages in the Rocket.Chat monorepo. Apply this pattern in jest.config.ts for all relevant packages to maintain uniform test discovery.

Applied to files:

  • ee/packages/license/src/validateLicenseForPreview.spec.ts
📚 Learning: 2026-02-24T19:22:48.358Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 38493
File: apps/meteor/tests/e2e/omnichannel/omnichannel-send-pdf-transcript.spec.ts:66-67
Timestamp: 2026-02-24T19:22:48.358Z
Learning: In Playwright end-to-end tests (e.g., under apps/meteor/tests/e2e/...), prefer locating elements by translated text (getByText) and ARIA roles (getByRole) over data-qa attributes. If translation values change, update the corresponding test locators accordingly. Never use data-qa locators. This guideline applies to all Playwright e2e test specs in the repository and helps keep tests robust to UI text changes and accessible semantics.

Applied to files:

  • ee/packages/license/src/validateLicenseForPreview.spec.ts
📚 Learning: 2026-03-06T18:10:15.268Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/code/CodeBlock.spec.tsx:47-68
Timestamp: 2026-03-06T18:10:15.268Z
Learning: In tests (especially those using testing-library/dom/jsdom) for Rocket.Chat components, the HTML <code> element has an implicit ARIA role of 'code'. Therefore, screen.getByRole('code') or screen.findByRole('code') will locate <code> elements even without a role attribute. Do not flag findByRole('code') as invalid in reviews; prefer using the implicit role instead of adding role="code" unless necessary for accessibility.

Applied to files:

  • ee/packages/license/src/validateLicenseForPreview.spec.ts
📚 Learning: 2026-03-16T21:50:37.589Z
Learnt from: amitb0ra
Repo: RocketChat/Rocket.Chat PR: 39676
File: .changeset/migrate-users-register-openapi.md:3-3
Timestamp: 2026-03-16T21:50:37.589Z
Learning: For changes related to OpenAPI migrations in Rocket.Chat/OpenAPI, when removing endpoint types and validators from rocket.chat/rest-typings (e.g., UserRegisterParamsPOST, /v1/users.register) document this as a minor changeset (not breaking) per RocketChat/Rocket.Chat-Open-API#150 Rule 7. Note that the endpoint type is re-exposed via a module augmentation .d.ts in the consuming package (e.g., packages/web-ui-registration/src/users-register.d.ts). In reviews, ensure the changeset clearly states: this is a non-breaking change, the major version should not be bumped, and the changeset reflects a minor version bump. Do not treat this as a breaking change during OpenAPI migrations.

Applied to files:

  • .changeset/license-validate-preview.md
🪛 LanguageTool
.changeset/license-validate-preview.md

[style] ~7-~7: ‘with success’ might be wordy. Consider a shorter alternative.
Context: ...d from the UI. A valid license responds with success; an invalid one responds with the valid...

(EN_WORDINESS_PREMIUM_WITH_SUCCESS)

🔇 Additional comments (5)
.changeset/license-validate-preview.md (1)

1-8: LGTM!

packages/rest-typings/src/v1/licenses.ts (1)

56-68: LGTM!

ee/packages/license/src/license.ts (1)

55-63: LGTM!

Also applies to: 279-279, 457-460, 475-477

apps/meteor/ee/server/api/licenses.ts (2)

1-3: LGTM!

Also applies to: 74-77


78-88: 🗄️ Data Integrity & Integration | ⚡ Quick win

Unhandled NotReadyForValidation/InvalidLicenseError will bypass the structured failure shape.

License.validateLicenseForPreview throws NotReadyForValidation and InvalidLicenseError for malformed/premature input (per ee/packages/license/src/license.ts), but this handler has no try/catch around the call. Rocket.Chat's REST framework (Restivus) does catch thrown errors generically and emits a JSON failure, but the resulting payload (error, stack, errorType) will differ in shape from the deliberate { error: 'license-invalid', reasons } failure used for actual invalid licenses — clients previewing a malformed/empty license string would get an inconsistent error contract from the same endpoint.

Worth confirming whether the UI consuming this endpoint needs a consistent shape for all failure modes, and if so, wrapping the call to normalize the response.

#!/bin/bash
# Check how sibling licenses.add route handles License errors for comparison
ast-grep run --pattern $'API.v1.addRoute(\n  $$$\n)' --lang typescript apps/meteor/ee/server/api/licenses.ts
rg -n -B2 -A15 "licenses.add" apps/meteor/ee/server/api/licenses.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: feature Pull requests that introduces new feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants