Skip to content

fix(lastfm): stabilize callback origin for connect flow - #163

Merged
LucasSantana-Dev merged 3 commits into
mainfrom
fix/prod-lastfm-origin-state-callback
Mar 12, 2026
Merged

LucasSantana-Dev merged 3 commits into
mainfrom
fix/prod-lastfm-origin-state-callback

Conversation

@LucasSantana-Dev

@LucasSantana-Dev LucasSantana-Dev commented Mar 11, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • harden Last.fm backend callback origin resolution in /api/lastfm/connect
  • ignore invalid/non-absolute WEBAPP_BACKEND_URL values and fall back to OAuth-derived origin
  • keep endpoint contracts unchanged and preserve signed state flow
  • document WEBAPP_BACKEND_URL as absolute URL in README
  • add changelog entry for production Last.fm connect hardening

Why

Production smoke on March 11, 2026 observed Last.fm connect redirects with a relative callback parameter (cb=%2Fapi%2Flastfm%2Fcallback...) in one environment path, which can break split-origin linking. This change guarantees an absolute callback URL is used.

Tests

  • npm run test --workspace=packages/backend -- tests/integration/routes/lastfm.test.ts
  • npm run test --workspace=packages/frontend -- src/services/api.test.ts
  • npm run lint

Notes

  • Added regression test for WEBAPP_BACKEND_URL='/' to ensure fallback to OAuth-derived origin.

Summary by CodeRabbit

  • Bug Fixes

    • Last.fm callback URL generation now ignores invalid/relative backend URLs and falls back to the OAuth redirect origin so production links use an absolute callback host.
    • Bot "/lastfm link" now prioritizes the absolute backend URL for generated links, preventing stale legacy domains in embeds.
  • Documentation

    • Clarified that WEBAPP_BACKEND_URL must be an absolute URL and documented the fallback to the redirect URI origin for Last.fm connect links.

@vercel

vercel Bot commented Mar 11, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lucky Ready Ready Preview, Comment Mar 12, 2026 3:14am

Request Review

@netlify

netlify Bot commented Mar 11, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for regal-bunny-0c8efe ready!

Name Link
🔨 Latest commit 43e8221
🔍 Latest deploy log https://app.netlify.com/projects/regal-bunny-0c8efe/deploys/69b22f5ad3d062000882e7a9
😎 Deploy Preview https://deploy-preview-163--regal-bunny-0c8efe.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai

coderabbitai Bot commented Mar 11, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@LucasSantana-Dev has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 22 minutes and 38 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b42c7fd2-0dba-4e1b-8f0d-61ae3736996b

📥 Commits

Reviewing files that changed from the base of the PR and between a346eac and 43e8221.

📒 Files selected for processing (8)
  • CHANGELOG.md
  • README.md
  • docs/LASTFM_SETUP.md
  • packages/backend/jest.config.cjs
  • packages/backend/src/routes/lastfm.ts
  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/bot/src/functions/general/commands/lastfm.ts
📝 Walkthrough

Walkthrough

Backend and bot now prefer an absolute WEBAPP_BACKEND_URL for generating Last.fm connect/callback origins; if that value is absent or not absolute, both fall back to the origin derived from WEBAPP_REDIRECT_URI. Documentation and tests updated to reflect and validate this behavior.

Changes

Cohort / File(s) Summary
Documentation
CHANGELOG.md, README.md, docs/LASTFM_SETUP.md
Clarified that WEBAPP_BACKEND_URL must be an absolute URL and is the canonical host for Last.fm connect links; documented fallback to the origin of WEBAPP_REDIRECT_URI.
Backend Last.fm route
packages/backend/src/routes/lastfm.ts
Added parseAbsoluteOrigin() and refactored resolveBackendBaseUrl() to use parsed WEBAPP_BACKEND_URL origin when valid, otherwise fall back to OAuth-derived origin. Minor formatting adjustments.
Backend tests
packages/backend/tests/integration/routes/lastfm.test.ts
Added integration test verifying fallback to OAuth origin when WEBAPP_BACKEND_URL is non-absolute (e.g., '/'), ensuring redirect location encodes correct callback state.
Bot command implementation
packages/bot/src/functions/general/commands/lastfm.ts
Added getAbsoluteOrigin() helper and changed getConnectUrl to prefer WEBAPP_BACKEND_URL origin (fallback: WEBAPP_REDIRECT_URI origin); updated error messaging accordingly.
Bot tests
packages/bot/src/functions/general/commands/lastfm.spec.ts
New Jest suite covering connect URL generation: prefers backend URL, normalizes trailing slashes, falls back to redirect URI (including legacy paths), and asserts error cases for missing config/secrets.
Test config
packages/backend/jest.config.cjs
Adjusted coverage rules to explicitly include playbackRoutes.ts in collectCoverageFrom while leaving lastfm.ts excluded.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: stabilizing the Last.fm callback origin for the connect flow by enforcing absolute URLs and fallback logic.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/prod-lastfm-origin-state-callback

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 and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/backend/src/routes/lastfm.ts (1)

210-215: Consider extracting the nested ternary for readability.

SonarCloud flags the nested ternary as a code smell. While functionally correct, extracting this to a helper or sequential checks would improve readability.

♻️ Suggested refactor
-            const state =
-                typeof parsedQuery.data.state === 'string'
-                    ? parsedQuery.data.state
-                    : typeof stateFromCookie === 'string'
-                      ? stateFromCookie
-                      : null
+            const state = extractState(parsedQuery.data.state, stateFromCookie)

Add a helper function near the top of the file:

