File size: 7,950 Bytes
226daaa
 
 
 
 
2fa42d9
cbe5958
 
2fa42d9
8672672
 
cbe5958
 
8672672
 
2fa42d9
 
 
 
 
 
 
 
 
 
 
 
 
 
8672672
 
2fa42d9
 
8672672
2fa42d9
226daaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cbe5958
 
 
 
226daaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fa42d9
226daaa
 
 
cbe5958
 
 
 
 
 
 
 
 
 
 
 
 
226daaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fa42d9
226daaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import axios from "axios";
import * as OTPAuth from "otpauth";
import fs from "fs";
import { fileURLToPath } from "url";

let _spDcCache = null;
let cachedToken = null;
let tokenExpiresAt = 0;

export function updateSpDc(value) {
  _spDcCache = value;
  cachedToken = null;
  tokenExpiresAt = 0;
}

function getSpDc() {
  if (_spDcCache) return _spDcCache;

  try {
    const cookiePath = new URL('../cookies.txt', import.meta.url).pathname;
    const text = fs.readFileSync(cookiePath, 'utf8');
    for (const line of text.split('\n')) {
      if (!line.trim() || line.startsWith('#')) continue;
      const parts = line.split('\t');
      if (parts.length >= 7 && parts[5] === 'sp_dc') {
        _spDcCache = parts[6].trim();
        return _spDcCache;
      }
    }
  } catch (e) {
    console.error('Failed to read sp_dc from cookies.txt:', e.message);
  }

  throw new Error('sp_dc not found in cookies.txt — please update the file.');
}
const DEFAULT_SECRETS_URL = "https://git.gay/thereallo/totp-secrets/raw/branch/main/secrets/secretDict.json";
const FALLBACK_SECRETS_URL = "https://raw.githubusercontent.com/xyloflake/spot-secrets-go/refs/heads/main/secrets/secretDict.json";

// Global variables to store the current TOTP configuration
let currentTotp = null;
let currentTotpVersion = null;
let lastFetchTime = 0;
const FETCH_INTERVAL = 60 * 60 * 1000; // 1 hour in milliseconds

// Initialize TOTP secrets on startup
initializeTOTPSecrets();

// Set up periodic updates
setInterval(updateTOTPSecrets, FETCH_INTERVAL);

async function initializeTOTPSecrets() {
  try {
    await updateTOTPSecrets();
  } catch (error) {
    console.error('Failed to initialize TOTP secrets:', error);
    // Fallback to the original hardcoded secret
    useFallbackSecret();
  }
}

async function updateTOTPSecrets() {
  try {
    const now = Date.now();
    if (now - lastFetchTime < FETCH_INTERVAL) {
      return; // Don't fetch too frequently
    }

    console.log('Fetching updated TOTP secrets...');
    const secrets = await fetchSecrets();
    const newestVersion = findNewestVersion(secrets);
    
    if (newestVersion && newestVersion !== currentTotpVersion) {
      const secretData = secrets[newestVersion];
      const totpSecret = createTotpSecret(secretData);
      
      currentTotp = new OTPAuth.TOTP({
        period: 30,
        digits: 6,
        algorithm: "SHA1",
        secret: totpSecret
      });
      
      currentTotpVersion = newestVersion;
      lastFetchTime = now;
      console.log(`TOTP secrets updated to version ${newestVersion}`);
    } else {
      console.log(`No new TOTP secrets found, using version ${newestVersion}`);
    }
  } catch (error) {
    console.error('Failed to update TOTP secrets:', error);
    // Keep using current TOTP if available, otherwise use fallback
    if (!currentTotp) {
      useFallbackSecret();
    }
  }
}

