Signed, expiring stream URLs with HMAC in Node.js
A stateless capability token for streaming one track to one user: base64url payload, HMAC-SHA256 signature, constant-time verification, expiry, and optional binding to the browser session.
The audio in Melodius streams through its own relay. Each stream URL is a capability: it lets one user stream one track until it expires, and says nothing about where the audio comes from. Here is how those URLs are built.
Why a token, not a session check
An audio element fetches its source with range requests, many of them for one song, and the desktop and Android players are not browsers with cookies. A signed token works everywhere, needs no database read per request, and can be checked in microseconds.
The format
const payload = base64url(JSON.stringify({ t: trackId, u: userId, e: expiresAtSeconds, s: 1? }));
const token = `${payload}.${hmacSha256(secret, "stream_relay:" + payload)}`;- Tokens live for twelve hours, long enough for a queue, short enough that a leaked one dies.
- The signed string is prefixed with
stream_relay:. That domain separation means a signature made for another purpose with the same secret can never pass as a stream token. - No provider, URL or source appears in the token. It names a track id, nothing else.
Verifying it
const [payload, signature, extra] = token.split(".");
if (!payload || !signature || extra !== undefined) return null;
const expected = Buffer.from(sign(payload));
const received = Buffer.from(signature);
if (expected.length !== received.length || !timingSafeEqual(expected, received)) return null;
// then parse, validate types and the track id pattern, check expiry- Exactly two parts. A third part means someone is experimenting, so it fails.
timingSafeEqualcompares in constant time, so response timing reveals nothing about how much of a forged signature was right. It throws on different lengths, hence the length check first.- Only after the signature passes is the payload parsed, and every field is type-checked; the track id must match a strict pattern before it reaches any lookup.
Session-bound tokens
A URL copied out of the browser's network tab would otherwise play anywhere. Tokens issued to the web player carry a flag that also requires that user's session cookie, so the URL alone is useless. Tokens for the apps, which authenticate differently, leave it off.
Small rules that matter
- Sign a domain-separated string, not the bare payload.
- Compare signatures in constant time.
- Reject structurally odd tokens before parsing anything.
- Validate every field after verification, not before.
- Keep the payload free of anything you would not show the user.