function extractState(
    queryState: string | undefined,
    cookieState: unknown,
): string | null {
    if (typeof queryState === 'string') return queryState
    if (typeof cookieState === 'string') return cookieState
    return null
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/backend/src/routes/lastfm.ts` around lines 210 - 215, Extract the
nested ternary that computes the state into a small helper to improve
readability: create a function (e.g., extractState(queryState, cookieState))
that returns queryState if it's a string, else cookieState if it's a string,
else null, and replace the existing ternary assignment to the local variable
state (which currently uses parsedQuery.data.state and stateFromCookie) with a
call to that helper.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/backend/src/routes/lastfm.ts`:
- Around line 210-215: Extract the nested ternary that computes the state into a
small helper to improve readability: create a function (e.g.,
extractState(queryState, cookieState)) that returns queryState if it's a string,
else cookieState if it's a string, else null, and replace the existing ternary
assignment to the local variable state (which currently uses
parsedQuery.data.state and stateFromCookie) with a call to that helper.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 585e4439-b3a0-4982-83bd-be91a19e1d4c

📥 Commits

Reviewing files that changed from the base of the PR and between 15070aa and 5f20bfd.

📒 Files selected for processing (4)
  • CHANGELOG.md
  • README.md
  • packages/backend/src/routes/lastfm.ts
  • packages/backend/tests/integration/routes/lastfm.test.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: Quality Gates
  • GitHub Check: SonarCloud Scan
🧰 Additional context used
📓 Path-based instructions (24)
**/*.{js,jsx,ts,tsx,vue,html}

📄 CodeRabbit inference engine (.cursor/rules/accessibility-openness.mdc)

Provide accessible UI components using semantic HTML and ARIA attributes where necessary

Files:

  • packages/backend/src/routes/lastfm.ts
  • packages/backend/tests/integration/routes/lastfm.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/dependency-injection.mdc)

**/*.{ts,tsx,js,jsx}: Prefer constructor injection for classes that require dependencies
Avoid global mutable singletons unless necessary
Use explicit interfaces for external dependencies to make testing easier

**/*.{ts,tsx,js,jsx}: Include required references in PRs/code for non-trivial logic: TypeScript (official docs), MDN (JavaScript reference), and official docs for any runtime/framework/libraries used (e.g., Node.js, React) as applicable.
Before assuming behavior of an API, include the doc link and a ≤25-word quote when the change relies on it.

**/*.{ts,tsx,js,jsx}: Prefer named exports for clear usage and easier refactors in TypeScript/JavaScript
Keep import order consistent: external first, then internal modules
Remove dead code and unused imports

**/*.{ts,tsx,js,jsx}: Use PascalCase naming convention for React/UI components
Use camelCase naming convention for variables and functions
Use UPPER_SNAKE_CASE naming convention for constants
Maintain consistent import grouping and ordering within the project, keeping third-party imports separate from local imports
For external data sources (HTTP, database), always validate and sanitize input using type guards or schema validators

**/*.{ts,tsx,js,jsx}: Use Prettier with no semicolons, single quotes, 4-space indent, 80 character width
Files must not exceed 250 lines and this is enforced

Implement TypeScript typecheck and linter in CI quality checks

**/*.{ts,tsx,js,jsx}: Use TypeScript for enhanced type safety
Implement error handling and error logging
Avoid commenting code unless extremely necessary - code should explain itself with descriptive names
Leave NO todos, placeholders or missing pieces in the code
Variables and functions must use camelCase
Constants must use UPPER_SNAKE_CASE
Use arrow functions for methods and computed properties
Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements
Maintain consistent import grouping/order: external imports first, then...

Files:

  • packages/backend/src/routes/lastfm.ts
  • packages/backend/tests/integration/routes/lastfm.test.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/error-handling.mdc)

**/*.{js,jsx,ts,tsx}: Never throw strings. Throw Error (or typed subclasses) with descriptive messages
Include causal error as cause when available for better debugging
Define clear, stable error codes (e.g., ERR_AUTH_EXPIRED, ERR_NETWORK_TIMEOUT)
Provide optional metadata (e.g., details, retryable, status, correlationId) in error objects
Use domain error classes per area (e.g., AuthenticationError, ValidationError, NetworkError)
Log errors with structure (message, code, stack, cause, correlationId, user context where appropriate)
Mark retryable vs nonRetryable errors where helpful for operations
Set timeouts and handle aborts/cancellations; avoid dangling requests in API/network code
Implement backoff for transient failures; avoid infinite retries
Map HTTP status → domain errors; 4xx vs 5xx behave differently (e.g., retry for 5xx/network)

**/*.{js,jsx,ts,tsx}: Use functional components with hooks in React/React Native. Avoid class components.
Keep components focused on a single responsibility; extract complex logic into custom hooks.
Keep state local when possible. Use Context/Zustand/Redux only when necessary for state management.
If props or state traverse more than 3 levels, consider using context or a feature-scoped store instead of prop drilling.
Use performance optimization techniques: React.memo, useMemo, useCallback, Suspense (web), and virtualization for long lists; avoid unnecessary re-renders.
Web accessibility: use semantic HTML, labels, focus management, keyboard navigation, and aria-* attributes as needed.
React Native accessibility: use accessibility props (accessible, accessibilityLabel), proper roles and labels.
Identify and extract repetitive UI components proactively to components/ with clear props and minimal coupling.
Web styles: prefer co-located styles or design system tokens; avoid global style leakage.
React Native styles: prefer StyleSheet.create, design tokens, and theme providers; avoid in...

Files:

  • packages/backend/src/routes/lastfm.ts
  • packages/backend/tests/integration/routes/lastfm.test.ts
**/*.{ts,tsx}

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

Introduce interfaces at module boundaries to enable testing and substitutions

**/*.{ts,tsx}: Avoid using any type in TypeScript. If unavoidable, use unknown with type guards and justify with a code comment
Prefer interface for defining public object shapes in TypeScript, use type for unions and utility types
Use TypeScript utility types such as Partial, Pick, Omit, Readonly, and Record when appropriate
Use I{Name} naming convention for interfaces in TypeScript
Use T{Name} naming convention for type aliases and utility types in TypeScript

**/*.{ts,tsx}: Functions must be less than 50 lines with cyclomatic complexity less than 10
Do not use any types - ESLint enforces this at error level

**/*.{ts,tsx}: Prefer types over interfaces for most cases
Don't ever use any - type safety always
Avoid enums; use const objects instead
For complex types, create a separate file to declare them and import them
Avoid using any type; if unavoidable, use unknown with type guards and justify with code comment
Prefer interface for public API shapes; use type for unions and utility types
Use TypeScript utility types (Partial, Pick, Omit, Readonly, Record)

Files:

  • packages/backend/src/routes/lastfm.ts
  • packages/backend/tests/integration/routes/lastfm.test.ts
packages/backend/src/routes/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

packages/backend/src/routes/**/*.ts: Backend route handlers must use asyncHandler wrapper and throw AppError.xxx() instead of manual try/catch blocks
Rate limiting: use apiLimiter (100/min), authLimiter (20/15min), or writeLimiter (30/min) as appropriate

Place routes under packages/backend/src/routes/ directory

Files:

  • packages/backend/src/routes/lastfm.ts
packages/backend/src/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

packages/backend/src/**/*.ts: Validation must use Zod schemas in backend/src/schemas/ and be applied via validateBody, validateParams, or validateQuery
Do not reassign req.query in Express middleware - it is read-only in Express 5

Files:

  • packages/backend/src/routes/lastfm.ts
**/*.{js,ts,tsx,jsx}

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

**/*.{js,ts,tsx,jsx}: Minimize comments in code; explain the 'why' when non-obvious, let code express the 'what' through clear naming
Document trade-offs briefly when deviating from ideal patterns

**/*.{js,ts,tsx,jsx}: Store secrets, ports, and hosts in environment variables (.env, .env.example) and never hardcode them
Avoid redundant or decorative AI comments; code should be self-explanatory and only commented when logic is non-obvious; prefer refactoring over lengthy comments

Files:

  • packages/backend/src/routes/lastfm.ts
  • packages/backend/tests/integration/routes/lastfm.test.ts
packages/backend/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-backend-api.mdc)

packages/backend/src/**/*.{ts,tsx}: Use shared config and env from @lucky/shared when needed; avoid duplicating env parsing in backend code
Keep tokens and secrets in environment variables only; never hardcode or expose in code

Files:

  • packages/backend/src/routes/lastfm.ts
packages/backend/src/{routes,middleware}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-backend-api.mdc)

Return consistent JSON error responses with appropriate HTTP status codes; do not expose stack traces or secrets in responses

Files:

  • packages/backend/src/routes/lastfm.ts
packages/backend/src/routes/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-backend-api.mdc)

