Repository navigation
fix(webapp): support cloudflare api domain + wildcard cors - #126
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
✅ Deploy Preview for regal-bunny-0c8efe ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📜 Recent 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). (3)
📝 WalkthroughWalkthroughThis PR introduces dynamic API origin resolution for split-domain deployments. The backend now accepts configured CORS origins plus specific wildcard domains, while the frontend auto-detects API endpoints based on deployment environment when not explicitly configured. Changes
Sequence Diagram(s)sequenceDiagram
participant Client as Frontend Client
participant Server as Backend Server
rect rgba(100, 150, 200, 0.5)
Note over Client,Server: OLD: Static /api routing
Client->>Server: GET /api/data<br/>(origin: current host)
Server->>Server: Check static frontendUrl origin
alt Origin matches
Server->>Client: 200 OK
else Origin mismatch
Server->>Client: CORS blocked
end
end
rect rgba(100, 200, 150, 0.5)
Note over Client,Server: NEW: Dynamic origin + host-based API resolution
Client->>Client: inferApiBase():<br/>Check VITE_API_BASE_URL<br/>or map hostname
Client->>Server: GET https://api.lucassantana.tech/data<br/>(origin: dashboard.lucassantana.tech)
Server->>Server: isAllowedOrigin():<br/>Parse origin, validate against<br/>configured + wildcard list
alt Origin allowed
Server->>Client: 200 OK
else Origin denied
Server->>Client: CORS error
end
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (4)
packages/frontend/src/vite-env.d.ts (1)
1-5: Consider extendingImportMetafor complete type coverage.The
ImportMetaEnvdeclaration is correct, but for full type safety you may want to also extend theImportMetainterface to ensureimport.meta.envresolves toImportMetaEnv.🔧 Optional enhancement for complete type coverage
/// <reference types="vite/client" /> interface ImportMetaEnv { readonly VITE_API_BASE_URL?: string } + +interface ImportMeta { + readonly env: ImportMetaEnv +}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/frontend/src/vite-env.d.ts` around lines 1 - 5, Extend the ImportMeta interface so TypeScript knows that import.meta.env is of type ImportMetaEnv: add an interface declaration for ImportMeta with a readonly env: ImportMetaEnv property to pair with the existing ImportMetaEnv declaration (referencing ImportMetaEnv, ImportMeta, and import.meta.env to locate where to change).packages/frontend/src/services/api.ts (1)
25-27: Consider usingglobalThisfor broader compatibility.SonarCloud suggests preferring
globalThisoverwindow. Whilewindowworks fine in browser-only code,globalThisis more universal and aligns with modern JavaScript standards.♻️ Optional refactor to use globalThis
- if (typeof window !== 'undefined') { - const protocol = window.location.protocol || 'https:' - const hostname = window.location.hostname + if (typeof globalThis.window !== 'undefined') { + const protocol = globalThis.location?.protocol || 'https:' + const hostname = globalThis.location?.hostname ?? ''🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/frontend/src/services/api.ts` around lines 25 - 27, Replace the browser-specific typeof window check and usage with globalThis to improve cross-environment compatibility: change the conditional that currently uses "typeof window !== 'undefined'" to check "typeof globalThis !== 'undefined' && globalThis.location", and read protocol and hostname from globalThis.location (preserving the protocol fallback 'https:' and the hostname extraction into the existing protocol and hostname variables). Update the code that assigns protocol and hostname (the variables named protocol and hostname) so they come from globalThis.location when available.packages/backend/src/middleware/index.ts (2)
15-18: UseSetfor O(1) origin lookups.SonarCloud correctly identifies that
configuredOriginsshould be aSetfor efficient membership checks. This is especially relevant if multiple origins are configured.♻️ Refactor to use Set
- const configuredOrigins = frontendUrl + const configuredOrigins = new Set(frontendUrl .split(',') .map((origin) => origin.trim()) .filter((origin) => origin.length > 0) + ) const isAllowedOrigin = (origin: string): boolean => { - if (configuredOrigins.includes(origin)) { + if (configuredOrigins.has(origin)) { return true }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/backend/src/middleware/index.ts` around lines 15 - 18, Replace the configuredOrigins array with a Set for O(1) lookups: construct configuredOrigins from frontendUrl by splitting, trimming and filtering, then wrapping the results in a Set (preserve the same trimming/filtering logic). Update any membership checks that currently use configuredOrigins.includes(...) or indexOf(...) to use configuredOrigins.has(...) instead—look for the configuredOrigins symbol and the CORS/origin-checking middleware (the origin => ... handler) in this file and change those checks accordingly.
15-42: Update.env.exampleto document comma-separatedWEBAPP_FRONTEND_URLsupport.The code supports comma-separated origins in
WEBAPP_FRONTEND_URL(lines 15–16), but.env.exampleonly shows single URL examples. Add an example demonstrating multiple origins, such as:# WEBAPP_FRONTEND_URL=https://lucky.lucassantana.tech,http://localhost:3000This clarifies the feature for operators configuring multiple frontend origins.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/backend/src/middleware/index.ts` around lines 15 - 42, The .env.example doesn't show that WEBAPP_FRONTEND_URL supports comma-separated origins; update the example to include a commented example demonstrating multiple origins (e.g., WEBAPP_FRONTEND_URL containing two URLs separated by a comma) so operators know the variable parsed by frontendUrl and used to build configuredOrigins for isAllowedOrigin; ensure the example shows both a production and localhost entry (e.g., one HTTPS domain and one http://localhost:3000) and keep it commented like other env entries.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/frontend/src/services/api.ts`:
- Around line 18-47: The frontend is still using hardcoded "/api/..." paths
which bypass the resolved base URL from inferApiBase/API_BASE; update all usages
(e.g., the EventSource creation in musicApi.ts and the getConnectUrl function)
to use the configured API_BASE instead of hardcoded strings. Replace instances
like '/api/guilds/${guildId}/music/stream' with
`${API_BASE}/guilds/${guildId}/music/stream` and '/api/lastfm/connect' with
`${API_BASE}/lastfm/connect`, and ensure the modules import API_BASE (from the
file that defines inferApiBase/API_BASE) so requests work across different
origins; note API_BASE is already trimmed of trailing slashes so string
concatenation as shown is safe.
---
Nitpick comments:
In `@packages/backend/src/middleware/index.ts`:
- Around line 15-18: Replace the configuredOrigins array with a Set for O(1)
lookups: construct configuredOrigins from frontendUrl by splitting, trimming and
filtering, then wrapping the results in a Set (preserve the same
trimming/filtering logic). Update any membership checks that currently use
configuredOrigins.includes(...) or indexOf(...) to use
configuredOrigins.has(...) instead—look for the configuredOrigins symbol and the
CORS/origin-checking middleware (the origin => ... handler) in this file and
change those checks accordingly.
- Around line 15-42: The .env.example doesn't show that WEBAPP_FRONTEND_URL
supports comma-separated origins; update the example to include a commented
example demonstrating multiple origins (e.g., WEBAPP_FRONTEND_URL containing two
URLs separated by a comma) so operators know the variable parsed by frontendUrl
and used to build configuredOrigins for isAllowedOrigin; ensure the example
shows both a production and localhost entry (e.g., one HTTPS domain and one
http://localhost:3000) and keep it commented like other env entries.
In `@packages/frontend/src/services/api.ts`:
- Around line 25-27: Replace the browser-specific typeof window check and usage
with globalThis to improve cross-environment compatibility: change the
conditional that currently uses "typeof window !== 'undefined'" to check "typeof
globalThis !== 'undefined' && globalThis.location", and read protocol and
hostname from globalThis.location (preserving the protocol fallback 'https:' and
the hostname extraction into the existing protocol and hostname variables).
Update the code that assigns protocol and hostname (the variables named protocol
and hostname) so they come from globalThis.location when available.
In `@packages/frontend/src/vite-env.d.ts`:
- Around line 1-5: Extend the ImportMeta interface so TypeScript knows that
import.meta.env is of type ImportMetaEnv: add an interface declaration for
ImportMeta with a readonly env: ImportMetaEnv property to pair with the existing
ImportMetaEnv declaration (referencing ImportMetaEnv, ImportMeta, and
import.meta.env to locate where to change).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 3d320d52-1c8a-4533-87e3-949518dea6c9
📒 Files selected for processing (8)
.github/workflows/deploy.ymlCHANGELOG.mdREADME.mddocs/WEBAPP_SETUP.mdpackages/backend/src/middleware/index.tspackages/frontend/src/services/api.tspackages/frontend/src/vite-env.d.tsvercel.json
📜 Review details
🧰 Additional context used
📓 Path-based instructions (28)
**/*.{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/frontend/src/vite-env.d.tspackages/backend/src/middleware/index.tspackages/frontend/src/services/api.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 enforcedImplement 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/frontend/src/vite-env.d.tspackages/backend/src/middleware/index.tspackages/frontend/src/services/api.ts
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/error-handling.mdc)
**/*.{js,jsx,ts,tsx}: Never throw strings. ThrowError(or typed subclasses) with descriptive messages
Include causal error ascausewhen 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)
MarkretryablevsnonRetryableerrors 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, andaria-*attributes as needed.
React Native accessibility: use accessibility props (accessible,accessibilityLabel), proper roles and labels.
Identify and extract repetitive UI components proactively tocomponents/with clear props and minimal coupling.
Web styles: prefer co-located styles or design system tokens; avoid global style leakage.
React Native styles: preferStyleSheet.create, design tokens, and theme providers; avoid in...
Files:
packages/frontend/src/vite-env.d.tspackages/backend/src/middleware/index.tspackages/frontend/src/services/api.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)
Introduce interfaces at module boundaries to enable testing and substitutions
**/*.{ts,tsx}: Avoid usinganytype in TypeScript. If unavoidable, useunknownwith type guards and justify with a code comment
Preferinterfacefor defining public object shapes in TypeScript, usetypefor unions and utility types
Use TypeScript utility types such asPartial,Pick,Omit,Readonly, andRecordwhen appropriate
UseI{Name}naming convention for interfaces in TypeScript
UseT{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 useanytypes - ESLint enforces this at error level
**/*.{ts,tsx}: Prefer types over interfaces for most cases
Don't ever useany- type safety always
Avoid enums; use const objects instead
For complex types, create a separate file to declare them and import them
Avoid usinganytype; if unavoidable, useunknownwith type guards and justify with code comment
Preferinterfacefor public API shapes; usetypefor unions and utility types
Use TypeScript utility types (Partial, Pick, Omit, Readonly, Record)
Files:
packages/frontend/src/vite-env.d.tspackages/backend/src/middleware/index.tspackages/frontend/src/services/api.ts
packages/frontend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
packages/frontend/src/**/*.{ts,tsx}: Frontend errors are created by Axios interceptor and should be of typeApiErrorwith status and details from backend
Frontend uses path alias@/mapped tosrc/- use this alias for all imports from the src directoryDo not depend on
@lucky/sharedpackage in frontend code; make API calls to backend via configured base URL (env)
Files:
packages/frontend/src/vite-env.d.tspackages/frontend/src/services/api.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/frontend/src/vite-env.d.tspackages/backend/src/middleware/index.tspackages/frontend/src/services/api.ts
packages/frontend/**
📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)
The
frontendpackage uses React with Vite and must not depend on the shared package
Files:
packages/frontend/src/vite-env.d.tspackages/frontend/src/services/api.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/frontend/src/vite-env.d.tspackages/backend/src/middleware/index.tspackages/frontend/src/services/api.ts
**/{.github/workflows,}/*.{yml,yaml}
📄 CodeRabbit inference engine (.cursor/rules/ci-cd.mdc)
**/{.github/workflows,}/*.{yml,yaml}: CI pipeline must include setup step (node install, environment)
CI pipeline must include lint step (TypeScript typecheck + linter)
CI pipeline must include build step (production build)
CI pipeline must include test step (unit + integration) with coverage report
CI pipeline must include quality step (static analysis, vulnerability scan)
Files:
.github/workflows/deploy.yml
**/{.github/workflows,dependabot.yml}/*.{yml,yaml}
📄 CodeRabbit inference engine (.cursor/rules/ci-cd.mdc)
Configure dependency update bot with PR templates and tests (recommended)
Files:
.github/workflows/deploy.yml
**/.github/workflows/*.{yml,yaml}
📄 CodeRabbit inference engine (.cursor/rules/ci-cd.mdc)
**/.github/workflows/*.{yml,yaml}: Configure SAST / secrets scan on PRs (recommended)
Publish artifacts only from protected pipeline steps
Files:
.github/workflows/deploy.yml
{jest.config.*,*.coverage.*,.nycrc*,nyc.config.*,coveragerc,.github/workflows/*.yml,.github/workflows/*.yaml}
📄 CodeRabbit inference engine (.cursor/rules/testing-quality.mdc)
Minimum recommended coverage threshold: 85% (raise per project risk)
Files:
.github/workflows/deploy.yml
{.github/workflows/*.{yml,yaml},*.github/workflows/*.{yml,yaml},.gitlab-ci.yml,.circleci/config.yml,bitbucket-pipelines.yml}
📄 CodeRabbit inference engine (.cursor/rules/testing-quality.mdc)
CI must run in order: lint → build → test → quality checks
Files:
.github/workflows/deploy.yml
{.github/workflows/**/*.{yml,yaml},**/.gitlab-ci.yml,.circleci/config.yml}
📄 CodeRabbit inference engine (.cursor/rules/workflow.mdc)
{.github/workflows/**/*.{yml,yaml},**/.gitlab-ci.yml,.circleci/config.yml}: CI/CD pipeline must include in order: Setup (Node install, env config) → Lint (TypeScript typecheck, linter) → Build (production build, artifacts) → Test (unit, integration, coverage) → Quality (static analysis, vulnerability scan)
Publish artifacts only from protected pipeline steps in CI/CD
Files:
.github/workflows/deploy.yml
{**/scripts/**,scripts/**,.github/workflows/**/*.{yml,yaml},**/.gitlab-ci.yml,.circleci/config.yml}
📄 CodeRabbit inference engine (.cursor/rules/workflow.mdc)
{**/scripts/**,scripts/**,.github/workflows/**/*.{yml,yaml},**/.gitlab-ci.yml,.circleci/config.yml}: Use cross-platform environment handling in scripts, cross-platform deletion utilities instead of OS-specific commands, pass non-interactive flags (--yes, --ci) by default in automation, and avoid OS-specific commands
Ensure logs are stream-friendly (no pagers) in scripts; when a pager might be used, pipe to cat
Files:
.github/workflows/deploy.yml
**/index.ts
📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)
Use
index.tsonly to re-export a small, intentional surface per module
Files:
packages/backend/src/middleware/index.ts
packages/backend/src/**/*.ts
📄 CodeRabbit inference engine (CLAUDE.md)
packages/backend/src/**/*.ts: Validation must use Zod schemas inbackend/src/schemas/and be applied viavalidateBody,validateParams, orvalidateQuery
Do not reassignreq.queryin Express middleware - it is read-only in Express 5
Files:
packages/backend/src/middleware/index.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/sharedwhen 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/middleware/index.ts
packages/backend/src/{services,middleware}/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/lucky-backend-api.mdc)
packages/backend/src/{services,middleware}/**/*.{ts,tsx}: Implement Discord OAuth for authentication in backend services
Use SessionService in middleware for session handling; keep session and auth logic centralized
Files:
packages/backend/src/middleware/index.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/middleware/index.ts
packages/backend/**
📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)
The
backendpackage depends onsharedand contains Express API with auth and guild routes
Files:
packages/backend/src/middleware/index.ts
packages/backend/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/subagent-backend.mdc)
packages/backend/**/*.ts: Apply.cursor/rules/lucky-backend-api.mdcfor structure and conventions when acting as backend specialist
Use.cursor/skills/backend-express/SKILL.mdfor Express routes, middleware, and services when acting as backend specialist
Use@lucky/sharedfor config and DB/Redis when needed in backend code
Files:
packages/backend/src/middleware/index.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:
CHANGELOG.mdREADME.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.mdand relevantdocs/files when behavior or setup changes
Files:
CHANGELOG.mddocs/WEBAPP_SETUP.md
packages/frontend/src/{stores,services}/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/lucky-frontend.mdc)
Store application state in
packages/frontend/src/stores/and API calls inpackages/frontend/src/services/api.ts
Files:
packages/frontend/src/services/api.ts
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
**/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/WEBAPP_SETUP.md
🧠 Learnings (16)
📚 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 package.json : Use npm workspaces monorepo structure with packages in `packages/*` directory containing: `shared` (config, services, types, utils), `bot` (Discord.js/Discord Player), `backend` (Express API), and `frontend` (React/Vite)
Applied to files:
vercel.json
📚 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: For React, Vite, and Tailwind work in the frontend package, use the `frontend-react-vite` skill
Applied to files:
vercel.jsonREADME.mddocs/WEBAPP_SETUP.md
📚 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/frontend/** : The `frontend` package uses React with Vite and must not depend on the shared package
Applied to files:
vercel.jsonREADME.md
📚 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 package.json : Use `npm run build` for shared → bot → backend build order; use `npm run build:frontend` separately for frontend
Applied to files:
vercel.json
📚 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: Run `npm run build` to build the monorepo (shared → bot → backend); `npm run build:frontend` for the frontend package
Applied to files:
vercel.json
📚 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:
vercel.jsonpackages/backend/src/middleware/index.tsCHANGELOG.mdpackages/frontend/src/services/api.tsREADME.mddocs/WEBAPP_SETUP.md
📚 Learning: 2026-03-09T20:21:15.586Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-shared.mdc:0-0
Timestamp: 2026-03-09T20:21:15.586Z
Learning: Applies to packages/shared/**/*.ts : Organize the Lucky Shared Package with the following directory structure: Config in `packages/shared/src/config/` (environment, constants, feature toggles, YouTube config); Services in `packages/shared/src/services/` (DatabaseService, Redis client/operations, FeatureToggleService, ReactionRoles, RoleManagement); Types in `packages/shared/src/types/` (errors, commands, common, discord, music); Utils in `packages/shared/src/utils/` (error handling, retry, embeds, log, monitoring, composables, prismaClient)
Applied to files:
vercel.json
📚 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 package.json : Use `npm run dev:bot`, `npm run dev:backend`, and `npm run dev:frontend` for development, and `npm run db:*` commands for database operations
Applied to files:
vercel.json
📚 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:
vercel.jsonpackages/frontend/src/services/api.ts
📚 Learning: 2026-03-09T20:21:15.586Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-shared.mdc:0-0
Timestamp: 2026-03-09T20:21:15.586Z
Learning: Applies to packages/shared/**/*.ts : Use the single Prisma client located at `packages/shared/src/utils/database/prismaClient.ts`; maintain schema in repo root at `prisma/schema.prisma`; run migrations from root using `npm run db:migrate`
Applied to files:
vercel.json
📚 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} : Use SessionService in middleware for session handling; keep session and auth logic centralized
Applied to files:
packages/backend/src/middleware/index.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 {CHANGELOG.md,docs/**} : Update `CHANGELOG.md` and relevant `docs/` files when behavior or setup changes
Applied to files:
CHANGELOG.md
📚 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/backend/** : The `backend` package depends on `shared` and contains Express API with auth and guild routes
Applied to files:
packages/frontend/src/services/api.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: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 **/docs/**/*.{md,mdx} : Keep API documentation in sync with code changes
Applied to files:
README.md
📚 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 **/docs/**/*.{md,mdx} : Document significant architectural design choices
Applied to files:
README.md
🪛 GitHub Check: SonarCloud Code Analysis
packages/backend/src/middleware/index.ts
[warning] 15-15: configuredOrigins should be a Set, and use configuredOrigins.has() to check existence or non-existence.
packages/frontend/src/services/api.ts
[warning] 26-26: Prefer globalThis over window.
[warning] 27-27: Prefer globalThis over window.
[warning] 25-25: Prefer globalThis.window over window.
🔇 Additional comments (6)
vercel.json (1)
1-6: LGTM!Removing the
/api/*rewrite is correct given the new dynamic API base resolution in the frontend. The frontend now explicitly targets the appropriate backend origin rather than relying on Vercel to proxy requests, which prevents the OAuth infinite loop issue..github/workflows/deploy.yml (1)
44-45: LGTM!The timeout adjustment is appropriate. Based on the webhook configuration in
deploy/hooks.json, the server returns "Deploy triggered" immediately while executing the deployment script asynchronously. A 10-second connect timeout and 20-second request timeout are sufficient for acknowledging the webhook trigger without waiting for the full deployment to complete.packages/backend/src/middleware/index.ts (1)
46-53: CORS origin callback correctly handles missing and invalid origins.The implementation properly allows requests without an
originheader (same-origin or non-browser clients) and rejects invalid origins with an explicit error. This is secure and follows best practices.CHANGELOG.md (1)
19-23: LGTM!The changelog entries accurately document all the key changes in this PR: CORS wildcard domain support, frontend API auto-resolution, Vercel routing fix, environment variable support, and deploy webhook timeouts. The entries follow Keep a Changelog format and are appropriately categorized under "Fixed".
docs/WEBAPP_SETUP.md (1)
72-79: LGTM!Documentation clearly explains the new
VITE_API_BASE_URLenvironment variable for hosted deployments and the comma-separated origins support forWEBAPP_FRONTEND_URL. This aligns well with the code changes inapi.tsand the backend middleware.README.md (1)
131-134: LGTM!The README update clearly explains the
VITE_API_BASE_URLrequirement for hosted deployments and the fallback auto-targeting behavior. This helps operators understand when and why to configure the environment variable, preventing auth/API misrouting issues.
| const configuredApiBase = import.meta.env.VITE_API_BASE_URL?.trim() | ||
|
|
||
| const inferApiBase = (): string => { | ||
| if (configuredApiBase && configuredApiBase.length > 0) { | ||
| return configuredApiBase | ||
| } | ||
|
|
||
| if (typeof window !== 'undefined') { | ||
| const protocol = window.location.protocol || 'https:' | ||
| const hostname = window.location.hostname | ||
|
|
||
| if ( | ||
| hostname === 'lucassantana.tech' || | ||
| hostname.endsWith('.lucassantana.tech') | ||
| ) { | ||
| return `${protocol}//api.lucassantana.tech/api` | ||
| } | ||
|
|
||
| if ( | ||
| hostname === 'luk-homeserver.com.br' || | ||
| hostname.endsWith('.luk-homeserver.com.br') | ||
| ) { | ||
| return `${protocol}//api.luk-homeserver.com.br/api` | ||
| } | ||
| } | ||
|
|
||
| return '/api' | ||
| } | ||
|
|
||
| const API_BASE = inferApiBase().replace(/\/+$/, '') |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Search for hardcoded /api/ paths in frontend services that bypass API_BASE
rg -n --type=ts '/api/' packages/frontend/src/services/ | grep -v 'API_BASE' | grep -v 'import'Repository: LucasSantana-Dev/Lucky
Length of output: 281
Use API_BASE for EventSource and other API endpoints instead of hardcoding /api/ paths.
The inferApiBase function correctly resolves the API base URL from environment variables with host-based fallbacks. However, hardcoded paths in packages/frontend/src/services/musicApi.ts (line 74) and packages/frontend/src/services/api.ts (line 345) bypass this configuration:
EventSourceat line 74 hardcodes/api/guilds/${guildId}/music/streamgetConnectUrlat line 345 hardcodes/api/lastfm/connect
These will fail when the frontend and backend are on different origins. Replace with ${API_BASE}/guilds/${guildId}/music/stream and similar patterns.
🧰 Tools
🪛 GitHub Check: SonarCloud Code Analysis
[warning] 26-26: Prefer globalThis over window.
[warning] 27-27: Prefer globalThis over window.
[warning] 25-25: Prefer globalThis.window over window.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/frontend/src/services/api.ts` around lines 18 - 47, The frontend is
still using hardcoded "/api/..." paths which bypass the resolved base URL from
inferApiBase/API_BASE; update all usages (e.g., the EventSource creation in
musicApi.ts and the getConnectUrl function) to use the configured API_BASE
instead of hardcoded strings. Replace instances like
'/api/guilds/${guildId}/music/stream' with
`${API_BASE}/guilds/${guildId}/music/stream` and '/api/lastfm/connect' with
`${API_BASE}/lastfm/connect`, and ensure the modules import API_BASE (from the
file that defines inferApiBase/API_BASE) so requests work across different
origins; note API_BASE is already trimmed of trailing slashes so string
concatenation as shown is safe.
|
|
Size Change: +76 B (+0.03%) Total Size: 291 kB
ℹ️ View Unchanged
|
|


Summary
*.lucassantana.tech->https://api.lucassantana.tech/api*.luk-homeserver.com.br->https://api.luk-homeserver.com.br/apiDEPLOY_WEBHOOK_URLrepo secret tohttps://api.lucassantana.tech/webhook/deployValidation
npm run type:check --workspace=packages/frontendnpm run type:check --workspace=packages/backendSummary by CodeRabbit
Bug Fixes
New Features
Documentation