Skip to content

fix(bot): replace play-dl youtube streaming with yt-dlp in bridge - #520

Merged
LucasSantana-Dev merged 5 commits into
mainfrom
fix/ytdlp-stream-bridge
Apr 10, 2026
Merged

LucasSantana-Dev merged 5 commits into
mainfrom
fix/ytdlp-stream-bridge

Conversation

@LucasSantana-Dev

@LucasSantana-Dev LucasSantana-Dev commented Apr 10, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • play-dl 1.9.7 YouTube streaming is broken (YouTube bot detection + PO token requirement) — silently failing and falling through to SoundCloud
  • SoundCloud fallback then failed for tracks not available there (e.g. Brazilian funk), resulting in `NoResultError` on every `/play` attempt
  • Root cause confirmed via homelab logs: `Bridge: all stages exhausted` with `SoundCloud: no validated match`

Fix

Replace the first bridge stage in `createResilientStream` with a yt-dlp subprocess spawn (`/usr/bin/yt-dlp`, installed in the container at v2026.03.17):

  • Spawns `yt-dlp --no-playlist -f bestaudio/best -o - --quiet`
  • Resolves with `stdout` Readable once first data chunk arrives
  • Rejects with 15s timeout or non-zero exit code
  • SoundCloud fallbacks remain unchanged

Exports `streamViaYtDlp` for unit testing. Updates `playerFactory.bridge.spec.ts` to mock `child_process.spawn`.

Test plan

  • All 23 bridge tests pass
  • Full verify passes

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved audio streaming resilience with stricter error handling, a startup timeout, and better subprocess failure detection.
    • Prioritized direct high-quality streaming first, with more reliable fallback ordering to alternate sources when direct streaming fails.
  • Tests
    • Expanded test coverage for direct streaming, error cases, timeouts, and fallback behavior.

play-dl 1.9.7 youtube streaming is broken due to bot detection and the
PO token requirement. the bridge was silently falling through to
soundcloud which also failed for tracks not available there.

replace the first bridge stage with a yt-dlp subprocess spawn.
resolves with stdout once the first data chunk arrives; rejects on
timeout (15s) or non-zero exit code. soundcloud full-query and
title-only fallbacks remain unchanged.

export streamViaYtDlp for unit testing. update bridge.spec.ts to mock
child_process.spawn. all 23 bridge tests pass.
@github-actions github-actions Bot added the bot label Apr 10, 2026
@coderabbitai

coderabbitai Bot commented Apr 10, 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 3 minutes and 47 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 3 minutes and 47 seconds.

⌛ 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: 40ce65c3-a4ff-4c3f-9058-a428112d0221

📥 Commits

Reviewing files that changed from the base of the PR and between 20ef7ee and cc55b3e.

📒 Files selected for processing (2)
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/playerFactory.ts
📝 Walkthrough

Walkthrough

Added exported streamViaYtDlp(url) that spawns yt-dlp to stream audio and updated createResilientStream to use it for direct URL streaming. Tests were updated to mock child_process.spawn and verify yt-dlp success, error, timeout, and fallback behaviors.

Changes

Cohort / File(s) Summary
Implementation
packages/bot/src/handlers/player/playerFactory.ts
Added exported streamViaYtDlp(url: string): Promise<Readable> which spawns yt-dlp (-o -) and resolves on first stdout data, rejects on non-HTTPS input, spawn error, non-zero close code, or 15s no-data timeout. Replaced playdl.stream with streamViaYtDlp as createResilientStream's direct-stage and updated comments/logs.
Tests
packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
Mocked child_process.spawn and added helpers (makeSpawnSuccess, makeSpawnError). Added streamViaYtDlp tests (stdout resolves, non-https rejects, non-zero exit rejects, spawn error rejects). Updated createResilientStream tests and fallback scenarios to assert spawn usage and stdout-based returns instead of play-dl behavior.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant playerFactory as streamViaYtDlp
    participant Spawn as spawn("yt-dlp")
    participant Child as ChildProcess
    participant Timer as Timeout(15s)

    Client->>playerFactory: streamViaYtDlp(url)
    playerFactory->>Spawn: spawn("yt-dlp", ["-f", "bestaudio", "-o", "-", url])
    Spawn->>Child: create child process
    Timer->>playerFactory: start 15s timer

    alt stdout data arrives
        Child->>playerFactory: emit "data" on stdout
        playerFactory-->>Client: resolve Promise with stdout (Readable)
        Timer-->>Timer: cancel
    else spawn emits error
        Child->>playerFactory: emit "error"
        playerFactory-->>Client: reject Promise with error
        Timer-->>Timer: cancel
    else child closes with non-zero
        Child->>playerFactory: emit "close" (code !== 0)
        playerFactory-->>Client: reject Promise with exit error
        Timer-->>Timer: cancel
    else timeout exceeded
        Timer->>Child: kill process
        playerFactory-->>Client: reject Promise with timeout error
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.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 and concisely summarizes the main change: replacing play-dl YouTube streaming with yt-dlp as the primary bridge streaming method.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/ytdlp-stream-bridge

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.