Structure routes in packages/backend/src/routes/ directory with separate files for auth, guilds, toggles, and index routes

Files:

  • packages/backend/src/routes/lastfm.ts
packages/backend/**

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

The backend package depends on shared and contains Express API with auth and guild routes

Files:

  • packages/backend/src/routes/lastfm.ts
  • packages/backend/tests/integration/routes/lastfm.test.ts
**/*.{js,mjs,ts,mts}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Use Node.js version ≥22 with ESM (ECMAScript modules) only; no CommonJS

Files:

  • packages/backend/src/routes/lastfm.ts
  • packages/backend/tests/integration/routes/lastfm.test.ts
packages/backend/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-backend.mdc)

packages/backend/**/*.ts: Apply .cursor/rules/lucky-backend-api.mdc for structure and conventions when acting as backend specialist
Use .cursor/skills/backend-express/SKILL.md for Express routes, middleware, and services when acting as backend specialist
Use @lucky/shared for config and DB/Redis when needed in backend code

Files:

  • packages/backend/src/routes/lastfm.ts
  • packages/backend/tests/integration/routes/lastfm.test.ts
{CHANGELOG.md,README.md}

📄 CodeRabbit inference engine (.cursor/rules/agent-rules.mdc)

ALWAYS update CHANGELOG.md and README.md as changes are made.

Files:

  • README.md
  • CHANGELOG.md
README.md

📄 CodeRabbit inference engine (.cursor/rules/templates-examples.mdc)

README.md must be updated if behavior changed

Update README.md if behavior changed

Files:

  • README.md
**/*.{test,spec}.{js,jsx,ts,tsx}

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

**/*.{test,spec}.{js,jsx,ts,tsx}: Test behavior, not implementation. Prefer Testing Library utilities for testing React/React Native components.
For React Native tests: mock native modules and test component interactions and accessibility labels.

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

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

**/*.{test,spec}.{ts,tsx,js,jsx}: Test behavior, not implementation details
Prefer unit tests for core logic; add integration tests at meaningful boundaries

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/testing-quality.mdc)

**/*.{test,spec}.{js,ts,jsx,tsx}: Use Jest + a React testing library for unit and component tests as applicable
Test behavior, not implementation details

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
packages/backend/tests/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-backend-api.mdc)

Organize tests in packages/backend/tests/ with unit tests under unit/ and integration tests under integration/, following existing patterns with fixtures and setup

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
{packages/*/tests/**/*.test.{js,ts},tests/**/*.test.{js,ts}}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Add or adjust unit and integration tests when changing behavior; follow existing patterns in packages/*/tests and root tests/ directories

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
**/*.{spec,test}.{ts,tsx,js,jsx}

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

**/*.{spec,test}.{ts,tsx,js,jsx}: Use Jest for unit and integration tests
Test behavior, not implementation details
Run unit, integration tests, and coverage report in CI quality checks

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
packages/backend/tests/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-backend.mdc)

Follow existing patterns for unit and integration tests in packages/backend/tests/

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
CHANGELOG.md

📄 CodeRabbit inference engine (.cursor/rules/templates-examples.mdc)

CHANGELOG.md must be updated with all changes in pull requests

Always update CHANGELOG.md with all code changes

Update CHANGELOG.md with all changes, include breaking changes documentation, and reference issues and PRs

Files:

  • CHANGELOG.md
{CHANGELOG.md,docs/**}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Update CHANGELOG.md and relevant docs/ files when behavior or setup changes

Files:

  • CHANGELOG.md
🧠 Learnings (10)
📚 Learning: 2026-03-09T20:20:56.345Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-frontend.mdc:0-0
Timestamp: 2026-03-09T20:20:56.345Z
Learning: Applies to packages/frontend/src/**/*.{ts,tsx} : Do not depend on `lucky/shared` package in frontend code; make API calls to backend via configured base URL (env)

Applied to files:

  • packages/backend/src/routes/lastfm.ts
  • packages/backend/tests/integration/routes/lastfm.test.ts
📚 Learning: 2026-03-09T20:21:58.981Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-frontend.mdc:0-0
Timestamp: 2026-03-09T20:21:58.981Z
Learning: Keep frontend code scoped to `packages/frontend`; communicate with backend via `services/api.ts` using the configured env base URL; do not access shared database or Redis directly

Applied to files:

  • packages/backend/src/routes/lastfm.ts
📚 Learning: 2026-03-09T20:20:32.235Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/documentation.mdc:0-0
Timestamp: 2026-03-09T20:20:32.235Z
Learning: Applies to README.md : Update README.md if behavior changed

Applied to files:

  • README.md
📚 Learning: 2026-03-09T20:22:47.441Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-09T20:22:47.441Z
Learning: Do not hardcode secrets, IPs, or ports; use `.env` and `docs/` for required variables

Applied to files:

  • README.md
📚 Learning: 2026-03-09T20:21:38.087Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-backend.mdc:0-0
Timestamp: 2026-03-09T20:21:38.087Z
Learning: Applies to packages/backend/tests/**/*.ts : Follow existing patterns for unit and integration tests in `packages/backend/tests/`

Applied to files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
📚 Learning: 2026-03-09T20:20:38.683Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-backend-api.mdc:0-0
Timestamp: 2026-03-09T20:20:38.683Z
Learning: Applies to packages/backend/tests/**/*.{ts,tsx} : Organize tests in `packages/backend/tests/` with unit tests under `unit/` and integration tests under `integration/`, following existing patterns with fixtures and setup

Applied to files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
📚 Learning: 2026-03-09T20:21:08.600Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-project.mdc:0-0
Timestamp: 2026-03-09T20:21:08.600Z
Learning: Applies to {packages/*/tests/**/*.test.{js,ts},tests/**/*.test.{js,ts}} : Add or adjust unit and integration tests when changing behavior; follow existing patterns in `packages/*/tests` and root `tests/` directories

Applied to files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
📚 Learning: 2026-03-09T20:21:31.448Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/quality.mdc:0-0
Timestamp: 2026-03-09T20:21:31.448Z
Learning: Applies to tests/**/*.test.{ts,tsx,js,jsx} : Add integration tests where appropriate

Applied to files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
📚 Learning: 2026-03-09T20:20:56.345Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-frontend.mdc:0-0
Timestamp: 2026-03-09T20:20:56.345Z
Learning: Applies to packages/frontend/tests/**/*.{ts,tsx,js} : Write tests in `packages/frontend/tests/` using existing test patterns (e.g., Playwright for e2e if configured)

Applied to files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
📚 Learning: 2026-03-09T20:20:38.683Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-backend-api.mdc:0-0
Timestamp: 2026-03-09T20:20:38.683Z
Learning: Applies to packages/backend/src/{services,middleware}/**/*.{ts,tsx} : Implement Discord OAuth for authentication in backend services

Applied to files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
🪛 GitHub Check: SonarCloud Code Analysis
packages/backend/src/routes/lastfm.ts

[warning] 213-215: Extract this nested ternary operation into an independent statement.

See more on https://sonarcloud.io/project/issues?id=LucasSantana-Dev_Nexus&issues=AZzbf9ABHitx1-szgqa7&open=AZzbf9ABHitx1-szgqa7&pullRequest=163