async function fetchSecrets() {
  const urlOption = process.env.SECRETS_URL || DEFAULT_SECRETS_URL;
  
  // Try loading from local file
  if (urlOption.startsWith("file://") || (!urlOption.startsWith("http://") && !urlOption.startsWith("https://"))) {
    try {
      let filePath = urlOption;
      if (urlOption.startsWith("file://")) {
        filePath = fileURLToPath(urlOption);
      }
      console.log(`Reading secrets from local file: ${filePath}`);
      const fileContent = await fs.promises.readFile(filePath, 'utf8');
      return JSON.parse(fileContent);
    } catch (error) {
      console.error(`Failed to read secrets from local file: ${error.message}`);
      throw error;
    }
  }

  // Remote fetching with fallback
  try {
    console.log(`Fetching secrets from remote URL: ${urlOption}`);
    const response = await axios.get(urlOption, {
      timeout: 10000,
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
      }
    });
    return response.data;
  } catch (error) {
    console.error(`Failed to fetch secrets from URL (${urlOption}): ${error.message}`);
    // If the error was from the default primary URL, try the fallback URL
    if (urlOption === DEFAULT_SECRETS_URL) {
      try {
        console.log(`Trying fallback secrets URL: ${FALLBACK_SECRETS_URL}`);
        const response = await axios.get(FALLBACK_SECRETS_URL, {
          timeout: 10000,
          headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
          }
        });
        return response.data;
      } catch (fallbackError) {
        console.error(`Failed to fetch secrets from fallback URL: ${fallbackError.message}`);
        throw fallbackError;
      }
    }
    throw error;
  }
}

function findNewestVersion(secrets) {
  const versions = Object.keys(secrets).map(Number);
  return Math.max(...versions).toString();
}

function createTotpSecret(data) {
  const mappedData = data.map((value, index) => value ^ ((index % 33) + 9));
  const hexData = Buffer.from(mappedData.join(""), "utf8").toString("hex");
  return OTPAuth.Secret.fromHex(hexData);
}

function useFallbackSecret() {
  // Fallback to the original hardcoded secret
  // This secret will most likely fail because Spotify is rotating the secrets every couple of days
  // This is really just kept in here for reference
  const fallbackData = [99, 111, 47, 88, 49, 56, 118, 65, 52, 67, 50, 104, 117, 101, 55, 94, 95, 75, 94, 49, 69, 36, 85, 64, 74, 60];
  const totpSecret = createTotpSecret(fallbackData);
  
  currentTotp = new OTPAuth.TOTP({
    period: 30,
    digits: 6,
    algorithm: "SHA1",
    secret: totpSecret
  });
  
  currentTotpVersion = "19"; // Fallback version
  console.log('Using fallback TOTP secret');
}

export async function getToken(reason = "init", productType = "mobile-web-player") {
  if (cachedToken && Date.now() < tokenExpiresAt) {
    return cachedToken;
  }

  // Ensure we have a TOTP instance
  if (!currentTotp) {
    await initializeTOTPSecrets();
  }

  const payload = await generateAuthPayload(reason, productType);

  const url = new URL("https://open.spotify.com/api/token");
  Object.entries(payload).forEach(([key, value]) => url.searchParams.append(key, value));

  const response = await axios.get(url.toString(), {
    headers: {
      'User-Agent': userAgent(),
      'Origin': 'https://open.spotify.com/',
      'Referer': 'https://open.spotify.com/',
      'Cookie': `sp_dc=${getSpDc()}`,
    },
  });

  const token = response.data?.accessToken;
  if (token) {
    cachedToken = token;
    const expiresTimestamp = response.data?.accessTokenExpirationTimestampMs;
    if (expiresTimestamp && !isNaN(expiresTimestamp)) {
      // Refresh 5 minutes before actual expiry
      tokenExpiresAt = Number(expiresTimestamp) - 5 * 60 * 1000;
    } else {
      tokenExpiresAt = Date.now() + 50 * 60 * 1000;
    }
  }

  return token;
}

async function generateAuthPayload(reason, productType) {
  const localTime = Date.now();
  const serverTime = await getServerTime();

  return {
    reason,
    productType,
    totp: generateTOTP(localTime),
    totpVer: currentTotpVersion || "19",
    totpServer: generateTOTP(Math.floor(serverTime / 30))
  };
}

async function getServerTime() {
  try {
    const { data } = await axios.get("https://open.spotify.com/api/server-time", {
      headers: {
        'User-Agent': userAgent(),
        'Origin': 'https://open.spotify.com/',
        'Referer': 'https://open.spotify.com/',
        'Cookie': `sp_dc=${getSpDc()}`,
      },
    });

    const time = Number(data.serverTime);
    if (isNaN(time)) throw new Error("Invalid server time");
    return time * 1000;
  } catch {
    return Date.now();
  }
}

function generateTOTP(timestamp) {
  if (!currentTotp) {
    throw new Error("TOTP not initialized");
  }
  return currentTotp.generate({ timestamp });
}

function userAgent() {
  return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36";
}