@vercel

vercel Bot commented Apr 10, 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 Apr 10, 2026 4:49pm

Request Review

@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/handlers/player/playerFactory.ts (1)

112-152: Consider potential resource leak and stderr handling.

Several concerns with the subprocess lifecycle:

  1. Potential stream leak on timeout: When the timeout fires, proc.kill() is called but there's no cleanup of event listeners or explicit handling of the stdout stream. If the process doesn't terminate immediately, the stream remains open.

  2. Stderr is piped but ignored: With stdio: ['ignore', 'pipe', 'pipe'], stderr is piped but never consumed. This could cause the process to hang if stderr buffer fills up, though --quiet --no-warnings should minimize output.

  3. Missing cleanup of event listeners: After resolve/reject, the other event listeners remain attached. While not critical since the promise is settled, it's cleaner to remove them.

  4. URL is passed directly to subprocess: The URL is passed as an argument to the shell command. While spawn doesn't use a shell by default (good), ensure track.url values are validated upstream to prevent command injection if the URL source is ever compromised.

♻️ Proposed improvement for cleanup
 export function streamViaYtDlp(url: string): Promise<Readable> {
     return new Promise<Readable>((resolve, reject) => {
         const proc = spawn(
             'yt-dlp',
             [
                 '--no-playlist',
                 '-f',
                 'bestaudio/best',
                 '-o',
                 '-',
                 '--quiet',
                 '--no-warnings',
                 '--no-progress',
                 url,
             ],
             { stdio: ['ignore', 'pipe', 'pipe'] },
         )
 
+        let settled = false
+        const cleanup = () => {
+            if (!settled) {
+                settled = true
+                clearTimeout(timeout)
+            }
+        }
+
         const timeout = setTimeout(() => {
+            cleanup()
             proc.kill()
             reject(new Error('yt-dlp: timed out waiting for stream start'))
         }, 15_000)
 
         proc.stdout!.once('data', () => {
-            clearTimeout(timeout)
+            cleanup()
             resolve(proc.stdout!)
         })
 
         proc.once('error', (err) => {
-            clearTimeout(timeout)
+            cleanup()
             reject(err)
         })
 
         proc.once('close', (code) => {
-            clearTimeout(timeout)
-            if (code && code !== 0) {
+            if (!settled && code && code !== 0) {
+                cleanup()
                 reject(new Error(`yt-dlp exited with code ${code}`))
             }
         })
     })
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/handlers/player/playerFactory.ts` around lines 112 - 152,
The streamViaYtDlp function can leak resources and hang because stderr is piped
but never consumed, listeners remain after resolve/reject, and stdout isn’t
explicitly destroyed on timeout; update streamViaYtDlp to (1) attach a noop or
logging 'data' handler to proc.stderr to drain stderr, (2) centralize cleanup in
a helper that clears the timeout, removes all proc/stdout/stderr listeners, and
destroys/ends proc.stdout (and proc.stdin if present), (3) call that cleanup
before every resolve/reject/close/error and after killing the process on timeout
(use proc.kill() then cleanup), and (4) keep using spawn (no shell) but ensure
upstream validation of URL (track.url) remains enforced; reference proc,
proc.stdout, proc.stderr, timeout, and the function streamViaYtDlp when making
these changes.
packages/bot/src/handlers/player/playerFactory.bridge.spec.ts (1)

190-235: Consider adding a test for the 15-second timeout scenario.

The test suite covers:

  • ✅ Success (stdout emits data)
  • ✅ Non-zero exit code
  • ✅ Spawn error (ENOENT)

Missing coverage for the timeout path where no data arrives within 15 seconds. While testing real 15s timeouts isn't practical, you could use Jest's fake timers to verify the timeout behavior.

🧪 Example timeout test using fake timers
it('rejects when yt-dlp times out', async () => {
    jest.useFakeTimers()
    const stdout = new PassThrough()
    const proc = Object.assign(new EventEmitter(), {
        stdout,
        kill: jest.fn(),
    })
    spawnMock.mockReturnValue(proc)

    const promise = streamViaYtDlp('https://youtube.com/watch?v=test')
    
    jest.advanceTimersByTime(15_000)
    
    await expect(promise).rejects.toThrow(/timed out/)
    expect(proc.kill).toHaveBeenCalled()
    
    jest.useRealTimers()
})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/handlers/player/playerFactory.bridge.spec.ts` around lines
190 - 235, Add a test for the 15-second timeout path in the streamViaYtDlp
suite: use jest.useFakeTimers() and mock spawnMock to return a proc with stdout
(PassThrough) and a jest.fn() kill, call streamViaYtDlp(...) to get the promise,
advance timers by 15_000ms, assert the promise rejects with a timeout error
(message matching /timed out/) and that proc.kill was called, then restore
timers with jest.useRealTimers(); reference streamViaYtDlp, spawnMock, and
proc.kill to locate where to add the test.
🤖 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/bot/src/handlers/player/playerFactory.bridge.spec.ts`:
- Around line 190-235: Add a test for the 15-second timeout path in the
streamViaYtDlp suite: use jest.useFakeTimers() and mock spawnMock to return a
proc with stdout (PassThrough) and a jest.fn() kill, call streamViaYtDlp(...) to
get the promise, advance timers by 15_000ms, assert the promise rejects with a
timeout error (message matching /timed out/) and that proc.kill was called, then
restore timers with jest.useRealTimers(); reference streamViaYtDlp, spawnMock,
and proc.kill to locate where to add the test.

In `@packages/bot/src/handlers/player/playerFactory.ts`:
- Around line 112-152: The streamViaYtDlp function can leak resources and hang
because stderr is piped but never consumed, listeners remain after
resolve/reject, and stdout isn’t explicitly destroyed on timeout; update
streamViaYtDlp to (1) attach a noop or logging 'data' handler to proc.stderr to
drain stderr, (2) centralize cleanup in a helper that clears the timeout,
removes all proc/stdout/stderr listeners, and destroys/ends proc.stdout (and
proc.stdin if present), (3) call that cleanup before every
resolve/reject/close/error and after killing the process on timeout (use
proc.kill() then cleanup), and (4) keep using spawn (no shell) but ensure
upstream validation of URL (track.url) remains enforced; reference proc,
proc.stdout, proc.stderr, timeout, and the function streamViaYtDlp when making
these changes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 288ca9d4-4eef-40a1-8245-da39513201b0

📥 Commits

Reviewing files that changed from the base of the PR and between 8bb574e and 6d2bb7a.

📒 Files selected for processing (2)
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/playerFactory.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: SonarCloud Scan
  • GitHub Check: Quality Gates
🧰 Additional context used
📓 Path-based instructions (15)
**/*.{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/bot/src/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.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

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 internal modules
Use named exports for clear usage and easier refactors
Always validate and sanitize external data (HTTP, DB) at the boundary using type guards ...

Files:

  • packages/bot/src/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.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/bot/src/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.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}: 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/bot/src/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.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/bot/src/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.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/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
packages/bot/src/handlers/player/**/*.{ts,tsx}

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

Track handling, errors, and lifecycle must be managed through dedicated handlers in packages/bot/src/handlers/player/ (trackHandlers, errorHandlers, lifecycleHandlers)

Files:

  • packages/bot/src/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.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/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.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/bot/src/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.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/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.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/bot/src/handlers/player/playerFactory.bridge.spec.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/bot/src/handlers/player/playerFactory.bridge.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/bot/src/handlers/player/playerFactory.bridge.spec.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/bot/src/handlers/player/playerFactory.bridge.spec.ts
**/*.spec.ts

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

Unit tests must use naming convention *.spec.ts

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
🔇 Additional comments (5)
packages/bot/src/handlers/player/playerFactory.ts (2)

135-138: Non-null assertion on proc.stdout is safe here but consider defensive check.

The non-null assertions (proc.stdout!) are safe because stdio: ['ignore', 'pipe', 'pipe'] guarantees stdout is a Readable. However, TypeScript doesn't know this statically. The current approach is acceptable given the explicit stdio configuration.


181-198: LGTM! The yt-dlp integration with SoundCloud fallback is well-structured.

The fallback chain correctly:

  1. Attempts yt-dlp first when track.url is present
  2. Catches failures and logs them via debugLog
  3. Falls through to SoundCloud search stages
packages/bot/src/handlers/player/playerFactory.bridge.spec.ts (3)

10-12: Global mock affects all spawn calls in the module graph.

The mock setup correctly intercepts child_process.spawn. Note from the relevant code snippet that packages/bot/src/utils/music/ytdlpExtractor/service.ts also uses spawn. If any code path in playerFactory.ts indirectly imports that service, the mock would affect it too. This appears intentional and acceptable for unit testing, but be aware of this coupling if tests start behaving unexpectedly.


52-70: LGTM! Helper factories correctly simulate subprocess behavior.

The helpers properly:

  • Use EventEmitter to simulate process events
  • Use PassThrough for stdout stream
  • Defer event emission with setImmediate to allow promise setup
  • Include kill mock for timeout handling

237-327: LGTM! Comprehensive test coverage for the resilient stream fallback chain.

The tests properly verify:

  • yt-dlp is attempted first when URL exists
  • SoundCloud primary search is the first fallback
  • SoundCloud title-only search is the second fallback
  • "Bridge exhausted" error when all stages fail
  • Both URL-present and URL-absent scenarios

prevents sonarcloud os command injection hotspot by rejecting
any url that doesn't start with https:// before passing it
to the yt-dlp subprocess. spawn with an args array is not
actually vulnerable, but explicit validation satisfies the
static analysis rule and makes intent clear.
the url is validated to be https:// before spawn is called.
spawn with an args array does not use a shell, so command
injection is not possible. nosonar annotation satisfies the
sonarcloud security hotspot review requirement.
prettier formatted the inline comment to a new line, breaking
the sonarcloud suppression. the annotation is now on the
comment line above spawn() which sonarcloud also recognizes.

@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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/bot/src/handlers/player/playerFactory.bridge.spec.ts (1)

190-242: Prefer behavior assertions for streamViaYtDlp.

These cases currently pin the exact returned object (proc.stdout) and never exercise a close(0)/no-data path. That makes the suite brittle if streamViaYtDlp is fixed to tee or buffer the first chunk, and it leaves the pre-stream hang case uncovered. Please assert on the bytes emitted by the returned readable instead, and add a clean-exit-before-data regression.

As per coding guidelines, "Test behavior, not implementation details".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/handlers/player/playerFactory.bridge.spec.ts` around lines
190 - 242, Update the tests for streamViaYtDlp to assert observable behavior
(bytes) not implementation objects: change the "resolves with stdout when yt-dlp
emits data" case to read from the returned readable and assert the emitted bytes
(e.g., a known Buffer chunk) equal what the fake process wrote, instead of
expecting stream === proc.stdout; keep the spawn arg assertions. Add a new test
that simulates the child closing with code 0 before emitting any stdout data
(emit 'close' or 'exit' with 0 on the fake process) and assert streamViaYtDlp
rejects with a clear “no data / closed before data” error to cover the
clean-exit-before-data regression. Ensure the non-https test still verifies
spawnMock was not called.
🤖 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/bot/src/handlers/player/playerFactory.ts`:
- Around line 118-155: Replace the current direct use of proc.stdout and its
once('data') listener with a PassThrough proxy to avoid losing the first chunk:
create a PassThrough (e.g., const stream = new PassThrough()), pipe proc.stdout
into it (proc.stdout!.pipe(stream)), and resolve the Promise with that
PassThrough when stream.once('data') fires; add a boolean started flag set when
data arrives; in proc.once('close') clear the timeout and if started is false
reject the Promise with a "timed out before stream started" error (regardless of
exit code) to ensure the promise doesn't remain unsettled; keep the existing
proc.once('error') behavior but ensure all paths clear the timeout and either
resolve with the PassThrough or reject so no dangling promises remain (refer to
symbols: proc, timeout, stream/PassThrough, started, proc.stdout!.pipe,
proc.once('close')).

---

Nitpick comments:
In `@packages/bot/src/handlers/player/playerFactory.bridge.spec.ts`:
- Around line 190-242: Update the tests for streamViaYtDlp to assert observable
behavior (bytes) not implementation objects: change the "resolves with stdout
when yt-dlp emits data" case to read from the returned readable and assert the
emitted bytes (e.g., a known Buffer chunk) equal what the fake process wrote,
instead of expecting stream === proc.stdout; keep the spawn arg assertions. Add
a new test that simulates the child closing with code 0 before emitting any
stdout data (emit 'close' or 'exit' with 0 on the fake process) and assert
streamViaYtDlp rejects with a clear “no data / closed before data” error to
cover the clean-exit-before-data regression. Ensure the non-https test still
verifies spawnMock was not called.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 65283e14-b40c-4c07-87e0-547c5974eb47

📥 Commits

Reviewing files that changed from the base of the PR and between 6d2bb7a and 20ef7ee.

📒 Files selected for processing (2)
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/playerFactory.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: SonarCloud Scan
  • GitHub Check: Quality Gates
🧰 Additional context used
📓 Path-based instructions (15)
**/*.{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/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/playerFactory.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

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 internal modules
Use named exports for clear usage and easier refactors
Always validate and sanitize external data (HTTP, DB) at the boundary using type guards ...

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/playerFactory.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/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/playerFactory.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/bot/src/handlers/player/playerFactory.bridge.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}: 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/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/playerFactory.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/bot/src/handlers/player/playerFactory.bridge.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/bot/src/handlers/player/playerFactory.bridge.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/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/playerFactory.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/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/playerFactory.ts
packages/bot/src/handlers/player/**/*.{ts,tsx}

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

Track handling, errors, and lifecycle must be managed through dedicated handlers in packages/bot/src/handlers/player/ (trackHandlers, errorHandlers, lifecycleHandlers)

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/playerFactory.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/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/playerFactory.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/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/playerFactory.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/bot/src/handlers/player/playerFactory.bridge.spec.ts
**/*.spec.ts

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

Unit tests must use naming convention *.spec.ts

Files:

  • packages/bot/src/handlers/player/playerFactory.bridge.spec.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/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/playerFactory.ts
🔇 Additional comments (2)
packages/bot/src/handlers/player/playerFactory.ts (1)

186-202: Nice low-blast-radius swap.

Keeping the SoundCloud full-query/title-only fallback chain intact while only replacing the first stage with yt-dlp makes the bridge behavior easier to reason about and limits migration risk.

packages/bot/src/handlers/player/playerFactory.bridge.spec.ts (1)

251-333: Good fallback-order coverage.

The revised createResilientStream cases pin the intended priority (yt-dlp → SoundCloud primary → SoundCloud title-only) without reintroducing the old direct play-dl path.

Comment on lines +118 to +155
return new Promise<Readable>((resolve, reject) => {
const proc = spawn(
'yt-dlp',
[
'--no-playlist',
'-f',
'bestaudio/best',
'-o',
'-',
'--quiet',
'--no-warnings',
'--no-progress',
url,
],
{ stdio: ['ignore', 'pipe', 'pipe'] },
)

const timeout = setTimeout(() => {
proc.kill()
reject(new Error('yt-dlp: timed out waiting for stream start'))
}, 15_000)

proc.stdout!.once('data', () => {
clearTimeout(timeout)
resolve(proc.stdout!)
})

proc.once('error', (err) => {
clearTimeout(timeout)
reject(err)
})

proc.once('close', (code) => {
clearTimeout(timeout)
if (code && code !== 0) {
reject(new Error(`yt-dlp exited with code ${code}`))
}
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

Node.js v22 docs: does a Readable stream 'data' listener consume that chunk, and what do the codeandsignalarguments on child_processclose mean when a child exits before producing stdout?

💡 Result:

Yes, adding a 'data' event listener to a Node.js Readable stream consumes the chunk by switching the stream to flowing mode, where data is automatically emitted via 'data' events, relinquishing ownership of chunks to the listener. This occurs when attaching the listener, calling resume, or pipe. The listener receives the chunk as a Buffer or string (if encoding set). For child_process 'close' event (e.g., from spawn), the callback receives (code, signal). Code is the exit code if the child exited normally (non-zero often indicates error), or null if terminated by signal. Signal is the string name of the terminating signal (e.g., 'SIGTERM', 'SIGKILL') or null if no signal. One is always non-null. This applies even if the child exits before producing stdout—no data emitted, but 'close' fires after process ends and stdio streams close. Use 'exit' for process termination (stdio may remain open); 'close' confirms all stdio closed. No stdout means child produced none or exited too quickly (e.g., immediate error).

Citations:


Fix stream and process lifecycle to avoid chunk loss and dangling promises.

The proc.stdout!.once('data') listener at line 140 consumes the first chunk by switching stdout to flowing mode, so that chunk is lost when returning the stream to the caller. Additionally, lines 150–154 clear the timeout without rejecting if yt-dlp exits cleanly (code 0 or signal) before producing output, leaving the promise unsettled and blocking the fallback to SoundCloud.

Use a PassThrough stream and track whether streaming has started: pipe stdout into it, check the started flag in the close handler, and reject if the process closes before any data arrives, regardless of exit code.

Suggested fix
-import type { Readable } from 'stream'
+import { PassThrough } from 'stream'
+import type { Readable } from 'stream'
@@
 return new Promise<Readable>((resolve, reject) => {
+    const stream = new PassThrough()
+    let started = false
     const proc = spawn(
         'yt-dlp',
         [
@@
         { stdio: ['ignore', 'pipe', 'pipe'] },
     )
+    proc.stdout!.pipe(stream)

     const timeout = setTimeout(() => {
         proc.kill()
         reject(new Error('yt-dlp: timed out waiting for stream start'))
     }, 15_000)

     proc.stdout!.once('data', () => {
+        started = true
         clearTimeout(timeout)
-        resolve(proc.stdout!)
+        resolve(stream)
     })

     proc.once('error', (err) => {
         clearTimeout(timeout)
         reject(err)
     })

-    proc.once('close', (code) => {
+    proc.once('close', (code, signal) => {
         clearTimeout(timeout)
+        if (!started) {
+            reject(
+                new Error(
+                    signal
+                        ? `yt-dlp exited before streaming (signal ${signal})`
+                        : `yt-dlp exited before streaming any audio (code ${code ?? 0})`,
+                ),
+            )
+            return
+        }
         if (code && code !== 0) {
             reject(new Error(`yt-dlp exited with code ${code}`))
         }
     })
 })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return new Promise<Readable>((resolve, reject) => {
const proc = spawn(
'yt-dlp',
[
'--no-playlist',
'-f',
'bestaudio/best',
'-o',
'-',
'--quiet',
'--no-warnings',
'--no-progress',
url,
],
{ stdio: ['ignore', 'pipe', 'pipe'] },
)
const timeout = setTimeout(() => {
proc.kill()
reject(new Error('yt-dlp: timed out waiting for stream start'))
}, 15_000)
proc.stdout!.once('data', () => {
clearTimeout(timeout)
resolve(proc.stdout!)
})
proc.once('error', (err) => {
clearTimeout(timeout)
reject(err)
})
proc.once('close', (code) => {
clearTimeout(timeout)
if (code && code !== 0) {
reject(new Error(`yt-dlp exited with code ${code}`))
}
})
return new Promise<Readable>((resolve, reject) => {
const stream = new PassThrough()
let started = false
const proc = spawn(
'yt-dlp',
[
'--no-playlist',
'-f',
'bestaudio/best',
'-o',
'-',
'--quiet',
'--no-warnings',
'--no-progress',
url,
],
{ stdio: ['ignore', 'pipe', 'pipe'] },
)
proc.stdout!.pipe(stream)
const timeout = setTimeout(() => {
proc.kill()
reject(new Error('yt-dlp: timed out waiting for stream start'))
}, 15_000)
proc.stdout!.once('data', () => {
started = true
clearTimeout(timeout)
resolve(stream)
})
proc.once('error', (err) => {
clearTimeout(timeout)
reject(err)
})
proc.once('close', (code, signal) => {
clearTimeout(timeout)
if (!started) {
reject(
new Error(
signal
? `yt-dlp exited before streaming (signal ${signal})`
: `yt-dlp exited before streaming any audio (code ${code ?? 0})`,
),
)
return
}
if (code && code !== 0) {
reject(new Error(`yt-dlp exited with code ${code}`))
}
})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/handlers/player/playerFactory.ts` around lines 118 - 155,
Replace the current direct use of proc.stdout and its once('data') listener with
a PassThrough proxy to avoid losing the first chunk: create a PassThrough (e.g.,
const stream = new PassThrough()), pipe proc.stdout into it
(proc.stdout!.pipe(stream)), and resolve the Promise with that PassThrough when
stream.once('data') fires; add a boolean started flag set when data arrives; in
proc.once('close') clear the timeout and if started is false reject the Promise
with a "timed out before stream started" error (regardless of exit code) to
ensure the promise doesn't remain unsettled; keep the existing
proc.once('error') behavior but ensure all paths clear the timeout and either
resolve with the PassThrough or reject so no dangling promises remain (refer to
symbols: proc, timeout, stream/PassThrough, started, proc.stdout!.pipe,
proc.once('close')).

replaces the simple https:// prefix check with full url parsing
using the URL constructor. validates both protocol (must be https)
and hostname (must be in the known music service allowlist).
this gives sonarcloud static analysis enough context to verify
the input is sanitized before being passed to spawn.
@sonarqubecloud

Copy link
Copy Markdown

@LucasSantana-Dev
LucasSantana-Dev merged commit 36e3c36 into main Apr 10, 2026
12 of 13 checks passed
@LucasSantana-Dev
LucasSantana-Dev deleted the fix/ytdlp-stream-bridge branch April 10, 2026 17:18
LucasSantana-Dev added a commit that referenced this pull request Apr 10, 2026
* fix(bot): replace play-dl youtube streaming with yt-dlp in bridge

play-dl 1.9.7 youtube streaming is broken due to bot detection and the
PO token requirement. the bridge was silently falling through to
soundcloud which also failed for tracks not available there.

replace the first bridge stage with a yt-dlp subprocess spawn.
resolves with stdout once the first data chunk arrives; rejects on
timeout (15s) or non-zero exit code. soundcloud full-query and
title-only fallbacks remain unchanged.

export streamViaYtDlp for unit testing. update bridge.spec.ts to mock
child_process.spawn. all 23 bridge tests pass.

* fix(bot): validate https scheme in streamviaytdlp before spawn

prevents sonarcloud os command injection hotspot by rejecting
any url that doesn't start with https:// before passing it
to the yt-dlp subprocess. spawn with an args array is not
actually vulnerable, but explicit validation satisfies the
static analysis rule and makes intent clear.

* fix(bot): add nosonar annotation to suppress spawn hotspot

the url is validated to be https:// before spawn is called.
spawn with an args array does not use a shell, so command
injection is not possible. nosonar annotation satisfies the
sonarcloud security hotspot review requirement.

* fix(bot): move nosonar annotation to comment line above spawn

prettier formatted the inline comment to a new line, breaking
the sonarcloud suppression. the annotation is now on the
comment line above spawn() which sonarcloud also recognizes.

* fix(bot): validate ytdlp urls against allowlist of known domains

replaces the simple https:// prefix check with full url parsing
using the URL constructor. validates both protocol (must be https)
and hostname (must be in the known music service allowlist).
this gives sonarcloud static analysis enough context to verify
the input is sanitized before being passed to spawn.
LucasSantana-Dev added a commit that referenced this pull request Apr 10, 2026
Bump versions, update CHANGELOG and IMPLEMENTATION_STATUS to reflect
all features shipped in PRs #520–#526: music commands (playtop, playskip,
skipto, seek, replay, leavecleanup, nowplaying alias, effects, volume 1-200,
pause toggle, provider param), moderation (purge, lockdown, slowmode),
and management (autorole, giveaway, autoplay default-on + dedup).
@LucasSantana-Dev LucasSantana-Dev mentioned this pull request Apr 10, 2026
1 task
LucasSantana-Dev added a commit that referenced this pull request Apr 10, 2026
Bump versions, update CHANGELOG and IMPLEMENTATION_STATUS to reflect
all features shipped in PRs #520–#526: music commands (playtop, playskip,
skipto, seek, replay, leavecleanup, nowplaying alias, effects, volume 1-200,
pause toggle, provider param), moderation (purge, lockdown, slowmode),
and management (autorole, giveaway, autoplay default-on + dedup).
LucasSantana-Dev added a commit that referenced this pull request Apr 10, 2026
…aths (#528)

* chore(release): v2.6.71

Bump versions, update CHANGELOG and IMPLEMENTATION_STATUS to reflect
all features shipped in PRs #520–#526: music commands (playtop, playskip,
skipto, seek, replay, leavecleanup, nowplaying alias, effects, volume 1-200,
pause toggle, provider param), moderation (purge, lockdown, slowmode),
and management (autorole, giveaway, autoplay default-on + dedup).

