@jamiew/soundcloud-mcp 0.0.0-stage → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +242 -2
- package/build/client.js +428 -0
- package/build/icon.js +22 -0
- package/build/index.js +26 -0
- package/build/server.js +25 -0
- package/build/stdio/auth.js +28 -0
- package/build/stdio/authTools.js +41 -0
- package/build/stdio/config.js +10 -0
- package/build/stdio/log.js +10 -0
- package/build/stdio/oauth.js +244 -0
- package/build/stdio/tokenStore.js +38 -0
- package/build/tools.js +682 -0
- package/build/types.js +138 -0
- package/package.json +70 -5
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import crypto from "node:crypto";
|
|
3
|
+
import http from "node:http";
|
|
4
|
+
import { URL } from "node:url";
|
|
5
|
+
import { AUTH_BASE, SoundCloudAuthError, } from "../client.js";
|
|
6
|
+
import { OAuthTokenResponseSchema } from "../types.js";
|
|
7
|
+
import { CLIENT_ID, CLIENT_SECRET, REDIRECT_URI } from "./config.js";
|
|
8
|
+
import { debug, logError } from "./log.js";
|
|
9
|
+
import { clearTokens, isExpired, loadTokens, saveTokens } from "./tokenStore.js";
|
|
10
|
+
/** Tools return this message as is, so keep it short and actionable. */
|
|
11
|
+
export class OAuthError extends SoundCloudAuthError {
|
|
12
|
+
}
|
|
13
|
+
const MISSING_CREDENTIALS = "Set SOUNDCLOUD_CLIENT_ID and SOUNDCLOUD_CLIENT_SECRET in this server's environment first.";
|
|
14
|
+
export function generatePKCEChallenge() {
|
|
15
|
+
const codeVerifier = crypto.randomBytes(32).toString("base64url");
|
|
16
|
+
const codeChallenge = crypto.createHash("sha256").update(codeVerifier).digest("base64url");
|
|
17
|
+
const state = crypto.randomBytes(16).toString("hex");
|
|
18
|
+
return { codeVerifier, codeChallenge, state };
|
|
19
|
+
}
|
|
20
|
+
export function getAuthorizationUrl(pkce) {
|
|
21
|
+
const params = new URLSearchParams({
|
|
22
|
+
client_id: CLIENT_ID,
|
|
23
|
+
redirect_uri: REDIRECT_URI,
|
|
24
|
+
response_type: "code",
|
|
25
|
+
code_challenge: pkce.codeChallenge,
|
|
26
|
+
code_challenge_method: "S256",
|
|
27
|
+
state: pkce.state,
|
|
28
|
+
});
|
|
29
|
+
return `${AUTH_BASE}/authorize?${params.toString()}`;
|
|
30
|
+
}
|
|
31
|
+
async function tokenRequest(body, extraHeaders = {}) {
|
|
32
|
+
if (!CLIENT_ID || !CLIENT_SECRET)
|
|
33
|
+
throw new OAuthError(MISSING_CREDENTIALS);
|
|
34
|
+
const response = await fetch(`${AUTH_BASE}/oauth/token`, {
|
|
35
|
+
method: "POST",
|
|
36
|
+
headers: {
|
|
37
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
38
|
+
Accept: "application/json; charset=utf-8",
|
|
39
|
+
...extraHeaders,
|
|
40
|
+
},
|
|
41
|
+
body: body.toString(),
|
|
42
|
+
});
|
|
43
|
+
const token = response.ok && OAuthTokenResponseSchema.safeParse(await response.json()).data;
|
|
44
|
+
if (!token) {
|
|
45
|
+
throw new OAuthError("SoundCloud token request failed. Check app credentials or reconnect.");
|
|
46
|
+
}
|
|
47
|
+
return token;
|
|
48
|
+
}
|
|
49
|
+
async function exchangeCode(code, codeVerifier) {
|
|
50
|
+
const token = await tokenRequest(new URLSearchParams({
|
|
51
|
+
grant_type: "authorization_code",
|
|
52
|
+
client_id: CLIENT_ID,
|
|
53
|
+
client_secret: CLIENT_SECRET,
|
|
54
|
+
redirect_uri: REDIRECT_URI,
|
|
55
|
+
code_verifier: codeVerifier,
|
|
56
|
+
code,
|
|
57
|
+
}));
|
|
58
|
+
return saveTokens(token);
|
|
59
|
+
}
|
|
60
|
+
export async function getClientCredentialsToken() {
|
|
61
|
+
const credentials = Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64");
|
|
62
|
+
return tokenRequest(new URLSearchParams({ grant_type: "client_credentials" }), {
|
|
63
|
+
Authorization: `Basic ${credentials}`,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
async function requestRefresh(refresh_token) {
|
|
67
|
+
const token = await tokenRequest(new URLSearchParams({
|
|
68
|
+
grant_type: "refresh_token",
|
|
69
|
+
client_id: CLIENT_ID,
|
|
70
|
+
client_secret: CLIENT_SECRET,
|
|
71
|
+
refresh_token,
|
|
72
|
+
}));
|
|
73
|
+
return saveTokens(token);
|
|
74
|
+
}
|
|
75
|
+
// Refresh tokens are single-use, so parallel tool calls must share one refresh.
|
|
76
|
+
let refreshing = null;
|
|
77
|
+
function refreshToken(refresh_token) {
|
|
78
|
+
refreshing ??= requestRefresh(refresh_token).finally(() => {
|
|
79
|
+
refreshing = null;
|
|
80
|
+
});
|
|
81
|
+
return refreshing;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Revokes the app at SoundCloud, then deletes the token file even if SoundCloud
|
|
85
|
+
* refused, so signing out never leaves a token on disk.
|
|
86
|
+
*/
|
|
87
|
+
export async function signOut(sc) {
|
|
88
|
+
if (!hasUserToken())
|
|
89
|
+
return "not-logged-in";
|
|
90
|
+
let result = "revoked";
|
|
91
|
+
try {
|
|
92
|
+
await sc.disconnect();
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
debug("SoundCloud disconnect failed:", error);
|
|
96
|
+
result = "forgotten";
|
|
97
|
+
}
|
|
98
|
+
clearTokens();
|
|
99
|
+
return result;
|
|
100
|
+
}
|
|
101
|
+
export const SIGN_OUT_MESSAGES = {
|
|
102
|
+
revoked: "Signed out. SoundCloud revoked this app's access and the local token is deleted.",
|
|
103
|
+
forgotten: "Deleted the local token, but SoundCloud did not confirm the revocation. Remove the app in your SoundCloud settings to be sure.",
|
|
104
|
+
"not-logged-in": "Not logged in; nothing to sign out.",
|
|
105
|
+
};
|
|
106
|
+
// Returns a valid USER access token, refreshing if it's near expiry.
|
|
107
|
+
// Throws if the user hasn't logged in yet.
|
|
108
|
+
export async function getValidAccessToken() {
|
|
109
|
+
const tokens = loadTokens();
|
|
110
|
+
if (!tokens) {
|
|
111
|
+
throw new OAuthError("Log in with the connect_soundcloud tool or `soundcloud-mcp-auth`.");
|
|
112
|
+
}
|
|
113
|
+
if (tokens.access_token && !isExpired(tokens)) {
|
|
114
|
+
return tokens.access_token;
|
|
115
|
+
}
|
|
116
|
+
if (!tokens.refresh_token) {
|
|
117
|
+
throw new OAuthError("Token expired and cannot be refreshed. Use connect_soundcloud or run `soundcloud-mcp-auth`.");
|
|
118
|
+
}
|
|
119
|
+
debug("Access token expired; refreshing");
|
|
120
|
+
const refreshed = await refreshToken(tokens.refresh_token);
|
|
121
|
+
return refreshed.access_token;
|
|
122
|
+
}
|
|
123
|
+
export function hasUserToken() {
|
|
124
|
+
return loadTokens() !== null;
|
|
125
|
+
}
|
|
126
|
+
// Client-credentials tokens (public data) have no refresh token, so we just
|
|
127
|
+
// cache one in memory and re-fetch when it nears expiry.
|
|
128
|
+
let cachedClientToken = null;
|
|
129
|
+
async function getCachedClientCredentialsToken() {
|
|
130
|
+
const now = Date.now() / 1000;
|
|
131
|
+
if (cachedClientToken &&
|
|
132
|
+
now < cachedClientToken.obtained_at + cachedClientToken.expires_in - 60) {
|
|
133
|
+
return cachedClientToken.access_token;
|
|
134
|
+
}
|
|
135
|
+
const token = await getClientCredentialsToken();
|
|
136
|
+
cachedClientToken = {
|
|
137
|
+
access_token: token.access_token,
|
|
138
|
+
obtained_at: now,
|
|
139
|
+
expires_in: token.expires_in ?? 3600,
|
|
140
|
+
};
|
|
141
|
+
return cachedClientToken.access_token;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* The API client's tokens: the logged-in user's when there is one (library and
|
|
145
|
+
* writes), otherwise cached client credentials for public calls.
|
|
146
|
+
* `refreshAccessToken` runs after an unexpected 401. Without a login, a 401
|
|
147
|
+
* means the call needs a user, so fail instead of minting another public token
|
|
148
|
+
* (SoundCloud allows 50 per 12 hours).
|
|
149
|
+
*/
|
|
150
|
+
export const tokenProvider = {
|
|
151
|
+
getAccessToken: () => hasUserToken() ? getValidAccessToken() : getCachedClientCredentialsToken(),
|
|
152
|
+
async refreshAccessToken() {
|
|
153
|
+
const tokens = loadTokens();
|
|
154
|
+
if (tokens?.refresh_token) {
|
|
155
|
+
const refreshed = await refreshToken(tokens.refresh_token);
|
|
156
|
+
return refreshed.access_token;
|
|
157
|
+
}
|
|
158
|
+
throw new SoundCloudAuthError("This needs a SoundCloud login. Call connect_soundcloud, then try again.");
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
function openBrowser(url) {
|
|
162
|
+
// rundll32 opens the URL without cmd.exe, which would split it at `&`.
|
|
163
|
+
const [cmd, args] = process.platform === "darwin"
|
|
164
|
+
? ["open", [url]]
|
|
165
|
+
: process.platform === "win32"
|
|
166
|
+
? ["rundll32", ["url.dll,FileProtocolHandler", url]]
|
|
167
|
+
: ["xdg-open", [url]];
|
|
168
|
+
try {
|
|
169
|
+
spawn(cmd, args, { stdio: "ignore", detached: true }).unref();
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
debug("Could not open browser automatically:", error);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
// Runs the full Authorization Code + PKCE flow: spins up a one-shot local
|
|
176
|
+
// server on the redirect URI's port, opens the browser, captures the callback
|
|
177
|
+
// code automatically, exchanges it for tokens, and persists them.
|
|
178
|
+
export function loginWithBrowser(options = {}) {
|
|
179
|
+
const { openBrowser: shouldOpen = true, timeoutMs = 300_000 } = options;
|
|
180
|
+
if (!CLIENT_ID || !CLIENT_SECRET) {
|
|
181
|
+
return Promise.reject(new OAuthError(MISSING_CREDENTIALS));
|
|
182
|
+
}
|
|
183
|
+
const pkce = generatePKCEChallenge();
|
|
184
|
+
const authUrl = getAuthorizationUrl(pkce);
|
|
185
|
+
const redirect = new URL(REDIRECT_URI);
|
|
186
|
+
const port = parseInt(redirect.port, 10) || (redirect.protocol === "https:" ? 443 : 80);
|
|
187
|
+
return new Promise((resolve, reject) => {
|
|
188
|
+
let settled = false;
|
|
189
|
+
const finish = (fn) => {
|
|
190
|
+
if (settled)
|
|
191
|
+
return;
|
|
192
|
+
settled = true;
|
|
193
|
+
clearTimeout(timer);
|
|
194
|
+
server.close();
|
|
195
|
+
fn();
|
|
196
|
+
};
|
|
197
|
+
const server = http.createServer(async (req, res) => {
|
|
198
|
+
const reqUrl = new URL(req.url || "/", `http://localhost:${port}`);
|
|
199
|
+
if (reqUrl.pathname !== redirect.pathname) {
|
|
200
|
+
res.writeHead(404).end();
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
const send = (status, message) => {
|
|
204
|
+
res.writeHead(status, { "Content-Type": "text/html; charset=utf-8" });
|
|
205
|
+
res.end(`<html><body style="font-family:system-ui;text-align:center;padding-top:80px"><h1>${message}</h1><p>You can close this tab and return to your terminal.</p></body></html>`);
|
|
206
|
+
};
|
|
207
|
+
const error = reqUrl.searchParams.get("error");
|
|
208
|
+
const code = reqUrl.searchParams.get("code");
|
|
209
|
+
const state = reqUrl.searchParams.get("state");
|
|
210
|
+
if (error) {
|
|
211
|
+
send(400, "SoundCloud login failed");
|
|
212
|
+
finish(() => reject(new OAuthError("SoundCloud login failed. Try connecting again.")));
|
|
213
|
+
}
|
|
214
|
+
else if (state !== pkce.state) {
|
|
215
|
+
send(400, "Invalid state");
|
|
216
|
+
finish(() => reject(new OAuthError("OAuth state mismatch (possible CSRF).")));
|
|
217
|
+
}
|
|
218
|
+
else if (!code) {
|
|
219
|
+
send(400, "Missing authorization code");
|
|
220
|
+
finish(() => reject(new OAuthError("No authorization code in callback.")));
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
try {
|
|
224
|
+
const token = await exchangeCode(code, pkce.codeVerifier);
|
|
225
|
+
send(200, "SoundCloud connected!");
|
|
226
|
+
finish(() => resolve(token));
|
|
227
|
+
}
|
|
228
|
+
catch (err) {
|
|
229
|
+
send(500, "Token exchange failed");
|
|
230
|
+
finish(() => reject(err instanceof Error ? err : new OAuthError(String(err))));
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
server.on("error", (err) => finish(() => reject(err)));
|
|
235
|
+
const timer = setTimeout(() => finish(() => reject(new OAuthError("Timed out waiting for SoundCloud callback."))), timeoutMs);
|
|
236
|
+
// Listen only on the redirect URI's host (normally localhost), not the whole network.
|
|
237
|
+
server.listen(port, redirect.hostname.replace(/^\[|\]$/g, ""), () => {
|
|
238
|
+
logError(`Waiting for SoundCloud OAuth callback on ${REDIRECT_URI}`);
|
|
239
|
+
logError(`Authorize URL:\n${authUrl}\n`);
|
|
240
|
+
if (shouldOpen)
|
|
241
|
+
openBrowser(authUrl);
|
|
242
|
+
});
|
|
243
|
+
});
|
|
244
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { TOKEN_FILE } from "./config.js";
|
|
4
|
+
import { debug } from "./log.js";
|
|
5
|
+
export function loadTokens() {
|
|
6
|
+
try {
|
|
7
|
+
if (!fs.existsSync(TOKEN_FILE))
|
|
8
|
+
return null;
|
|
9
|
+
return JSON.parse(fs.readFileSync(TOKEN_FILE, "utf8"));
|
|
10
|
+
}
|
|
11
|
+
catch (error) {
|
|
12
|
+
debug("Failed to read token file:", error);
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export function saveTokens(token) {
|
|
17
|
+
const stored = { ...token, obtained_at: Math.floor(Date.now() / 1000) };
|
|
18
|
+
fs.mkdirSync(path.dirname(TOKEN_FILE), { recursive: true, mode: 0o700 });
|
|
19
|
+
// Refresh tokens are single-use, so a half-written file would end the login.
|
|
20
|
+
const tmp = `${TOKEN_FILE}.${process.pid}.tmp`;
|
|
21
|
+
fs.writeFileSync(tmp, JSON.stringify(stored, null, 2), { mode: 0o600 });
|
|
22
|
+
fs.chmodSync(tmp, 0o600);
|
|
23
|
+
fs.renameSync(tmp, TOKEN_FILE);
|
|
24
|
+
return stored;
|
|
25
|
+
}
|
|
26
|
+
export function clearTokens() {
|
|
27
|
+
try {
|
|
28
|
+
fs.rmSync(TOKEN_FILE, { force: true });
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
debug("Failed to clear token file:", error);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
// Refresh five minutes early; SoundCloud refresh tokens are single-use.
|
|
35
|
+
export function isExpired(token) {
|
|
36
|
+
const expiresAt = token.obtained_at + (token.expires_in ?? 3600);
|
|
37
|
+
return Date.now() / 1000 >= expiresAt - 300;
|
|
38
|
+
}
|