EDT-Shuffler
A fair, explainable playlist shuffler for Spotify — plus a Party mode that builds a tempo-matched set between 70 and 175 BPM for DJs and private events.
Zero dependencies. Node built-ins only (node:http, node:sqlite,
node:crypto). MIT.
cd EDT-Shuffler
npm test # 40+ assertions, no network
npm start # http://localhost:8787 (demo mode, seeded library)
With no Spotify credentials configured the app boots in demo mode: a deterministic 75-track library, three playlists, a lopsided play history, and simulated playback. That is enough to exercise the real engine, the real database and the real UI without creating a Spotify app.
Read this before you promise anyone anything
Two platform facts shape this build. They are not opinions; sources and dates
are in docs/PLATFORM-CONSTRAINTS.md.
| Reality | Consequence |
|---|---|
Spotify closed audio-features (tempo), preview_url and popularity to apps created after 2024-11-27. |
Party mode needs BPM from your own tags or an opt-in provider. "Most popular" means most played in your account, not Spotify popularity. |
| Spotify development mode allows 5 users; extended quota needs a company with 250k+ MAU. | This is the real ceiling on "100,000 members". See docs/CAPACITY.md. |
Also deliberate: EDT-Shuffler never streams, downloads or mixes audio. It computes an order and hands it to the user's own Spotify client (Premium, open device). That keeps it out of Spotify's streaming-SDA licensing problem and out of the "no segue/mix/overlap" rule.
Run your own (Spotify's 5-user limit)
A Spotify app in development mode lets only 5 people sign in, so one shared copy can't serve everyone. Each person runs their own copy with their own free Spotify developer app. You need Spotify Premium and Node.js 22.5 or newer.
- Get the code:
git clone https://git.edt-labs.xyz/cybertr0n/EDT-Shuffler.git - Make a Spotify app at https://developer.spotify.com/dashboard → Create app.
- Redirect URI:
http://127.0.0.1:8787/auth/spotify/callback(or${PUBLIC_URL}/auth/spotify/callbackif you host it somewhere) - APIs: tick Web API and Web Playback SDK.
- Under User Management, add the email of your Spotify account.
- Redirect URI:
- Configure:
cp .env.example .env, then setSPOTIFY_CLIENT_ID,SPOTIFY_CLIENT_SECRETandPUBLIC_URL=http://127.0.0.1:8787. Optional:BPM_PROVIDER=reccobeatsso Party mode gets song tempos automatically. - Start:
npm start, open http://127.0.0.1:8787 and press Connect Spotify.
To see how it works first, try the live demo (no Spotify needed): https://edt-labs.xyz/shuffler-demo/.
What you can do once signed in:
- Shuffle a playlist five ways (even share, most played, trending, least played, true shuffle). Every row says why it is there.
- Reshuffle for a new order, Play this order on any open Spotify device, or Save this order back to the same playlist (playlists you created only).
- Party mode: pick a BPM, genres and length; steady, ramp or build to peak.
What it does
Five shuffle modes, all operating on playlists you already made (it never creates playlists):
| Mode | Signal |
|---|---|
| Even share (default) | Windowed deficit round-robin: over any run of 2 × list size picks, every track appears the same number of times, give or take one. |
| Most played | Sub-linear play count, so one anthem cannot crowd out 200 tracks. |
| Trending now | Plays in the last 14 days versus the 14 days before. |
| Least played | Inverse play count; never-played tracks first. |
| True shuffle | Uniform random with artist spacing. |
Every row in the queue carries a reason: 0 plays — first in line,
12 plays lifetime, 2 in the last window · +1.4 vs even share,
6 plays in 14d vs 1 before.
Artist spacing: no artist repeats inside three tracks when the list allows it, and the API says so when it cannot (a 2-artist playlist physically cannot).
Party mode ($1/month): choose 70–175 BPM, genres, length and shape (steady, ramp, build-to-peak). Tempo is normalised across half/double time, so a 174 BPM drum-and-bass track counts as 87 BPM at a 87 BPM request. BPM coverage is reported as a percentage — the build refuses to fake a "124 BPM house set" out of three tracks.
Play telemetry: Spotify does not expose per-user play counts, so
play_events records what this app observed, plus a backfill from
/me/player/recently-played. That table is what makes "most played on their
current personal list" possible at all.
How the even shuffle works
Naive weighted random still clumps. A lifetime deficit (even_share - plays)
sounds right and is wrong: a track with 500 plays has a deficit so deep it is
never scheduled again, and it can never catch up because the even share keeps
rising. This build balances a rolling window instead:
window = min(max(2 × list_size, 12), 400) # last N play events
target = window / list_size
due(track) = target - plays_of_that_track_in_the_window
pick = highest due, ties shuffled in 0.5-wide bands
Played tracks drop to the back of the queue, under-played tracks come forward, and eviction from the window means nothing is punished forever. A regression test simulates 240 consecutive picks with one track sitting on 500 lifetime plays and asserts the spread stays within 2.
Weighted modes use Efraimidis–Spirakis sampling without replacement
(key = u^(1/w), sort descending) — one pass, exact weighted permutation, no
rejection loop, no duplicates.
Configuration
Copy .env.example to .env. Everything is optional.
| Variable | Purpose |
|---|---|
PORT, HOST, PUBLIC_URL |
Bind address and the origin used for OAuth callbacks. |
APP_SECRET |
Encrypts stored OAuth tokens and salts IP hashes. Generated into .app-secret (0600) if unset. Losing it logs everyone out. |
GOOGLE_CLIENT_ID / _SECRET |
Optional. Spotify is the account; set these only for Google as an alternative. |
SPOTIFY_CLIENT_ID / _SECRET |
Library + playback. Redirect URI: ${PUBLIC_URL}/auth/spotify/callback. |
STRIPE_SECRET_KEY, STRIPE_PRICE_ID, STRIPE_WEBHOOK_SECRET |
Party plan. Webhook: ${PUBLIC_URL}/billing/webhook. |
PRICE_CENTS |
Default 100 ($1.00). Read §5 of CAPACITY.md before shipping it. |
PARTY_UNLOCK_HOURS |
Hours one rewarded video unlocks Party (default 4). |
PARTY_AD_UNIT |
Ad Manager ad unit path; enables the rewarded unlock button. |
ADSENSE_CLIENT |
AdSense client id for display ads on the public pages. |
MAIL_TRANSPORT |
console (default), resend, postmark, webhook. |
BPM_PROVIDER |
manual (default) or reccobeats. |
RUN_JOBS |
In-process hourly reminder sweep + daily retention purge. |
Spotify is both the account and the data source. Google sign-in is optional.
API
| Method | Path | Notes |
|---|---|---|
| GET | /api/session |
User, entitlement, modes, limits. |
| GET | /api/playlists |
Library with per-list BPM coverage. |
| POST | /api/playlists/sync |
Pull metadata from Spotify (rate-limited). |
| POST | /api/queue/preview |
{playlistId, mode, artistGap} → ordered items + reasons. |
| POST | /api/queue/apply |
Recomputes server-side, then hands the order to Spotify. |
| POST | /api/party/preview |
{playlistId, bpm, genres, minutes, curve} → set + coverage. |
| POST | /api/party/apply |
Requires an active Party entitlement (402 otherwise). |
| POST | /api/party/unlock/start |
Single-use nonce for the rewarded video. |
| POST | /api/party/unlock/complete |
Grants PARTY_UNLOCK_HOURS, once per UTC day. |
| POST | /api/telemetry/play |
Record one observed play. |
| POST | /api/telemetry/import-recent |
Backfill deduped plays from Spotify. |
| POST | /api/bpm/import |
spotify_track_id,bpm CSV. |
| POST | /billing/webhook |
Stripe, signature-verified and idempotent. |
The order handed to Spotify is recomputed on the server; a client cannot dictate what gets played.
Rewarded unlock. Party can also be opened by watching a video: the server
issues a single-use nonce, the page reports completion, and the account gets
PARTY_UNLOCK_HOURS of access, once per UTC day. The server cannot cryptographically
verify a web rewarded view (Ad Manager offers server-side verification for apps only),
so this is a speed bump: minimum elapsed time, one grant per day, per-user nonces.
Set PARTY_AD_UNIT and define window.playRewardedAd({unit, minSeconds}) to resolve
on the network's rewarded event; the in-page countdown is demo-only.
Security notes
- OAuth authorization-code + PKCE, single-use state rows with a 10-minute TTL.
- Sessions are random 32-byte ids in an
HttpOnly,SameSite=Laxcookie, stored server-side, deleted on logout. - Spotify access and refresh tokens are encrypted with AES-256-GCM and keys
derived per purpose (HKDF) from
APP_SECRET. - Stripe webhooks verify
t=,v1=HMAC with a 5-minute timestamp tolerance, andstripe_event_idis unique so replays are no-ops. - Cross-origin POSTs are refused; CSP,
X-Frame-Options: DENYandX-Content-Type-Options: nosniffare set on every response. - IPs are HMAC'd before storage.
- Metadata older than 30 days and no longer in any playlist is purged, because Spotify's terms forbid building a permanent mirror of their catalogue.
- No secret is ever logged.
.envand.app-secretare gitignored.
Project layout
src/
server.mjs zero-dep HTTP, static files, CSRF, rate limits, jobs
routes.mjs every endpoint
db.mjs schema, play statistics, retention
shuffle/engine.mjs fairness + weighted modes + spacing repair
shuffle/party.mjs BPM normalisation, genre filter, set ordering
bpm/resolver.mjs manual/CSV → cache → optional provider
spotify/client.mjs encrypted tokens, shared limiter, ordered playback
billing/stripe.mjs checkout, portal, webhook verification, entitlements
jobs/reminders.mjs the only automated email
demo/seed.mjs deterministic demo account
public/ the whole UI (no build step)
test/ node:test suites
docs/ constraints, prior art, capacity
ops/ Postgres schema + sample systemd unit
Postgres is a schema translation away (ops/schema.postgres.sql); SQLite is the
default so a clone runs with no services.
Tests
npm test
Covers: permutation integrity per mode, seed determinism, the 240-pick fairness simulation, artist spacing, graceful degradation on one-artist lists, BPM half/double folding, tempo windows, genre aliasing, no-BPM reporting, Stripe signature verification (good/tampered/stale/rotated), entitlement grace, fee maths, token encryption round-trip, per-account play isolation, dedupe, retention purge, CSV parsing with quotes, and demo seed idempotency.
Deploying
- Put Caddy/nginx in front for TLS; the app binds
127.0.0.1. - Hidden requirements are exact: OAuth redirect URIs must match
PUBLIC_URLbyte-for-byte, including scheme and port. docs/CAPACITY.mdhas sizing for 1k / 10k / 100k members and why the last one is a Spotify-access problem before it is a server problem.
Report a bug
Found a problem with EDT-Shuffler? Open an issue at https://git.edt-labs.xyz/cybertr0n/EDT-Shuffler/issues/new (free account on git.edt-labs.xyz). Say what device and version you have, what you did, and what happened; a screenshot or log helps. No account? Email [email protected].
Security problem, or a report with private details (serial numbers, account names, IP addresses)? Don't post it as an issue, since issues are visible to other users: email [email protected] instead.
Licence
MIT. Spotify, Google and Stripe are trademarks of their owners; this project is not affiliated with any of them.