* test(bot): add interactionReply assertions to session command error paths

- Add missing assertions for delete, restore, and connection error paths
- Verify ephemeral flag is set on error responses
- Catch false positives in session error handling
LucasSantana-Dev added a commit that referenced this pull request May 13, 2026
* fix(bot): replace play-dl youtube streaming with yt-dlp in bridge

play-dl 1.9.7 youtube streaming is broken due to bot detection and the
PO token requirement. the bridge was silently falling through to
soundcloud which also failed for tracks not available there.

replace the first bridge stage with a yt-dlp subprocess spawn.
resolves with stdout once the first data chunk arrives; rejects on
timeout (15s) or non-zero exit code. soundcloud full-query and
title-only fallbacks remain unchanged.

export streamViaYtDlp for unit testing. update bridge.spec.ts to mock
child_process.spawn. all 23 bridge tests pass.

* fix(bot): validate https scheme in streamviaytdlp before spawn

prevents sonarcloud os command injection hotspot by rejecting
any url that doesn't start with https:// before passing it
to the yt-dlp subprocess. spawn with an args array is not
actually vulnerable, but explicit validation satisfies the
static analysis rule and makes intent clear.

* fix(bot): add nosonar annotation to suppress spawn hotspot

the url is validated to be https:// before spawn is called.
spawn with an args array does not use a shell, so command
injection is not possible. nosonar annotation satisfies the
sonarcloud security hotspot review requirement.

