suno 0.5.4

Generate AI music from your terminal — Suno v5.5 with tags, exclude, vocal control, and all generation features
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! hCaptcha bypass via piloted Chrome.
//!
//! Suno gates `/api/generate/v2-web/` with an invisible hCaptcha challenge.
//! The request body's `token` field must contain a freshly-solved hCaptcha
//! response. Headless HTTP clients can't pass it; only a real browser with
//! a warm behavioural fingerprint does.
//!
//! This module spawns a hidden Chrome instance with `--remote-debugging-port`
//! enabled, injects the user's Suno cookies via CDP, navigates to
//! suno.com/create, then renders an invisible hCaptcha widget and calls
//! `hcaptcha.execute()` to obtain a token. The Chrome instance is reused
//! across calls so subsequent generations are fast.
//!
//! Discovered + verified end-to-end on 2026-04-08.

use std::process::Stdio;
use std::sync::OnceLock;
use std::time::Duration;

use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::{Child, Command};
use tokio::sync::Mutex;
use tokio::time::{sleep, timeout};
use tokio_tungstenite::tungstenite::Message;

use crate::auth::AuthState;
use crate::errors::CliError;

/// Suno's hCaptcha sitekey, captured from the live web app's
/// `hcaptcha.render(...)` arguments on 2026-04-08.
const SUNO_HCAPTCHA_SITEKEY: &str = "d65453de-3f1a-4aac-9366-a0f06e52b2ce";
/// Port for the suno-cli managed Chrome instance. Picked high to avoid
/// colliding with the user's main Chrome (which is rarely on 9233).
const CDP_PORT: u16 = 9233;
const CDP_HOST: &str = "127.0.0.1";

/// Singleton holder for the Chrome process so the same instance survives
/// across multiple `generate()` calls within one CLI invocation.
static CHROME: OnceLock<Mutex<Option<Child>>> = OnceLock::new();

fn chrome_slot() -> &'static Mutex<Option<Child>> {
    CHROME.get_or_init(|| Mutex::new(None))
}

/// Solve a fresh hCaptcha challenge and return the token to attach to a
/// `/api/generate/v2-web/` request body.
pub async fn solve(auth: &AuthState) -> Result<String, CliError> {
    ensure_chrome_running().await?;
    let target = find_or_create_suno_tab().await?;
    let token = render_and_execute(&target.web_socket_debugger_url, auth).await?;
    Ok(token)
}

/// Either reuse a Chrome instance already listening on `CDP_PORT` or spawn
/// a new hidden one with the suno-cli profile dir. Idempotent.
async fn ensure_chrome_running() -> Result<(), CliError> {
    if cdp_version().await.is_ok() {
        return Ok(());
    }

    // Need to spawn it.
    let chrome_path = locate_chrome()?;
    let profile_dir = directories::ProjectDirs::from("com", "suno-cli", "suno-cli")
        .map(|d| d.data_dir().join("chrome-profile"))
        .ok_or_else(|| CliError::Config("could not resolve data dir for chrome profile".into()))?;
    std::fs::create_dir_all(&profile_dir)?;

    eprintln!("Launching headless Chrome for captcha solver (one-time per session)...");

    // NOTE: do NOT use --headless. hCaptcha's bot-detection trips on headless
    // mode and returns "challenge-expired". We run a real headed Chrome but
    // shove it far offscreen + give it a 1x1 window so the user never sees it.
    let child = Command::new(&chrome_path)
        .arg(format!("--remote-debugging-port={CDP_PORT}"))
        .arg(format!("--user-data-dir={}", profile_dir.display()))
        .arg("--no-first-run")
        .arg("--no-default-browser-check")
        .arg("--disable-search-engine-choice-screen")
        .arg("--disable-features=TranslateUI")
        .arg("--window-position=-32000,-32000")
        .arg("--window-size=1,1")
        .arg("--silent-launch")
        .arg("about:blank")
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|e| CliError::Config(format!("failed to spawn Chrome at {chrome_path:?}: {e}")))?;

    {
        let mut slot = chrome_slot().lock().await;
        *slot = Some(child);
    }

    // Wait up to 10s for CDP to come up
    for _ in 0..20 {
        sleep(Duration::from_millis(500)).await;
        if cdp_version().await.is_ok() {
            return Ok(());
        }
    }

    Err(CliError::Config(
        "Chrome was spawned but never opened the CDP port. Try `suno chrome-launch` for a visible Chrome window.".into(),
    ))
}

