Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: derive Spotify OAuth redirect URI from the request origin

[._.]/ Adam Eivy8a5ad66af553
diff --git a/.env.example b/.env.example
index f609c83f4b..f21cf7ffe9 100644
--- a/.env.example
+++ b/.env.example
@@ -43,13 +43,15 @@ PGPASSWORD=portos
# HOST=0.0.0.0
# Public-facing hostname baked into OAuth redirect URIs for Google Calendar/Gmail
-# (googleAuth.js) and Spotify (spotifyAuth.js). Google and Spotify default to
-# "localhost"; Spotify otherwise auto-detects the active Tailscale hostname and
-# HTTPS state. Set this explicit override when the provider must use another host.
+# (googleAuth.js) and Spotify (spotifyAuth.js). Google defaults to "localhost".
+# Spotify prefers the origin the browser actually used to reach the request, and
+# only falls back to this value (then the detected Tailscale hostname/HTTPS state,
+# then localhost). Set this override when the provider must use another host.
# PUBLIC_HOST=host-example.ts.net
# Explicit override for the Spotify OAuth redirect URI (spotifyAuth.js). When set, it is
-# used verbatim instead of PUBLIC_HOST or the active Tailscale hostname/HTTPS state.
+# used verbatim instead of the request origin, PUBLIC_HOST, or the detected Tailscale
+# hostname/HTTPS state.
# It must match the redirect URI registered in the Spotify dashboard byte-for-byte.
# SPOTIFY_REDIRECT_URI=https://host-example.ts.net:5555/api/spotify/oauth/callback
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index 6482867cb9..8fa3c51c72 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -19301,7 +19301,7 @@
"sources": [
{
"source": "server/routes/spotify.js",
- "line": 56
+ "line": 71
}
]
},
@@ -19312,7 +19312,7 @@
"sources": [
{
"source": "server/routes/spotify.js",
- "line": 19
+ "line": 34
}
]
},
@@ -19323,7 +19323,7 @@
"sources": [
{
"source": "server/routes/spotify.js",
- "line": 30
+ "line": 45
}
]
},
@@ -19334,7 +19334,7 @@
"sources": [
{
"source": "server/routes/spotify.js",
- "line": 38
+ "line": 53
}
]
},
@@ -19345,7 +19345,7 @@
"sources": [
{
"source": "server/routes/spotify.js",
- "line": 13
+ "line": 28
}
]
},
@@ -19356,7 +19356,7 @@
"sources": [
{
"source": "server/routes/spotify.js",
- "line": 63
+ "line": 78
}
]
},
diff --git a/server/routes/spotify.js b/server/routes/spotify.js
index 3b00902b0e..819eafd01f 100644
--- a/server/routes/spotify.js
+++ b/server/routes/spotify.js
@@ -8,10 +8,25 @@ import * as spotifySync from '../services/spotifySync.js';
const router = Router();
+// OAuth must use the same public origin the browser used to reach this request.
+// Certificate metadata is not guaranteed to be present on every HTTPS install,
+// while the request host is authoritative for the current callback round-trip.
+function requestOrigin(req) {
+ const proto = (req.headers['x-forwarded-proto'] || req.protocol || 'http')
+ .toString().split(',')[0].trim();
+ const host = (req.headers['x-forwarded-host'] || req.headers.host || '')
+ .toString().split(',')[0].trim();
+ return ['http', 'https'].includes(proto) && host ? `${proto}://${host}` : null;
+}
+
+function requestRedirectOptions(req) {
+ return { origin: requestOrigin(req) };
+}
+
// Status — config (enabled/interval) + machine-local cursor state + OAuth status.
// No API call, so cheap and safe to poll from the settings tab.
router.get('/status', asyncHandler(async (req, res) => {
- const status = await spotifySync.getStatus();
+ const status = await spotifySync.getStatus(requestRedirectOptions(req));
res.json(status);
}));
@@ -22,13 +37,13 @@ router.post('/auth/credentials', asyncHandler(async (req, res) => {
clientSecret: z.string().min(1),
});
const data = validateRequest(schema, req.body);
- const result = await spotifyAuth.saveCredentials(data);
+ const result = await spotifyAuth.saveCredentials(data, requestRedirectOptions(req));
res.json(result);
}));
// Build the Spotify authorize URL (the SPA opens it to start the OAuth flow).
router.get('/auth/url', asyncHandler(async (req, res) => {
- const result = await spotifyAuth.getAuthUrl();
+ const result = await spotifyAuth.getAuthUrl(requestRedirectOptions(req));
res.json(result);
}));
@@ -42,7 +57,7 @@ router.get('/oauth/callback', asyncHandler(async (req, res) => {
const { code, error: authError } = req.query;
if (authError) return res.redirect(settingsUrl(String(authError)));
if (!code) return res.redirect(settingsUrl('Missing authorization code'));
- const error = await spotifyAuth.handleCallback(String(code)).then(() => null)
+ const error = await spotifyAuth.handleCallback(String(code), requestRedirectOptions(req)).then(() => null)
.catch((err) => {
// This catch replaces asyncHandler's logging (the redirect swallows the
// throw), so keep the failure visible in server logs.
diff --git a/server/routes/spotify.test.js b/server/routes/spotify.test.js
new file mode 100644
index 0000000000..836c3ddf10
--- /dev/null
+++ b/server/routes/spotify.test.js
@@ -0,0 +1,61 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+const mocks = vi.hoisted(() => ({
+ getRedirectUri: vi.fn(({ origin } = {}) => `${origin || 'http://localhost:5555'}/api/spotify/oauth/callback`),
+ getStatus: vi.fn(async () => ({ auth: {} })),
+ getAuthUrl: vi.fn(async () => ({ url: 'https://accounts.spotify.com/authorize' })),
+ saveCredentials: vi.fn(async (_data, options) => ({ redirectUri: mocks.getRedirectUri(options) })),
+ handleCallback: vi.fn(async () => ({ success: true })),
+ clearAuth: vi.fn(async () => ({ cleared: true })),
+}));
+
+vi.mock('../services/spotifyAuth.js', () => ({
+ getRedirectUri: (...args) => mocks.getRedirectUri(...args),
+ getAuthUrl: (...args) => mocks.getAuthUrl(...args),
+ saveCredentials: (...args) => mocks.saveCredentials(...args),
+ handleCallback: (...args) => mocks.handleCallback(...args),
+ clearAuth: (...args) => mocks.clearAuth(...args),
+}));
+
+vi.mock('../services/spotifySync.js', () => ({
+ getStatus: (...args) => mocks.getStatus(...args),
+ runSync: vi.fn(),
+}));
+
+import spotifyRoutes from './spotify.js';
+
+function makeApp() {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/spotify', spotifyRoutes);
+ app.use(errorMiddleware);
+ return app;
+}
+
+describe('Spotify routes', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('derives the status redirect URI from the forwarded public origin', async () => {
+ const response = await request(makeApp())
+ .get('/api/spotify/status')
+ .set('X-Forwarded-Proto', 'https')
+ .set('X-Forwarded-Host', 'host-example.ts.net:5555');
+
+ expect(response.status).toBe(200);
+ expect(mocks.getStatus).toHaveBeenCalledWith({ origin: 'https://host-example.ts.net:5555' });
+ });
+
+ it('uses the request origin for the OAuth authorize URL', async () => {
+ await request(makeApp())
+ .get('/api/spotify/auth/url')
+ .set('X-Forwarded-Proto', 'https')
+ .set('X-Forwarded-Host', 'host-example.ts.net:5555');
+
+ expect(mocks.getAuthUrl).toHaveBeenCalledWith({ origin: 'https://host-example.ts.net:5555' });
+ });
+});
diff --git a/server/services/spotifyAuth.js b/server/services/spotifyAuth.js
index 62c7496c78..39ef9ff89c 100644
--- a/server/services/spotifyAuth.js
+++ b/server/services/spotifyAuth.js
@@ -51,10 +51,13 @@ const ACCOUNTS_BASE = 'https://accounts.spotify.com';
* googleAuth's env-driven constant so it stays stable across the auth-url and
* callback round-trip. Surfaced in the auth status so the user can copy the
* exact string into the Spotify dashboard (it must match byte-for-byte).
+ * An explicit request origin takes precedence over machine metadata so remote
+ * Tailscale HTTPS users see the same callback URI the browser will use.
*/
-export function getRedirectUri() {
+export function getRedirectUri({ origin } = {}) {
if (process.env.SPOTIFY_REDIRECT_URI) return process.env.SPOTIFY_REDIRECT_URI;
const port = process.env.PORT || 5555;
+ if (origin) return `${origin.replace(/\/$/, '')}/api/spotify/oauth/callback`;
if (process.env.PUBLIC_HOST) {
return `http://${process.env.PUBLIC_HOST}:${port}/api/spotify/oauth/callback`;
}
@@ -103,9 +106,9 @@ export async function getCredentials() {
return JSON.parse(raw);
}
-export async function saveCredentials({ clientId, clientSecret }) {
+export async function saveCredentials({ clientId, clientSecret }, options = {}) {
await ensureAuthDir();
- const credentials = { clientId, clientSecret, redirectUri: getRedirectUri() };
+ const credentials = { clientId, clientSecret, redirectUri: getRedirectUri(options) };
await atomicWrite(CREDENTIALS_FILE, credentials);
console.log('🎧 Spotify OAuth credentials saved');
return { hasCredentials: true, redirectUri: credentials.redirectUri };
@@ -160,7 +163,7 @@ async function requestToken(params) {
return json;
}
-export async function getAuthUrl() {
+export async function getAuthUrl(options = {}) {
const credentials = await getCredentials();
if (!credentials?.clientId) {
throw new ServerError('No Spotify OAuth credentials configured', { status: 400 });
@@ -168,18 +171,18 @@ export async function getAuthUrl() {
const params = new URLSearchParams({
client_id: credentials.clientId,
response_type: 'code',
- redirect_uri: getRedirectUri(),
+ redirect_uri: getRedirectUri(options),
scope: SPOTIFY_SCOPES.join(' '),
show_dialog: 'false',
});
return { url: `${ACCOUNTS_BASE}/authorize?${params.toString()}` };
}
-export async function handleCallback(code) {
+export async function handleCallback(code, options = {}) {
const tokens = await requestToken({
grant_type: 'authorization_code',
code,
- redirect_uri: getRedirectUri(),
+ redirect_uri: getRedirectUri(options),
});
await saveTokens(withExpiry(tokens));
console.log('🎧 Spotify OAuth callback processed, tokens stored');
@@ -230,7 +233,7 @@ export async function getAccessToken() {
return refreshPromise;
}
-export async function getAuthStatus() {
+export async function getAuthStatus(options = {}) {
const credentials = await getCredentials();
const tokens = await getTokens();
return {
@@ -238,6 +241,6 @@ export async function getAuthStatus() {
hasTokens: !!(tokens?.access_token || tokens?.refresh_token),
expiresAt: Number.isFinite(tokens?.expires_at) ? new Date(tokens.expires_at).toISOString() : null,
scope: tokens?.scope || null,
- redirectUri: getRedirectUri(),
+ redirectUri: getRedirectUri(options),
};
}
diff --git a/server/services/spotifyAuth.test.js b/server/services/spotifyAuth.test.js
index b2f89052dc..279dcf5f02 100644
--- a/server/services/spotifyAuth.test.js
+++ b/server/services/spotifyAuth.test.js
@@ -80,6 +80,15 @@ describe('spotifyAuth pure helpers', () => {
expect(getRedirectUri()).toBe('https://example.test/api/spotify/oauth/callback');
});
+ it('uses a request origin when the caller supplies the public URL', () => {
+ delete process.env.SPOTIFY_REDIRECT_URI;
+ delete process.env.PUBLIC_HOST;
+ process.env.PORT = '5555';
+
+ expect(getRedirectUri({ origin: 'https://host-example.ts.net:5555/' }))
+ .toBe('https://host-example.ts.net:5555/api/spotify/oauth/callback');
+ });
+
it('builds the callback path from PUBLIC_HOST/PORT otherwise', () => {
delete process.env.SPOTIFY_REDIRECT_URI;
process.env.PUBLIC_HOST = 'myhost';
diff --git a/server/services/spotifySync.js b/server/services/spotifySync.js
index 93194d3277..d7ce42e436 100644
--- a/server/services/spotifySync.js
+++ b/server/services/spotifySync.js
@@ -253,11 +253,11 @@ async function doRunSync() {
}
// Status for the settings UI: config + cursor state + auth status (no API call).
-export async function getStatus() {
+export async function getStatus(options = {}) {
const [config, state, auth] = await Promise.all([
getSpotifyConfig(),
readSyncState(),
- getAuthStatus(),
+ getAuthStatus(options),
]);
return { config, state, auth };
}