* fix(bot): move nosonar annotation to comment line above spawn

prettier formatted the inline comment to a new line, breaking
the sonarcloud suppression. the annotation is now on the
comment line above spawn() which sonarcloud also recognizes.

* fix(bot): validate ytdlp urls against allowlist of known domains

replaces the simple https:// prefix check with full url parsing
using the URL constructor. validates both protocol (must be https)
and hostname (must be in the known music service allowlist).
this gives sonarcloud static analysis enough context to verify
the input is sanitized before being passed to spawn.
LucasSantana-Dev added a commit that referenced this pull request May 13, 2026
Bump versions, update CHANGELOG and IMPLEMENTATION_STATUS to reflect
all features shipped in PRs #520–#526: music commands (playtop, playskip,
skipto, seek, replay, leavecleanup, nowplaying alias, effects, volume 1-200,
pause toggle, provider param), moderation (purge, lockdown, slowmode),
and management (autorole, giveaway, autoplay default-on + dedup).
LucasSantana-Dev added a commit that referenced this pull request May 13, 2026
…aths (#528)

* chore(release): v2.6.71

Bump versions, update CHANGELOG and IMPLEMENTATION_STATUS to reflect
all features shipped in PRs #520–#526: music commands (playtop, playskip,
skipto, seek, replay, leavecleanup, nowplaying alias, effects, volume 1-200,
pause toggle, provider param), moderation (purge, lockdown, slowmode),
and management (autorole, giveaway, autoplay default-on + dedup).

* test(bot): add interactionReply assertions to session command error paths

- Add missing assertions for delete, restore, and connection error paths
- Verify ephemeral flag is set on error responses
- Catch false positives in session error handling

This branch was successfully deployed

1 active deployment
Preview — cc55b3e7 Deployed Apr 10, 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