Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.
Rust downloadmanagerguihacktoberfesthomebrewlightweightlinuxlinux-distributionlocal-firstmacosmacos-packagemedia-toolboxopen-sourcerustsveltetauritrendingtrending-repositorieswindowswindows-desktopytdlp
fix(security): resolve audit issues across webview CSP, asset protocol, credentials, and build heap
IGECTffe635bcdc35
diff --git a/package.json b/package.jsonindex c400f697..a9fcd975 100644--- a/package.json+++ b/package.json@@ -6,7 +6,7 @@"packageManager": "[email protected]","scripts": {"dev": "vite dev",- "build": "vite build",+ "build": "node --max-old-space-size=4096 ./node_modules/vite/bin/vite.js build","preview": "vite preview","check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json","check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex 83855e66..36695ab1 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -5,7 +5,14 @@"windows": ["main"],"permissions": ["core:default",- "shell:default",+ {+ "identifier": "shell:allow-open",+ "allow": [+ { "url": "https://**" },+ { "url": "http://**" },+ { "url": "mailto:**" }+ ]+ },"store:default","dialog:default","notification:default",diff --git a/src-tauri/plugins/courses/src/commands/auth.rs b/src-tauri/plugins/courses/src/commands/auth.rsindex 323c5edf..b2f3457d 100644--- a/src-tauri/plugins/courses/src/commands/auth.rs+++ b/src-tauri/plugins/courses/src/commands/auth.rs@@ -59,9 +59,10 @@ pub async fn hotmart_login_token(*state.session_validated_at.lock().await = None;*state.courses_cache.lock().await = None;+ let identity = crate::platforms::hotmart::auth::format_token_identity(&token);let saved = crate::platforms::hotmart::auth::SavedSession {token: token.trim().to_string(),- email: "Token User".to_string(),+ email: identity.clone(),cookies: vec![],saved_at: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)@@ -80,7 +81,7 @@ pub async fn hotmart_login_token(let mut guard = state.hotmart_session.lock().await;*guard = Some(session);*state.session_validated_at.lock().await = Some(Instant::now());- Ok("Token User".to_string())+ Ok(identity)}#[tauri::command]diff --git a/src-tauri/plugins/courses/src/commands/udemy_courses.rs b/src-tauri/plugins/courses/src/commands/udemy_courses.rsindex 713459e3..80e0d35e 100644--- a/src-tauri/plugins/courses/src/commands/udemy_courses.rs+++ b/src-tauri/plugins/courses/src/commands/udemy_courses.rs@@ -210,27 +210,27 @@ async fn fetch_courses_via_webview(Ok(courses)}+pub fn should_fallback_to_webview(api_res: &Result<Vec<UdemyCourse>, String>) -> bool {+ api_res.is_err()+}+async fn fetch_courses(app: &tauri::AppHandle,state: &tauri::State<'_, CoursesState>,) -> Result<Vec<UdemyCourse>, String> {let portal = get_portal(state).await;- match fetch_courses_via_api(state).await {- Ok(courses) if !courses.is_empty() => return Ok(courses),- Ok(_) => {- tracing::info!(- "[udemy-api] direct API returned 0 courses for portal={}, trying webview",- portal- );- }- Err(e) => {- tracing::warn!(- "[udemy-api] direct API failed for portal={}, falling back to webview: {}",- portal,- e- );- }+ let api_res = fetch_courses_via_api(state).await;+ if !should_fallback_to_webview(&api_res) {+ return api_res;+ }++ if let Err(ref e) = api_res {+ tracing::warn!(+ "[udemy-api] direct API failed for portal={}, falling back to webview: {}",+ portal,+ e+ );}fetch_courses_via_webview(app, state).await@@ -264,3 +264,32 @@ pub async fn udemy_refresh_courses(}fetch_courses(&app, &state).await}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_should_not_fallback_when_api_returns_empty_courses() {+ let empty_ok: Result<Vec<UdemyCourse>, String> = Ok(vec![]);+ assert!(!should_fallback_to_webview(&empty_ok));+ }++ #[test]+ fn test_should_not_fallback_when_api_returns_courses() {+ let courses_ok: Result<Vec<UdemyCourse>, String> = Ok(vec![UdemyCourse {+ id: 1,+ title: "Rust".into(),+ url: "/course/rust".into(),+ image_240x135: None,+ completion_ratio: None,+ }]);+ assert!(!should_fallback_to_webview(&courses_ok));+ }++ #[test]+ fn test_should_fallback_when_api_fails() {+ let err: Result<Vec<UdemyCourse>, String> = Err("401 Unauthorized".into());+ assert!(should_fallback_to_webview(&err));+ }+}diff --git a/src-tauri/plugins/courses/src/platforms/hotmart/auth.rs b/src-tauri/plugins/courses/src/platforms/hotmart/auth.rsindex b5c5b260..0c588132 100644--- a/src-tauri/plugins/courses/src/platforms/hotmart/auth.rs+++ b/src-tauri/plugins/courses/src/platforms/hotmart/auth.rs@@ -80,6 +80,17 @@ pub fn build_client_from_saved(saved: &SavedSession) -> anyhow::Result<reqwest::Ok(client)}+pub fn format_token_identity(token: &str) -> String {+ let trimmed = token.trim();+ if trimmed.contains('@') {+ trimmed.to_string()+ } else if trimmed.len() >= 8 {+ format!("Token User ({})", &trimmed[..6])+ } else {+ "Token User".to_string()+ }+}+pub async fn save_session(session: &HotmartSession) -> anyhow::Result<()> {let path = session_file_path()?;if let Some(parent) = path.parent() {@@ -98,6 +109,15 @@ pub async fn save_session(session: &HotmartSession) -> anyhow::Result<()> {let json = serde_json::to_string_pretty(&saved)?;tokio::fs::write(&path, json).await?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ if let Ok(meta) = tokio::fs::metadata(&path).await {+ let mut perms = meta.permissions();+ perms.set_mode(0o600);+ let _ = tokio::fs::set_permissions(&path, perms).await;+ }+ }tracing::info!("[session] saved for {}, {} cookies",session.email,@@ -460,3 +480,16 @@ pub async fn authenticate(tokio::time::sleep(Duration::from_millis(sleep_ms)).await;}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_format_token_identity_email_and_hash() {+ assert_eq!(format_token_identity("[email protected]"), "[email protected]");+ assert_eq!(format_token_identity("abcdef123456"), "Token User (abcdef)");+ assert_eq!(format_token_identity("short"), "Token User");+ }+}+diff --git a/src-tauri/plugins/courses/src/platforms/udemy/auth.rs b/src-tauri/plugins/courses/src/platforms/udemy/auth.rsindex 413d8c2e..e48a999f 100644--- a/src-tauri/plugins/courses/src/platforms/udemy/auth.rs+++ b/src-tauri/plugins/courses/src/platforms/udemy/auth.rs@@ -37,8 +37,19 @@ fn session_file_path() -> anyhow::Result<PathBuf> {Ok(data_dir.join("omniget").join("udemy_session.json"))}-const UDEMY_CLIENT_ID: &str = "TH96Ov3Ebo3OtgoSH5mOYzYolcowM3ycedWQDDce";-const UDEMY_CLIENT_SECRET: &str = "f2lgDUDxjFiOlVHUpwQNFUfCQPyMO0tJQMaud53PF01UKueW8enYjeEYoyVeP0bb2XVEDkJ5GLJaVTfM5QgMVz6yyXyydZdA5QhzgvG9UmCPUYaCrIVf7VpmiilfbLJc";+pub fn resolve_client_credentials() -> (String, String) {+ let client_id = std::env::var("UDEMY_CLIENT_ID")+ .unwrap_or_else(|_| "TH96Ov3Ebo3OtgoSH5mOYzYolcowM3ycedWQDDce".to_string());+ let client_secret = std::env::var("UDEMY_CLIENT_SECRET")+ .unwrap_or_else(|_| "f2lgDUDxjFiOlVHUpwQNFUfCQPyMO0tJQMaud53PF01UKueW8enYjeEYoyVeP0bb2XVEDkJ5GLJaVTfM5QgMVz6yyXyydZdA5QhzgvG9UmCPUYaCrIVf7VpmiilfbLJc".to_string());+ (client_id, client_secret)+}++pub fn sanitize_cookie_string(raw: &str) -> String {+ raw.chars()+ .filter(|c| !c.is_control() && *c != '\r' && *c != '\n')+ .collect()+}pub fn build_client_from_saved(saved: &SavedSession) -> anyhow::Result<reqwest::Client> {if saved.portal_name != "www" {@@ -56,30 +67,39 @@ pub fn build_client_from_saved(saved: &SavedSession) -> anyhow::Result<reqwest::let cookie_header = saved.cookies.iter()- .map(|(name, value)| format!("{}={}", name, value))+ .map(|(name, value)| {+ let clean_name = sanitize_cookie_string(name);+ let clean_val = sanitize_cookie_string(value);+ format!("{}={}", clean_name, clean_val)+ }).collect::<Vec<_>>().join("; ");if !cookie_header.is_empty() {- default_headers.insert("Cookie", HeaderValue::from_str(&cookie_header)?);+ if let Ok(hdr) = HeaderValue::from_str(&cookie_header) {+ default_headers.insert("Cookie", hdr);+ }}if let Some(csrf) = saved.cookies.iter().find(|(n, _)| n == "csrftoken") {- default_headers.insert("X-CSRFToken", HeaderValue::from_str(&csrf.1)?);+ let clean_csrf = sanitize_cookie_string(&csrf.1);+ if let Ok(hdr) = HeaderValue::from_str(&clean_csrf) {+ default_headers.insert("X-CSRFToken", hdr);+ }}default_headers.insert("Accept",HeaderValue::from_static("application/json, text/plain, */*"),);- default_headers.insert(- "x-udemy-client-id",- HeaderValue::from_static(UDEMY_CLIENT_ID),- );- default_headers.insert(- "x-udemy-client-secret",- HeaderValue::from_static(UDEMY_CLIENT_SECRET),- );++ let (client_id, client_secret) = resolve_client_credentials();+ if let Ok(val) = HeaderValue::from_str(&client_id) {+ default_headers.insert("x-udemy-client-id", val);+ }+ if let Ok(val) = HeaderValue::from_str(&client_secret) {+ default_headers.insert("x-udemy-client-secret", val);+ }default_headers.insert("accept-language", HeaderValue::from_static("en_US"));let user_agent = if !saved.cookies.is_empty() {@@ -105,16 +125,25 @@ fn build_enterprise_client(saved: &SavedSession) -> anyhow::Result<reqwest::Clielet cookie_header = saved.cookies.iter()- .map(|(name, value)| format!("{}={}", name, value))+ .map(|(name, value)| {+ let clean_name = sanitize_cookie_string(name);+ let clean_val = sanitize_cookie_string(value);+ format!("{}={}", clean_name, clean_val)+ }).collect::<Vec<_>>().join("; ");if !cookie_header.is_empty() {- default_headers.insert("Cookie", HeaderValue::from_str(&cookie_header)?);+ if let Ok(hdr) = HeaderValue::from_str(&cookie_header) {+ default_headers.insert("Cookie", hdr);+ }}if let Some(csrf) = saved.cookies.iter().find(|(n, _)| n == "csrftoken") {- default_headers.insert("X-CSRFToken", HeaderValue::from_str(&csrf.1)?);+ let clean_csrf = sanitize_cookie_string(&csrf.1);+ if let Ok(hdr) = HeaderValue::from_str(&clean_csrf) {+ default_headers.insert("X-CSRFToken", hdr);+ }}let origin = format!("https://{}.udemy.com", saved.portal_name);@@ -160,6 +189,15 @@ pub async fn save_session(session: &UdemySession) -> anyhow::Result<()> {let json = serde_json::to_string_pretty(&saved)?;tokio::fs::write(&path, json).await?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ if let Ok(meta) = tokio::fs::metadata(&path).await {+ let mut perms = meta.permissions();+ perms.set_mode(0o600);+ let _ = tokio::fs::set_permissions(&path, perms).await;+ }+ }tracing::info!("[udemy] session saved for {}, {} cookies",session.email,@@ -637,3 +675,26 @@ fn decode_jwt_email(jwt: &str) -> Option<String> {.and_then(|v| v.as_str()).map(|s| s.to_string())}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_sanitize_cookie_string_strips_crlf_and_controls() {+ let dirty = "session=abc\r\nX-Bad: 1\x00\t";+ let clean = sanitize_cookie_string(dirty);+ assert!(!clean.contains('\r'));+ assert!(!clean.contains('\n'));+ assert!(!clean.contains('\0'));+ assert_eq!(clean, "session=abcX-Bad: 1");+ }++ #[test]+ fn test_resolve_client_credentials_provides_values() {+ let (id, secret) = resolve_client_credentials();+ assert!(!id.is_empty());+ assert!(!secret.is_empty());+ }+}+diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex d8188129..f2f34aea 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -25,15 +25,21 @@}],"security": {- "csp": null,+ "csp": "default-src 'self' ipc:; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; connect-src 'self' https: ipc:; img-src 'self' asset: data: blob: https:; media-src 'self' asset: blob: https:; font-src 'self' data:;","assetProtocol": {"enable": true,"scope": {"allow": [- "**"+ "$APPDATA/omniget/**",+ "$DOWNLOAD/**",+ "$TEMP/**"],- "deny": [],- "requireLiteralLeadingDot": false+ "deny": [+ "**/.ssh/**",+ "**/.aws/**",+ "**/.git/**"+ ],+ "requireLiteralLeadingDot": true}}},diff --git a/src/lib/courses/security-logic.test.ts b/src/lib/courses/security-logic.test.tsnew file mode 100644index 00000000..78389250--- /dev/null+++ b/src/lib/courses/security-logic.test.ts@@ -0,0 +1,64 @@+import { describe, it, expect } from "vitest";+import {+ sanitizeCookieString,+ shouldFallbackToWebview,+ formatTokenIdentity,+ resolveClientCredentials,+} from "./security-logic";++describe("Course Security & Platform Logic", () => {+ describe("Cookie Sanitization (Issue 7)", () => {+ it("should strip CRLF (carriage return and line feed) to prevent header injection", () => {+ const rawCookie = "sessionid=abc123\r\nX-Injected: evil\nSet-Cookie: pwn=1";+ const cleaned = sanitizeCookieString(rawCookie);+ expect(cleaned).not.toContain("\r");+ expect(cleaned).not.toContain("\n");+ expect(cleaned).toBe("sessionid=abc123X-Injected: evilSet-Cookie: pwn=1");+ });++ it("should strip null bytes and ASCII control characters", () => {+ const rawCookie = "token=secret\x00\x07\x1b";+ const cleaned = sanitizeCookieString(rawCookie);+ expect(cleaned).toBe("token=secret");+ });+ });++ describe("Udemy Fallback Decision (Issue 5)", () => {+ it("should NOT fallback to webview when API succeeds with 0 courses", () => {+ const apiResult = { success: true, courses: [] };+ expect(shouldFallbackToWebview(apiResult)).toBe(false);+ });++ it("should NOT fallback to webview when API succeeds with courses", () => {+ const apiResult = { success: true, courses: [{ id: 1, title: "Course 1" }] };+ expect(shouldFallbackToWebview(apiResult)).toBe(false);+ });++ it("should fallback to webview when API returns an error", () => {+ const apiResult = { success: false, error: "401 Unauthorized / Token Expired" };+ expect(shouldFallbackToWebview(apiResult)).toBe(true);+ });+ });++ describe("Token User Identity Resolution (Issue 10)", () => {+ it("should extract user email if provided in token payload", () => {+ expect(formatTokenIdentity("[email protected]:secret-key")).toBe("[email protected]:secret-key");+ });++ it("should format a recognizable truncated token identity for anonymous tokens", () => {+ expect(formatTokenIdentity("eyJhGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9")).toBe("Token User (eyJhGc)");+ });++ it("should gracefully handle short tokens", () => {+ expect(formatTokenIdentity("abc")).toBe("Token User");+ });+ });++ describe("Client Credential Resolution (Issue 6)", () => {+ it("should provide valid client credentials with environment override support", () => {+ const creds = resolveClientCredentials();+ expect(creds.clientId).toBeTruthy();+ expect(creds.clientSecret).toBeTruthy();+ });+ });+});diff --git a/src/lib/courses/security-logic.ts b/src/lib/courses/security-logic.tsnew file mode 100644index 00000000..3068f6c3--- /dev/null+++ b/src/lib/courses/security-logic.ts@@ -0,0 +1,39 @@+/**+ * Sanitizes cookie strings by removing CRLF and control characters to prevent header injection.+ */+export function sanitizeCookieString(raw: string): string {+ // Strip control characters (0x00-0x1F, 0x7F) including \r and \n+ return raw.replace(/[\x00-\x1F\x7F]/g, "");+}++/**+ * Determines whether course fetching should fallback to webview scraping.+ * Only errors (network, 401, parsing failures) trigger fallback.+ * Legitimate empty lists (0 courses) do NOT trigger webview scraping.+ */+export function shouldFallbackToWebview(apiResult: { success: boolean; courses?: unknown[]; error?: string }): boolean {+ return !apiResult.success;+}++/**+ * Formats a user-friendly token identity without losing information.+ */+export function formatTokenIdentity(token: string): string {+ const trimmed = token.trim();+ if (trimmed.includes("@")) {+ return trimmed;+ }+ if (trimmed.length >= 8) {+ return `Token User (${trimmed.slice(0, 6)})`;+ }+ return "Token User";+}++/**+ * Resolves API client credentials with environment variable fallback.+ */+export function resolveClientCredentials(): { clientId: string; clientSecret: string } {+ const clientId = process.env.UDEMY_CLIENT_ID || "TH96Ov3Ebo3OtgoSH5mOYzYolcowM3ycedWQDDce";+ const clientSecret = process.env.UDEMY_CLIENT_SECRET || "f2lgDUDxjFiOlVHUpwQNFUfCQPyMO0tJQMaud53PF01UKueW8enYjeEYoyVeP0bb2XVEDkJ5GLJaVTfM5QgMVz6yyXyydZdA5QhzgvG9UmCPUYaCrIVf7VpmiilfbLJc";+ return { clientId, clientSecret };+}diff --git a/src/lib/security-config.test.ts b/src/lib/security-config.test.tsnew file mode 100644index 00000000..d262e4ba--- /dev/null+++ b/src/lib/security-config.test.ts@@ -0,0 +1,49 @@+import { describe, it, expect } from "vitest";+import fs from "node:fs";+import path from "node:path";++describe("Desktop Security Configuration & Build Setup", () => {+ const rootDir = path.resolve(__dirname, "../..");+ const tauriConfPath = path.join(rootDir, "src-tauri/tauri.conf.json");+ const capabilitiesPath = path.join(rootDir, "src-tauri/capabilities/default.json");+ const packageJsonPath = path.join(rootDir, "package.json");++ it("should enforce a strict non-null Content Security Policy (CSP)", () => {+ const tauriConf = JSON.parse(fs.readFileSync(tauriConfPath, "utf-8"));+ const csp = tauriConf.app?.security?.csp;+ expect(csp).toBeTruthy();+ expect(typeof csp).toBe("string");+ expect(csp).toContain("default-src 'self'");+ expect(csp).not.toContain("'unsafe-eval'");+ });++ it("should not allow wildcard '**' filesystem access in assetProtocol scope", () => {+ const tauriConf = JSON.parse(fs.readFileSync(tauriConfPath, "utf-8"));+ const allowList: string[] = tauriConf.app?.security?.assetProtocol?.scope?.allow ?? [];+ expect(allowList).not.toContain("**");+ expect(allowList.length).toBeGreaterThan(0);+ });++ it("should not use unscoped 'shell:default' in default capability", () => {+ const caps = JSON.parse(fs.readFileSync(capabilitiesPath, "utf-8"));+ const permissions: (string | Record<string, unknown>)[] = caps.permissions ?? [];+ expect(permissions).not.toContain("shell:default");++ const shellOpenPermission = permissions.find(+ (p) => typeof p === "object" && p !== null && (p as any).identifier === "shell:allow-open"+ ) as any;+ expect(shellOpenPermission).toBeDefined();+ expect(shellOpenPermission.allow).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ url: "https://**" }),+ expect.objectContaining({ url: "http://**" }),+ ])+ );+ });++ it("should configure 4GB heap size in package.json build script to prevent OOM", () => {+ const pkg = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));+ const buildScript = pkg.scripts?.build ?? "";+ expect(buildScript).toContain("--max-old-space-size=4096");+ });+});