import { json } from '@sveltejs/kit'; import type { RequestHandler } from './$types'; import crypto from 'crypto'; // Browser version for headers const BROWSER_VERSION = '131'; // Common headers for Spotify requests const COMMON_HEADERS = { 'Content-Type': 'application/json', 'User-Agent': `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${BROWSER_VERSION}.0.0.0 Safari/537.36`, 'Sec-Ch-Ua': `"Chromium";v="${BROWSER_VERSION}", "Not(A:Brand";v="24", "Google Chrome";v="${BROWSER_VERSION}"` }; // Fallback secret (from SpotAPI code) const FALLBACK_SECRET = [ 44, 55, 47, 42, 70, 40, 34, 114, 76, 74, 50, 111, 120, 97, 75, 76, 94, 102, 43, 69, 49, 120, 118, 80, 64, 78 ]; // Function to fetch latest secret async function getLatestTotpSecret() { return { version: 61, secret: FALLBACK_SECRET }; } // Generate TOTP function generateTotp(secret: number[]) { const transformed = secret.map((e, t) => e ^ ((t % 33) + 9)); const joined = transformed.map((num) => num.toString()).join(''); const hexStr = Buffer.from(joined, 'ascii').toString('hex'); const base32Secret = Buffer.from(hexStr, 'hex').toString('base64').replace(/=/g, ''); // Simple TOTP generation (using crypto for HMAC) const timeStep = Math.floor(Date.now() / 1000 / 30); const timeHex = timeStep.toString(16).padStart(16, '0'); const hmac = crypto.createHmac('sha1', Buffer.from(base32Secret, 'base64')); hmac.update(Buffer.from(timeHex, 'hex')); const digest = hmac.digest(); const offset = digest[19] & 0xf; const code = (digest.readUInt32BE(offset) & 0x7fffffff) % 1000000; return code.toString().padStart(6, '0'); } // Extract all JavaScript links from HTML function extractJsLinks(html: string): string[] { const jsLinks: string[] = []; const scriptTagRegex = /]+src="([^"]+\.js)"[^>]*>/g; let match; while ((match = scriptTagRegex.exec(html)) !== null) { jsLinks.push(match[1]); } return jsLinks; } // Get session and extract data async function getSessionData() { const response = await fetch('https://open.spotify.com', { headers: COMMON_HEADERS }); const html = await response.text(); const cookie = response.headers.get('set-cookie')?.match(/sp_t=([^;]+)/)?.[1] || ''; // Extract base64-encoded appServerConfig const appServerConfigMatch = html.match( /