-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.js
More file actions
217 lines (193 loc) · 5.63 KB
/
setup.js
File metadata and controls
217 lines (193 loc) · 5.63 KB
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
#!/usr/bin/env node
"use strict";
/**
* Spotify OAuth setup wizard.
*
* Usage from Yoki:
* sp setup <CLIENT_ID>
*
* Spotify app must have http://127.0.0.1:8888/callback registered as a redirect URI.
*/
const http = require("http");
const url = require("url");
const querystring = require("querystring");
const crypto = require("crypto");
const {
readInput,
writeResponse,
background,
error,
saveConfig,
saveTokens,
stripKeyword,
httpRequest,
getClientId,
makePkce,
AUTHORIZE_URL,
TOKEN_URL,
} = require("./lib");
const REDIRECT_URI = "http://127.0.0.1:8888/callback";
const SCOPES = [
"user-read-playback-state",
"user-modify-playback-state",
"user-read-currently-playing",
"user-library-read",
"user-library-modify",
"playlist-read-private",
"playlist-read-collaborative",
].join(" ");
function openBrowser(targetUrl) {
const { execFile } = require("child_process");
const platform = process.platform;
if (platform === "win32") {
execFile("cmd", ["/c", "start", "", targetUrl], (err) => {
if (err) console.error("Failed to open browser:", err);
});
} else if (platform === "darwin") {
execFile("open", [targetUrl], (err) => {
if (err) console.error("Failed to open browser:", err);
});
} else {
execFile("xdg-open", [targetUrl], (err) => {
if (err) console.error("Failed to open browser:", err);
});
}
}
function waitForCode(timeout) {
timeout = timeout || 90000;
return new Promise(function (resolve) {
const result = {};
const server = http.createServer(function (req, res) {
const parsed = url.parse(req.url, true);
if (parsed.pathname !== "/callback") {
res.writeHead(404);
res.end();
return;
}
const params = parsed.query || {};
if (params.code) {
result.code = params.code;
result.state = params.state || "";
const body = "<html><body style='font-family:sans-serif;text-align:center;padding:40px'><h1>Spotify connected</h1><p>You can close this tab and return to Yoki.</p></body></html>";
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Content-Length": Buffer.byteLength(body) });
res.end(body);
} else if (params.error) {
result.error = params.error;
const body = "<html><body><h1>Authentication failed</h1></body></html>";
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Content-Length": Buffer.byteLength(body) });
res.end(body);
} else {
res.writeHead(400);
res.end();
return;
}
// Close server after receiving callback
server.close();
});
server.listen(8888, "127.0.0.1");
const timer = setTimeout(function () {
server.close();
resolve(result);
}, timeout);
server.on("close", function () {
clearTimeout(timer);
resolve(result);
});
});
}
async function main() {
const inp = await readInput();
const ctx = inp.context || {};
const override = stripKeyword(inp.query || "", "setup", "auth", "login").trim();
const clientId = override || getClientId(ctx);
if (!clientId) {
writeResponse(
error(
"No Spotify Client ID available",
"Yoki couldn't fetch a Client ID from the credentials service.\n\n" +
"Make sure you're signed in to Yoki, then try again. " +
"Power users can supply their own:\n" +
" sp setup <CLIENT_ID>\n" +
"(get one at https://developer.spotify.com/dashboard with " +
"redirect URI http://127.0.0.1:8888/callback)."
)
);
return;
}
if (override) {
saveConfig(ctx, { client_id: override });
}
const pkce = makePkce();
const state = crypto.randomBytes(16).toString("base64url");
const authParams = {
client_id: clientId,
response_type: "code",
redirect_uri: REDIRECT_URI,
code_challenge_method: "S256",
code_challenge: pkce.challenge,
state: state,
scope: SCOPES,
};
const authUrl = AUTHORIZE_URL + "?" + querystring.stringify(authParams);
openBrowser(authUrl);
const result = await waitForCode(90000);
if (result.error) {
writeResponse(error("Spotify auth declined", result.error));
return;
}
if (!result.code) {
writeResponse(
error("Auth timeout", "Did not receive a callback within 90 seconds.")
);
return;
}
if (result.state !== state) {
writeResponse(error("State mismatch", "CSRF check failed."));
return;
}
const body = {
grant_type: "authorization_code",
code: result.code,
redirect_uri: REDIRECT_URI,
client_id: clientId,
code_verifier: pkce.verifier,
};
let res;
try {
res = await httpRequest("POST", TOKEN_URL, body);
} catch (e) {
writeResponse(error("Token exchange failed", e.message));
return;
}
if (res.status !== 200) {
writeResponse(
error(
"Token exchange failed",
"HTTP " + res.status + ": " + res.body.toString("utf-8").slice(0, 200)
)
);
return;
}
let tok;
try {
tok = JSON.parse(res.body.toString("utf-8"));
} catch (e) {
writeResponse(error("Token parse error", "Spotify returned invalid JSON"));
return;
}
const tokens = {
access_token: tok.access_token,
refresh_token: tok.refresh_token,
expires_at: Math.floor(Date.now() / 1000) + (tok.expires_in || 3600) - 30,
token_type: tok.token_type || "Bearer",
scope: tok.scope || SCOPES,
};
saveTokens(ctx, tokens);
writeResponse(
background("Spotify connected", { title: "Spotify", body: "Plugin authenticated successfully" })
);
}
main().catch(function (e) {
writeResponse(error("Setup crashed: " + e.message));
process.exit(1);
});