Skip to content

Commit 15b650b

Browse files
authored
fix: added totp to spotify autoplay endpoint (#21)
Fixes: #20
1 parent aca3ca8 commit 15b650b

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

build/functions/autoPlay.js

+35-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
const undici = require('undici');
22
const { JSDOM } = require('jsdom');
3+
const crypto = require('crypto');
34

45
async function scAutoPlay(url) {
56
const res = await undici.fetch(`${url}/recommended`);
@@ -28,7 +29,39 @@ async function scAutoPlay(url) {
2829
}
2930

3031
async function spAutoPlay(track_id) {
31-
const data = await undici.fetch("https://open.spotify.com/get_access_token?reason=transport&productType=embed");
32+
const TOTP_SECRET = new Uint8Array([53,53,48,55,49,52,53,56,53,51,52,56,55,52,57,57,53,57,50,50,52,56,54,51,48,51,50,57,51,52,55]);
33+
34+
const hmac = crypto.createHmac('sha1', TOTP_SECRET);
35+
36+
function generateTotp() {
37+
const counter = Math.floor(Date.now() / 30000);
38+
const counterBuffer = Buffer.alloc(8);
39+
counterBuffer.writeBigInt64BE(BigInt(counter));
40+
41+
hmac.update(counterBuffer);
42+
const hmacResult = hmac.digest();
43+
44+
const offset = hmacResult[hmacResult.length - 1] & 15;
45+
const truncatedValue =
46+
((hmacResult[offset] & 127) << 24) |
47+
((hmacResult[offset + 1] & 255) << 16) |
48+
((hmacResult[offset + 2] & 255) << 8) |
49+
(hmacResult[offset + 3] & 255);
50+
51+
const totp = (truncatedValue % 1000000).toString().padStart(6, '0');
52+
return [totp, counter * 30000];
53+
}
54+
55+
const [totp, timestamp] = generateTotp();
56+
const params = {
57+
"reason": "transport",
58+
"productType": "embed",
59+
"totp": totp,
60+
"totpVer": 5,
61+
"ts": timestamp,
62+
}
63+
64+
const data = await undici.fetch("https://open.spotify.com/get_access_token?" + new URLSearchParams(params).toString());
3265

3366
const body = await data.json();
3467

@@ -44,4 +77,4 @@ async function spAutoPlay(track_id) {
4477
return json.tracks[Math.floor(Math.random() * json.tracks.length)].id
4578
}
4679

47-
module.exports = { scAutoPlay, spAutoPlay };
80+
module.exports = { scAutoPlay, spAutoPlay };

0 commit comments

Comments
 (0)