🔇 Additional comments (5)
README.md (1)

177-179: LGTM!

The documentation updates accurately reflect the new behavior requiring an absolute URL for WEBAPP_BACKEND_URL. The inline example and table annotation are clear and consistent.

Also applies to: 195-195

CHANGELOG.md (1)

32-34: LGTM!

The changelog entry accurately describes the fix and is correctly placed under the [Unreleased] > Fixed section following the Keep a Changelog format.

packages/backend/src/routes/lastfm.ts (2)

73-88: LGTM!

The parseAbsoluteOrigin utility is clean and defensive—it correctly returns null for invalid or relative URLs. The refactored resolveBackendBaseUrl properly chains the env-based origin with the OAuth fallback, and the trim() call handles whitespace-only values gracefully.


20-23: LGTM!

Formatting change only—no semantic impact.

packages/backend/tests/integration/routes/lastfm.test.ts (1)

264-280: LGTM!

The regression test correctly validates that a non-absolute WEBAPP_BACKEND_URL ('/') triggers the fallback to the OAuth-derived origin. The test follows existing patterns and properly verifies the redirect URL contains the expected callback.

@vercel

vercel Bot commented Mar 11, 2026

Copy link
Copy Markdown
Contributor

Deployment failed with the following error:

Resource is limited - try again in 19 hours (more than 100, code: "api-deployments-free-per-day").

Learn More: https://vercel.com/luksantanas-projects?upgradeToPro=build-rate-limit

@LucasSantana-Dev

Copy link
Copy Markdown
Owner Author

CI update (2026-03-11):

  • SonarCloud is green after the coverage config fix in packages/backend/jest.config.cjs (lastfm route included in collectCoverageFrom).
  • Internal required checks are green: Quality Gates, Security, SonarCloud Scan, SonarCloud Code Analysis.
  • Remaining blocker is external Vercel quota/rate-limit: "Deployment rate limited — retry in ~19h".

No further functional code changes are pending on this PR. Next retry should be a minimal retrigger commit after the Vercel cooldown window.

@LucasSantana-Dev

Copy link
Copy Markdown
Owner Author

Timed retry is scheduled for 2026-03-11 22:25 BRT.

Planned execution:

  • run one controlled empty retrigger commit
  • watch checks to completion
  • merge immediately if required checks are green
  • run post-merge smoke probes and attach artifact path

Current status remains: blocked only by external Vercel quota window.

@LucasSantana-Dev

Copy link
Copy Markdown
Owner Author

Policy update for timed retry flow:

  • Scheduled retry remains set for 2026-03-11 22:25 -03 (job 1)
  • If retry attempt 2 still fails only on Vercel quota, merge will be deferred until quota resets
  • No admin bypass path will be used

@LucasSantana-Dev

Copy link
Copy Markdown
Owner Author

Track C preflight check (2026-03-11 14:43 -03):

  • Scheduled retry job is still queued:
    • at job 1 at 2026-03-11 22:25:00 -03
  • Retry runner script is present + syntactically valid:
    • /tmp/lucky_pr163_timed_retry.sh
  • Queue command still points to the expected runner path.
  • Current checks remain unchanged: only external Vercel quota is failing; internal quality/security checks are green.
  • Policy branch in script remains enforced:
    • if attempt 2 still fails only on Vercel quota, merge is deferred and no admin bypass is used.

No early retrigger was executed in this preflight.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
packages/bot/src/functions/general/commands/lastfm.spec.ts (1)

46-53: Consider using RegExp.exec() per SonarCloud hint.

This is a minor style preference; String.match() works correctly here, but RegExp.exec() is slightly more explicit for extracting capture groups.

