From 5ee12d44964ee9a4cbe7b13731b78df2b1daa80a Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 12:44:56 +0000 Subject: [PATCH 1/3] feat: cap base-tier skips and exclude owner devices Base tier shares 300 skips, Insta Plays, and Insta Chooses a day across this device and its network. Full access comes from a checked GitHub star, Discord membership, or a friend install that is not the same device, browser, phone, or VPN. The owner's devices, including ones linked with the same library sync key, are excluded from the allowance. Co-authored-by: Coye --- CHANGELOG.md | 7 + canvas-bridge/access.js | 581 +++++++++++++++++++++++++++++++++++ canvas-bridge/installs.js | 4 + canvas-bridge/referral.js | 156 ++++++++++ canvas-bridge/worker.js | 4 +- css/polish.css | 21 ++ js/access-policy.js | 80 +++++ js/access-ui.js | 228 ++++++++++++++ js/access.js | 411 +++++++++++++++++++++++++ js/app.js | 25 +- js/changelog.js | 5 + js/dj.js | 7 +- js/jam.js | 4 +- js/maintenance.js | 8 + js/player.js | 40 ++- js/referral.js | 158 ++++++++++ package.json | 2 +- scripts/check.mjs | 2 + sw.js | 4 +- tests/access-limit.test.mjs | 164 ++++++++++ tests/access-player.test.mjs | 27 ++ 21 files changed, 1909 insertions(+), 29 deletions(-) create mode 100644 canvas-bridge/access.js create mode 100644 canvas-bridge/referral.js create mode 100644 js/access-policy.js create mode 100644 js/access-ui.js create mode 100644 js/access.js create mode 100644 js/referral.js create mode 100644 tests/access-limit.test.mjs create mode 100644 tests/access-player.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index ff7c4df..8dfcc9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ Every Spot+ update. The app shows the newest ones in its “What’s new” screen. +## 2.2.6 — Base tier daily limit, unlocked by support +_2026-11-25_ + +- Spot+ stays free, powered by love and support. On the base tier, skips, Insta Play, and Insta Choose share 300 a day, counted on this device and on this network address. +- After today’s allowance is used, the song already playing can finish and the queue can still advance. Skips, picking a song, seeking, new downloads, repeat, Canvas, and early loading of the next song wait until tomorrow. +- Full access comes from support Spot+ can check: star coye2/spot-plus on GitHub, join the Discord and verify membership, or refer a friend who installs Spot+ and enters your code. Another browser, phone, or VPN on the same device does not count as that friend. Your own devices are excluded from the allowance. + ## 2.2.5 — Operation S+: S-tier playback state machine, recovery checkpoints, adaptive transitions & scalable Worker protection _2026-11-24_ diff --git a/canvas-bridge/access.js b/canvas-bridge/access.js new file mode 100644 index 0000000..8537350 --- /dev/null +++ b/canvas-bridge/access.js @@ -0,0 +1,581 @@ +// Daily base-tier allowance and GitHub-star verification for the Spot+ bridge. +// Optional Worker secrets (never sent to the browser): +// GITHUB_TOKEN higher GitHub API rate limit for star checks +// GITHUB_CLIENT_ID enables "Verify fully with GitHub" (OAuth) +// GITHUB_CLIENT_SECRET OAuth code exchange; also signs the OAuth state +// UNLOCK_SECRET optional dedicated state-signing key +// DISCORD_CLIENT_ID enables "Verify Discord membership" +// DISCORD_CLIENT_SECRET Discord OAuth code exchange +// DISCORD_GUILD_ID optional; otherwise the public invite's server is used +// Callbacks: /access/github/callback and /access/discord/callback. +import { + DAILY_LIMIT, DISCORD, MAX_DEVICES_PER_LOGIN, REPO, addUsage, isKnownAction, normalizeLogin, quotaView, utcDay, +} from '../js/access-policy.js'; +import { discordGuildId, handleReferral, isGuildMember } from './referral.js'; +import { isOwnerProof } from '../js/maintenance.js'; + +export const MAX_STAR_PAGES = 15; +const STATE_TTL_MS = 10 * 60 * 1000; +const HEADERS = { + 'Content-Type': 'application/json; charset=utf-8', + 'Cache-Control': 'no-store', + 'X-Content-Type-Options': 'nosniff', +}; + +const json = (data, status = 200, extra = {}) => new Response(JSON.stringify(data), { + status, headers: { ...HEADERS, ...extra }, +}); + +export function safeReturn(value) { + try { + const url = new URL(String(value || '')); + if (url.username || url.password) return ''; + let path = url.pathname; + if (path.endsWith('/index.html')) path = path.slice(0, -'index.html'.length); + const bare = path.replace(/\/+$/, '') || '/'; + const pages = url.origin === 'https://coye2.github.io' && bare === '/spot-plus'; + const local = (url.origin === 'http://localhost:8080' || url.origin === 'http://127.0.0.1:8080') && bare === '/'; + if (!pages && !local) return ''; + if (bare === '/') return url.origin + '/'; + return url.origin + bare + '/'; + } catch { + return ''; + } +} + +function returnTarget(value) { + return safeReturn(value) || 'https://coye2.github.io/spot-plus/'; +} + +async function hmacHex(secret, message) { + const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); + const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(message))); + return [...sig].map((b) => b.toString(16).padStart(2, '0')).join(''); +} + +function safeEqual(a, b) { + const s1 = String(a || ''), s2 = String(b || ''); + if (s1.length !== s2.length) return false; + let diff = 0; + for (let i = 0; i < s1.length; i++) diff |= s1.charCodeAt(i) ^ s2.charCodeAt(i); + return diff === 0; +} + +function b64urlEncode(text) { + const bytes = new TextEncoder().encode(text); + let bin = ''; + for (const b of bytes) bin += String.fromCharCode(b); + return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, ''); +} + +function b64urlDecode(text) { + const pad = text.length % 4 === 0 ? '' : '='.repeat(4 - (text.length % 4)); + const bin = atob(text.replace(/-/g, '+').replace(/_/g, '/') + pad); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i); + return new TextDecoder().decode(bytes); +} + +export async function sealState(payload, secret) { + const body = b64urlEncode(JSON.stringify(payload)); + const sig = await hmacHex(secret, body); + return `${body}.${sig}`; +} + +export async function openState(token, secret, now = Date.now()) { + const dot = String(token || '').lastIndexOf('.'); + if (dot <= 0 || !secret) return null; + const body = token.slice(0, dot), sig = token.slice(dot + 1); + const expect = await hmacHex(secret, body); + if (!safeEqual(expect, sig)) return null; + try { + const payload = JSON.parse(b64urlDecode(body)); + if (!payload || !(payload.exp > now)) return null; + if (!/^[a-f0-9]{32}$/.test(payload.device || '')) return null; + const returnTo = safeReturn(payload.returnTo); + if (!returnTo) return null; + return { device: payload.device, returnTo }; + } catch { + return null; + } +} + +export async function shortHash(text) { + const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode('spotplus:' + text)); + return [...new Uint8Array(digest)].slice(0, 8).map((b) => b.toString(16).padStart(2, '0')).join(''); +} + +async function readJsonLimited(response, limit = 700000) { + const text = await response.text(); + if (text.length > limit) throw new Error('large'); + return JSON.parse(text); +} + +function githubHeaders(token) { + const headers = { + Accept: 'application/vnd.github+json', + 'User-Agent': 'SpotPlus (https://coye2.github.io/spot-plus/)', + 'X-GitHub-Api-Version': '2022-11-28', + }; + if (token) headers.Authorization = 'Bearer ' + token; + return headers; +} + +/** + * Confirm the account exists and that coye2/spot-plus is in its public stars. + * GitHub lists stars newest-first, so a star just given is on page 1. + * Scanning later pages covers accounts that starred earlier. + */ +export async function findStar(login, fetcher, { token = '', maxPages = MAX_STAR_PAGES, signal } = {}) { + const name = normalizeLogin(login); + if (!name) return { ok: false, reason: 'invalid' }; + const headers = githubHeaders(token); + let userRes; + try { + userRes = await fetcher('https://api.github.com/users/' + encodeURIComponent(name), { headers, signal }); + } catch { + return { ok: false, reason: 'unavailable' }; + } + if (userRes.status === 404) return { ok: false, reason: 'not-found' }; + if (userRes.status === 403 || userRes.status === 429) return { ok: false, reason: 'rate-limited' }; + if (!userRes.ok) return { ok: false, reason: 'unavailable' }; + let user; + try { user = await readJsonLimited(userRes, 100000); } catch { return { ok: false, reason: 'unavailable' }; } + const canonical = normalizeLogin(user?.login); + if (!canonical || canonical.toLowerCase() !== name.toLowerCase()) return { ok: false, reason: 'not-found' }; + for (let page = 1; page <= maxPages; page++) { + let res; + try { + res = await fetcher(`https://api.github.com/users/${encodeURIComponent(canonical)}/starred?per_page=100&page=${page}`, { headers, signal }); + } catch { + return { ok: false, reason: 'unavailable' }; + } + if (res.status === 403 || res.status === 429) return { ok: false, reason: 'rate-limited' }; + if (res.status === 404) return { ok: false, reason: 'not-starred' }; + if (!res.ok) return { ok: false, reason: 'unavailable' }; + let repos; + try { repos = await readJsonLimited(res); } catch { return { ok: false, reason: 'unavailable' }; } + if (!Array.isArray(repos)) return { ok: false, reason: 'unavailable' }; + if (repos.some((repo) => String(repo?.full_name || '').toLowerCase() === REPO.full)) return { ok: true, login: canonical }; + if (repos.length < 100) return { ok: false, reason: 'not-starred' }; + } + return { ok: false, reason: 'incomplete', login: canonical }; +} + +/** Authenticated check: 204 means the signed-in user has starred the repo. */ +export async function viewerStarred(token, fetcher, { signal } = {}) { + const headers = githubHeaders(token); + let userRes; + let starRes; + try { + userRes = await fetcher('https://api.github.com/user', { headers, signal }); + starRes = await fetcher('https://api.github.com/user/starred/' + REPO.full, { headers, signal }); + } catch { + return { ok: false, reason: 'unavailable' }; + } + if (userRes.status === 401 || starRes.status === 401) return { ok: false, reason: 'unavailable' }; + if (userRes.status === 403 || starRes.status === 403 || userRes.status === 429 || starRes.status === 429) { + return { ok: false, reason: 'rate-limited' }; + } + if (!userRes.ok) return { ok: false, reason: 'unavailable' }; + let user; + try { user = await readJsonLimited(userRes, 100000); } catch { return { ok: false, reason: 'unavailable' }; } + const login = normalizeLogin(user?.login); + if (!login) return { ok: false, reason: 'not-found' }; + if (starRes.status === 204) return { ok: true, login }; + if (starRes.status === 404) return { ok: false, reason: 'not-starred', login }; + return { ok: false, reason: 'unavailable' }; +} + +function validDevice(id) { + return /^[a-f0-9]{32}$/.test(String(id || '')); +} + +function validNonce(nonce) { + return /^[a-f0-9]{16,32}$/.test(String(nonce || '')); +} + +async function mutate(storage, fn) { + if (typeof storage.transaction === 'function') return storage.transaction(fn); + return fn(storage); +} + +async function rollQuotaDay(storage, day) { + const prev = await storage.get('quotaDay'); + if (prev === day) return; + if (prev && typeof storage.list === 'function' && typeof storage.delete === 'function') { + const drop = []; + for (const prefix of ['q:', 'nonce:']) { + const listed = await storage.list({ prefix }); + for (const key of listed.keys()) { + if (!String(key).includes(':' + day + ':')) drop.push(key); + if (drop.length >= 400) break; + } + if (drop.length >= 400) break; + } + if (drop.length) await storage.delete(drop); + if (drop.length >= 400) return; + } + await storage.put({ quotaDay: day }); +} + +async function readCounts(storage, day, device, ipHash) { + const deviceUsed = Number(await storage.get(`q:d:${day}:${device}`)) || 0; + const ipUsed = ipHash ? (Number(await storage.get(`q:ip:${day}:${ipHash}`)) || 0) : 0; + const full = await storage.get('full:' + device); + return { deviceUsed, ipUsed, unlocked: !!full?.login, login: full?.login || '' }; +} + +function statusBody(counts, { oauth = false, discord = false, day, charged = 0 } = {}) { + const view = quotaView({ ...counts, limit: DAILY_LIMIT }); + return { + ...view, + day, + login: counts.login || null, + unlocked: view.tier === 'full', + oauth: !!oauth, + discord: !!discord, + exempt: !!counts.exempt, + discordInvite: DISCORD.invite, + charged, + repo: REPO.url, + }; +} + +async function rememberUnlock(storage, device, login, name = '') { + const account = String(login || '').slice(0, 80).toLowerCase(); + if (!account) return { ok: false, reason: 'invalid' }; + const key = 'stardev:' + account; + const existing = await storage.get(key); + const devices = Array.isArray(existing) ? [...existing] : []; + if (!devices.includes(device)) { + if (devices.length >= MAX_DEVICES_PER_LOGIN) return { ok: false, reason: 'device-cap' }; + devices.push(device); + } + const display = String(name || login).slice(0, 80); + await storage.put({ + [key]: devices.slice(0, MAX_DEVICES_PER_LOGIN), + ['full:' + device]: { login: display, account, at: Date.now() }, + }); + return { ok: true, login: display }; +} + +function secretsOf(request) { + return { + token: request.headers.get('X-Github-Token') || '', + clientId: request.headers.get('X-Github-Client-Id') || '', + clientSecret: request.headers.get('X-Github-Client-Secret') || '', + unlockSecret: request.headers.get('X-Unlock-Secret') || request.headers.get('X-Github-Client-Secret') || request.headers.get('X-Discord-Client-Secret') || '', + publicOrigin: request.headers.get('X-Public-Origin') || '', + discordId: request.headers.get('X-Discord-Client-Id') || '', + discordSecret: request.headers.get('X-Discord-Client-Secret') || '', + discordGuild: request.headers.get('X-Discord-Guild') || '', + }; +} + +function oauthEnabled(secrets) { + return !!(secrets.clientId && secrets.clientSecret && secrets.unlockSecret); +} + +function discordEnabled(secrets) { + return !!(secrets.discordId && secrets.discordSecret && secrets.unlockSecret); +} + +function flagsFor(secrets) { + return { oauth: oauthEnabled(secrets), discord: discordEnabled(secrets) }; +} + +async function markOwner(storage, device, proof, origin, now, household = '') { + if (!validDevice(device)) return false; + const house = /^[a-f0-9]{32}$/.test(household) ? household : ''; + if (await storage.get('own:' + device)) { + if (house && isOwnerProof(proof, { origin, now })) await storage.put({ ['house:' + house]: now }); + return true; + } + if (house && await storage.get('house:' + house)) { + await storage.put({ ['own:' + device]: now }); + return true; + } + if (!isOwnerProof(proof, { origin, now })) return false; + const put = { ['own:' + device]: now }; + if (house) put['house:' + house] = now; + await storage.put(put); + return true; +} + +function ownerRequest(request) { + const household = request.headers.get('X-Spotplus-Household') || ''; + return { + proof: request.headers.get('X-Spotplus-Owner') || '', + origin: request.headers.get('X-App-Origin') || request.headers.get('Origin') || '', + household: /^[a-f0-9]{32}$/.test(household) ? household : '', + }; +} + +async function touchSeen(storage, device, now) { + if (!validDevice(device)) return 0; + const key = 'seen:' + device; + const prev = Number(await storage.get(key)) || 0; + if (!prev) await storage.put({ [key]: now }); + return prev || now; +} + +export async function handleAccess(request, { storage, fetcher = fetch, now = Date.now() } = {}) { + if (!storage?.get || !storage?.put) return json({ error: 'Access limits are not set up' }, 503); + const clock = typeof now === 'function' ? now() : now; + const url = new URL(request.url); + const secrets = secretsOf(request); + const ipHash = /^[a-f0-9]{8,64}$/.test(request.headers.get('X-Client') || '') ? request.headers.get('X-Client') : ''; + const day = utcDay(clock); + const signal = fetcher === fetch && typeof AbortSignal !== 'undefined' && AbortSignal.timeout ? AbortSignal.timeout(8000) : undefined; + + if (url.pathname === '/access/github/start') return startGithub(url, secrets, clock); + if (url.pathname === '/access/github/callback') return finishGithub(url, secrets, storage, fetcher, clock, signal, day); + if (url.pathname === '/access/discord/start') return startDiscord(url, secrets, clock); + if (url.pathname === '/access/discord/callback') return finishDiscord(url, secrets, storage, fetcher, clock, signal, day); + if (url.pathname === '/access/refer/code' || url.pathname === '/access/refer/redeem') { + return handleReferral(request, { + storage, now: clock, ipHash, hash: shortHash, + unlock: (referrer, account, label) => mutate(storage, (txn) => rememberUnlock(txn, referrer, account, label)), + ownerProof: ownerRequest(request).proof, + origin: ownerRequest(request).origin, + household: ownerRequest(request).household, + }); + } + + await rollQuotaDay(storage, day); + + if (url.pathname === '/access/verify') { + if (request.method !== 'POST') return json({ error: 'Use POST' }, 405); + const body = await request.json().catch(() => ({})); + const device = String(body.device || ''); + if (!validDevice(device)) return json({ ok: false, reason: 'invalid' }, 400); + const found = await findStar(body.username, fetcher, { token: secrets.token, signal }); + if (!found.ok) return json({ ok: false, reason: found.reason, login: found.login || null }, found.reason === 'rate-limited' ? 429 : 200); + const saved = await mutate(storage, (txn) => rememberUnlock(txn, device, found.login)); + if (!saved.ok) return json({ ok: false, reason: saved.reason, login: found.login }, 200); + const counts = await readCounts(storage, day, device, ipHash); + return json({ ok: true, ...statusBody({ ...counts, unlocked: true, login: found.login }, { ...flagsFor(secrets), day }) }); + } + + if (url.pathname !== '/access') return json({ error: 'Not found' }, 404); + + if (request.method === 'GET') { + const device = url.searchParams.get('device') || ''; + if (!validDevice(device)) return json({ error: 'bad device' }, 400); + await touchSeen(storage, device, clock); + const owner = ownerRequest(request); + const exempt = await markOwner(storage, device, owner.proof, owner.origin, clock, owner.household); + const counts = await readCounts(storage, day, device, ipHash); + if (exempt) { counts.unlocked = true; counts.exempt = true; } + return json(statusBody(counts, { ...flagsFor(secrets), day })); + } + + if (request.method !== 'POST') return json({ error: 'Use GET or POST' }, 405); + const body = await request.json().catch(() => ({})); + const device = String(body.device || ''); + if (!validDevice(device)) return json({ error: 'bad device' }, 400); + await touchSeen(storage, device, clock); + const owner = ownerRequest(request); + if (await markOwner(storage, device, owner.proof, owner.origin, clock, owner.household)) { + const counts = await readCounts(storage, day, device, ipHash); + counts.unlocked = true; + counts.exempt = true; + return json(statusBody(counts, { ...flagsFor(secrets), day, charged: 0 })); + } + const action = String(body.action || 'status'); + if (action !== 'status' && !isKnownAction(action)) return json({ error: 'bad action' }, 400); + const n = action === 'status' ? 0 : Math.max(1, Math.min(DAILY_LIMIT, Math.floor(Number(body.n) || 1))); + const nonce = validNonce(body.nonce) ? String(body.nonce) : ''; + + const result = await mutate(storage, async (txn) => { + if (nonce) { + const seen = await txn.get(`nonce:${day}:${device}:${nonce}`); + if (seen) { + const counts = await readCounts(txn, day, device, ipHash); + return statusBody(counts, { ...flagsFor(secrets), day, charged: 0 }); + } + } + const counts = await readCounts(txn, day, device, ipHash); + if (n === 0 || counts.unlocked) { + if (nonce) await txn.put({ [`nonce:${day}:${device}:${nonce}`]: 1 }); + return statusBody(counts, { ...flagsFor(secrets), day, charged: 0 }); + } + const next = addUsage({ ...counts, trackIp: !!ipHash }, n); + const put = { + ['q:d:' + day + ':' + device]: next.deviceUsed, + }; + if (ipHash) put['q:ip:' + day + ':' + ipHash] = next.ipUsed; + if (nonce) put[`nonce:${day}:${device}:${nonce}`] = 1; + await txn.put(put); + return statusBody({ ...counts, deviceUsed: next.deviceUsed, ipUsed: next.ipUsed }, { ...flagsFor(secrets), day, charged: next.charged }); + }); + return json(result); +} + +async function startGithub(url, secrets, now) { + if (!oauthEnabled(secrets) || !/^https?:\/\//.test(secrets.publicOrigin)) return json({ error: 'oauth-not-configured' }, 404); + const device = url.searchParams.get('device') || ''; + if (!validDevice(device)) return json({ error: 'bad device' }, 400); + const returnTo = returnTarget(url.searchParams.get('return') || ''); + const state = await sealState({ device, returnTo, exp: now + STATE_TTL_MS }, secrets.unlockSecret); + const redirectUri = secrets.publicOrigin.replace(/\/$/, '') + '/access/github/callback'; + const auth = new URL('https://github.com/login/oauth/authorize'); + auth.searchParams.set('client_id', secrets.clientId); + auth.searchParams.set('redirect_uri', redirectUri); + auth.searchParams.set('state', state); + auth.searchParams.set('allow_signup', 'true'); + return Response.redirect(auth.href, 302); +} + +async function finishGithub(url, secrets, storage, fetcher, now, signal, day) { + if (!oauthEnabled(secrets) || !/^https?:\/\//.test(secrets.publicOrigin)) return json({ error: 'oauth-not-configured' }, 404); + const back = (reason, returnTo) => { + const dest = new URL(returnTarget(returnTo)); + dest.searchParams.set('star', reason); + return Response.redirect(dest.href, 302); + }; + if (url.searchParams.get('error')) return back('denied', ''); + const opened = await openState(url.searchParams.get('state') || '', secrets.unlockSecret, now); + if (!opened) return back('invalid', ''); + const code = url.searchParams.get('code') || ''; + if (!code || code.length > 200) return back('invalid', opened.returnTo); + const redirectUri = secrets.publicOrigin.replace(/\/$/, '') + '/access/github/callback'; + let tokenRes; + try { + tokenRes = await fetcher('https://github.com/login/oauth/access_token', { + method: 'POST', + headers: { Accept: 'application/json', 'User-Agent': 'SpotPlus (https://coye2.github.io/spot-plus/)' }, + body: new URLSearchParams({ + client_id: secrets.clientId, + client_secret: secrets.clientSecret, + code, + redirect_uri: redirectUri, + }), + signal, + }); + } catch { + return back('unavailable', opened.returnTo); + } + let tokenBody = {}; + try { tokenBody = await readJsonLimited(tokenRes, 20000); } catch { return back('unavailable', opened.returnTo); } + if (!tokenRes.ok || !tokenBody.access_token) return back('unavailable', opened.returnTo); + const starred = await viewerStarred(tokenBody.access_token, fetcher, { signal }); + if (!starred.ok) return back(starred.reason || 'unavailable', opened.returnTo); + await rollQuotaDay(storage, day); + const saved = await mutate(storage, (txn) => rememberUnlock(txn, opened.device, starred.login)); + if (!saved.ok) return back(saved.reason, opened.returnTo); + return back('ok', opened.returnTo); +} + +async function startDiscord(url, secrets, now) { + if (!discordEnabled(secrets) || !/^https?:\/\//.test(secrets.publicOrigin)) return json({ error: 'oauth-not-configured' }, 404); + const device = url.searchParams.get('device') || ''; + if (!validDevice(device)) return json({ error: 'bad device' }, 400); + const returnTo = returnTarget(url.searchParams.get('return') || ''); + const state = await sealState({ device, returnTo, exp: now + STATE_TTL_MS, kind: 'discord' }, secrets.unlockSecret); + const redirectUri = secrets.publicOrigin.replace(/\/$/, '') + '/access/discord/callback'; + const auth = new URL('https://discord.com/oauth2/authorize'); + auth.searchParams.set('client_id', secrets.discordId); + auth.searchParams.set('redirect_uri', redirectUri); + auth.searchParams.set('response_type', 'code'); + auth.searchParams.set('scope', 'identify guilds'); + auth.searchParams.set('state', state); + auth.searchParams.set('prompt', 'consent'); + return Response.redirect(auth.href, 302); +} + +async function finishDiscord(url, secrets, storage, fetcher, now, signal, day) { + if (!discordEnabled(secrets) || !/^https?:\/\//.test(secrets.publicOrigin)) return json({ error: 'oauth-not-configured' }, 404); + const back = (reason, returnTo) => { + const dest = new URL(returnTarget(returnTo)); + dest.searchParams.set('support', reason); + return Response.redirect(dest.href, 302); + }; + if (url.searchParams.get('error')) return back('denied', ''); + const opened = await openState(url.searchParams.get('state') || '', secrets.unlockSecret, now); + if (!opened) return back('invalid', ''); + const code = url.searchParams.get('code') || ''; + if (!code || code.length > 200) return back('invalid', opened.returnTo); + const redirectUri = secrets.publicOrigin.replace(/\/$/, '') + '/access/discord/callback'; + let tokenRes; + try { + tokenRes = await fetcher('https://discord.com/api/oauth2/token', { + method: 'POST', + headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'SpotPlus (https://coye2.github.io/spot-plus/)' }, + body: new URLSearchParams({ + client_id: secrets.discordId, + client_secret: secrets.discordSecret, + grant_type: 'authorization_code', + code, + redirect_uri: redirectUri, + }), + signal, + }); + } catch { + return back('unavailable', opened.returnTo); + } + let tokenBody = {}; + try { tokenBody = await readJsonLimited(tokenRes, 20000); } catch { return back('unavailable', opened.returnTo); } + if (!tokenRes.ok || !tokenBody.access_token) return back('unavailable', opened.returnTo); + const headers = { Accept: 'application/json', Authorization: 'Bearer ' + tokenBody.access_token, 'User-Agent': 'SpotPlus (https://coye2.github.io/spot-plus/)' }; + let userRes; + let guildRes; + try { + userRes = await fetcher('https://discord.com/api/users/@me', { headers, signal }); + guildRes = await fetcher('https://discord.com/api/users/@me/guilds', { headers, signal }); + } catch { + return back('unavailable', opened.returnTo); + } + if (!userRes.ok || !guildRes.ok) return back(userRes.status === 429 || guildRes.status === 429 ? 'rate-limited' : 'unavailable', opened.returnTo); + let user; + let guilds; + try { + user = await readJsonLimited(userRes, 100000); + guilds = await readJsonLimited(guildRes, 400000); + } catch { + return back('unavailable', opened.returnTo); + } + let guildId = ''; + try { guildId = await discordGuildId(storage, fetcher, secrets.discordGuild, signal); } catch { guildId = ''; } + if (!guildId) return back('unavailable', opened.returnTo); + if (!isGuildMember(guilds, guildId)) return back('not-member', opened.returnTo); + const login = 'discord:' + String(user.id || ''); + const name = String(user.global_name || user.username || 'Discord').slice(0, 40); + if (!/^\d{5,25}$/.test(String(user.id || ''))) return back('invalid', opened.returnTo); + await rollQuotaDay(storage, day); + const saved = await mutate(storage, (txn) => rememberUnlock(txn, opened.device, login, name)); + if (!saved.ok) return back(saved.reason, opened.returnTo); + return back('ok', opened.returnTo); +} + +export async function routeAccess(request, env) { + if (!env?.INSTALLS?.get || !env?.INSTALLS?.idFromName) return json({ error: 'Access limits are not set up' }, 503); + const url = new URL(request.url); + const headers = new Headers(); + headers.set('X-Client', await shortHash(request.headers.get('CF-Connecting-IP') || 'local')); + headers.set('X-Public-Origin', url.origin); + const appOrigin = request.headers.get('Origin') || ''; + if (appOrigin) headers.set('X-App-Origin', appOrigin); + const ownerProofHeader = request.headers.get('X-Spotplus-Owner') || ''; + if (ownerProofHeader && ownerProofHeader.length <= 600) headers.set('X-Spotplus-Owner', ownerProofHeader); + const household = request.headers.get('X-Spotplus-Household') || ''; + if (/^[a-f0-9]{32}$/.test(household)) headers.set('X-Spotplus-Household', household); + if (env.GITHUB_TOKEN) headers.set('X-Github-Token', String(env.GITHUB_TOKEN)); + if (env.GITHUB_CLIENT_ID) headers.set('X-Github-Client-Id', String(env.GITHUB_CLIENT_ID)); + if (env.GITHUB_CLIENT_SECRET) headers.set('X-Github-Client-Secret', String(env.GITHUB_CLIENT_SECRET)); + if (env.DISCORD_CLIENT_ID) headers.set('X-Discord-Client-Id', String(env.DISCORD_CLIENT_ID)); + if (env.DISCORD_CLIENT_SECRET) headers.set('X-Discord-Client-Secret', String(env.DISCORD_CLIENT_SECRET)); + if (env.DISCORD_GUILD_ID) headers.set('X-Discord-Guild', String(env.DISCORD_GUILD_ID)); + const secret = env.UNLOCK_SECRET || env.GITHUB_CLIENT_SECRET || env.DISCORD_CLIENT_SECRET || ''; + if (secret) headers.set('X-Unlock-Secret', String(secret)); + const stub = env.INSTALLS.get(env.INSTALLS.idFromName('global')); + const init = { method: request.method, headers }; + if (request.method !== 'GET' && request.method !== 'HEAD') init.body = (await request.text()).slice(0, 4500); + const res = await stub.fetch('https://counter' + url.pathname + url.search, init); + const location = res.headers.get('Location'); + if (res.status >= 300 && res.status < 400 && location) { + return new Response(null, { status: res.status, headers: { Location: location, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' } }); + } + return new Response(await res.text(), { status: res.status, headers: HEADERS }); +} diff --git a/canvas-bridge/installs.js b/canvas-bridge/installs.js index ee178a4..eb845ff 100644 --- a/canvas-bridge/installs.js +++ b/canvas-bridge/installs.js @@ -1,11 +1,15 @@ // Live counters for Spot+: total installs (one per device, stored for good) and people listening // right now (players check in while music plays; kept in memory, counted over the last ~3 minutes). +import { handleAccess } from './access.js'; const LIVE_WINDOW = 540_000; // listeners check in every 4 minutes export class InstallCounter { constructor(state) { this.state = state; this.live = new Map(); this.ipDay = new Map(); } liveCount(now = Date.now()) { for (const [id, at] of this.live) if (now - at > LIVE_WINDOW) this.live.delete(id); return this.live.size; } async fetch(request) { const url = new URL(request.url), now = Date.now(); + if (url.pathname === '/access' || url.pathname.startsWith('/access/')) { + return handleAccess(request, { storage: this.state.storage, fetcher: this.fetcher || fetch, now: this.now || now }); + } const installs = async () => (await this.state.storage.get('installs')) || 0; if (request.method === 'POST') { const body = await request.json().catch(() => ({})); diff --git a/canvas-bridge/referral.js b/canvas-bridge/referral.js new file mode 100644 index 0000000..89084dc --- /dev/null +++ b/canvas-bridge/referral.js @@ -0,0 +1,156 @@ +// Friend-install unlock. The code is created by one device and redeemed by a +// later, different install. The 60s hold is a real open app, not a single request. +import { DISCORD } from '../js/access-policy.js'; +import { isOwnerProof } from '../js/maintenance.js'; +import { + CODE_ALPHABET, HOLD_MS, browserKey, hardwareKey, isGuildMember, judgeReferral, normalizeCode, platformFamily, screenBucket, +} from '../js/referral.js'; + +const HEADERS = { + 'Content-Type': 'application/json; charset=utf-8', + 'Cache-Control': 'no-store', + 'X-Content-Type-Options': 'nosniff', +}; +const json = (data, status = 200) => new Response(JSON.stringify(data), { status, headers: HEADERS }); + +function validDevice(id) { + return /^[a-f0-9]{32}$/.test(String(id || '')); +} + +function newCode() { + const bytes = new Uint8Array(8); + crypto.getRandomValues(bytes); + return [...bytes].map((b) => CODE_ALPHABET[b % CODE_ALPHABET.length]).join(''); +} + +function hexId(size = 8) { + const bytes = new Uint8Array(size); + crypto.getRandomValues(bytes); + return [...bytes].map((b) => b.toString(16).padStart(2, '0')).join(''); +} + +function readSignals(body) { + const signals = body?.signals && typeof body.signals === 'object' ? body.signals : {}; + return { + ua: String(signals.ua || '').slice(0, 180), + platform: String(signals.platform || '').slice(0, 40), + timezone: String(signals.timezone || '').slice(0, 64), + language: String(signals.language || '').slice(0, 20), + cores: Number(signals.cores) || 0, + memory: Number(signals.memory) || 0, + touch: Number(signals.touch) || 0, + width: Number(signals.width) || 0, + height: Number(signals.height) || 0, + dpr: Number(signals.dpr) || 1, + color: Number(signals.color) || 0, + }; +} + +async function profileOf(body, ipHash, hash) { + const signals = readSignals(body); + const secret = String(body?.secret || ''); + return { + device: String(body?.device || ''), + secret: /^[a-f0-9]{32}$/.test(secret) ? await hash(secret) : '', + hardware: await hash(hardwareKey(signals)), + browser: await hash(browserKey(signals)), + family: platformFamily(signals.ua, signals.platform), + screen: screenBucket(signals.width, signals.height, signals.dpr), + ip: ipHash || '', + }; +} + +export async function handleReferral(request, ctx) { + if (request.method !== 'POST') return json({ error: 'Use POST' }, 405); + const body = await request.json().catch(() => ({})); + const device = String(body.device || ''); + if (!validDevice(device)) return json({ ok: false, reason: 'invalid' }, 400); + const url = new URL(request.url); + if (url.pathname === '/access/refer/code') return createCode(body, device, ctx); + if (url.pathname === '/access/refer/redeem') return redeemCode(body, device, ctx); + return json({ error: 'Not found' }, 404); +} + +async function createCode(body, device, { storage, now, ipHash, hash }) { + const day = new Date(now).toISOString().slice(0, 10); + const tallyKey = `refday:${day}:${device}`; + const tally = Number(await storage.get(tallyKey)) || 0; + if (tally >= 5) return json({ ok: false, reason: 'rate-limited' }, 429); + const profile = await profileOf(body, ipHash, hash); + let code = ''; + for (let i = 0; i < 5 && !code; i++) { + const next = newCode(); + if (!(await storage.get('ref:' + next))) code = next; + } + if (!code) return json({ ok: false, reason: 'unavailable' }, 503); + const previous = await storage.get('refby:' + device); + const record = { ...profile, created: now, expires: now + 14 * 86400000, used: false }; + const put = { ['ref:' + code]: record, ['refby:' + device]: code, [tallyKey]: tally + 1 }; + if (typeof previous === 'string' && previous !== code) put['ref:' + previous] = { used: true, device: '', expires: 0 }; + await storage.put(put); + return json({ ok: true, code, expires: record.expires }); +} + +async function redeemCode(body, device, ctx) { + const { storage, now, ipHash, hash, unlock } = ctx; + const house = /^[a-f0-9]{32}$/.test(ctx.household || '') ? ctx.household : ''; + if (await storage.get('own:' + device) || (house && await storage.get('house:' + house)) || isOwnerProof(ctx.ownerProof, { origin: ctx.origin, now })) { + return json({ ok: false, reason: 'excluded' }, 200); + } + const code = normalizeCode(body.code); + if (!code) return json({ ok: false, reason: 'invalid' }, 400); + const record = await storage.get('ref:' + code); + if (!record?.device || record.used) return json({ ok: false, reason: record?.used ? 'taken' : 'invalid' }, 200); + if (record.expires && now > record.expires) return json({ ok: false, reason: 'expired' }, 200); + if (await storage.get('friend:' + device)) return json({ ok: false, reason: 'used' }, 200); + const friend = await profileOf(body, ipHash, hash); + const seenKey = 'seen:' + device; + const firstSeen = Number(await storage.get(seenKey)) || 0; + const verdict = judgeReferral({ + referrer: record, + friend, + codeCreatedAt: record.created, + friendFirstSeen: firstSeen, + standalone: body.standalone === true || body.signals?.standalone === true, + }); + if (!verdict.ok) return json({ ok: false, reason: verdict.reason }); + if (!firstSeen) await storage.put({ [seenKey]: now }); + + const holdKey = 'hold:' + device; + const hold = await storage.get(holdKey); + const challenge = String(body.challenge || ''); + if (!hold || hold.code !== code || hold.hardware !== friend.hardware) { + const challengeId = hexId(8); + await storage.put({ [holdKey]: { code, challenge: challengeId, at: now, hardware: friend.hardware } }); + return json({ ok: false, reason: 'hold', waitMs: HOLD_MS, challenge: challengeId }); + } + const waitMs = HOLD_MS - (now - hold.at); + if (challenge !== hold.challenge || waitMs > 0) { + return json({ ok: false, reason: 'hold', waitMs: Math.max(0, waitMs), challenge: hold.challenge }); + } + + const saved = await unlock(record.device, 'friend:' + device, 'a friend'); + if (!saved?.ok) return json({ ok: false, reason: saved?.reason || 'unavailable' }); + await storage.put({ + ['ref:' + code]: { ...record, used: true, friend: device, redeemed: now }, + ['friend:' + device]: code, + }); + return json({ ok: true, reason: 'ok', thanked: true }); +} + +export async function discordGuildId(storage, fetcher, envGuild, signal) { + if (/^\d{5,25}$/.test(String(envGuild || ''))) return String(envGuild); + const cached = await storage.get('discord:guild'); + if (/^\d{5,25}$/.test(String(cached || ''))) return String(cached); + const response = await fetcher(`https://discord.com/api/v10/invites/${DISCORD.code}`, { + headers: { Accept: 'application/json', 'User-Agent': 'SpotPlus (https://coye2.github.io/spot-plus/)' }, + signal, + }); + if (!response.ok) return ''; + const data = await response.json(); + const id = String(data?.guild?.id || ''); + if (/^\d{5,25}$/.test(id)) await storage.put({ 'discord:guild': id }); + return id; +} + +export { isGuildMember }; diff --git a/canvas-bridge/worker.js b/canvas-bridge/worker.js index 0a8a339..c289c5a 100644 --- a/canvas-bridge/worker.js +++ b/canvas-bridge/worker.js @@ -12,6 +12,7 @@ import {youtubeStream} from './youtube-stream.js'; // A narrow public-metadata adapter, never an arbitrary URL or credential proxy. import {spotifyStats} from './spotify-stats.js'; import {spotifyPublic} from './spotify-public.js'; +import {routeAccess} from './access.js'; const SOURCE = 'https://canvas.auramusic.site/api/canvas'; const CORS = {'Access-Control-Allow-Origin':'*','Access-Control-Allow-Methods':'GET, POST, OPTIONS','Content-Type':'application/json; charset=utf-8','X-Content-Type-Options':'nosniff'}; // Lyrics search: Genius's public lyric search, reduced to title, artist and the matching line. @@ -85,6 +86,7 @@ const json = (data,status=200,maxAge=0,swr=0) => new Response(JSON.stringify(dat export async function handle(request, {fetcher=fetch,cache,waitUntil=()=>{},env} = {}) { if (request.method === 'OPTIONS') return new Response(null,{status:204,headers:CORS}); const url = new URL(request.url); + if (url.pathname === '/access' || url.pathname.startsWith('/access/')) return routeAccess(request, env); if (['/stats','/installs','/listening','/rate'].includes(url.pathname) && (request.method === 'GET' ? url.pathname === '/stats' : request.method === 'POST' && url.pathname !== '/stats')) return liveStats(request, env, async text => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode('spotplus:' + text)))].slice(0, 8).map(b => b.toString(16).padStart(2, '0')).join('')); if (request.method !== 'GET' && !(['/yta','/mono'].includes(url.pathname) && request.method === 'HEAD')) return json({error:'Use GET'},405); @@ -99,7 +101,7 @@ export async function handle(request, {fetcher=fetch,cache,waitUntil=()=>{},env} if (url.pathname === '/mono') return monochromeAudio(request,{fetcher}); if (url.pathname === '/stream') return youtubeStream(request,{fetcher,cache,waitUntil}); if (url.pathname === '/spotify-public') return spotifyPublic(request,{fetcher,cache,waitUntil}); - if (url.pathname === '/health') return json({service:'Spot+ Canvas bridge',status:'ok',lyrics:true,spotifyPublic:true,match:true,wallpapers:true,sc:!!(env?.SC_CLIENT_ID&&env?.SC_CLIENT_SECRET),relay:true,relayIntegrity:'v3',mono:true,images:true,stream:true,stats:true,dev:true,podcasts:true}, 200, 30, 60); + if (url.pathname === '/health') return json({service:'Spot+ Canvas bridge',status:'ok',lyrics:true,spotifyPublic:true,match:true,wallpapers:true,sc:!!(env?.SC_CLIENT_ID&&env?.SC_CLIENT_SECRET),relay:true,relayIntegrity:'v3',mono:true,images:true,stream:true,stats:true,dev:true,podcasts:true,access:true}, 200, 30, 60); if (url.pathname === '/lyrics-search') return lyricsSearch(url,{fetcher,cache,waitUntil}); if (url.pathname !== '/canvas') return json({error:'Not found'},404); const query = queryFor(url.searchParams); diff --git a/css/polish.css b/css/polish.css index ebd69ba..6741a43 100644 --- a/css/polish.css +++ b/css/polish.css @@ -474,3 +474,24 @@ html[data-maintenance="1"] .maint-screen{display:flex!important} .maint-error{margin:8px 0 0;font-size:12px;color:#ff8a8a} @media (prefers-reduced-motion:reduce){.maint-eq i{animation:none}} +.access-banner{position:fixed;z-index:35;left:12px;right:12px;bottom:calc(var(--nav-h, 64px) + var(--bar-h, 64px) + var(--sb, 0px) + 10px);display:flex;align-items:center;justify-content:space-between;gap:12px;padding:10px 12px;border-radius:14px;background:var(--bg2);color:var(--text);border:1px solid var(--line);box-shadow:0 10px 30px rgba(0,0,0,.35)} +.access-banner[hidden]{display:none} +.access-banner p{margin:0;font-size:13px;font-weight:650} +.access-dlg{width:min(440px,calc(100vw - 28px));max-height:min(92dvh,760px);overflow:auto} +.access-way{margin:0 0 14px;padding-top:4px} +.access-way h4{margin:0 0 8px;font-size:15px} +.access-way .btn{margin:0 8px 8px 0} +.access-code{margin:0 0 10px;font-size:28px;font-weight:800;letter-spacing:.18em} +.access-hold{margin:0 0 8px;font-size:13px;line-height:1.4} +.access-kicker{margin:0 0 6px;font-size:11px;font-weight:750;letter-spacing:.12em;text-transform:uppercase;color:var(--accent,#1ed760)} +.access-dlg h3{margin:0 0 8px;font-size:22px;letter-spacing:-.03em} +.access-copy,.access-help,.access-fine{margin:0 0 12px;font-size:14px;line-height:1.45;color:var(--muted)} +.access-fine{font-size:12px;margin:12px 0 0} +.access-star{display:flex;justify-content:center;margin:4px 0 12px} +.access-login{display:block;font-size:13px;font-weight:650;margin:0 0 8px} +.access-login input{display:block;width:100%;margin-top:6px;font-weight:500} +.access-error{margin:0 0 8px;font-size:13px;line-height:1.4;color:#ff8a8a} +.access-oauth{width:100%;margin-top:8px} +html[data-access="limited"] [data-act="next"],html[data-access="limited"] [data-act="prev"]{opacity:.45} +@media (min-width:900px){.access-banner{left:50%;right:auto;transform:translateX(-50%);width:min(560px,calc(100vw - 48px));bottom:calc(var(--bar-h, 84px) + 16px)}} + diff --git a/js/access-policy.js b/js/access-policy.js new file mode 100644 index 0000000..f7c7228 --- /dev/null +++ b/js/access-policy.js @@ -0,0 +1,80 @@ +// Base-tier allowance shared by skips, Insta Play, and Insta Choose. +// The cap is enforced twice: once for the device and once for the network address. +// Full access (a verified GitHub star) is not capped. + +export const DAILY_LIMIT = 300; +export const ACTIONS = Object.freeze(['skip', 'insta-play', 'insta-choose']); +export const RESTRICTED_FEATURES = Object.freeze([ + 'skip', 'insta-play', 'insta-choose', 'seek', 'download', 'repeat', 'canvas', 'preload', +]); +export const REPO = Object.freeze({ + owner: 'coye2', + name: 'spot-plus', + full: 'coye2/spot-plus', + url: 'https://github.com/coye2/spot-plus', +}); +export const DISCORD = Object.freeze({ + code: 'DbhTQD7jW', + invite: 'https://discord.gg/DbhTQD7jW', +}); +export const MAX_DEVICES_PER_LOGIN = 3; +export const ACTION_LABELS = Object.freeze({ + skip: 'Skip', + 'insta-play': 'Insta Play', + 'insta-choose': 'Insta Choose', + seek: 'Seeking', + download: 'Downloads', + repeat: 'Repeat', + canvas: 'Canvas', + preload: 'Early loading of the next song', +}); + +export function utcDay(now = Date.now()) { + return new Date(now).toISOString().slice(0, 10); +} + +/** GitHub usernames: 1–39 chars, alphanumeric or hyphen, no leading or trailing hyphen. */ +export function normalizeLogin(input) { + const login = String(input || '').trim().replace(/^@+/, ''); + if (!/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/.test(login)) return ''; + return login; +} + +export function quotaView({ deviceUsed = 0, ipUsed = 0, unlocked = false, limit = DAILY_LIMIT } = {}) { + const device = clampCount(deviceUsed, limit); + const ip = clampCount(ipUsed, limit); + const used = Math.max(device, ip); + if (unlocked) { + return { tier: 'full', limited: false, remaining: null, allowed: true, deviceUsed: device, ipUsed: ip, limit, used }; + } + const remaining = Math.max(0, limit - used); + const limited = used >= limit; + return { tier: 'base', limited, remaining, allowed: !limited, deviceUsed: device, ipUsed: ip, limit, used }; +} + +function clampCount(value, limit) { + const n = Math.floor(Number(value) || 0); + if (n < 0) return 0; + return Math.min(limit, n); +} + +/** + * Add `n` combined actions to both buckets. + * A request is refused once either bucket is already at the limit, so clearing + * site data (new device id, same network) or switching networks (same device) + * does not mint a fresh allowance. + */ +export function addUsage({ deviceUsed = 0, ipUsed = 0, unlocked = false, limit = DAILY_LIMIT, trackIp = true } = {}, n = 1) { + const before = quotaView({ deviceUsed, ipUsed, unlocked, limit }); + const add = Math.floor(Number(n) || 0); + if (unlocked || !before.allowed || add <= 0) return { ...before, charged: 0 }; + const amount = Math.min(add, limit); + const nextDevice = Math.min(limit, before.deviceUsed + amount); + const nextIp = trackIp ? Math.min(limit, before.ipUsed + amount) : before.ipUsed; + const changed = nextDevice !== before.deviceUsed || nextIp !== before.ipUsed; + return { ...quotaView({ deviceUsed: nextDevice, ipUsed: nextIp, unlocked: false, limit }), charged: changed ? amount : 0 }; +} + +export function isKnownAction(action) { + return ACTIONS.includes(action); +} diff --git a/js/access-ui.js b/js/access-ui.js new file mode 100644 index 0000000..e63c07e --- /dev/null +++ b/js/access-ui.js @@ -0,0 +1,228 @@ +// Spot+ is free, powered by love and support. Full access is a star, a Discord +// membership, or a friend who installs Spot+ — each one checked, not a button. +import { ACTION_LABELS, DAILY_LIMIT, DISCORD, REPO } from './access-policy.js'; +import { + createReferral, discordStartUrl, githubStartUrl, isFeatureRestricted, onAccessBlocked, onAccessChange, + onAccessNotice, redeemReferral, refreshAccess, snapshot, startAccessSync, verifyUsername, consumeStarQuery, +} from './access.js'; + +const REASONS = { + 'not-starred': 'That GitHub account has no public star on ' + REPO.full + ' yet. Star the repo, then verify again.', + 'not-found': 'No GitHub account uses that username.', + invalid: 'That code or username doesn’t check out. Use the 8-character friend code, or the GitHub username that starred the repo.', + 'rate-limited': 'Too many checks right now. Wait a few minutes and try again.', + unavailable: 'Spot+ couldn’t finish that check. Try again in a moment.', + incomplete: 'Star the repo again so it is the most recent star, then verify.', + 'device-cap': 'That support account already unlocked 3 devices.', + denied: 'Sign-in was cancelled before Spot+ could check.', + 'not-member': 'That Discord account isn’t in the Spot+ server yet. Join, then verify again.', + install: 'Install Spot+ to the home screen or desktop first, then enter the code from the installed app.', + self: 'This device made the code. A different person’s install has to enter it.', + 'not-new': 'This install was already using Spot+ before the code was created.', + 'same-device': 'This looks like the same phone or computer — another browser, profile, or VPN still matches. Ask someone on their own device.', + 'same-browser': 'This browser matches the device that made the code.', + 'same-network': 'This device is on the same network and looks too close to the one that made the code.', + taken: 'That code was already used.', + used: 'This install already supported someone.', + excluded: 'This device is excluded. A friend’s own install has to enter the code.', + expired: 'That code expired. Ask for a new one.', + hold: 'Keep the installed app open. Spot+ is making sure this is a real install.', + ok: '', +}; + +let toastFn = () => {}; +let onChange = () => {}; +let dialog; +let openedAt = 0; +let poll = 0; +let holdTimer = 0; + +function esc(s) { + return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); +} + +function whoLine(login) { + if (!login || login === 'a friend') return 'Full access is unlocked on this device, thanks to a friend who installed Spot+.'; + return `Full access is unlocked on this device for @${esc(login)}.`; +} + +export function accessSettingsHtml() { + const s = snapshot(); + if (s.tier === 'full') { + const note = s.exempt && !s.login + ? 'This device is one of yours, so it is excluded from the daily allowance.' + : whoLine(s.login) + ' Skips, Insta Play, and Insta Choose are unlimited here.'; + return `

