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: add timeouts and single-flight refresh for Spotify auth and privacy-broker fetches (#2538)

Adam Eivy2b0f19689e34
diff --git a/server/services/privacyBrokers.js b/server/services/privacyBrokers.js
index e0866e49ab..1951ba010d 100644
--- a/server/services/privacyBrokers.js
+++ b/server/services/privacyBrokers.js
@@ -24,6 +24,11 @@ import { join } from 'path';
import { query, withTransaction } from '../lib/db.js';
import { ServerError } from '../lib/errorHandler.js';
import { PATHS } from '../lib/fileUtils.js';
+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
+
+// Cap on each registry fetch so a hung broker source can't stall a
+// user-triggered refresh indefinitely (both fetchers run under Promise.all).
+const BROKER_FETCH_TIMEOUT_MS = 15000;
// ─── Case state machine (pure) ──────────────────────────────────────────────
@@ -343,13 +348,13 @@ const BADBOOL_URL = 'https://raw.githubusercontent.com/bugbounty-zz/data-broker-
const CA_REGISTRY_URL = 'https://cppa.ca.gov/data_broker_registry.csv';
async function defaultFetchBadbool() {
- const res = await fetch(BADBOOL_URL).catch(() => null);
+ const res = await fetchWithTimeout(BADBOOL_URL, {}, BROKER_FETCH_TIMEOUT_MS).catch(() => null);
if (!res || !res.ok) return [];
return parseBadboolList(await res.json().catch(() => null));
}
async function defaultFetchCaRegistry() {
- const res = await fetch(CA_REGISTRY_URL).catch(() => null);
+ const res = await fetchWithTimeout(CA_REGISTRY_URL, {}, BROKER_FETCH_TIMEOUT_MS).catch(() => null);
if (!res || !res.ok) return [];
return parseCaRegistryCsv(await res.text().catch(() => ''));
}
diff --git a/server/services/spotifyAuth.js b/server/services/spotifyAuth.js
index f6e5e0497a..1e23f7e47e 100644
--- a/server/services/spotifyAuth.js
+++ b/server/services/spotifyAuth.js
@@ -23,6 +23,11 @@
*/
import { dataPath, ensureDir, atomicWrite, tryReadFile } from '../lib/fileUtils.js';
import { ServerError } from '../lib/errorHandler.js';
+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
+
+// Cap on each token-endpoint round-trip so a hung accounts.spotify.com can't
+// stall an OAuth callback or a history-sync refresh indefinitely.
+const TOKEN_TIMEOUT_MS = 15000;
const AUTH_DIR = dataPath('spotify');
const CREDENTIALS_FILE = dataPath('spotify', 'credentials.json');
@@ -129,14 +134,14 @@ async function requestToken(params) {
throw new ServerError('No Spotify OAuth credentials configured', { status: 400 });
}
const basic = Buffer.from(`${credentials.clientId}:${credentials.clientSecret}`).toString('base64');
- const res = await fetch(`${ACCOUNTS_BASE}/api/token`, {
+ const res = await fetchWithTimeout(`${ACCOUNTS_BASE}/api/token`, {
method: 'POST',
headers: {
Authorization: `Basic ${basic}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams(params).toString(),
- });
+ }, TOKEN_TIMEOUT_MS);
const json = await res.json().catch(() => ({}));
if (!res.ok) {
throw new ServerError(
@@ -173,6 +178,24 @@ export async function handleCallback(code) {
return { success: true };
}
+// Single-flight guard: while one refresh is in flight, concurrent callers await
+// the same promise instead of each POSTing their own refresh (Spotify rotates
+// the grant, so a double-refresh means the loser writes a stale token — classic
+// last-write-wins). Cleared in `finally` so a failed refresh can be retried.
+let refreshPromise = null;
+
+async function refreshAccessToken(tokens) {
+ const refreshed = await requestToken({
+ grant_type: 'refresh_token',
+ refresh_token: tokens.refresh_token,
+ });
+ const merged = withExpiry({ ...tokens, ...refreshed });
+ if (!refreshed.refresh_token) merged.refresh_token = tokens.refresh_token;
+ await saveTokens(merged);
+ console.log('🎧 Spotify OAuth access token refreshed');
+ return merged.access_token;
+}
+
/**
* Return a valid access token, refreshing via the stored refresh token when the
* current one is expired/near-expiry. Returns `null` when the user hasn't
@@ -181,6 +204,9 @@ export async function handleCallback(code) {
*
* Spotify may OMIT `refresh_token` from a refresh response (it stays valid), so
* the existing refresh token is preserved when the response doesn't carry one.
+ *
+ * Concurrent callers that all find the token expired share ONE refresh via the
+ * module-level `refreshPromise` (single-flight), so the grant is rotated once.
*/
export async function getAccessToken() {
const tokens = await getTokens();
@@ -188,15 +214,12 @@ export async function getAccessToken() {
if (!isTokenExpired(tokens)) return tokens.access_token;
if (!tokens?.refresh_token) return null;
- const refreshed = await requestToken({
- grant_type: 'refresh_token',
- refresh_token: tokens.refresh_token,
- });
- const merged = withExpiry({ ...tokens, ...refreshed });
- if (!refreshed.refresh_token) merged.refresh_token = tokens.refresh_token;
- await saveTokens(merged);
- console.log('🎧 Spotify OAuth access token refreshed');
- return merged.access_token;
+ if (!refreshPromise) {
+ refreshPromise = refreshAccessToken(tokens).finally(() => {
+ refreshPromise = null;
+ });
+ }
+ return refreshPromise;
}
export async function getAuthStatus() {
diff --git a/server/services/spotifyAuth.test.js b/server/services/spotifyAuth.test.js
index 6c074a9de3..b646db6e8b 100644
--- a/server/services/spotifyAuth.test.js
+++ b/server/services/spotifyAuth.test.js
@@ -1,5 +1,24 @@
-import { describe, it, expect, afterEach } from 'vitest';
-import { isTokenExpired, withExpiry, getRedirectUri } from './spotifyAuth.js';
+import { describe, it, expect, afterEach, vi } from 'vitest';
+
+const mocks = {
+ ensureDir: vi.fn(async () => {}),
+ atomicWrite: vi.fn(async () => {}),
+ tryReadFile: vi.fn(async () => null),
+ fetchWithTimeout: vi.fn(),
+};
+
+vi.mock('../lib/fileUtils.js', () => ({
+ dataPath: (...parts) => `/tmp/${parts.join('/')}`,
+ ensureDir: (...args) => mocks.ensureDir(...args),
+ atomicWrite: (...args) => mocks.atomicWrite(...args),
+ tryReadFile: (...args) => mocks.tryReadFile(...args),
+}));
+
+vi.mock('../lib/fetchWithTimeout.js', () => ({
+ fetchWithTimeout: (...args) => mocks.fetchWithTimeout(...args),
+}));
+
+import { isTokenExpired, withExpiry, getRedirectUri, getAccessToken } from './spotifyAuth.js';
describe('spotifyAuth pure helpers', () => {
describe('withExpiry', () => {
@@ -57,3 +76,70 @@ describe('spotifyAuth pure helpers', () => {
});
});
});
+
+describe('getAccessToken', () => {
+ afterEach(() => {
+ mocks.ensureDir.mockClear();
+ mocks.atomicWrite.mockClear();
+ mocks.tryReadFile.mockReset().mockResolvedValue(null);
+ mocks.fetchWithTimeout.mockReset();
+ });
+
+ const expiredTokens = JSON.stringify({ access_token: 'old', refresh_token: 'r1', expires_at: 1 });
+ const credentials = JSON.stringify({ clientId: 'cid', clientSecret: 'secret' });
+
+ // tryReadFile is called per file (tokens.json then credentials.json inside
+ // requestToken); route by the requested path.
+ const routeReads = () => mocks.tryReadFile.mockImplementation(async (path) => {
+ if (String(path).endsWith('tokens.json')) return expiredTokens;
+ if (String(path).endsWith('credentials.json')) return credentials;
+ return null;
+ });
+
+ it('passes a finite timeout to fetchWithTimeout on refresh', async () => {
+ routeReads();
+ mocks.fetchWithTimeout.mockResolvedValue({
+ ok: true,
+ json: async () => ({ access_token: 'fresh', expires_in: 3600 }),
+ });
+
+ await getAccessToken();
+
+ expect(mocks.fetchWithTimeout).toHaveBeenCalledTimes(1);
+ const timeoutArg = mocks.fetchWithTimeout.mock.calls[0][2];
+ expect(Number.isFinite(timeoutArg)).toBe(true);
+ expect(timeoutArg).toBeGreaterThan(0);
+ });
+
+ it('single-flights concurrent refreshes into one token request', async () => {
+ routeReads();
+ let resolveFetch;
+ mocks.fetchWithTimeout.mockReturnValue(new Promise((res) => { resolveFetch = res; }));
+
+ const p1 = getAccessToken();
+ const p2 = getAccessToken();
+ // Wait until the shared refresh has actually issued its single fetch before
+ // releasing it (both callers await getTokens/getCredentials first).
+ while (mocks.fetchWithTimeout.mock.calls.length === 0) {
+ await new Promise((r) => setTimeout(r, 0));
+ }
+ resolveFetch({ ok: true, json: async () => ({ access_token: 'fresh', expires_in: 3600 }) });
+
+ const [t1, t2] = await Promise.all([p1, p2]);
+ expect(t1).toBe('fresh');
+ expect(t2).toBe('fresh');
+ expect(mocks.fetchWithTimeout).toHaveBeenCalledTimes(1);
+ });
+
+ it('clears the single-flight guard so a later refresh can run again', async () => {
+ routeReads();
+ mocks.fetchWithTimeout
+ .mockRejectedValueOnce(new Error('network down'))
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ access_token: 'fresh', expires_in: 3600 }) });
+
+ await expect(getAccessToken()).rejects.toThrow();
+ // Guard released in finally → the next call issues a fresh request.
+ await expect(getAccessToken()).resolves.toBe('fresh');
+ expect(mocks.fetchWithTimeout).toHaveBeenCalledTimes(2);
+ });
+});