♻️ Optional refactor
 function getConnectUrlFromEmbed(): string {
     const description = String(successEmbedMock.mock.calls.at(-1)?.[1] ?? '')
-    const match = description.match(/\[Click here to connect\]\(([^)]+)\)/)
+    const match = /\[Click here to connect\]\(([^)]+)\)/.exec(description)
     if (!match) {
         throw new Error(`Expected connect link in embed description: ${description}`)
     }
     return match[1]
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/functions/general/commands/lastfm.spec.ts` around lines 46 -
53, Replace the use of String.match in getConnectUrlFromEmbed with a RegExp.exec
call to explicitly extract the capture group: create a RegExp instance for
/\[Click here to connect\]\(([^)]+)\)/, call its exec() against the description
(from successEmbedMock.mock.calls.at(-1)?.[1]), check the returned array for
null and throw the same error if missing, and return the first capture group
(index 1) from the exec result instead of using match.
packages/backend/src/routes/lastfm.ts (1)

210-215: Consider extracting nested ternary for readability.

SonarCloud flagged the nested ternary. While functionally correct, extracting this to a helper or using a clearer structure would improve maintainability.

♻️ Optional refactor
-            const state =
-                typeof parsedQuery.data.state === 'string'
-                    ? parsedQuery.data.state
-                    : typeof stateFromCookie === 'string'
-                      ? stateFromCookie
-                      : null
+            const state = getStateFromSources(
+                parsedQuery.data.state,
+                stateFromCookie,
+            )

Add helper above the route setup:

function getStateFromSources(
    queryState: string | undefined,
    cookieState: unknown,
): string | null {
    if (typeof queryState === 'string') return queryState
    if (typeof cookieState === 'string') return cookieState
    return null
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/backend/src/routes/lastfm.ts` around lines 210 - 215, The nested
ternary assigning state (based on parsedQuery.data.state and stateFromCookie) is
hard to read; extract this logic into a small helper (e.g.,
getStateFromSources(queryState, cookieState)) or replace the ternary with a
clear if/return sequence: check typeof parsedQuery.data.state === 'string'
first, then typeof stateFromCookie === 'string', otherwise return null; call
this helper from the route where state is currently computed to improve
readability and maintainability.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/backend/src/routes/lastfm.ts`:
- Around line 210-215: The nested ternary assigning state (based on
parsedQuery.data.state and stateFromCookie) is hard to read; extract this logic
into a small helper (e.g., getStateFromSources(queryState, cookieState)) or
replace the ternary with a clear if/return sequence: check typeof
parsedQuery.data.state === 'string' first, then typeof stateFromCookie ===
'string', otherwise return null; call this helper from the route where state is
currently computed to improve readability and maintainability.

In `@packages/bot/src/functions/general/commands/lastfm.spec.ts`:
- Around line 46-53: Replace the use of String.match in getConnectUrlFromEmbed
with a RegExp.exec call to explicitly extract the capture group: create a RegExp
instance for /\[Click here to connect\]\(([^)]+)\)/, call its exec() against the
description (from successEmbedMock.mock.calls.at(-1)?.[1]), check the returned
array for null and throw the same error if missing, and return the first capture
group (index 1) from the exec result instead of using match.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: dfa63500-76fb-47ec-bcfd-e29ab2585fc4

📥 Commits

Reviewing files that changed from the base of the PR and between 5f20bfd and a346eac.

📒 Files selected for processing (8)
  • CHANGELOG.md
  • README.md
  • docs/LASTFM_SETUP.md
  • packages/backend/jest.config.cjs
  • packages/backend/src/routes/lastfm.ts
  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/bot/src/functions/general/commands/lastfm.ts
✅ Files skipped from review due to trivial changes (1)
  • README.md
📜 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: SonarCloud Scan
  • GitHub Check: Quality Gates
🧰 Additional context used
📓 Path-based instructions (31)
{CHANGELOG.md,README.md}

📄 CodeRabbit inference engine (.cursor/rules/agent-rules.mdc)

ALWAYS update CHANGELOG.md and README.md as changes are made.

Files:

  • CHANGELOG.md
CHANGELOG.md

📄 CodeRabbit inference engine (.cursor/rules/templates-examples.mdc)

CHANGELOG.md must be updated with all changes in pull requests

Always update CHANGELOG.md with all code changes

Update CHANGELOG.md with all changes, include breaking changes documentation, and reference issues and PRs

Files:

  • CHANGELOG.md
{CHANGELOG.md,docs/**}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Update CHANGELOG.md and relevant docs/ files when behavior or setup changes

Files:

  • CHANGELOG.md
  • docs/LASTFM_SETUP.md
**/*.{js,jsx,ts,tsx,vue,html}

📄 CodeRabbit inference engine (.cursor/rules/accessibility-openness.mdc)

Provide accessible UI components using semantic HTML and ARIA attributes where necessary

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/bot/src/functions/general/commands/lastfm.ts
  • packages/backend/src/routes/lastfm.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/dependency-injection.mdc)

**/*.{ts,tsx,js,jsx}: Prefer constructor injection for classes that require dependencies
Avoid global mutable singletons unless necessary
Use explicit interfaces for external dependencies to make testing easier

**/*.{ts,tsx,js,jsx}: Include required references in PRs/code for non-trivial logic: TypeScript (official docs), MDN (JavaScript reference), and official docs for any runtime/framework/libraries used (e.g., Node.js, React) as applicable.
Before assuming behavior of an API, include the doc link and a ≤25-word quote when the change relies on it.

**/*.{ts,tsx,js,jsx}: Prefer named exports for clear usage and easier refactors in TypeScript/JavaScript
Keep import order consistent: external first, then internal modules
Remove dead code and unused imports

**/*.{ts,tsx,js,jsx}: Use PascalCase naming convention for React/UI components
Use camelCase naming convention for variables and functions
Use UPPER_SNAKE_CASE naming convention for constants
Maintain consistent import grouping and ordering within the project, keeping third-party imports separate from local imports
For external data sources (HTTP, database), always validate and sanitize input using type guards or schema validators

**/*.{ts,tsx,js,jsx}: Use Prettier with no semicolons, single quotes, 4-space indent, 80 character width
Files must not exceed 250 lines and this is enforced

Implement TypeScript typecheck and linter in CI quality checks

**/*.{ts,tsx,js,jsx}: Use TypeScript for enhanced type safety
Implement error handling and error logging
Avoid commenting code unless extremely necessary - code should explain itself with descriptive names
Leave NO todos, placeholders or missing pieces in the code
Variables and functions must use camelCase
Constants must use UPPER_SNAKE_CASE
Use arrow functions for methods and computed properties
Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements
Maintain consistent import grouping/order: external imports first, then...

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/bot/src/functions/general/commands/lastfm.ts
  • packages/backend/src/routes/lastfm.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/error-handling.mdc)

**/*.{js,jsx,ts,tsx}: Never throw strings. Throw Error (or typed subclasses) with descriptive messages
Include causal error as cause when available for better debugging
Define clear, stable error codes (e.g., ERR_AUTH_EXPIRED, ERR_NETWORK_TIMEOUT)
Provide optional metadata (e.g., details, retryable, status, correlationId) in error objects
Use domain error classes per area (e.g., AuthenticationError, ValidationError, NetworkError)
Log errors with structure (message, code, stack, cause, correlationId, user context where appropriate)
Mark retryable vs nonRetryable errors where helpful for operations
Set timeouts and handle aborts/cancellations; avoid dangling requests in API/network code
Implement backoff for transient failures; avoid infinite retries
Map HTTP status → domain errors; 4xx vs 5xx behave differently (e.g., retry for 5xx/network)

**/*.{js,jsx,ts,tsx}: Use functional components with hooks in React/React Native. Avoid class components.
Keep components focused on a single responsibility; extract complex logic into custom hooks.
Keep state local when possible. Use Context/Zustand/Redux only when necessary for state management.
If props or state traverse more than 3 levels, consider using context or a feature-scoped store instead of prop drilling.
Use performance optimization techniques: React.memo, useMemo, useCallback, Suspense (web), and virtualization for long lists; avoid unnecessary re-renders.
Web accessibility: use semantic HTML, labels, focus management, keyboard navigation, and aria-* attributes as needed.
React Native accessibility: use accessibility props (accessible, accessibilityLabel), proper roles and labels.
Identify and extract repetitive UI components proactively to components/ with clear props and minimal coupling.
Web styles: prefer co-located styles or design system tokens; avoid global style leakage.
React Native styles: prefer StyleSheet.create, design tokens, and theme providers; avoid in...

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/bot/src/functions/general/commands/lastfm.ts
  • packages/backend/src/routes/lastfm.ts
**/*.{test,spec}.{js,jsx,ts,tsx}

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

**/*.{test,spec}.{js,jsx,ts,tsx}: Test behavior, not implementation. Prefer Testing Library utilities for testing React/React Native components.
For React Native tests: mock native modules and test component interactions and accessibility labels.

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/bot/src/functions/general/commands/lastfm.spec.ts
**/*.{ts,tsx}

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

Introduce interfaces at module boundaries to enable testing and substitutions

**/*.{ts,tsx}: Avoid using any type in TypeScript. If unavoidable, use unknown with type guards and justify with a code comment
Prefer interface for defining public object shapes in TypeScript, use type for unions and utility types
Use TypeScript utility types such as Partial, Pick, Omit, Readonly, and Record when appropriate
Use I{Name} naming convention for interfaces in TypeScript
Use T{Name} naming convention for type aliases and utility types in TypeScript

**/*.{ts,tsx}: Functions must be less than 50 lines with cyclomatic complexity less than 10
Do not use any types - ESLint enforces this at error level

**/*.{ts,tsx}: Prefer types over interfaces for most cases
Don't ever use any - type safety always
Avoid enums; use const objects instead
For complex types, create a separate file to declare them and import them
Avoid using any type; if unavoidable, use unknown with type guards and justify with code comment
Prefer interface for public API shapes; use type for unions and utility types
Use TypeScript utility types (Partial, Pick, Omit, Readonly, Record)

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/bot/src/functions/general/commands/lastfm.ts
  • packages/backend/src/routes/lastfm.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

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

**/*.{test,spec}.{ts,tsx,js,jsx}: Test behavior, not implementation details
Prefer unit tests for core logic; add integration tests at meaningful boundaries

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/bot/src/functions/general/commands/lastfm.spec.ts
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/testing-quality.mdc)

**/*.{test,spec}.{js,ts,jsx,tsx}: Use Jest + a React testing library for unit and component tests as applicable
Test behavior, not implementation details

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/bot/src/functions/general/commands/lastfm.spec.ts
**/*.{js,ts,tsx,jsx}

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

**/*.{js,ts,tsx,jsx}: Minimize comments in code; explain the 'why' when non-obvious, let code express the 'what' through clear naming
Document trade-offs briefly when deviating from ideal patterns

**/*.{js,ts,tsx,jsx}: Store secrets, ports, and hosts in environment variables (.env, .env.example) and never hardcode them
Avoid redundant or decorative AI comments; code should be self-explanatory and only commented when logic is non-obvious; prefer refactoring over lengthy comments

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/bot/src/functions/general/commands/lastfm.ts
  • packages/backend/src/routes/lastfm.ts
packages/backend/tests/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-backend-api.mdc)

Organize tests in packages/backend/tests/ with unit tests under unit/ and integration tests under integration/, following existing patterns with fixtures and setup

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
packages/backend/**

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

The backend package depends on shared and contains Express API with auth and guild routes

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/backend/jest.config.cjs
  • packages/backend/src/routes/lastfm.ts
**/*.{js,mjs,ts,mts}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Use Node.js version ≥22 with ESM (ECMAScript modules) only; no CommonJS

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/bot/src/functions/general/commands/lastfm.ts
  • packages/backend/src/routes/lastfm.ts
{packages/*/tests/**/*.test.{js,ts},tests/**/*.test.{js,ts}}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Add or adjust unit and integration tests when changing behavior; follow existing patterns in packages/*/tests and root tests/ directories

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
**/*.{spec,test}.{ts,tsx,js,jsx}

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

**/*.{spec,test}.{ts,tsx,js,jsx}: Use Jest for unit and integration tests
Test behavior, not implementation details
Run unit, integration tests, and coverage report in CI quality checks

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/bot/src/functions/general/commands/lastfm.spec.ts
packages/backend/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-backend.mdc)

packages/backend/**/*.ts: Apply .cursor/rules/lucky-backend-api.mdc for structure and conventions when acting as backend specialist
Use .cursor/skills/backend-express/SKILL.md for Express routes, middleware, and services when acting as backend specialist
Use @lucky/shared for config and DB/Redis when needed in backend code

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/backend/src/routes/lastfm.ts
packages/backend/tests/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-backend.mdc)

Follow existing patterns for unit and integration tests in packages/backend/tests/

Files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
**/docs/**/*.{md,mdx}

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

**/docs/**/*.{md,mdx}: Keep API documentation in sync with code changes
Document significant architectural design choices

Files:

  • docs/LASTFM_SETUP.md
packages/bot/src/functions/**/commands/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Discord bot commands must be structured in packages/bot/src/functions/<category>/commands/<name>.ts with handlers in <category>/handlers/

Files:

  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/bot/src/functions/general/commands/lastfm.ts
packages/bot/src/functions/*/commands/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)

packages/bot/src/functions/*/commands/**/*.{ts,tsx}: Command model must include data (slash builder), execute, and category properties exported from packages/bot/src/models/Command.ts
Use @discordjs/builders for building the data (SlashCommandBuilder) in command definitions
Command execute function must receive { interaction, client } parameters from CommandExecuteParams type
Use interactionReply and createUserFriendlyError utilities from @lucky/shared/general utils for command replies and error handling
Use existing validators from packages/bot/src/utils/command/ for voice channel, queue, and guild validations in commands

Files:

  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/bot/src/functions/general/commands/lastfm.ts
packages/bot/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)

packages/bot/**/*.{ts,tsx}: Use useMainPlayer() from discord-player to access the player instance; do not instantiate player directly
Do not duplicate queue or player state outside Discord Player; use shared services from @lucky/shared for persistent data like track history and session information
Use errorLog and debugLog from @lucky/shared/utils for logging throughout the bot package
Use embed and reply utilities from @lucky/shared for consistent message formatting and error sanitization across the bot
Use services from @lucky/shared (DatabaseService, Redis client) for database and cache access; do not instantiate Prisma or Redis directly in the bot package

Files:

  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/bot/src/functions/general/commands/lastfm.ts
packages/bot/**

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

The bot package depends on shared and contains Discord bot commands and player handlers using Discord.js and Discord Player

Files:

  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/bot/src/functions/general/commands/lastfm.ts
**/*.spec.ts

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

Unit tests must use naming convention *.spec.ts

Files:

  • packages/bot/src/functions/general/commands/lastfm.spec.ts
packages/bot/src/functions/{general,music,download}/commands/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)

packages/bot/src/functions/{general,music,download}/commands/**/*.ts: Apply .cursor/rules/lucky-discord-bot.mdc rules for Discord bot commands and player implementation
Use .cursor/skills/discord-commands/SKILL.md for implementing slash commands

Files:

  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/bot/src/functions/general/commands/lastfm.ts
packages/bot/src/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)

Use @lucky/shared for database, Redis, logging, and embed utilities instead of implementing them locally

Files:

  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/bot/src/functions/general/commands/lastfm.ts
packages/backend/src/routes/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

packages/backend/src/routes/**/*.ts: Backend route handlers must use asyncHandler wrapper and throw AppError.xxx() instead of manual try/catch blocks
Rate limiting: use apiLimiter (100/min), authLimiter (20/15min), or writeLimiter (30/min) as appropriate

Place routes under packages/backend/src/routes/ directory

Files:

  • packages/backend/src/routes/lastfm.ts
packages/backend/src/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

packages/backend/src/**/*.ts: Validation must use Zod schemas in backend/src/schemas/ and be applied via validateBody, validateParams, or validateQuery
Do not reassign req.query in Express middleware - it is read-only in Express 5

Files:

  • packages/backend/src/routes/lastfm.ts
packages/backend/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-backend-api.mdc)

packages/backend/src/**/*.{ts,tsx}: Use shared config and env from @lucky/shared when needed; avoid duplicating env parsing in backend code
Keep tokens and secrets in environment variables only; never hardcode or expose in code

Files:

  • packages/backend/src/routes/lastfm.ts
packages/backend/src/{routes,middleware}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-backend-api.mdc)

Return consistent JSON error responses with appropriate HTTP status codes; do not expose stack traces or secrets in responses

Files:

  • packages/backend/src/routes/lastfm.ts
packages/backend/src/routes/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-backend-api.mdc)

Structure routes in packages/backend/src/routes/ directory with separate files for auth, guilds, toggles, and index routes

Files:

  • packages/backend/src/routes/lastfm.ts
🧠 Learnings (23)
📚 Learning: 2026-03-09T20:21:38.098Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-backend.mdc:0-0
Timestamp: 2026-03-09T20:21:38.098Z
Learning: Applies to packages/backend/tests/**/*.ts : Follow existing patterns for unit and integration tests in `packages/backend/tests/`

Applied to files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/backend/jest.config.cjs
📚 Learning: 2026-03-09T20:20:38.694Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-backend-api.mdc:0-0
Timestamp: 2026-03-09T20:20:38.694Z
Learning: Applies to packages/backend/tests/**/*.{ts,tsx} : Organize tests in `packages/backend/tests/` with unit tests under `unit/` and integration tests under `integration/`, following existing patterns with fixtures and setup

Applied to files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/backend/jest.config.cjs
📚 Learning: 2026-03-09T20:21:08.612Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-project.mdc:0-0
Timestamp: 2026-03-09T20:21:08.612Z
Learning: Applies to {packages/*/tests/**/*.test.{js,ts},tests/**/*.test.{js,ts}} : Add or adjust unit and integration tests when changing behavior; follow existing patterns in `packages/*/tests` and root `tests/` directories

Applied to files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/backend/jest.config.cjs
📚 Learning: 2026-03-09T20:21:31.459Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/quality.mdc:0-0
Timestamp: 2026-03-09T20:21:31.459Z
Learning: Applies to tests/**/*.test.{ts,tsx,js,jsx} : Add integration tests where appropriate