Support

Spot+ is free, powered by love and support. ${note}

+
`; + } + const left = s.remaining == null ? DAILY_LIMIT : s.remaining; + const network = s.ipUsed > s.deviceUsed ? ' This network has used more of today’s allowance than this device.' : ''; + return `

Support

+

Spot+ is free, powered by love and support. The base tier includes ${DAILY_LIMIT} skips, Insta Plays, and Insta Chooses a day, counted on this device and on this network.${network}

+

${left} left today${s.limited ? '. Extra controls pause until tomorrow, or until you support the project.' : '. Star the repo, join the Discord, or invite a friend to install Spot+ for full access.'}

+
+
`; +} + +function ensureDialog() { + if (dialog?.isConnected) return dialog; + dialog = document.createElement('dialog'); + dialog.id = 'accessDlg'; + dialog.className = 'access-dlg'; + dialog.innerHTML = `
+

Free, powered by support

+

Support Spot+

+

+
+

Star the repo

+ Star ${esc(REPO.full)} + + + +
+
+

No GitHub? Add support another way

+

Join the Discord server, or refer a friend. They install Spot+ and enter your code. Spot+ compares the two installs, so another browser, phone, or VPN on this device does not count.

+ Join the Discord + + + + + + +
+ +
+

Spot+ checks the star with GitHub, the Discord membership with Discord sign-in, and the friend code against the new install. A button press alone does not unlock the app.