/// Locate a Chrome binary on the host. Looks in the usual macOS / Linux /
/// Windows install paths and falls back to `$PATH`.
fn locate_chrome() -> Result<String, CliError> {
    let candidates: &[&str] = if cfg!(target_os = "macos") {
        &[
            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
            "/Applications/Chromium.app/Contents/MacOS/Chromium",
            "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
        ]
    } else if cfg!(target_os = "linux") {
        &[
            "/usr/bin/google-chrome",
            "/usr/bin/google-chrome-stable",
            "/usr/bin/chromium",
            "/usr/bin/chromium-browser",
            "/snap/bin/chromium",
        ]
    } else {
        &[
            "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
            "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
        ]
    };
    for c in candidates {
        if std::path::Path::new(c).exists() {
            return Ok(c.to_string());
        }
    }
    Err(CliError::Config(
        "Could not find a Chrome/Chromium binary. Install Google Chrome or set SUNO_CHROME_PATH."
            .into(),
    ))
}

/// CDP target descriptor returned by `/json/list`.
#[derive(Debug, Deserialize)]
struct Target {
    #[serde(rename = "type")]
    target_type: String,
    url: String,
    #[serde(rename = "webSocketDebuggerUrl")]
    web_socket_debugger_url: String,
}

async fn cdp_version() -> Result<serde_json::Value, CliError> {
    let url = format!("http://{CDP_HOST}:{CDP_PORT}/json/version");
    let resp = reqwest::Client::new()
        .get(&url)
        .timeout(Duration::from_secs(2))
        .send()
        .await
        .map_err(|e| CliError::Config(format!("CDP /json/version: {e}")))?;
    let v: serde_json::Value = resp
        .json()
        .await
        .map_err(|e| CliError::Config(format!("CDP json parse: {e}")))?;
    Ok(v)
}

async fn cdp_list() -> Result<Vec<Target>, CliError> {
    let url = format!("http://{CDP_HOST}:{CDP_PORT}/json/list");
    let resp = reqwest::Client::new()
        .get(&url)
        .timeout(Duration::from_secs(5))
        .send()
        .await
        .map_err(|e| CliError::Config(format!("CDP /json/list: {e}")))?;
    let list: Vec<Target> = resp
        .json()
        .await
        .map_err(|e| CliError::Config(format!("CDP json parse: {e}")))?;
    Ok(list)
}

/// Find the existing suno.com tab in the managed Chrome, or open a new one
/// at suno.com/create.
async fn find_or_create_suno_tab() -> Result<Target, CliError> {
    let targets = cdp_list().await?;
    if let Some(t) = targets
        .into_iter()
        .find(|t| t.target_type == "page" && t.url.contains("suno.com"))
    {
        return Ok(t);
    }

    // No suno tab — open one. CDP exposes a /json/new?url= helper.
    let url = format!(
        "http://{CDP_HOST}:{CDP_PORT}/json/new?{}",
        urlencode("https://suno.com/create")
    );
    let resp = reqwest::Client::new()
        .put(&url)
        .timeout(Duration::from_secs(10))
        .send()
        .await
        .map_err(|e| CliError::Config(format!("CDP /json/new: {e}")))?;
    let t: Target = resp
        .json()
        .await
        .map_err(|e| CliError::Config(format!("CDP /json/new parse: {e}")))?;
    // Give the page a moment to start loading before we attach
    sleep(Duration::from_millis(800)).await;
    Ok(t)
}

fn urlencode(s: &str) -> String {
    s.replace(":", "%3A").replace("/", "%2F")
}