Applied to files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/backend/jest.config.cjs
📚 Learning: 2026-03-09T20:20:56.356Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-frontend.mdc:0-0
Timestamp: 2026-03-09T20:20:56.356Z
Learning: Applies to packages/frontend/src/**/*.{ts,tsx} : Do not depend on `lucky/shared` package in frontend code; make API calls to backend via configured base URL (env)

Applied to files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/backend/src/routes/lastfm.ts
📚 Learning: 2026-03-09T20:20:38.694Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-backend-api.mdc:0-0
Timestamp: 2026-03-09T20:20:38.694Z
Learning: Applies to packages/backend/src/{services,middleware}/**/*.{ts,tsx} : Implement Discord OAuth for authentication in backend services

Applied to files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
📚 Learning: 2026-03-09T20:20:56.356Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-frontend.mdc:0-0
Timestamp: 2026-03-09T20:20:56.356Z
Learning: Applies to packages/frontend/tests/**/*.{ts,tsx,js} : Write tests in `packages/frontend/tests/` using existing test patterns (e.g., Playwright for e2e if configured)

Applied to files:

  • packages/backend/tests/integration/routes/lastfm.test.ts
  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/backend/jest.config.cjs
📚 Learning: 2026-03-09T20:22:47.453Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-09T20:22:47.453Z
Learning: For unit tests and Jest ESM mocks, use the `testing-lucky` skill