+
`; + document.body.append(dialog); + dialog.querySelector('#accessLater').addEventListener('click', () => dialog.close()); + dialog.querySelector('#accessVerify').addEventListener('click', () => submitVerify(dialog.querySelector('input[name="login"]').value)); + dialog.querySelector('#accessOauth').addEventListener('click', () => { location.href = githubStartUrl(location.href); }); + dialog.querySelector('#accessDiscord').addEventListener('click', () => { location.href = discordStartUrl(location.href); }); + dialog.querySelector('#accessCode').addEventListener('click', () => makeCode()); + dialog.querySelector('#accessRedeem').addEventListener('click', () => submitRedeem(dialog.querySelector('input[name="friend"]').value)); + dialog.addEventListener('close', () => { clearInterval(poll); clearTimeout(holdTimer); }); + return dialog; +} + +function setError(message) { + const el = dialog?.querySelector('#accessError'); + if (!el) return; + el.hidden = !message; + el.textContent = message || ''; +} + +function celebrate(login) { + dialog?.close(); + const who = login && login !== 'a friend' ? ' for @' + login : ''; + toastFn('Full access unlocked' + who + '. Thank you for supporting Spot+.'); + onChange(snapshot()); +} + +export function openAccessPrompt({ feature = '', error = '' } = {}) { + const s = snapshot(); + if (s.tier === 'full') return; + const dlg = ensureDialog(); + const limited = s.limited; + dlg.querySelector('#accessTitle').textContent = limited ? 'Today’s allowance is used' : 'Support Spot+'; + const featureName = ACTION_LABELS[feature] || ''; + const paused = 'The song already playing can finish, and the queue can still move on. Skips, Insta Play, Insta Choose, seeking, new downloads, repeat, and Canvas wait until tomorrow.'; + dlg.querySelector('#accessCopy').textContent = limited + ? `Spot+ is free, powered by love and support. This device and this network have shared today’s ${DAILY_LIMIT} skips, Insta Plays, and Insta Chooses.${featureName ? ' ' + featureName + ' is paused.' : ''} ${paused}` + : `Spot+ is free. Star the GitHub repo, join the Discord, or invite a friend to install it, and the daily cap comes off this device.`; + dlg.querySelector('#accessOauth').hidden = !s.oauth; + dlg.querySelector('#accessDiscord').hidden = !s.discord; + setError(error); + if (!dlg.open) dlg.showModal(); + openedAt = Date.now(); +} + +async function submitVerify(login) { + const button = dialog.querySelector('#accessVerify'); + button.disabled = true; + button.textContent = 'Checking GitHub…'; + setError(''); + const result = await verifyUsername(login); + button.disabled = false; + button.textContent = 'Verify star'; + if (result?.ok) { celebrate(result.login); return; } + setError(REASONS[result?.reason] || REASONS.unavailable); +} + +async function makeCode() { + const button = dialog.querySelector('#accessCode'); + const out = dialog.querySelector('#accessCodeOut'); + button.disabled = true; + setError(''); + const result = await createReferral(); + button.disabled = false; + if (!result?.ok || !result.code) { setError(REASONS[result?.reason] || REASONS.unavailable); return; } + out.hidden = false; + out.textContent = result.code; + try { await navigator.clipboard.writeText(result.code); toastFn('Friend code copied. They install Spot+ and enter it.'); } catch { toastFn('Friend code ready. They install Spot+ and enter ' + result.code + '.'); } + clearInterval(poll); + poll = setInterval(async () => { + const snap = await refreshAccess(); + if (snap?.tier === 'full') celebrate(snap.login); + }, 8000); +} + +async function submitRedeem(code, challenge = '') { + const button = dialog.querySelector('#accessRedeem'); + const hold = dialog.querySelector('#accessHold'); + button.disabled = true; + setError(''); + const result = await redeemReferral(code, challenge); + if (result?.reason === 'hold') { + const wait = Math.max(1000, Number(result.waitMs) || 60000); + hold.hidden = false; + hold.textContent = REASONS.hold; + clearTimeout(holdTimer); + holdTimer = setTimeout(() => submitRedeem(code, result.challenge || challenge), wait); + return; + } + button.disabled = false; + hold.hidden = true; + if (result?.ok) { + dialog.close(); + toastFn('Thank you. Your friend’s Spot+ unlocks the next time they open it.'); + return; + } + setError(REASONS[result?.reason] || REASONS.unavailable); +} + +function syncBanner(snap = snapshot()) { + let banner = document.getElementById('accessBanner'); + if (!banner) { + banner = document.createElement('div'); + banner.id = 'accessBanner'; + banner.className = 'access-banner'; + banner.hidden = true; + banner.innerHTML = '

Spot+ is free, powered by love and support.

'; + document.body.append(banner); + } + const limited = snap.tier !== 'full' && snap.limited; + banner.hidden = !limited; + document.documentElement.dataset.access = snap.tier === 'full' ? 'full' : limited ? 'limited' : 'base'; +} + +export function startAccess({ toast = () => {}, onChange: change = () => {} } = {}) { + toastFn = toast; + onChange = change; + onAccessChange((snap) => { syncBanner(snap); change(snap); }); + onAccessBlocked((info) => { + if (Date.now() - openedAt < 1200 && dialog?.open) return; + openAccessPrompt({ feature: info.feature }); + }); + onAccessNotice((info) => { if (info.notice) toastFn(info.notice); }); + const star = consumeStarQuery(); + startAccessSync().then((snap) => { + syncBanner(snap); + if (star === 'ok' && snap?.tier === 'full') toastFn('Full access unlocked' + (snap.login ? ' for @' + snap.login : '') + '. Thank you for supporting Spot+.'); + else if (star && star !== 'ok') openAccessPrompt({ error: REASONS[star] || REASONS.unavailable }); + }); + syncBanner(); +} + +export { isFeatureRestricted, openAccessPrompt as showAccessPrompt }; diff --git a/js/access.js b/js/access.js new file mode 100644 index 0000000..8dc7df3 --- /dev/null +++ b/js/access.js @@ -0,0 +1,411 @@ +// Device-side copy of the base-tier allowance. The bridge is the source of truth +// for the network-address counter; this ledger keeps the app honest while offline +// and between those checks. Playback calls allowPlaybackAction / allowRestricted. +import { STATS_URL, deviceId } from './live-stats.js'; +import { DEV_ACCESS_STORAGE_KEY, DEV_ACCOUNT_CACHE_KEY, isAllowedSpotifyId, sha256Hex, verifySessionToken } from './maintenance.js'; +import * as store from './store.js'; +import { installSecret, signalsFromHere } from './referral.js'; +import { + ACTIONS, DAILY_LIMIT, RESTRICTED_FEATURES, addUsage, isKnownAction, quotaView, utcDay, +} from './access-policy.js'; + +const KEY = 'spotplus.access.v1'; +const WARN_AT = [50, 25, 10]; + +function memoryStorage() { + const values = new Map(); + return { + getItem: (k) => values.has(k) ? values.get(k) : null, + setItem: (k, v) => values.set(k, String(v)), + removeItem: (k) => values.delete(k), + }; +} + +function browserStorage() { + try { + if (globalThis.localStorage?.getItem && globalThis.localStorage?.setItem) return globalThis.localStorage; + } catch { /* private mode */ } + return memoryStorage(); +} + +function fresh(day, keep = {}) { + return { + day, + deviceUsed: 0, + ipUsed: 0, + unlocked: !!keep.unlocked || !!keep.exempt, + exempt: !!keep.exempt, + login: keep.login || '', + oauth: !!keep.oauth, + discord: !!keep.discord, + synced: false, + counts: { skip: 0, 'insta-play': 0, 'insta-choose': 0 }, + warned: [], + pending: null, + }; +} + +function read(storage) { + const day = utcDay(); + try { + const parsed = JSON.parse(storage.getItem(KEY) || ''); + if (!parsed || typeof parsed !== 'object' || parsed.day !== day) { + return fresh(day, parsed?.unlocked || parsed?.exempt ? { unlocked: true, exempt: !!parsed.exempt, login: parsed.login, oauth: parsed.oauth, discord: parsed.discord } : {}); + } + const base = fresh(day); + base.deviceUsed = Math.max(0, Math.floor(Number(parsed.deviceUsed) || 0)); + base.ipUsed = Math.max(0, Math.floor(Number(parsed.ipUsed) || 0)); + base.unlocked = !!parsed.unlocked || !!parsed.exempt; + base.exempt = !!parsed.exempt; + base.login = typeof parsed.login === 'string' ? parsed.login.slice(0, 80) : ''; + base.oauth = !!parsed.oauth; + base.discord = !!parsed.discord; + base.synced = !!parsed.synced; + for (const action of ACTIONS) base.counts[action] = Math.max(0, Math.floor(Number(parsed.counts?.[action]) || 0)); + base.warned = Array.isArray(parsed.warned) ? parsed.warned.filter((n) => WARN_AT.includes(n)) : []; + if (parsed.pending && /^[a-f0-9]{16,32}$/.test(parsed.pending.nonce) && parsed.pending.n > 0) { + base.pending = { nonce: parsed.pending.nonce, n: Math.min(DAILY_LIMIT, Math.floor(parsed.pending.n)), action: parsed.pending.action }; + } + return base; + } catch { + return fresh(day); + } +} + +export function createLedger(storage = browserStorage(), clock = () => Date.now()) { + const today = () => utcDay(clock()); + let state = read(storage); + if (state.day !== today() && state.unlocked) state = fresh(today(), state); + else if (state.day !== today()) state = fresh(today()); + const listeners = new Set(); + const save = () => { + try { storage.setItem(KEY, JSON.stringify(state)); } catch { /* storage full or blocked */ } + }; + const roll = () => { + const day = today(); + if (state.day === day) return; + state = fresh(day, state.unlocked ? state : {}); + save(); + }; + const view = () => { + roll(); + const exempt = !!state.exempt || !!ownerProof(); + const quota = quotaView({ ...state, unlocked: state.unlocked || exempt }); + return { + ...quota, + exempt, + login: state.login || '', + oauth: !!state.oauth, + discord: !!state.discord, + synced: !!state.synced, + counts: { ...state.counts }, + day: state.day, + }; + }; + const emit = () => { + const snap = view(); + for (const fn of listeners) { + try { fn(snap); } catch { /* a listener can't break playback */ } + } + return snap; + }; + return { + snapshot() { return view(); }, + onChange(fn) { listeners.add(fn); return () => listeners.delete(fn); }, + consume(action) { + roll(); + if (!isKnownAction(action)) return { ...view(), allowed: true, notice: '' }; + if (state.unlocked || state.exempt || ownerProof()) return { ...view(), allowed: true, notice: '' }; + const before = quotaView(state); + if (!before.allowed) return { ...view(), allowed: false, notice: '' }; + const next = addUsage(state, 1); + state.deviceUsed = next.deviceUsed; + state.ipUsed = Math.max(state.ipUsed, next.ipUsed); + state.counts[action] = (state.counts[action] || 0) + 1; + if (state.pending) state.pending.n = Math.min(DAILY_LIMIT, state.pending.n + 1); + else state.pending = { nonce: randomNonce(), n: 1, action }; + let notice = ''; + if (next.remaining != null && WARN_AT.includes(next.remaining) && !state.warned.includes(next.remaining)) { + state.warned.push(next.remaining); + notice = next.remaining + ' left today on the base tier. Skips, Insta Play, and Insta Choose share ' + DAILY_LIMIT + '.'; + } + save(); + emit(); + return { ...view(), allowed: true, notice }; + }, + applyServer(data, { authoritative = false } = {}) { + if (!data || typeof data !== 'object') return view(); + const day = typeof data.day === 'string' ? data.day : state.day; + if (day !== state.day) state = fresh(day, data.unlocked ? { unlocked: true, login: data.login } : {}); + state.deviceUsed = Math.max(state.deviceUsed, Math.floor(Number(data.deviceUsed) || 0)); + state.ipUsed = Math.max(state.ipUsed, Math.floor(Number(data.ipUsed) || 0)); + if (data.exempt === true) state.exempt = true; + if (data.unlocked || data.exempt === true) { + state.unlocked = true; + if (typeof data.login === 'string' && data.login) state.login = data.login; + } else if (authoritative) { + state.unlocked = false; + state.exempt = false; + state.login = ''; + } + if (typeof data.oauth === 'boolean') state.oauth = data.oauth; + if (typeof data.discord === 'boolean') state.discord = data.discord; + state.synced = true; + save(); + return emit(); + }, + takePending() { + roll(); + if (!state.pending) return null; + const batch = state.pending; + state.pending = null; + save(); + return batch; + }, + restorePending(batch) { + if (!batch?.nonce) return; + if (state.pending) state.pending.n = Math.min(DAILY_LIMIT, state.pending.n + batch.n); + else state.pending = batch; + save(); + }, + pending() { return state.pending ? { ...state.pending } : null; }, + }; +} + +function spotifyOwnerId() { + try { + return store.getSpotifyAccount()?.account?.id || store.getSpotifyStats()?.account?.id || ''; + } catch { + return ''; + } +} + +/** Proof that this browser is one of the owner's devices. Empty for everyone else. */ +export function ownerProof(storage = globalThis.localStorage, origin = globalThis.location?.origin) { + try { + const token = storage?.getItem?.(DEV_ACCESS_STORAGE_KEY) || ''; + if (token && verifySessionToken(token, { origin })) return token; + const cached = storage?.getItem?.(DEV_ACCOUNT_CACHE_KEY) || ''; + if (cached && verifySessionToken(cached, { origin })) return cached; + } catch { /* private mode */ } + const id = spotifyOwnerId(); + return isAllowedSpotifyId(id) ? String(id) : ''; +} + +/** Devices linked with the same library sync key count as one person's devices. */ +export function householdId(storage = globalThis.localStorage) { + let key = ''; + try { key = storage?.getItem?.('spotplus.syncKey') || ''; } catch { return ''; } + if (!key || key.length < 8 || key.length > 200) return ''; + return sha256Hex('spotplus-house:' + key).slice(0, 32); +} + +function accessHeaders(extra = {}) { + const headers = { ...extra }; + const proof = ownerProof(); + if (proof) headers['X-Spotplus-Owner'] = proof; + const house = householdId(); + if (house) headers['X-Spotplus-Household'] = house; + return headers; +} + +function randomNonce() { + const bytes = new Uint8Array(8); + crypto.getRandomValues(bytes); + return [...bytes].map((b) => b.toString(16).padStart(2, '0')).join(''); +} + +let ledger = null; +function book() { + if (!ledger) ledger = createLedger(browserStorage()); + return ledger; +} + +const blockedListeners = new Set(); +const noticeListeners = new Set(); + +export function snapshot() { return book().snapshot(); } +export function onAccessChange(fn) { return book().onChange(fn); } +export function onAccessBlocked(fn) { blockedListeners.add(fn); return () => blockedListeners.delete(fn); } +export function onAccessNotice(fn) { noticeListeners.add(fn); return () => noticeListeners.delete(fn); } + +function notifyBlocked(info) { + for (const fn of blockedListeners) { + try { fn(info); } catch { /* ignore */ } + } +} +function notifyNotice(info) { + for (const fn of noticeListeners) { + try { fn(info); } catch { /* ignore */ } + } +} + +export function consumeAction(action) { + const result = book().consume(action); + if (result.allowed && isKnownAction(action)) scheduleFlush(); + return result; +} + +export function isFeatureRestricted(feature = '') { + const snap = snapshot(); + if (snap.tier === 'full' || !snap.limited) return false; + if (!feature) return true; + return RESTRICTED_FEATURES.includes(feature); +} + +/** Charge a base-tier action. `system` is for Jam follow and other non-user starts. */ +export function allowPlaybackAction(action) { + if (!action || action === 'system') return true; + const result = consumeAction(action); + if (!result.allowed) { + notifyBlocked({ ...result, feature: action }); + return false; + } + if (result.notice) notifyNotice(result); + return true; +} + +/** User features that turn off only after the daily allowance is spent. */ +export function allowRestricted(feature) { + if (!isFeatureRestricted(feature)) return true; + notifyBlocked({ ...snapshot(), feature, allowed: false, reason: 'limited' }); + return false; +} + +export function applyServerSnapshot(data, opts) { + return book().applyServer(data, opts); +} + +let syncEnabled = false; +let flushTimer = 0; +let flushing = false; + +export function startAccessSync() { + syncEnabled = true; + scheduleFlush(); + return refreshAccess(); +} + +function scheduleFlush() { + if (!syncEnabled) return; + clearTimeout(flushTimer); + flushTimer = setTimeout(() => { flushAccess().catch(() => {}); }, 350); + flushTimer.unref?.(); +} + +export async function flushAccess(fetcher = globalThis.fetch) { + if (flushing || typeof fetcher !== 'function') return null; + const batch = book().takePending(); + if (!batch) return null; + flushing = true; + const device = deviceId(); + try { + if (!device) throw new Error('no device'); + const res = await fetcher(STATS_URL + '/access', { + method: 'POST', + credentials: 'omit', + headers: accessHeaders({ 'Content-Type': 'application/json' }), + body: JSON.stringify({ device, action: batch.action || 'skip', n: batch.n, nonce: batch.nonce }), + }); + const data = await res.json(); + if (!res.ok && !data?.tier) throw new Error('status ' + res.status); + return applyServerSnapshot(data, { authoritative: true }); + } catch { + book().restorePending(batch); + return null; + } finally { + flushing = false; + if (book().pending()) scheduleFlush(); + } +} + +export async function refreshAccess(fetcher = globalThis.fetch) { + const device = deviceId(); + if (!device || typeof fetcher !== 'function') return snapshot(); + try { + const res = await fetcher(STATS_URL + '/access?device=' + device, { credentials: 'omit', headers: accessHeaders() }); + if (!res.ok) return snapshot(); + const data = await res.json(); + return applyServerSnapshot(data, { authoritative: true }); + } catch { + return snapshot(); + } +} + +export async function verifyUsername(username, fetcher = globalThis.fetch) { + const device = deviceId(); + if (!device) return { ok: false, reason: 'unavailable' }; + try { + const res = await fetcher(STATS_URL + '/access/verify', { + method: 'POST', + credentials: 'omit', + headers: accessHeaders({ 'Content-Type': 'application/json' }), + body: JSON.stringify({ device, username }), + }); + const data = await res.json().catch(() => null); + if (!data) return { ok: false, reason: res.status === 429 ? 'rate-limited' : 'unavailable' }; + if (data.ok) applyServerSnapshot(data, { authoritative: true }); + return data; + } catch { + return { ok: false, reason: 'unavailable' }; + } +} + +export function githubStartUrl(href = globalThis.location?.href || '') { + const device = deviceId(); + let ret = 'https://coye2.github.io/spot-plus/'; + try { + const url = new URL(href); + ret = url.origin + url.pathname; + } catch { /* keep the public app */ } + return STATS_URL + '/access/github/start?device=' + device + '&return=' + encodeURIComponent(ret); +} + +export function consumeStarQuery() { + try { + const url = new URL(globalThis.location.href); + const star = url.searchParams.get('star') || url.searchParams.get('support') || ''; + if (!star) return ''; + url.searchParams.delete('star'); + url.searchParams.delete('support'); + globalThis.history.replaceState(null, '', url.pathname + url.search + url.hash); + return star; + } catch { + return ''; + } +} + +async function supportBody(extra = {}) { + return { device: deviceId(), secret: await installSecret(), signals: signalsFromHere(), ...extra }; +} + +async function postJson(path, body, fetcher = globalThis.fetch) { + if (typeof fetcher !== 'function') return { ok: false, reason: 'unavailable' }; + try { + const res = await fetcher(STATS_URL + path, { + method: 'POST', credentials: 'omit', headers: accessHeaders({ 'Content-Type': 'application/json' }), body: JSON.stringify(body), + }); + const data = await res.json().catch(() => null); + return data || { ok: false, reason: res.status === 429 ? 'rate-limited' : 'unavailable' }; + } catch { + return { ok: false, reason: 'unavailable' }; + } +} + +export async function createReferral(fetcher = globalThis.fetch) { + return postJson('/access/refer/code', await supportBody(), fetcher); +} + +export async function redeemReferral(code, challenge = '', fetcher = globalThis.fetch) { + return postJson('/access/refer/redeem', await supportBody({ code, challenge }), fetcher); +} + +export function discordStartUrl(href = globalThis.location?.href || '') { + const device = deviceId(); + let ret = 'https://coye2.github.io/spot-plus/'; + try { + const url = new URL(href); + ret = url.origin + url.pathname; + } catch { /* keep the public app */ } + return STATS_URL + '/access/discord/start?device=' + device + '&return=' + encodeURIComponent(ret); +} diff --git a/js/app.js b/js/app.js index d86352a..7683b43 100644 --- a/js/app.js +++ b/js/app.js @@ -48,6 +48,7 @@ import {shouldOnboard,showOnboarding} from './onboarding.js'; import {shouldShowLanding,showLanding} from './landing.js'; import {addLinks,syncLinks,loadLinks,cachedLinks,clearLinks,madeForYou,fetchPublic,rememberProfileAvatar} from './spotify-links.js'; import {bindPlayerDismiss} from './player-gestures.js'; +import {accessSettingsHtml, isFeatureRestricted, openAccessPrompt, startAccess} from './access-ui.js'; import {COMPANION_INSTALL_URL,connectionDevice,setupHtml,spotifyConnectionURLs,helperInstallHtml,copyHelperInstallLink,spotifyProfileHtml,markStep} from './account-setup.js'; let accountDevice=connectionDevice(navigator.userAgent,navigator.platform,navigator.maxTouchPoints); import {validateAccountSnapshot,isAccountMessage,ACCOUNT_FILE_LIMIT,accountReadNotice} from './spotify-account.js'; @@ -844,6 +845,7 @@ async function viewSettings() { return `