/// CDP request envelope.
#[derive(Serialize)]
struct CdpReq<'a> {
    id: u64,
    method: &'a str,
    params: serde_json::Value,
}

/// CDP cookie struct (subset of Network.CookieParam).
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct CdpCookie {
    name: String,
    value: String,
    domain: String,
    path: String,
    secure: bool,
    http_only: bool,
    same_site: &'static str,
}

type CdpStream =
    tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;

/// Send a CDP method and wait for the response (drains intervening events).
async fn cdp_call(
    ws: &mut CdpStream,
    id: u64,
    method: &str,
    params: serde_json::Value,
) -> Result<serde_json::Value, CliError> {
    let req = CdpReq { id, method, params };
    let payload = serde_json::to_string(&req).unwrap();
    ws.send(Message::Text(payload.into()))
        .await
        .map_err(|e| CliError::Config(format!("CDP ws send {method}: {e}")))?;
    loop {
        let msg = timeout(Duration::from_secs(60), ws.next())
            .await
            .map_err(|_| CliError::Config(format!("CDP {method} timeout")))?
            .ok_or_else(|| CliError::Config(format!("CDP {method} ws closed")))?
            .map_err(|e| CliError::Config(format!("CDP {method} ws err: {e}")))?;
        let text = match msg {
            Message::Text(t) => t.to_string(),
            Message::Binary(_) | Message::Ping(_) | Message::Pong(_) | Message::Frame(_) => {
                continue;
            }
            Message::Close(_) => {
                return Err(CliError::Config(format!("CDP {method} ws closed mid-call")));
            }
        };
        let v: serde_json::Value = serde_json::from_str(&text)
            .map_err(|e| CliError::Config(format!("CDP {method} json: {e}")))?;
        if v.get("id").and_then(|x| x.as_u64()) == Some(id) {
            if let Some(err) = v.get("error") {
                return Err(CliError::Config(format!("CDP {method} error: {err}")));
            }
            return Ok(v.get("result").cloned().unwrap_or(serde_json::Value::Null));
        }
        // Ignore unrelated events
    }
}

/// Connect to the page websocket, inject cookies, navigate to suno.com/create
/// if needed, then render an invisible hCaptcha widget and call
/// `hcaptcha.execute()` to obtain a token.
async fn render_and_execute(ws_url: &str, _auth: &AuthState) -> Result<String, CliError> {
    let (mut ws, _) = tokio_tungstenite::connect_async(ws_url)
        .await
        .map_err(|e| CliError::Config(format!("CDP ws connect: {e}")))?;

    let mut next_id: u64 = 0;
    let mut next = || -> u64 {
        next_id += 1;
        next_id
    };

    cdp_call(&mut ws, next(), "Network.enable", serde_json::json!({})).await?;
    cdp_call(&mut ws, next(), "Page.enable", serde_json::json!({})).await?;
    cdp_call(&mut ws, next(), "Runtime.enable", serde_json::json!({})).await?;

    // Inject cookies fresh from rookie every time so we always have the
    // latest from the user's main Chrome.
    let cookies = extract_cookies()?;
    if !cookies.is_empty() {
        cdp_call(
            &mut ws,
            next(),
            "Network.setCookies",
            serde_json::json!({ "cookies": cookies }),
        )
        .await?;
    }

    // Probe current URL — navigate if not already on suno.com/create
    let page_url = cdp_call(
        &mut ws,
        next(),
        "Runtime.evaluate",
        serde_json::json!({
            "expression": "location.href",
            "returnByValue": true,
        }),
    )
    .await?;
    let needs_nav = page_url
        .get("result")
        .and_then(|r| r.get("value"))
        .and_then(|v| v.as_str())
        .map(|s| !s.contains("suno.com/create"))
        .unwrap_or(true);
    if needs_nav {
        cdp_call(
            &mut ws,
            next(),
            "Page.navigate",
            serde_json::json!({ "url": "https://suno.com/create" }),
        )
        .await?;
        // Poll for hcaptcha global (up to 30s)
        let mut ready = false;
        for _ in 0..30 {
            sleep(Duration::from_secs(1)).await;
            let probe = cdp_call(
                &mut ws,
                next(),
                "Runtime.evaluate",
                serde_json::json!({
                    "expression": "typeof hcaptcha !== 'undefined' && !!hcaptcha.render",
                    "returnByValue": true,
                }),
            )
            .await?;
            if probe
                .get("result")
                .and_then(|r| r.get("value"))
                .and_then(|v| v.as_bool())
                .unwrap_or(false)
            {
                ready = true;
                break;
            }
        }
        if !ready {
            return Err(CliError::Config(
                "hcaptcha never finished loading on suno.com/create".into(),
            ));
        }
        // Extra settle so the SDK is fully wired up
        sleep(Duration::from_secs(2)).await;
    }

    // Render an invisible widget and execute it
    let solve_js = format!(
        r#"
        (async () => {{
            try {{
                const div = document.createElement('div');
                div.style.cssText = 'position:fixed;top:-9999px;left:-9999px;';
                document.body.appendChild(div);
                const id = hcaptcha.render(div, {{
                    sitekey: '{SUNO_HCAPTCHA_SITEKEY}',
                    size: 'invisible',
                    sentry: false,
                    endpoint: 'https://hcaptcha-endpoint-prod.suno.com',
                    assethost: 'https://hcaptcha-assets-prod.suno.com',
                    imghost: 'https://hcaptcha-imgs-prod.suno.com',
                    reportapi: 'https://hcaptcha-reportapi-prod.suno.com',
                }});
                const r = await hcaptcha.execute(id, {{ async: true }});
                return (r && r.response) ? r.response : '';
            }} catch (e) {{
                return 'ERR:' + String(e);
            }}
        }})()
        "#
    );

    let result = cdp_call(
        &mut ws,
        next(),
        "Runtime.evaluate",
        serde_json::json!({
            "expression": solve_js,
            "awaitPromise": true,
            "returnByValue": true,
        }),
    )
    .await?;

    let token = result
        .get("result")
        .and_then(|r| r.get("value"))
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string();

    if token.is_empty() {
        return Err(CliError::Config("hcaptcha returned empty token".into()));
    }
    if token.starts_with("ERR:") {
        return Err(CliError::Config(format!("hcaptcha solver: {token}")));
    }
    Ok(token)
}

/// Pull the user's Suno cookies from their main Chrome via `rookie`.
/// Returns them in CDP `Network.CookieParam` shape.
fn extract_cookies() -> Result<Vec<CdpCookie>, CliError> {
    let domains: Vec<String> = vec![
        "suno.com".into(),
        "auth.suno.com".into(),
        ".suno.com".into(),
    ];
    let mut out = Vec::new();
    let mut seen = std::collections::HashSet::new();

    let raw_cookies = match rookie::chrome(Some(domains)) {
        Ok(cs) => cs,
        Err(e) => {
            return Err(CliError::Config(format!(
                "could not read Chrome cookies via rookie: {e}"
            )));
        }
    };

    for c in raw_cookies {
        if !c.domain.contains("suno.com") {
            continue;
        }
        let key = (c.name.clone(), c.domain.clone());
        if !seen.insert(key) {
            continue;
        }
        out.push(CdpCookie {
            name: c.name,
            value: c.value,
            domain: c.domain,
            path: c.path,
            secure: c.secure,
            http_only: c.http_only,
            same_site: "Lax",
        });
    }
    Ok(out)
}

/// Drain the spawned Chrome's stderr in the background — keeps it from
/// blocking on a full pipe and gives us logs for debugging.
#[allow(dead_code)]
fn drain_stderr(child: &mut Child) {
    if let Some(stderr) = child.stderr.take() {
        let mut reader = BufReader::new(stderr).lines();
        tokio::spawn(async move {
            while let Ok(Some(_)) = reader.next_line().await {
                // discard
            }
        });
    }
}