Applied to files:

  • packages/bot/src/functions/general/commands/lastfm.spec.ts
📚 Learning: 2026-03-09T20:21:31.459Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/quality.mdc:0-0
Timestamp: 2026-03-09T20:21:31.459Z
Learning: Applies to **/*.{spec,test}.{ts,tsx,js,jsx} : Test behavior, not implementation details

Applied to files:

  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/backend/jest.config.cjs
📚 Learning: 2026-03-09T20:21:31.459Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/quality.mdc:0-0
Timestamp: 2026-03-09T20:21:31.459Z
Learning: Applies to **/*.{spec,test}.{ts,tsx,js,jsx} : Use Jest for unit and integration tests

Applied to files:

  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/backend/jest.config.cjs
📚 Learning: 2026-03-09T20:22:47.453Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-09T20:22:47.453Z
Learning: Add or adjust unit/integration tests in `packages/*/tests` and root `tests/` when changing behavior; follow existing patterns in the repository

Applied to files:

  • packages/bot/src/functions/general/commands/lastfm.spec.ts
📚 Learning: 2026-03-09T20:21:52.065Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-discord.mdc:0-0
Timestamp: 2026-03-09T20:21:52.065Z
Learning: Applies to packages/bot/src/functions/{general,music,download}/commands/**/*.ts : Apply `.cursor/rules/lucky-discord-bot.mdc` rules for Discord bot commands and player implementation

Applied to files:

  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/bot/src/functions/general/commands/lastfm.ts
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/src/functions/*/commands/**/*.{ts,tsx} : Use `interactionReply` and `createUserFriendlyError` utilities from `lucky/shared/general` utils for command replies and error handling

Applied to files:

  • packages/bot/src/functions/general/commands/lastfm.spec.ts
  • packages/bot/src/functions/general/commands/lastfm.ts
📚 Learning: 2026-03-09T20:21:52.065Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-discord.mdc:0-0
Timestamp: 2026-03-09T20:21:52.065Z
Learning: Applies to packages/bot/src/functions/{general,music,download}/commands/**/*.ts : Use `.cursor/skills/discord-commands/SKILL.md` for implementing slash commands

Applied to files:

  • packages/bot/src/functions/general/commands/lastfm.ts
📚 Learning: 2026-03-09T20:21:52.065Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-discord.mdc:0-0
Timestamp: 2026-03-09T20:21:52.065Z
Learning: Applies to packages/bot/src/functions/music/commands/**/*.ts : Use `.cursor/skills/music-queue-player/SKILL.md` for play, queue, skip, volume commands and player lifecycle management

Applied to files:

  • packages/bot/src/functions/general/commands/lastfm.ts
  • packages/backend/jest.config.cjs
📚 Learning: 2026-03-09T20:21:31.459Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/quality.mdc:0-0
Timestamp: 2026-03-09T20:21:31.459Z
Learning: Applies to **/*.{spec,test}.{ts,tsx,js,jsx} : Run unit, integration tests, and coverage report in CI quality checks

Applied to files:

  • packages/backend/jest.config.cjs
📚 Learning: 2026-03-09T20:21:31.459Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/quality.mdc:0-0
Timestamp: 2026-03-09T20:21:31.459Z
Learning: Applies to src/**/*.{ts,tsx,js,jsx} : Add performance metrics and monitoring for backend services

Applied to files:

  • packages/backend/jest.config.cjs
📚 Learning: 2026-03-09T20:21:31.459Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/quality.mdc:0-0
Timestamp: 2026-03-09T20:21:31.459Z
Learning: Applies to src/**/*.{ts,tsx,js,jsx} : Add performance budgets for frontend bundles

Applied to files:

  • packages/backend/jest.config.cjs
📚 Learning: 2026-03-09T20:21:38.098Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-backend.mdc:0-0
Timestamp: 2026-03-09T20:21:38.098Z
Learning: Applies to packages/backend/src/routes/**/*.ts : Place routes under `packages/backend/src/routes/` directory

Applied to files:

  • packages/backend/jest.config.cjs
📚 Learning: 2026-03-09T20:20:38.694Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-backend-api.mdc:0-0
Timestamp: 2026-03-09T20:20:38.694Z
Learning: Applies to packages/backend/src/routes/**/*.{ts,tsx} : Structure routes in `packages/backend/src/routes/` directory with separate files for auth, guilds, toggles, and index routes

Applied to files:

  • packages/backend/jest.config.cjs
📚 Learning: 2026-03-09T20:21:15.595Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-shared.mdc:0-0
Timestamp: 2026-03-09T20:21:15.595Z
Learning: Applies to packages/shared/**/*.ts : Do not add dependencies on `bot` or `backend` packages; shared is the foundational package used by both

Applied to files:

  • packages/backend/jest.config.cjs