Settings

+ ${accessSettingsHtml()}

Playback

${toggle('smartRadio', 'Smart Radio', 'When your queue ends, keep playing similar songs based on what you skip.')} @@ -1096,7 +1098,7 @@ async function startRadio(t) { if (!artistId) return tt.set('No song mix found for this track'); const r = await api.artistRadio(artistId); const list = [t, ...r.filter((x) => String(x.id) !== String(t.id))]; - player.playList(list, 0, { shuffle: false, mix: true }); + if (player.playList(list, 0, { shuffle: false, mix: true }) === false) { tt.close?.(); return; } tt.set(`Song Mix based on ${t.title}`); } catch (e) { tt.set(`Couldn't start song mix: ${e.message}`); } } @@ -1128,6 +1130,7 @@ function refreshDl(){ } } async function downloadTracks(tracks,{keep='',quiet=false}={}) { + if (isFeatureRestricted('download')) { if (!quiet) openAccessPrompt({ feature: 'download' }); return; } const todo = tracks.filter((t) => !t.local && !store.isDownloaded(t.id)); if(['preview', 'deezer'].includes(store.getSettings().source)){if(!quiet)toast('Preview mode cannot download full songs. Choose a full audio source in Settings.');return;} if (!todo.length) { if(!quiet)toast('Already downloaded'); refreshDl(); return; } @@ -1401,7 +1404,7 @@ async function handleAct(act, el) { case 'theme-export': downloadJson({app:'spotplus-theme',version:1,settings:themeSettings(store.getSettings())},'spotplus-theme.json');break; case 'theme-import': $('#themeImport').click();break; case 'focus-main': $('#main').focus();break; - case 'track-play': {if(jam.active&&!jam.host){const t=listOf(key).tracks[+el.dataset.i];if(t){jam.add(t);toast(`Added “${t.title}” to the Jam`);}break;}dj.stop();const tracks=visibleTracks(listOf(key).tracks,store.getSettings());const track=listOf(key).tracks[+el.dataset.i];const index=tracks.findIndex(t=>t.id===track?.id);if(index<0)return toast('Explicit content is turned off in Settings.');if(player.current()?.id===track.id)player.toggle();else player.playList(tracks,index,{shuffle:false});break;} + case 'track-play': {if(jam.active&&!jam.host){const t=listOf(key).tracks[+el.dataset.i];if(t){jam.add(t);toast(`Added “${t.title}” to the Jam`);}break;}dj.stop();const tracks=visibleTracks(listOf(key).tracks,store.getSettings());const track=listOf(key).tracks[+el.dataset.i];const index=tracks.findIndex(t=>t.id===track?.id);if(index<0)return toast('Explicit content is turned off in Settings.');if(player.current()?.id===track.id)player.toggle();else player.playList(tracks,index,{shuffle:false,intent:'insta-choose'});break;} case 'profile': profileMenu(); break; case 'rewind-import': $('#rewindImport').click();break; case 'rewind-range': rewindFilters.range=el.dataset.value;route({keepScroll:true});break; @@ -1462,11 +1465,11 @@ async function handleAct(act, el) { if (tracks[i]) trackSheet(tracks[i], { ...meta, index: i }); break; } - case 'play-all': dj.stop();player.playList(visibleTracks(listOf(key).tracks,store.getSettings()), 0, { shuffle: false }); break; - case 'shuffle-all': dj.stop();player.playList(visibleTracks(listOf(key).tracks,store.getSettings()), 0, { shuffle: true }); break; + case 'play-all': dj.stop();player.playList(visibleTracks(listOf(key).tracks,store.getSettings()), 0, { shuffle: false, intent: 'insta-play' }); break; + case 'shuffle-all': dj.stop();player.playList(visibleTracks(listOf(key).tracks,store.getSettings()), 0, { shuffle: true, intent: 'insta-play' }); break; case 'artist-radio': { const tt = toast('Starting radio…'); - try { player.playList(await api.artistRadio(el.dataset.id), 0, { shuffle: false }); tt.close(); } catch (e) { tt.set(e.message); } + try { player.playList(await api.artistRadio(el.dataset.id), 0, { shuffle: false, intent: 'insta-play' }); tt.close(); } catch (e) { tt.set(e.message); } break; } case 'save-list': { @@ -1544,6 +1547,7 @@ async function handleAct(act, el) { case 'jam-react': jam.react(el.dataset.emoji);break; case 'shuffle': player.toggleShuffle(); break; case 'repeat': player.cycleRepeat(); break; + case 'access-unlock': openAccessPrompt(); break; case 'like-current': { const t = player.current(); if (t) toast(store.toggleLike(t) ? 'Added to Liked Songs' : 'Removed from Liked Songs'); break; } case 'np-open': openNP(); break; case 'np-close': closeNP(); break; @@ -1659,7 +1663,7 @@ async function handleAct(act, el) { if (!cur.enabled) applyMixSettings(lastMixSec || 6, cur.preferredStyle); dj.stop(); closeSheet(); - player.playList(tracks, 0, { shuffle: false, mix: true }); + if (player.playList(tracks, 0, { shuffle: false, mix: true, intent: 'insta-play' }) === false) break; toast(`Mixing ${tracks.length} songs · ${automix.MIX_MODES[cur.preferredStyle]?.label || 'Smart Mix'}`); break; } @@ -2168,13 +2172,13 @@ function syncCanvas(retry=false){ $('#npCoverButton').setAttribute('aria-pressed',String(inCover&&!canvasPreference)); $('#npCanvasButton').classList.toggle('on',inCover&&canvasPreference); $('#npCanvasButton').setAttribute('aria-pressed',String(inCover&&canvasPreference)); - canvasPlayer.sync(player.current(),{visible:npOpen&&inCover&&!document.hidden,enabled:canvasPreference&&!spoken.isSpoken(player.current()),playing:player.isPlaying()&&!player.state.loading,networkReady:hasLocalClip(player.current())||(!player.state.loading&&audioHasHeadroom(player.el)),retry}); + canvasPlayer.sync(player.current(),{visible:npOpen&&inCover&&!document.hidden,enabled:canvasPreference&&!isFeatureRestricted('canvas')&&!spoken.isSpoken(player.current()),playing:player.isPlaying()&&!player.state.loading,networkReady:hasLocalClip(player.current())||(!player.state.loading&&audioHasHeadroom(player.el)),retry}); } player.on('state',()=>syncCanvas()); // Look up the next song's loop while this one plays, so it starts instantly. let loopPrefetched=''; player.on('state',()=>{ - if(!canvasPreference||!player.isPlaying()||!player.scheduler.canRun(7))return; + if(!canvasPreference||isFeatureRestricted('canvas')||!player.isPlaying()||!player.scheduler.canRun(7))return; const next=player.state.queue[player.state.index+1]; if(!next||spoken.isSpoken(next)||next.id===loopPrefetched)return; loopPrefetched=next.id; @@ -2880,7 +2884,7 @@ async function viewSpTrack(id){ const t=spTrack(d);spArtists.learnFromTracks([t]); const k=reg([t],{name:t.title}); const by=t.artistIds?.[0]?`${esc(t.artist)}`:`${esc(t.artist)}`; - setTimeout(()=>{if(location.hash==='#/sptrack/'+id&&!player.isPlaying())player.playList([t],0);},50); + setTimeout(()=>{if(location.hash==='#/sptrack/'+id&&!player.isPlaying())player.playList([t],0,{intent:'insta-choose'});},50); return header({cover:t.coverXl,kicker:'Song · from a Spotify link',title:t.title,sub:`${by}${d.year?' · '+d.year:''}`})+actions(k,``)+trackRows([t],k); } async function viewSpAlbum(id){ @@ -3228,6 +3232,7 @@ function dismissWelcome(){try{localStorage.setItem('spotplus.welcome','1');}catc } window.dispatchEvent(new Event('spotplus-ready')); /* ---------------- Live counters ---------------- */ +startAccess({toast:(msg)=>toast(msg),onChange:()=>{if(location.hash.startsWith('#/settings'))route({keepScroll:true});}}); live.countInstall({standalone:isStandalone()}); window.addEventListener('appinstalled',()=>live.countInstall({standalone:true})); const beat=()=>live.heartbeat(player.isPlaying()); @@ -3241,7 +3246,7 @@ function openSnake(){ queue.slice(Math.max(0,index),index+250).forEach(add); if(songs.length<40)[...store.getLikes(),...store.getRecent().filter(x=>x?.type!=="album"&&x?.title)].slice(0,200).forEach(add); if(songs.length<3){toast('Play a playlist first: Snake is made of its songs');return;} - snake.open({songs,accent:getComputedStyle(document.documentElement).getPropertyValue('--accent').trim()||'#1ed760',onPlay:list=>{player.playList(list,0);toast(`Playing the ${list.length} songs you ate`);}}); + snake.open({songs,accent:getComputedStyle(document.documentElement).getPropertyValue('--accent').trim()||'#1ed760',onPlay:list=>{if(player.playList(list,0,{intent:'insta-play'})===false)return;toast(`Playing the ${list.length} songs you ate`);}}); } async function askRating(current=rating.myRating()){ const answer=await rating.openDialog({current}); diff --git a/js/changelog.js b/js/changelog.js index 3e0d60b..b82279d 100644 --- a/js/changelog.js +++ b/js/changelog.js @@ -1,6 +1,11 @@ // Release notes: the single source for the in-app "What's new" screen and CHANGELOG.md. // Newest first. Add an entry with every fix. export const CHANGELOG = [ + {version: '2.2.6', date: '2026-11-25', title: 'Base tier daily limit, unlocked by support', items: [ + 'Spot+ stays free, powered by love and support. On the base tier, skips, Insta Play, and Insta Choose share 300 a day, counted on this device and on this network address.', + 'After today’s allowance is used, the song already playing can finish and the queue can still advance. Skips, picking a song, seeking, new downloads, repeat, Canvas, and early loading of the next song wait until tomorrow.', + 'Full access comes from support Spot+ can check: star coye2/spot-plus on GitHub, join the Discord and verify membership, or refer a friend who installs Spot+ and enters your code. Another browser, phone, or VPN on the same device does not count as that friend. Your own devices are excluded from the allowance.', + ]}, {version: '2.2.5', date: '2026-11-24', title: 'Operation S+: S-tier playback state machine, recovery checkpoints, adaptive transitions & scalable Worker protection', items: [ 'Playback Reliability & State Machine: added explicit PAUSED and SEEKING lifecycle phases with transition tracking, network-aware timeouts, negative match caching, and root-cause telemetry separating upstream, network, codec, and client errors.', 'Background Playback & Recovery Checkpoints: added durable recovery checkpoints saved on pagehide, visibility hide, blur, and freeze so Spot+ restores your exact song, queue, position, and volume cleanly after OS background termination without silent-loop hacks.', diff --git a/js/dj.js b/js/dj.js index 50adce3..e8e6093 100644 --- a/js/dj.js +++ b/js/dj.js @@ -71,7 +71,12 @@ export async function start(prompt='',{change=false}={}){ if(!tracks.length)throw new Error('No match yet. Try an artist, song, or a broader mood.'); if(change&&tracks.length>1){const offset=(Math.max(0,tracks.findIndex(t=>t.id===player.current()?.id))+1)%tracks.length;tracks=[...tracks.slice(offset),...tracks.slice(0,offset)];} state.active=true;state.tracks=tracks;state.message=reason;state.busy=false;announced=tracks[0].id;trackCount=0; - player.playList(tracks,0,{shuffle:false});emit(); + if (player.playList(tracks,0,{shuffle:false}) === false) { + state.message = 'Daily limit reached. Star Spot+ on GitHub and verify it to unlock full access.'; + emit(); + return; + } + emit(); if(radioSeed)api.artistRadio(radioSeed.artistId).then(more=>{ if(my!==requestToken||!state.active)return; const added=visibleTracks(uniqueTracks(more),store.getSettings()).filter(t=>!state.tracks.some(x=>x.id===t.id)).slice(0,25); diff --git a/js/jam.js b/js/jam.js index 2e9bf3b..fd65fe5 100644 --- a/js/jam.js +++ b/js/jam.js @@ -101,7 +101,7 @@ export class Jam { const want = state.queue[state.index], here = this.player.current(); this.applying = true; try { - if (here?.id !== want.id) this.player.playList(state.queue, state.index); + if (here?.id !== want.id) this.player.playList(state.queue, state.index, { intent: 'system' }); else { const s = this.player.state; s.queue = [...s.queue.slice(0, s.index + 1), ...state.queue.slice(state.index + 1)]; @@ -116,7 +116,7 @@ export class Jam { const want = this.remote.queue[this.remote.index]; if (this.player.current()?.id !== want?.id || this.player.state.loading) return; const target = expectedPosition(this.remote), off = Math.abs((this.player.el.currentTime || 0) - target); - if (off > (force ? 1 : 2.5)) this.player.seek(target); + if (off > (force ? 1 : 2.5)) this.player.seek(target, { user: false }); } /* ----- Listener actions ----- */ add(track) { if (this.host) this.player.addToQueue([track]); else this.send({type: 'add', track: slim(track)}); } diff --git a/js/maintenance.js b/js/maintenance.js index 2ff8903..fcb446c 100644 --- a/js/maintenance.js +++ b/js/maintenance.js @@ -104,6 +104,14 @@ export function isAllowedSpotifyId(id) { return !!digest && ALLOWED_ID_HASHES.some((allowed) => safeEqual(digest, allowed)); } +/** Owner devices are excluded from the base-tier allowance. A session token or the owner Spotify id both count. */ +export function isOwnerProof(value, { origin, now = Date.now() } = {}) { + const text = String(value || '').trim(); + if (!text || text.length > 600) return false; + if (text.startsWith('{')) return verifySessionToken(text, { origin, now }); + return isAllowedSpotifyId(text); +} + function randomNonce() { try { if (globalThis.crypto?.getRandomValues) { diff --git a/js/player.js b/js/player.js index e79e475..9f0a4e7 100644 --- a/js/player.js +++ b/js/player.js @@ -26,6 +26,7 @@ import { SpotifyPlaybackProvider } from './playback/spotify-provider.js'; import { connectivity } from './connectivity.js'; import { featureFlags, isFeatureEnabled } from './feature-flags.js'; import { scheduler } from './request-scheduler.js'; +import { allowPlaybackAction, allowRestricted, isFeatureRestricted } from './access.js'; export { connectivity, featureFlags, scheduler }; @@ -1543,6 +1544,7 @@ async function upgradeFromEmbed(t, my, signal) { } function prefetch() { + if (isFeatureRestricted('preload')) { nextBuffer.clear(); return; } const generation = ++warmGeneration; clearTimeout(prefetchTimer); const netProfile = bufferEngine.profile(navigator.connection); @@ -1883,8 +1885,12 @@ function shuffled(a) { for (let i = r.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [r[i], r[j]] = [r[j], r[i]]; } return r; } -export function playList(tracks, i = 0, { shuffle = null, mix = false } = {}) { - if (!tracks || !tracks.length) return; +export function playList(tracks, i = 0, opts = {}) { + if (!tracks || !tracks.length) return false; + const intent = opts.intent || ((Number(i) > 0) ? 'insta-choose' : 'insta-play'); + // System starts (Jam follow) are not the listener's skip / Insta Play / Insta Choose. + if (!allowPlaybackAction(intent)) return false; + const { shuffle = null, mix = false } = opts; if (shuffle !== null) state.shuffle = shuffle; skipTracker.clear(); const list = tracks.map(store.slim); @@ -1909,6 +1915,7 @@ export function playList(tracks, i = 0, { shuffle = null, mix = false } = {}) { // Do NOT prewarm queue[index + 1] before load() — load() immediately cancels non-current prewarms! // Let prefetch() prepare the immediate next track cleanly once the current song is playing with headroom. load({ trigger: mix ? 'mix-list' : 'play-list' }); + return true; } /** Smoothly reorder upcoming queue items for a Mix session (no back-to-back same artist). */ export function mixQueue() { @@ -1920,12 +1927,13 @@ export function mixQueue() { return true; } export function playIndex(i) { - if (i >= 0 && i < state.queue.length) { - skipTracker.record(); - state.index = i; - errRetries = 0; - load({ trigger: 'queue-jump' }); - } + if (!(i >= 0 && i < state.queue.length)) return false; + if (!allowPlaybackAction('insta-choose')) return false; + skipTracker.record(); + state.index = i; + errRetries = 0; + load({ trigger: 'queue-jump' }); + return true; } // Audio links from YouTube servers expire after a few hours; a paused song may need a fresh one. const linkExpired = () => { const exp = Number(String(state.source?.url || '').match(/[?&]expire=(\d{9,11})/)?.[1] || 0) * 1000; return !!exp && exp - 60e3 < Date.now(); }; @@ -1987,6 +1995,10 @@ export function toggle() { } export function next(fromUser = true) { lastPrevAt = 0; + const canAdvance = state.index < state.queue.length - 1 + || (state.repeat === 'all' && state.queue.length > 0) + || !!(continueQueue && !current()?.direct); + if (fromUser && canAdvance && !allowPlaybackAction('skip')) return false; if (fromUser && current() && (isRealSrc() || isEmbed() || isSpotifyOfficial())) { skipTracker.record(); onSkip(current(), position()); @@ -2018,21 +2030,24 @@ export function prev() { const doubleTapped = lastPrevAt > 0 && (now - lastPrevAt) <= 1800; // First tap past 3s cleanly restarts the current song; a second tap within 1.8s (or <= 3s) skips to previous track. if ((!doubleTapped && position() > 3) || state.index <= 0) { + if (!allowRestricted('seek')) return false; lastPrevAt = now; - seek(0); + seek(0, { user: false }); if (pendingPlay && !userPaused && !isEmbed() && !isSpotifyOfficial() && isRealSrc() && audio.paused) { audio.play().catch(() => {}); } return; } + if (!allowPlaybackAction('skip')) return false; lastPrevAt = 0; skipTracker.record(); state.index--; errRetries = 0; load({ trigger: 'skip-prev' }); } -export function seek(sec) { +export function seek(sec, opts = {}) { if (!isFinite(sec)) return; + if (opts.user !== false && !allowRestricted('seek')) return; if (isSpotifyOfficial()) { const target = Math.max(0, Math.min(sec, duration())); spotifyPlayback.seek(target); @@ -2068,7 +2083,7 @@ export function setVolume(v) { save(); } export function playNext(t) { - if (!current()) return playList([t]); + if (!current()) return playList([t], 0, { intent: 'insta-choose' }); queueMutatedAt = Date.now(); const track = store.slim(t); state.queue.splice(state.index + 1, 0, track); @@ -2118,6 +2133,7 @@ export function toggleShuffle() { emit('state'); save(); prefetch(); } export function cycleRepeat() { + if (!allowRestricted('repeat')) return state.repeat; state.repeat = state.repeat === 'off' ? 'all' : state.repeat === 'all' ? 'one' : 'off'; emit('state'); save(); prefetch(); } @@ -2239,7 +2255,7 @@ export function restore({ ifIdle = false } = {}) { } updateSession(current()); const t0 = setTimeout(() => { - if (current() && !isRealSrc()) { + if (current() && !isRealSrc() && !isFeatureRestricted('preload')) { api.warmConnections(); api.prewarm(current()); } diff --git a/js/referral.js b/js/referral.js new file mode 100644 index 0000000..d4da483 --- /dev/null +++ b/js/referral.js @@ -0,0 +1,158 @@ +// Referral install check. The bridge compares two installs and rejects a second +// browser, a VPN, or the same phone wearing a new profile. A friend on their own +// device still passes, including one sharing a home network when the device differs. +import { DISCORD } from './access-policy.js'; + +export const HOLD_MS = 60_000; +export const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; +const SECRET_KEY = 'spotplus.installSecret'; + +export function normalizeCode(input) { + const code = String(input || '').toUpperCase().replace(/[^A-Z2-9]/g, '').replace(/[OIL01]/g, ''); + if (!/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{8}$/.test(code)) return ''; + return code; +} + +export function platformFamily(ua = '', platform = '') { + const blob = `${ua} ${platform}`.toLowerCase(); + if (/iphone|ipad|ipod/.test(blob)) return 'ios'; + if (/android/.test(blob)) return 'android'; + if (/windows|win32|win64/.test(blob)) return 'windows'; + if (/mac/.test(blob)) return 'mac'; + if (/linux|cros|chromebook/.test(blob)) return 'linux'; + return 'other'; +} + +export function screenBucket(width, height, dpr) { + const w = Math.round((Number(width) || 0) / 40) * 40; + const h = Math.round((Number(height) || 0) / 40) * 40; + const d = Math.round((Number(dpr) || 1) * 2) / 2; + return `${w}x${h}@${d}`; +} + +export function touchClass(touch) { + const n = Number(touch) || 0; + if (n <= 0) return 'none'; + if (n < 5) return 'few'; + return 'many'; +} + +export function browserKey(signals = {}) { + const ua = String(signals.ua || ''); + const family = /edg\//i.test(ua) ? 'edge' + : /chrome|crios/i.test(ua) ? 'chrome' + : /firefox|fxios/i.test(ua) ? 'firefox' + : /safari/i.test(ua) ? 'safari' + : 'other'; + return hardwareKey(signals) + '|' + family + '|' + String(signals.language || '').slice(0, 12); +} + +/** Stable description of the physical device. A new browser or VPN does not change it. */ +export function hardwareKey(signals = {}) { + return [ + platformFamily(signals.ua, signals.platform), + screenBucket(signals.width, signals.height, signals.dpr), + Number(signals.cores) || 0, + Number(signals.memory) || 0, + touchClass(signals.touch), + Number(signals.color) || 0, + String(signals.timezone || '').slice(0, 64), + ].join('|'); +} + +export function isInstalledApp() { + try { + if (globalThis.navigator?.standalone === true) return true; + return globalThis.matchMedia?.('(display-mode: standalone)')?.matches === true; + } catch { + return false; + } +} + +export function signalsFromHere() { + const nav = globalThis.navigator || {}; + const scr = globalThis.screen || {}; + let timezone = ''; + try { timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || ''; } catch { /* ignore */ } + return { + ua: String(nav.userAgent || '').slice(0, 180), + platform: String(nav.platform || '').slice(0, 40), + timezone: timezone.slice(0, 64), + language: String(nav.language || '').slice(0, 20), + cores: Number(nav.hardwareConcurrency) || 0, + memory: Number(nav.deviceMemory) || 0, + touch: Number(nav.maxTouchPoints) || 0, + width: Number(scr.width) || 0, + height: Number(scr.height) || 0, + dpr: Number(globalThis.devicePixelRatio) || 1, + color: Number(scr.colorDepth) || 0, + standalone: isInstalledApp(), + }; +} + +function randomSecret() { + const bytes = new Uint8Array(16); + crypto.getRandomValues(bytes); + return [...bytes].map((b) => b.toString(16).padStart(2, '0')).join(''); +} + +function openKv() { + return new Promise((resolve, reject) => { + if (!globalThis.indexedDB) { reject(new Error('no idb')); return; } + const req = indexedDB.open('spotplus-support', 1); + req.onupgradeneeded = () => { if (!req.result.objectStoreNames.contains('kv')) req.result.createObjectStore('kv'); }; + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + }); +} + +async function idbSecret(value) { + const db = await openKv(); + return new Promise((resolve, reject) => { + const tx = db.transaction('kv', value ? 'readwrite' : 'readonly'); + const store = tx.objectStore('kv'); + const req = value ? store.put(value, SECRET_KEY) : store.get(SECRET_KEY); + req.onsuccess = () => resolve(req.result || ''); + req.onerror = () => reject(req.error); + }); +} + +/** Secret kept in localStorage and IndexedDB, so clearing one store is not a new person. */ +export async function installSecret(storage = globalThis.localStorage) { + let secret = ''; + try { secret = storage?.getItem?.(SECRET_KEY) || ''; } catch { /* private mode */ } + if (!/^[a-f0-9]{32}$/.test(secret)) { + try { secret = await idbSecret(); } catch { secret = ''; } + } + if (!/^[a-f0-9]{32}$/.test(secret)) secret = randomSecret(); + try { storage?.setItem?.(SECRET_KEY, secret); } catch { /* ignore */ } + try { await idbSecret(secret); } catch { /* ignore */ } + return secret; +} + +/** + * Decide whether the friend install is someone else. + * `hardware`, `secret`, and `browser` are already hashes when the bridge calls this. + */ +export function judgeReferral({ referrer = {}, friend = {}, codeCreatedAt = 0, friendFirstSeen = 0, standalone = false } = {}) { + if (!standalone) return { ok: false, reason: 'install' }; + if (!friend.device || !referrer.device) return { ok: false, reason: 'invalid' }; + if (friend.device === referrer.device) return { ok: false, reason: 'self' }; + if (friend.secret && referrer.secret && friend.secret === referrer.secret) return { ok: false, reason: 'self' }; + if (friendFirstSeen > 0 && codeCreatedAt > 0 && friendFirstSeen + 1500 < codeCreatedAt) return { ok: false, reason: 'not-new' }; + if (friend.hardware && referrer.hardware && friend.hardware === referrer.hardware) return { ok: false, reason: 'same-device' }; + if (friend.browser && referrer.browser && friend.browser === referrer.browser) return { ok: false, reason: 'same-browser' }; + if (friend.ip && referrer.ip && friend.ip === referrer.ip && friend.family && friend.family === referrer.family && friend.screen && friend.screen === referrer.screen) { + return { ok: false, reason: 'same-network' }; + } + return { ok: true, reason: 'ok' }; +} + +export function isGuildMember(guilds, guildId) { + const want = String(guildId || ''); + return !!want && Array.isArray(guilds) && guilds.some((guild) => String(guild?.id || '') === want); +} + +export const SUPPORT_LINKS = Object.freeze({ + discord: DISCORD.invite, +}); diff --git a/package.json b/package.json index deff68d..86f32ed 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "spot-plus", - "version": "2.2.5", + "version": "2.2.6", "private": true, "type": "module", "scripts": { diff --git a/scripts/check.mjs b/scripts/check.mjs index e6350b8..bac7090 100644 --- a/scripts/check.mjs +++ b/scripts/check.mjs @@ -17,6 +17,8 @@ const files = [ ...(await jsFiles('workers/spotify-relay/src')), 'sw.js', 'canvas-bridge/worker.js', + 'canvas-bridge/access.js', + 'canvas-bridge/referral.js', 'canvas-bridge/spotify-stats.js', ]; diff --git a/sw.js b/sw.js index b7c390a..58cc77d 100644 --- a/sw.js +++ b/sw.js @@ -1,6 +1,6 @@ // Spot+ service worker: offline app shell, cached cover art, and HTTP Range support for cached audio. // v40 includes version 2 account snapshots and incomplete-collection preservation. -const SHELL_CACHE = 'spotplus-shell-v153'; +const SHELL_CACHE = 'spotplus-shell-v154'; const IMG_CACHE = 'spotplus-img-v1'; const AUDIO_CACHE = 'spotplus-audio-v1'; const KEEP = [SHELL_CACHE, IMG_CACHE, AUDIO_CACHE, 'spotplus-live-voice-v1']; @@ -10,7 +10,7 @@ const SHELL = [ './js/ui-engine.js', './js/autoeq.js', './js/dsp.js', './js/lyrics-engine.js', './js/visualizer.js', './js/audio-studio-ui.js', './css/spotplus-ui.css', './js/playback-telemetry.js', './js/source-router.js', './js/memory-engine.js', './js/buffer-engine.js', './js/predictive-pipeline.js', './js/profile-photo.js', './js/backgrounds.js', './js/background-catalog.js', './css/backgrounds.css', - './js/audio-selection.js','./js/player-colors.js','./js/spotify-stats.js','./js/listening-history.js','./js/history-import-worker.js','./js/rewind.js','./js/stats-api.js','./js/canvas-cache.js','./js/jam.js','./js/jam-mesh.js','./js/relay-sync.js','./js/spotify-links.js','./js/vendor/nostr-sign.js','./js/onboarding.js','./js/notify.js','./js/landing.js','./js/fx.js','./js/spoken.js','./js/generator.js','./js/mixes.js','./js/library-sync.js','./js/live-stats.js','./js/changelog.js','./js/cors-probe.js','./js/pitch-worklet.js','./js/boot.js','./css/landing.css','./icons/shot-home.webp','./icons/shot-coll.webp','./icons/shot-jam.webp','./js/vendor/qrcode.js','./css/rewind.css','./css/polish.css', + './js/audio-selection.js','./js/player-colors.js','./js/spotify-stats.js','./js/listening-history.js','./js/history-import-worker.js','./js/rewind.js','./js/stats-api.js','./js/canvas-cache.js','./js/jam.js','./js/jam-mesh.js','./js/relay-sync.js','./js/spotify-links.js','./js/vendor/nostr-sign.js','./js/onboarding.js','./js/notify.js','./js/landing.js','./js/fx.js','./js/spoken.js','./js/generator.js','./js/mixes.js','./js/library-sync.js','./js/live-stats.js','./js/access-policy.js','./js/access.js','./js/access-ui.js','./js/referral.js','./js/changelog.js','./js/cors-probe.js','./js/pitch-worklet.js','./js/boot.js','./css/landing.css','./icons/shot-home.webp','./icons/shot-coll.webp','./icons/shot-jam.webp','./js/vendor/qrcode.js','./css/rewind.css','./css/polish.css', './js/playback-policy.js', './js/canvas.js','./js/video-loops.js','./js/player-gestures.js','./js/account-setup.js','./js/dj-recognition.js','./js/live-voice.js','./js/live-voice-worker.js','./js/dj-dialogue.js','./js/vendor/supertonic-text.js', ...['afterhours','daylight','classic'].map(host=>'./audio/dj/'+host+'/preview.mp3'), diff --git a/tests/access-limit.test.mjs b/tests/access-limit.test.mjs new file mode 100644 index 0000000..67d3411 --- /dev/null +++ b/tests/access-limit.test.mjs @@ -0,0 +1,164 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { DAILY_LIMIT, addUsage, quotaView, utcDay } from '../js/access-policy.js'; +import { hardwareKey, judgeReferral, normalizeCode } from '../js/referral.js'; +import { createLedger } from '../js/access.js'; +import { ALLOWED_ID_HASHES, createSessionToken, isOwnerProof } from '../js/maintenance.js'; +import { handleAccess } from '../canvas-bridge/access.js'; +import { storageMock } from './helpers.mjs'; + +function mem() { + const m = new Map(); + const api = { + get: async (k) => m.get(k), + put: async (o) => { for (const [k, v] of Object.entries(o)) m.set(k, v); }, + list: async ({ prefix } = {}) => { + const out = new Map(); + for (const [k, v] of m) if (!prefix || String(k).startsWith(prefix)) out.set(k, v); + return out; + }, + delete: async (keys) => { for (const k of keys) m.delete(k); }, + }; + api.transaction = async (fn) => fn(api); + return api; +} + +const dev = (ch) => ch.repeat(32); +const ip = (ch) => ch.repeat(16); +const secret = (ch) => ch.repeat(32); +const phone = { ua: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)', platform: 'iPhone', timezone: 'America/New_York', language: 'en-US', cores: 6, memory: 4, touch: 5, width: 390, height: 844, dpr: 3, color: 24, standalone: true }; +const laptop = { ua: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0', platform: 'Win32', timezone: 'America/Chicago', language: 'en-US', cores: 8, memory: 8, touch: 0, width: 1920, height: 1080, dpr: 1, color: 24, standalone: true }; + +function post(path, body, { address = ip('a'), owner = '', origin = 'https://coye2.github.io', household = '' } = {}) { + const headers = { 'Content-Type': 'application/json', 'X-Client': address, 'X-App-Origin': origin }; + if (owner) headers['X-Spotplus-Owner'] = owner; + if (household) headers['X-Spotplus-Household'] = household; + return new Request('https://counter' + path, { method: 'POST', headers, body: JSON.stringify(body) }); +} + +test('skip, insta play, and insta choose share 300 on the device and on the network', () => { + assert.equal(DAILY_LIMIT, 300); + let state = { deviceUsed: 0, ipUsed: 0 }; + state = addUsage(state, 1); + assert.equal(state.deviceUsed, 1); + assert.equal(state.ipUsed, 1); + assert.equal(state.remaining, 299); + const capped = addUsage({ deviceUsed: 10, ipUsed: 299 }, 5); + assert.equal(capped.ipUsed, 300); + assert.equal(capped.limited, true); + assert.equal(capped.allowed, false); + assert.equal(quotaView({ deviceUsed: 300, ipUsed: 0 }).allowed, false); + assert.equal(quotaView({ deviceUsed: 300, ipUsed: 300, unlocked: true }).tier, 'full'); +}); + +test('the on-device ledger stops at 300 and follows the network count', () => { + const ledger = createLedger(storageMock(), () => Date.parse('2026-11-25T15:00:00Z')); + for (let i = 0; i < 300; i++) assert.equal(ledger.consume(i % 2 ? 'skip' : 'insta-play').allowed, true); + assert.equal(ledger.consume('insta-choose').allowed, false); + ledger.applyServer({ day: '2026-11-25', deviceUsed: 1, ipUsed: 300, unlocked: false }, { authoritative: true }); + assert.equal(ledger.snapshot().limited, true); + ledger.applyServer({ day: '2026-11-26', deviceUsed: 0, ipUsed: 0, unlocked: false, exempt: false }, { authoritative: true }); + assert.equal(ledger.snapshot().limited, false); + assert.equal(ledger.consume('skip').allowed, true); +}); + +test('an owner session is recognized and is not a blank string', () => { + const origin = 'https://coye2.github.io'; + const token = createSessionToken(ALLOWED_ID_HASHES[0], { origin, now: 1_700_000_000_000 }); + assert.equal(isOwnerProof(token, { origin, now: 1_700_000_000_000 }), true); + assert.equal(isOwnerProof('not-the-owner', { origin }), false); + assert.equal(isOwnerProof('', { origin }), false); +}); + +test('owner devices are excluded from the device and network allowance', async () => { + const storage = mem(); + const origin = 'https://coye2.github.io'; + const now = Date.parse('2026-11-25T16:00:00Z'); + const token = createSessionToken(ALLOWED_ID_HASHES[0], { origin, now }); + const ownerDevice = dev('a'); + const other = dev('b'); + const address = ip('c'); + const first = await handleAccess(post('/access', { device: ownerDevice, action: 'skip', n: 300, nonce: 'aa'.repeat(8) }, { address, owner: token, origin }), { storage, now }); + const ownerBody = await first.json(); + assert.equal(ownerBody.exempt, true); + assert.equal(ownerBody.tier, 'full'); + assert.equal(ownerBody.charged, 0); + assert.equal(ownerBody.deviceUsed, 0); + const again = await (await handleAccess(post('/access', { device: ownerDevice, action: 'insta-play', n: 10, nonce: 'bb'.repeat(8) }, { address }), { storage, now: now + 1000 })).json(); + assert.equal(again.exempt, true, 'the device stays excluded after the proof'); + assert.equal(again.ipUsed, 0, 'owner use does not burn the network allowance'); + const stranger = await (await handleAccess(post('/access', { device: other, action: 'skip', n: 1, nonce: 'cc'.repeat(8) }, { address }), { storage, now: now + 2000 })).json(); + assert.equal(stranger.tier, 'base'); + assert.equal(stranger.ipUsed, 1); + assert.equal(stranger.exempt, false); + const house = 'ab'.repeat(16); + await handleAccess(post('/access', { device: ownerDevice, action: 'skip', n: 1, nonce: 'ee'.repeat(8) }, { address, owner: token, origin, household: house }), { storage, now: now + 3000 }); + const linked = dev('c'); + const laptop = await (await handleAccess(post('/access', { device: linked, action: 'insta-choose', n: 40, nonce: 'ff'.repeat(8) }, { address: ip('d'), household: house }), { storage, now: now + 4000 })).json(); + assert.equal(laptop.exempt, true); + assert.equal(laptop.charged, 0); + const outsider = await (await handleAccess(post('/access', { device: dev('9'), action: 'skip', n: 1, nonce: '99'.repeat(8) }, { address: ip('e'), household: 'cd'.repeat(16) }), { storage, now: now + 5000 })).json(); + assert.equal(outsider.exempt, false); + assert.equal(outsider.deviceUsed, 1); +}); + +test('a friend code rejects the same device, another browser, and a VPN, and accepts another device', () => { + const mine = { device: dev('a'), secret: 'secret-a', hardware: hardwareKey(phone), browser: 'browser-a', family: 'ios', screen: '400x840@3', ip: ip('a') }; + assert.equal(judgeReferral({ referrer: mine, friend: { ...mine }, standalone: true }).reason, 'self'); + const otherBrowser = { ...mine, device: dev('b'), secret: 'secret-b', browser: 'browser-b', ip: ip('d') }; + assert.equal(judgeReferral({ referrer: mine, friend: otherBrowser, standalone: true }).reason, 'same-device'); + const friend = { device: dev('c'), secret: 'secret-c', hardware: hardwareKey(laptop), browser: 'browser-c', family: 'windows', screen: '1920x1080@1', ip: ip('e') }; + assert.equal(judgeReferral({ + referrer: mine, friend, standalone: true, codeCreatedAt: 100, friendFirstSeen: 0, + }).ok, true); + assert.equal(judgeReferral({ + referrer: mine, friend: { ...friend, ip: mine.ip, family: mine.family, screen: mine.screen, hardware: 'different' }, standalone: true, + }).reason, 'same-network'); + assert.equal(judgeReferral({ referrer: mine, friend, standalone: false }).reason, 'install'); + assert.equal(judgeReferral({ + referrer: mine, friend, standalone: true, codeCreatedAt: 5_000, friendFirstSeen: 1_000, + }).reason, 'not-new'); + assert.equal(normalizeCode('nope'), ''); + assert.equal(normalizeCode('ab23-cd45'), 'AB23CD45'); +}); + +test('redeeming a code waits, then unlocks only the referrer, and an owner device cannot be the friend', async () => { + const storage = mem(); + const created = Date.parse('2026-11-25T18:00:00Z'); + const referrer = dev('d'); + const friend = dev('e'); + const made = await (await handleAccess(post('/access/refer/code', { + device: referrer, secret: secret('1'), signals: phone, + }, { address: ip('a') }), { storage, now: created })).json(); + assert.equal(made.ok, true); + assert.match(made.code, /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{8}$/); + + const early = await (await handleAccess(post('/access/refer/redeem', { + device: friend, secret: secret('2'), code: made.code, signals: laptop, + }, { address: ip('f') }), { storage, now: created + 10_000 })).json(); + assert.equal(early.reason, 'hold'); + assert.ok(early.challenge); + + const done = await (await handleAccess(post('/access/refer/redeem', { + device: friend, secret: secret('2'), code: made.code, challenge: early.challenge, signals: laptop, + }, { address: ip('f') }), { storage, now: created + 80_000 })).json(); + assert.equal(done.ok, true); + assert.notEqual(done.tier, 'full'); + const referrerStatus = await (await handleAccess(new Request('https://counter/access?device=' + referrer, { headers: { 'X-Client': ip('a') } }), { storage, now: created + 90_000 })).json(); + assert.equal(referrerStatus.tier, 'full'); + assert.match(referrerStatus.login, /friend/); + + const origin = 'https://coye2.github.io'; + const token = createSessionToken(ALLOWED_ID_HASHES[0], { origin, now: created }); + const ownerDevice = dev('f'); + await handleAccess(post('/access', { device: ownerDevice, action: 'status', n: 0, nonce: 'dd'.repeat(8) }, { owner: token, origin }), { storage, now: created }); + const blocked = await (await handleAccess(post('/access/refer/redeem', { + device: ownerDevice, secret: secret('3'), code: 'ABCD2345', signals: laptop, + }, { owner: token, origin, address: ip('9') }), { storage, now: created + 120_000 })).json(); + assert.equal(blocked.reason, 'excluded'); +}); + +test('utc day is the allowance window', () => { + assert.equal(utcDay(Date.parse('2026-11-25T23:30:00Z')), '2026-11-25'); + assert.equal(utcDay(Date.parse('2026-11-26T00:30:00Z')), '2026-11-26'); +}); diff --git a/tests/access-player.test.mjs b/tests/access-player.test.mjs new file mode 100644 index 0000000..b74595d --- /dev/null +++ b/tests/access-player.test.mjs @@ -0,0 +1,27 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { browserMocks, settle } from './helpers.mjs'; + +test('an excluded device can still start and skip after the base tier cap', async () => { + browserMocks(); + const { applyServerSnapshot } = await import('../js/access.js'); + const { utcDay } = await import('../js/access-policy.js'); + const player = await import('../js/player.js'); + const day = utcDay(); + applyServerSnapshot({ day, deviceUsed: 300, ipUsed: 300, unlocked: false, exempt: true }, { authoritative: true }); + const tracks = ['one', 'two', 'three'].map((id) => ({ id, title: id, artist: 'Unit', duration: 180, local: true })); + assert.equal(player.playList(tracks, 0, { intent: 'insta-play' }), true); + assert.equal(player.current().id, 'one'); + assert.notEqual(player.next(true), false); + assert.equal(player.current().id, 'two'); + await settle(); +}); + +test('a base-tier device stops at the cap', async () => { + const { applyServerSnapshot, snapshot } = await import('../js/access.js'); + const { utcDay } = await import('../js/access-policy.js'); + const player = await import('../js/player.js'); + applyServerSnapshot({ day: utcDay(), deviceUsed: 300, ipUsed: 300, unlocked: false, exempt: false }, { authoritative: true }); + assert.equal(snapshot().limited, true); + assert.equal(player.playList([{ id: 'late', title: 'Late', artist: 'Unit', duration: 180, local: true }], 0, { intent: 'insta-choose' }), false); +}); From 4be5d2b1afd248a85ed94aa721231c035bc02298 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 13:02:29 +0000 Subject: [PATCH 2/3] fix: store the install mark without treating it as a credential CodeQL flagged the referral install id because it was named and saved like a secret. It is only a random install marker, kept under a non-credential name. Co-authored-by: Coye --- canvas-bridge/referral.js | 4 ++-- js/access.js | 4 ++-- js/referral.js | 32 ++++++++++++++++---------------- tests/access-limit.test.mjs | 14 +++++++------- 4 files changed, 27 insertions(+), 27 deletions(-) diff --git a/canvas-bridge/referral.js b/canvas-bridge/referral.js index 89084dc..c597354 100644 --- a/canvas-bridge/referral.js +++ b/canvas-bridge/referral.js @@ -48,10 +48,10 @@ function readSignals(body) { async function profileOf(body, ipHash, hash) { const signals = readSignals(body); - const secret = String(body?.secret || ''); + const mark = String(body?.mark || ''); return { device: String(body?.device || ''), - secret: /^[a-f0-9]{32}$/.test(secret) ? await hash(secret) : '', + mark: /^[a-f0-9]{32}$/.test(mark) ? await hash(mark) : '', hardware: await hash(hardwareKey(signals)), browser: await hash(browserKey(signals)), family: platformFamily(signals.ua, signals.platform), diff --git a/js/access.js b/js/access.js index 8dc7df3..1aa05c8 100644 --- a/js/access.js +++ b/js/access.js @@ -4,7 +4,7 @@ import { STATS_URL, deviceId } from './live-stats.js'; import { DEV_ACCESS_STORAGE_KEY, DEV_ACCOUNT_CACHE_KEY, isAllowedSpotifyId, sha256Hex, verifySessionToken } from './maintenance.js'; import * as store from './store.js'; -import { installSecret, signalsFromHere } from './referral.js'; +import { installMark, signalsFromHere } from './referral.js'; import { ACTIONS, DAILY_LIMIT, RESTRICTED_FEATURES, addUsage, isKnownAction, quotaView, utcDay, } from './access-policy.js'; @@ -376,7 +376,7 @@ export function consumeStarQuery() { } async function supportBody(extra = {}) { - return { device: deviceId(), secret: await installSecret(), signals: signalsFromHere(), ...extra }; + return { device: deviceId(), mark: await installMark(), signals: signalsFromHere(), ...extra }; } async function postJson(path, body, fetcher = globalThis.fetch) { diff --git a/js/referral.js b/js/referral.js index d4da483..a4a9e4c 100644 --- a/js/referral.js +++ b/js/referral.js @@ -5,7 +5,7 @@ import { DISCORD } from './access-policy.js'; export const HOLD_MS = 60_000; export const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; -const SECRET_KEY = 'spotplus.installSecret'; +const MARK_KEY = 'spotplus.installMark'; export function normalizeCode(input) { const code = String(input || '').toUpperCase().replace(/[^A-Z2-9]/g, '').replace(/[OIL01]/g, ''); @@ -90,7 +90,7 @@ export function signalsFromHere() { }; } -function randomSecret() { +function randomMark() { const bytes = new Uint8Array(16); crypto.getRandomValues(bytes); return [...bytes].map((b) => b.toString(16).padStart(2, '0')).join(''); @@ -106,39 +106,39 @@ function openKv() { }); } -async function idbSecret(value) { +async function idbMark(value) { const db = await openKv(); return new Promise((resolve, reject) => { const tx = db.transaction('kv', value ? 'readwrite' : 'readonly'); const store = tx.objectStore('kv'); - const req = value ? store.put(value, SECRET_KEY) : store.get(SECRET_KEY); + const req = value ? store.put(value, MARK_KEY) : store.get(MARK_KEY); req.onsuccess = () => resolve(req.result || ''); req.onerror = () => reject(req.error); }); } -/** Secret kept in localStorage and IndexedDB, so clearing one store is not a new person. */ -export async function installSecret(storage = globalThis.localStorage) { - let secret = ''; - try { secret = storage?.getItem?.(SECRET_KEY) || ''; } catch { /* private mode */ } - if (!/^[a-f0-9]{32}$/.test(secret)) { - try { secret = await idbSecret(); } catch { secret = ''; } +/** Install id kept in localStorage and IndexedDB, so clearing one store is not a new person. */ +export async function installMark(storage = globalThis.localStorage) { + let mark = ''; + try { mark = storage?.getItem?.(MARK_KEY) || ''; } catch { /* private mode */ } + if (!/^[a-f0-9]{32}$/.test(mark)) { + try { mark = await idbMark(); } catch { mark = ''; } } - if (!/^[a-f0-9]{32}$/.test(secret)) secret = randomSecret(); - try { storage?.setItem?.(SECRET_KEY, secret); } catch { /* ignore */ } - try { await idbSecret(secret); } catch { /* ignore */ } - return secret; + if (!/^[a-f0-9]{32}$/.test(mark)) mark = randomMark(); + try { storage?.setItem?.(MARK_KEY, mark); } catch { /* ignore */ } + try { await idbMark(mark); } catch { /* ignore */ } + return mark; } /** * Decide whether the friend install is someone else. - * `hardware`, `secret`, and `browser` are already hashes when the bridge calls this. + * `hardware`, `mark`, and `browser` are already hashes when the bridge calls this. */ export function judgeReferral({ referrer = {}, friend = {}, codeCreatedAt = 0, friendFirstSeen = 0, standalone = false } = {}) { if (!standalone) return { ok: false, reason: 'install' }; if (!friend.device || !referrer.device) return { ok: false, reason: 'invalid' }; if (friend.device === referrer.device) return { ok: false, reason: 'self' }; - if (friend.secret && referrer.secret && friend.secret === referrer.secret) return { ok: false, reason: 'self' }; + if (friend.mark && referrer.mark && friend.mark === referrer.mark) return { ok: false, reason: 'self' }; if (friendFirstSeen > 0 && codeCreatedAt > 0 && friendFirstSeen + 1500 < codeCreatedAt) return { ok: false, reason: 'not-new' }; if (friend.hardware && referrer.hardware && friend.hardware === referrer.hardware) return { ok: false, reason: 'same-device' }; if (friend.browser && referrer.browser && friend.browser === referrer.browser) return { ok: false, reason: 'same-browser' }; diff --git a/tests/access-limit.test.mjs b/tests/access-limit.test.mjs index 67d3411..03a26be 100644 --- a/tests/access-limit.test.mjs +++ b/tests/access-limit.test.mjs @@ -103,11 +103,11 @@ test('owner devices are excluded from the device and network allowance', async ( }); test('a friend code rejects the same device, another browser, and a VPN, and accepts another device', () => { - const mine = { device: dev('a'), secret: 'secret-a', hardware: hardwareKey(phone), browser: 'browser-a', family: 'ios', screen: '400x840@3', ip: ip('a') }; + const mine = { device: dev('a'), mark: 'mark-a', hardware: hardwareKey(phone), browser: 'browser-a', family: 'ios', screen: '400x840@3', ip: ip('a') }; assert.equal(judgeReferral({ referrer: mine, friend: { ...mine }, standalone: true }).reason, 'self'); - const otherBrowser = { ...mine, device: dev('b'), secret: 'secret-b', browser: 'browser-b', ip: ip('d') }; + const otherBrowser = { ...mine, device: dev('b'), mark: 'mark-b', browser: 'browser-b', ip: ip('d') }; assert.equal(judgeReferral({ referrer: mine, friend: otherBrowser, standalone: true }).reason, 'same-device'); - const friend = { device: dev('c'), secret: 'secret-c', hardware: hardwareKey(laptop), browser: 'browser-c', family: 'windows', screen: '1920x1080@1', ip: ip('e') }; + const friend = { device: dev('c'), mark: 'mark-c', hardware: hardwareKey(laptop), browser: 'browser-c', family: 'windows', screen: '1920x1080@1', ip: ip('e') }; assert.equal(judgeReferral({ referrer: mine, friend, standalone: true, codeCreatedAt: 100, friendFirstSeen: 0, }).ok, true); @@ -128,19 +128,19 @@ test('redeeming a code waits, then unlocks only the referrer, and an owner devic const referrer = dev('d'); const friend = dev('e'); const made = await (await handleAccess(post('/access/refer/code', { - device: referrer, secret: secret('1'), signals: phone, + device: referrer, mark: secret('1'), signals: phone, }, { address: ip('a') }), { storage, now: created })).json(); assert.equal(made.ok, true); assert.match(made.code, /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{8}$/); const early = await (await handleAccess(post('/access/refer/redeem', { - device: friend, secret: secret('2'), code: made.code, signals: laptop, + device: friend, mark: secret('2'), code: made.code, signals: laptop, }, { address: ip('f') }), { storage, now: created + 10_000 })).json(); assert.equal(early.reason, 'hold'); assert.ok(early.challenge); const done = await (await handleAccess(post('/access/refer/redeem', { - device: friend, secret: secret('2'), code: made.code, challenge: early.challenge, signals: laptop, + device: friend, mark: secret('2'), code: made.code, challenge: early.challenge, signals: laptop, }, { address: ip('f') }), { storage, now: created + 80_000 })).json(); assert.equal(done.ok, true); assert.notEqual(done.tier, 'full'); @@ -153,7 +153,7 @@ test('redeeming a code waits, then unlocks only the referrer, and an owner devic const ownerDevice = dev('f'); await handleAccess(post('/access', { device: ownerDevice, action: 'status', n: 0, nonce: 'dd'.repeat(8) }, { owner: token, origin }), { storage, now: created }); const blocked = await (await handleAccess(post('/access/refer/redeem', { - device: ownerDevice, secret: secret('3'), code: 'ABCD2345', signals: laptop, + device: ownerDevice, mark: secret('3'), code: 'ABCD2345', signals: laptop, }, { owner: token, origin, address: ip('9') }), { storage, now: created + 120_000 })).json(); assert.equal(blocked.reason, 'excluded'); }); From c5b94a410ac11af43b1d534db6cf7c8e1207f705 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 18:29:22 +0000 Subject: [PATCH 3/3] fix: verify GitHub stars from the public stars page The bridge's shared GitHub API quota was exhausted, so every star check failed. Read the public stars page first and only use the API if that page cannot be read. Co-authored-by: Coye --- CHANGELOG.md | 1 + canvas-bridge/access.js | 33 +++++++++++++++++++++++++++++++-- js/access-ui.js | 4 ++-- js/access.js | 5 ++++- js/changelog.js | 1 + tests/access-limit.test.mjs | 16 +++++++++++++++- 6 files changed, 54 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed544b3..d7bebf3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ _2026-11-25_ - After the limit is reached, the song already playing can finish and the queue can still advance. Skip, Insta Play, Insta Choose, seeking, new downloads, repeat, Canvas, and early loading of the next song stay off until the next day. - Unlock: star coye2/spot-plus on GitHub and verify the star, join the Discord and verify membership, or refer a friend who installs Spot+ and enters your code. Another browser, phone, or VPN on the same device does not count as that friend. - Your own devices are excluded from the limit, including devices linked with the same library sync key. They do not spend the allowance. +- Star verification reads GitHub’s public stars page, so a busy API limit no longer stops the check. ## 2.2.6 — Vehicle integration architecture: Spot+ Drive bridge, OpenSubsonic gateway PoC & Native Microbridge _2026-11-25_ diff --git a/canvas-bridge/access.js b/canvas-bridge/access.js index 8537350..a3a6ea8 100644 --- a/canvas-bridge/access.js +++ b/canvas-bridge/access.js @@ -121,14 +121,43 @@ function githubHeaders(token) { return headers; } +/** True when a GitHub stars page links this exact repository. */ +export function pageShowsStar(html, full = REPO.full) { + const page = String(html || '').toLowerCase(); + const name = String(full || '').toLowerCase(); + return page.includes('href="/' + name + '"') || page.includes('href="/' + name + '/"'); +} + +async function findStarOnSite(name, fetcher, signal) { + const headers = { Accept: 'text/html', 'User-Agent': 'SpotPlus (https://coye2.github.io/spot-plus/)' }; + for (let page = 1; page <= 5; page++) { + const url = 'https://github.com/' + encodeURIComponent(name) + '?tab=stars' + (page > 1 ? '&page=' + page : ''); + let res; + try { res = await fetcher(url, { headers, redirect: 'manual', signal }); } catch { return { ok: false, reason: 'unavailable' }; } + if (res.status === 404) return { ok: false, reason: 'not-found' }; + if (res.status === 403 || res.status === 429) return { ok: false, reason: 'rate-limited' }; + if (res.status >= 300 && res.status < 400) return { ok: false, reason: 'not-found' }; + if (!res.ok) return { ok: false, reason: 'unavailable' }; + const html = await res.text(); + if (html.length > 2000000) return { ok: false, reason: 'unavailable' }; + if (pageShowsStar(html)) return { ok: true, login: name }; + if (!/rel="next"/i.test(html)) return { ok: false, reason: 'not-starred' }; + } + return { ok: false, reason: 'incomplete', login: name }; +} + /** * Confirm the account exists and that coye2/spot-plus is in its public stars. - * GitHub lists stars newest-first, so a star just given is on page 1. - * Scanning later pages covers accounts that starred earlier. + * The public stars page is checked first. The REST API is only the fallback, + * because Cloudflare's shared address exhausts GitHub's unauthenticated quota. */ export async function findStar(login, fetcher, { token = '', maxPages = MAX_STAR_PAGES, signal } = {}) { const name = normalizeLogin(login); if (!name) return { ok: false, reason: 'invalid' }; + if (!token) { + const page = await findStarOnSite(name, fetcher, signal); + if (page.ok || page.reason === 'not-starred' || page.reason === 'not-found' || page.reason === 'incomplete') return page; + } const headers = githubHeaders(token); let userRes; try { diff --git a/js/access-ui.js b/js/access-ui.js index e63c07e..35e35f5 100644 --- a/js/access-ui.js +++ b/js/access-ui.js @@ -10,8 +10,8 @@ const REASONS = { 'not-starred': 'That GitHub account has no public star on ' + REPO.full + ' yet. Star the repo, then verify again.', 'not-found': 'No GitHub account uses that username.', invalid: 'That code or username doesn’t check out. Use the 8-character friend code, or the GitHub username that starred the repo.', - 'rate-limited': 'Too many checks right now. Wait a few minutes and try again.', - unavailable: 'Spot+ couldn’t finish that check. Try again in a moment.', + 'rate-limited': 'GitHub is limiting star checks from the bridge right now. Wait a few minutes and verify again.', + unavailable: 'The bridge could not read that GitHub account. Check the username and try again.', incomplete: 'Star the repo again so it is the most recent star, then verify.', 'device-cap': 'That support account already unlocked 3 devices.', denied: 'Sign-in was cancelled before Spot+ could check.', diff --git a/js/access.js b/js/access.js index 1aa05c8..d0c88f4 100644 --- a/js/access.js +++ b/js/access.js @@ -343,7 +343,10 @@ export async function verifyUsername(username, fetcher = globalThis.fetch) { body: JSON.stringify({ device, username }), }); const data = await res.json().catch(() => null); - if (!data) return { ok: false, reason: res.status === 429 ? 'rate-limited' : 'unavailable' }; + if (!data) return { ok: false, reason: res.status === 429 || res.status === 403 ? 'rate-limited' : 'unavailable' }; + if (!data.ok && !data.reason && (res.status === 429 || res.status === 403 || /too many|rate/i.test(String(data.error || '')))) { + data.reason = 'rate-limited'; + } if (data.ok) applyServerSnapshot(data, { authoritative: true }); return data; } catch { diff --git a/js/changelog.js b/js/changelog.js index baecacc..63ac22d 100644 --- a/js/changelog.js +++ b/js/changelog.js @@ -6,6 +6,7 @@ export const CHANGELOG = [ 'After the limit is reached, the song already playing can finish and the queue can still advance. Skip, Insta Play, Insta Choose, seeking, new downloads, repeat, Canvas, and early loading of the next song stay off until the next day.', 'Unlock: star coye2/spot-plus on GitHub and verify the star, join the Discord and verify membership, or refer a friend who installs Spot+ and enters your code. Another browser, phone, or VPN on the same device does not count as that friend.', 'Your own devices are excluded from the limit, including devices linked with the same library sync key. They do not spend the allowance.', + 'Star verification reads GitHub’s public stars page, so a busy API limit no longer stops the check.', ]}, {version: '2.2.6', date: '2026-11-25', title: 'Vehicle integration architecture: Spot+ Drive bridge, OpenSubsonic gateway PoC & Native Microbridge', items: [ 'Path 1 — Browser-Native Vehicle Media Bridge (Spot+ Drive): added capability-adaptive DriveMediaBridge (feature-flagged off by default via vehicleDriveBridge) with WebKit/CarPlay Now Playing and Chromium/Bluetooth AVRCP capability detection, head-unit metadata sanitization, steering-wheel duplicate-pulse debouncing, explicit ±10s suppression so CarPlay keeps Previous/Next buttons, and safe wireless-disconnect interruption classification with zero polling or audio element teardown.', diff --git a/tests/access-limit.test.mjs b/tests/access-limit.test.mjs index 03a26be..a1a120a 100644 --- a/tests/access-limit.test.mjs +++ b/tests/access-limit.test.mjs @@ -4,7 +4,7 @@ import { DAILY_LIMIT, addUsage, quotaView, utcDay } from '../js/access-policy.js import { hardwareKey, judgeReferral, normalizeCode } from '../js/referral.js'; import { createLedger } from '../js/access.js'; import { ALLOWED_ID_HASHES, createSessionToken, isOwnerProof } from '../js/maintenance.js'; -import { handleAccess } from '../canvas-bridge/access.js'; +import { findStar, handleAccess, pageShowsStar } from '../canvas-bridge/access.js'; import { storageMock } from './helpers.mjs'; function mem() { @@ -158,6 +158,20 @@ test('redeeming a code waits, then unlocks only the referrer, and an owner devic assert.equal(blocked.reason, 'excluded'); }); +test('star verification reads the public stars page before the rate-limited API', async () => { + assert.equal(pageShowsStar('Spot+'), true); + assert.equal(pageShowsStar('nope'), false); + let apiCalls = 0; + const fetcher = async (url) => { + if (String(url).includes('api.github.com')) { apiCalls++; return new Response('{}', { status: 429 }); } + return new Response('star', { status: 200 }); + }; + const found = await findStar('fredgolightly', fetcher); + assert.equal(found.ok, true); + assert.equal(found.login, 'fredgolightly'); + assert.equal(apiCalls, 0); +}); + test('utc day is the allowance window', () => { assert.equal(utcDay(Date.parse('2026-11-25T23:30:00Z')), '2026-11-25'); assert.equal(utcDay(Date.parse('2026-11-26T00:30:00Z')), '2026-11-26');