Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,10 @@ RUN if [[ "$TARGET_ARCH" == "arm64-v8a" ]]; then \
# -----------------------------------------------------------------------------
FROM --platform=${RUNTIME_PLATFORM} debian:13.2

# The supervisor uses curl for the combined wrapper's webPlayback/license relay.
RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates \
&& rm -rf /var/lib/apt/lists/*

WORKDIR /app

COPY --from=build /app/wrapper /app/wrapper
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ through HTTP; clients use the raw TCP decrypt protocol on
| `POST` | `/login` | Body: `{"username": "...", "password": "..."}` or `{"apple_id": "...", "password": "..."}` (synonyms). Drives Apple's `AuthenticateFlow`. Returns `200` + token snapshot, `202` if **2FA** is required (then `POST /login/2fa`), or `401` on failure. |
| `POST` | `/login/2fa` | Body: `{"code": "123456"}`. Continues a login waiting for HSA2. |
| `GET` | `/playback` | Query string `?adam_id=<numeric store id>`. Returns `200` with a JSON object `{"songList":[...]}` containing the **whole MZ playback dispatch** Apple's `subDownload` URL bag returns (every flavor, key URI, asset URL, metadata field). CFData fields are base64; CFDate fields are ISO 8601. Needs an **authenticated** session; otherwise `401` / `503`. Apple errors -> `502`. |
| `GET` | `/webplayback` | Query string `?adamId=<numeric store id>`. Relays Apple's webPlayback response using the authenticated wrapper tokens. |
| `POST` | `/license` | Relays Apple's web playback license request. Accepts `challenge`, `uri`, `adamId`, and optional `drm-type` (`wv` or `pr`). |
| `DELETE` | `/login` | Aborts an in-flight login or clears cached tokens from memory. Apple's on-disk `mpl_db` cache is unchanged. |

## TCP Decrypt API
Expand Down
242 changes: 242 additions & 0 deletions src/rust/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::collections::HashMap;
use std::env;
use std::io::{self, BufRead, BufReader, Read, Write};
use std::net::{Shutdown, TcpListener, TcpStream};
use std::process::Command;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
Expand Down Expand Up @@ -216,6 +217,57 @@ fn handle_http_connection(mut stream: TcpStream, worker: Arc<Worker>) -> io::Res
worker.request_json(protocol::OP_PLAYBACK, json!({"adam_id": adam_id})),
)?;
}
("GET", "/webplayback") => {
let params = parse_query(&query);
let adam_id = params
.get("adam_id")
.or_else(|| params.get("adamId"))
.cloned()
.unwrap_or_default();
proxy_apple_json(&mut stream, &worker, "webplayback", &adam_id, None)?;
}
("GET", "/lyrics") => {
let params = parse_query(&query);
let adam_id = params
.get("adamId")
.or_else(|| params.get("adam_id"))
.cloned()
.unwrap_or_default();
let language = params
.get("language")
.cloned()
.unwrap_or_else(|| "en".to_string());
let script = params
.get("script")
.cloned()
.unwrap_or_else(|| "en-Latn".to_string());
let storefront = params
.get("storefront")
.cloned()
.unwrap_or_else(|| "us".to_string());
proxy_apple_lyrics(
&mut stream,
&worker,
&adam_id,
&language,
&script,
&storefront,
)?;
}
("POST", "/license") => {
let body_json = match parse_json_body(&body) {
Ok(v) => v,
Err(e) => {
write_json(
&mut stream,
400,
json!({"error":"invalid_json","detail":e.to_string()}),
)?;
return Ok(());
}
};
proxy_apple_json(&mut stream, &worker, "license", "", Some(body_json))?;
}
("POST", "/decrypt") => {
let _ = content_type;
write_json(
Expand All @@ -232,6 +284,196 @@ fn handle_http_connection(mut stream: TcpStream, worker: Arc<Worker>) -> io::Res
Ok(())
}

fn proxy_apple_json(
stream: &mut TcpStream,
worker: &Worker,
operation: &str,
adam_id: &str,
request_body: Option<Value>,
) -> io::Result<()> {
let me = worker
.request_json(protocol::OP_ME, Value::Null)
.map_err(worker_io_error)?;
if me.http_status != 200 {
return write_response(stream, me.http_status, "application/json", &me.body);
}
let account: Value = serde_json::from_slice(&me.body)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
let auth = account.get("auth").cloned().unwrap_or(Value::Null);
let dev_token = auth.get("dev_token").and_then(Value::as_str).unwrap_or("");
let music_token = auth
.get("music_user_token")
.and_then(Value::as_str)
.unwrap_or("");
if dev_token.is_empty() || music_token.is_empty() {
return write_json(
stream,
401,
json!({
"error": "not_authenticated",
"detail": "wrapper account has no Apple web tokens"
}),
);
}

let (url, payload) = match operation {
"webplayback" => (
"https://play.music.apple.com/WebObjects/MZPlay.woa/wa/webPlayback",
json!({"salableAdamId": adam_id}),
),
"license" => {
let mut payload = request_body.unwrap_or_else(|| json!({}));
if !payload.is_object() {
return write_json(stream, 400, json!({"error":"invalid_json"}));
}
let object = payload.as_object_mut().expect("object checked");
let drm_type = object
.get("drm-type")
.and_then(Value::as_str)
.unwrap_or("wv");
if drm_type != "wv" && drm_type != "pr" {
return write_json(
stream,
400,
json!({
"error":"invalid_drm_type",
"detail":"drm-type must be wv or pr"
}),
);
}
object.insert(
"key-system".to_string(),
Value::String(if drm_type == "pr" {
"com.microsoft.playready".to_string()
} else {
"com.widevine.alpha".to_string()
}),
);
object.insert("isLibrary".to_string(), Value::Bool(false));
object.insert("user-initiated".to_string(), Value::Bool(true));
object.remove("drm-type");
(
"https://play.itunes.apple.com/WebObjects/MZPlay.woa/wa/acquireWebPlaybackLicense",
payload,
)
}
_ => return write_json(stream, 500, json!({"error":"unknown_operation"})),
};

let payload_text = serde_json::to_string(&payload)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
let output = Command::new("curl")
.args([
"--silent",
"--show-error",
"--location",
"--max-time",
"60",
"--request",
"POST",
url,
"--header",
&format!("Authorization: Bearer {dev_token}"),
"--header",
&format!("X-Apple-Music-User-Token: {music_token}"),
"--header",
"Content-Type: application/json",
"--data",
&payload_text,
"--write-out",
"\n%{http_code}",
])
.output()
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("curl unavailable: {e}")))?;
let stdout = String::from_utf8_lossy(&output.stdout);
let (response_body, status_text) = stdout.rsplit_once('\n').unwrap_or((&stdout, "502"));
let status = status_text.trim().parse::<u16>().unwrap_or(502);
if !output.status.success() {
return write_json(
stream,
502,
json!({
"error":"apple_request_failed",
"detail": String::from_utf8_lossy(&output.stderr).trim()
}),
);
}
write_response(stream, status, "application/json", response_body.as_bytes())
}

fn proxy_apple_lyrics(
stream: &mut TcpStream,
worker: &Worker,
adam_id: &str,
language: &str,
script: &str,
storefront: &str,
) -> io::Result<()> {
if adam_id.is_empty() {
return write_json(stream, 400, json!({"error":"missing_adam_id"}));
}
let me = worker
.request_json(protocol::OP_ME, Value::Null)
.map_err(worker_io_error)?;
if me.http_status != 200 {
return write_response(stream, me.http_status, "application/json", &me.body);
}
let account: Value = serde_json::from_slice(&me.body)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
let auth = account.get("auth").cloned().unwrap_or(Value::Null);
let dev_token = auth.get("dev_token").and_then(Value::as_str).unwrap_or("");
let music_token = auth
.get("music_user_token")
.and_then(Value::as_str)
.unwrap_or("");
if dev_token.is_empty() || music_token.is_empty() {
return write_json(
stream,
401,
json!({"error":"not_authenticated","detail":"wrapper account has no Apple web tokens"}),
);
}

let url = format!(
"https://amp-api.music.apple.com/v1/catalog/{}/songs/{}/syllable-lyrics?l[lyrics]={}&extend=ttmlLocalizations&l[script]={}",
storefront, adam_id, language, script
);
let output = Command::new("curl")
.args([
"--silent",
"--show-error",
"--location",
"--max-time",
"60",
"--request",
"GET",
&url,
"--header",
&format!("Authorization: Bearer {dev_token}"),
"--header",
&format!("media-user-token: {music_token}"),
"--header",
"Origin: https://music.apple.com",
"--header",
"User-Agent: Music/5.7 Android/10 model/Pixel6GR1YH",
"--write-out",
"\n%{http_code}",
])
.output()
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("curl unavailable: {e}")))?;
let stdout = String::from_utf8_lossy(&output.stdout);
let (response_body, status_text) = stdout.rsplit_once('\n').unwrap_or((&stdout, "502"));
let status = status_text.trim().parse::<u16>().unwrap_or(502);
if !output.status.success() {
return write_json(
stream,
502,
json!({"error":"apple_request_failed","detail":String::from_utf8_lossy(&output.stderr).trim()}),
);
}
write_response(stream, status, "application/json", response_body.as_bytes())
}

fn split_target(target: &str) -> (String, String) {
match target.split_once('?') {
Some((p, q)) => (p.to_string(), q.to_string()),
Expand Down