📚 Learning: 2026-03-09T20:22:09.954Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/typescript.mdc:0-0
Timestamp: 2026-03-09T20:22:09.954Z
Learning: Applies to **/*.{ts,tsx,js,jsx} : Leave NO todos, placeholders or missing pieces in the code

Applied to files:

  • packages/backend/jest.config.cjs
📚 Learning: 2026-03-09T20:21:58.991Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-frontend.mdc:0-0
Timestamp: 2026-03-09T20:21:58.991Z
Learning: Keep frontend code scoped to `packages/frontend`; communicate with backend via `services/api.ts` using the configured env base URL; do not access shared database or Redis directly

Applied to files:

  • packages/backend/src/routes/lastfm.ts
🪛 GitHub Check: SonarCloud Code Analysis
packages/bot/src/functions/general/commands/lastfm.spec.ts

[warning] 48-48: Use the "RegExp.exec()" method instead.

See more on https://sonarcloud.io/project/issues?id=LucasSantana-Dev_Nexus&issues=AZzfE0NWkZa_-9vKGgjz&open=AZzfE0NWkZa_-9vKGgjz&pullRequest=163

packages/backend/src/routes/lastfm.ts

[warning] 213-215: Extract this nested ternary operation into an independent statement.

See more on https://sonarcloud.io/project/issues?id=LucasSantana-Dev_Nexus&issues=AZzbf9ABHitx1-szgqa7&open=AZzbf9ABHitx1-szgqa7&pullRequest=163

🔇 Additional comments (9)
packages/backend/jest.config.cjs (1)

20-21: LGTM!

The coverage configuration correctly uses an exclusion pattern followed by a specific inclusion to collect coverage from playbackRoutes.ts while keeping other music routes excluded.

CHANGELOG.md (1)

39-44: LGTM!

The changelog entries accurately document both the backend and bot changes for the Last.fm connect flow hardening. The descriptions are clear, include the PR reference, and follow the existing format.

packages/bot/src/functions/general/commands/lastfm.ts (2)

18-26: LGTM!

The getAbsoluteOrigin helper safely parses URLs and extracts origins, correctly handling empty/invalid inputs by returning null. The implementation aligns with the backend's parseAbsoluteOrigin pattern.


28-37: LGTM!

The URL resolution order (WEBAPP_BACKEND_URL → WEBAPP_REDIRECT_URI) is consistent with the backend's resolveBackendBaseUrl function, ensuring both bot and backend generate connect URLs with matching origins.

packages/backend/src/routes/lastfm.ts (1)

73-88: LGTM!

The parseAbsoluteOrigin helper and refactored resolveBackendBaseUrl correctly implement the origin resolution with proper fallback behavior. The logic is consistent with the bot's implementation.

packages/backend/tests/integration/routes/lastfm.test.ts (1)

264-280: LGTM!

Excellent regression test covering the core fix. The test correctly verifies that a non-absolute WEBAPP_BACKEND_URL (like /) is ignored and the OAuth origin from WEBAPP_REDIRECT_URI is used as fallback.

docs/LASTFM_SETUP.md (2)

21-22: LGTM!

The environment variable table clearly documents the new resolution order: WEBAPP_BACKEND_URL as the recommended canonical origin, with WEBAPP_REDIRECT_URI origin as the fallback.


35-35: LGTM!

The per-user linking instructions correctly reflect the fallback behavior, making it clear to operators when each environment variable is used.

packages/bot/src/functions/general/commands/lastfm.spec.ts (1)

1-63: LGTM!

Comprehensive test suite covering the key scenarios: preference for WEBAPP_BACKEND_URL, trailing slash normalization, fallback to WEBAPP_REDIRECT_URI, and error cases. The test setup properly isolates environment variables.

@LucasSantana-Dev

Copy link
Copy Markdown
Owner Author

Merge attempt blocked by base branch policy (2026-03-11 20:11:21 -03 / 2026-03-11 23:11:21 UTC).\n\nEvidence:\n- merge command: \n- result: base branch policy prohibits merge (no admin bypass used)\n- current state: , , , \n- checks snapshot: Quality Gates/Security/Sonar/CodeRabbit/GitGuardian/Vercel are green; neutral Netlify checks are completed.\n\nPer policy, no admin bypass was used. Continuing sequential flow to PR #168.

@LucasSantana-Dev

LucasSantana-Dev commented Mar 12, 2026 •

Copy link
Copy Markdown
Owner Author

Merge attempt blocked by base branch policy.

Attempted command:
gh pr merge 163 --squash --delete-branch --match-head-commit a346eace2880dbe57114dc82a88163e7f2c49134

Current gate snapshot:

  • mergeable=MERGEABLE
  • mergeStateStatus=BLOCKED
  • reviewDecision=APPROVED
  • gh pr checks 163: all required checks green

No admin bypass used. Stopping here per policy; this needs branch-policy/ruleset unblock before merge can proceed.

@LucasSantana-Dev

Copy link
Copy Markdown
Owner Author

Merge remains blocked under no-admin-bypass policy.

Latest merge attempt:
gh pr merge 163 --squash --auto --delete-branch --match-head-commit a346eace2880dbe57114dc82a88163e7f2c49134

Result:

  • GraphQL: Pull request Auto merge is not allowed for this repository (enablePullRequestAutoMerge)

Current state snapshot:

  • mergeable=MERGEABLE
  • mergeStateStatus=BLOCKED
  • reviewDecision=APPROVED
  • required checks are green (gh pr checks 163)

No admin bypass used. This PR cannot be merged until repository policy/settings are adjusted (or admin merge is explicitly allowed).

@LucasSantana-Dev
LucasSantana-Dev enabled auto-merge (squash) March 12, 2026 02:41
@LucasSantana-Dev

Copy link
Copy Markdown
Owner Author

Merge attempt blocked by base branch policy (no admin bypass used).\n\nEvidence snapshot (2026-03-11 America/Sao_Paulo):\n- PR is mergeable and approved; checks are green.\n- returns: "base branch policy prohibits the merge".\n- Active ruleset on is with , , and constraints.\n\nCurrent status: auto-merge request is enabled and waiting, but merge remains blocked by repository policy.

@LucasSantana-Dev

Copy link
Copy Markdown
Owner Author

Superseding previous malformed automation note (shell escaping issue).

Merge attempt is blocked by base branch policy (no admin bypass used).

Evidence snapshot (2026-03-11 America/Sao_Paulo):

  • PR is MERGEABLE and APPROVED.
  • All required checks are green.
  • Direct guarded merge attempt returned: "the base branch policy prohibits the merge".
  • Active main ruleset id 12822499 includes update + code_scanning (CodeQL) + code_quality constraints.

Current status: auto-merge request is enabled and waiting, but merge remains blocked by repository policy.

@sonarqubecloud

Copy link
Copy Markdown

@sonarqubecloud

Copy link
Copy Markdown

@LucasSantana-Dev
LucasSantana-Dev merged commit 5cce41e into main Mar 12, 2026
14 of 15 checks passed
@LucasSantana-Dev
LucasSantana-Dev deleted the fix/prod-lastfm-origin-state-callback branch March 12, 2026 03:40
@coderabbitai coderabbitai Bot mentioned this pull request Apr 12, 2026
6 tasks
LucasSantana-Dev added a commit that referenced this pull request May 13, 2026
* fix(lastfm): enforce absolute callback origin for connect flow

* ci(sonar): include lastfm route in backend coverage

* fix(lastfm): prioritize backend origin for link URLs

This branch was successfully deployed

1 active deployment
Preview — 43e82210 Deployed Mar 12, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant