/** * Signed cover-art URLs for the lock screen. iOS fetches Media Session artwork without reliable cookies, so * members get `/art/NN.png?exp=&sig=` links that work without cookies until they * expire. The HMAC key is random, generated once and kept in package storage. Runtime-free. */ export const ART_TTL_SECONDS = 12 * 60 * 60 const enc = new TextEncoder() const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') async function hmac(keyHex: string, msg: string): Promise { const raw = new Uint8Array(keyHex.match(/../g)!.map((h) => parseInt(h, 16))) const key = await crypto.subtle.importKey('raw', raw, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']) return b64url(new Uint8Array(await crypto.subtle.sign('HMAC', key, enc.encode(msg)))) } /** A fresh random key (64 hex characters). */ export function newArtKey(): string { return Array.from(crypto.getRandomValues(new Uint8Array(32)), (b) => b.toString(16).padStart(2, '0')).join('') } /** * Sign a cover URL. * * @param base - app base path * @param n - track number * @param keyHex - the HMAC key * @param now - the current time in ms * @returns the path with exp and sig */ export async function signArt(base: string, n: number, keyHex: string, now = Date.now()): Promise { const exp = Math.floor(now / 1000) + ART_TTL_SECONDS return `${base}/art/${String(n).padStart(2, '0')}.png?exp=${exp}&sig=${await hmac(keyHex, `art:${n}:${exp}`)}` } /** * Check a signed cover request. * * @param n - track number from the path * @param exp - the exp parameter * @param sig - the sig parameter * @param keyHex - the HMAC key * @param now - the current time in ms * @returns true when the signature matches and has not expired */ export async function verifyArt(n: number, exp: string | null, sig: string | null, keyHex: string, now = Date.now()): Promise { if (!exp || !sig || !/^\d{1,12}$/.test(exp) || Number(exp) * 1000 < now || Number(exp) * 1000 > now + (ART_TTL_SECONDS + 60) * 1000) return false const want = await hmac(keyHex, `art:${n}:${exp}`) if (want.length !== sig.length) return false let diff = 0 for (let i = 0; i < want.length; i++) diff |= want.charCodeAt(i) ^ sig.charCodeAt(i) return diff === 0 }