diff --git a/CHANGELOG.md b/CHANGELOG.md
index b0b8222..d7bebf3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,15 @@
Every Spot+ update. The app shows the newest ones in its “What’s new” screen.
+## 2.2.7 — Base tier daily limit, unlocked by support
+_2026-11-25_
+
+- Daily limit: on the base tier, Skip, Insta Play, and Insta Choose share 300 uses a day. The count is kept per device and per network address, and either one running out is enough.
+- 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
new file mode 100644
index 0000000..a3a6ea8
--- /dev/null
+++ b/canvas-bridge/access.js
@@ -0,0 +1,610 @@
+// 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;
+}
+
+/** 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.
+ * 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 {
+ 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..c597354
--- /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 mark = String(body?.mark || '');
+ return {
+ device: String(body?.device || ''),
+ 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),
+ 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..35e35f5
--- /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': '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.',
+ '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 ` Spot+ is free, powered by love and support. ${note} 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.'}Support
Support
+
Free, powered by support
+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.
+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..d0c88f4 --- /dev/null +++ b/js/access.js @@ -0,0 +1,414 @@ +// 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 { installMark, 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 || 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 { + 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(), mark: await installMark(), 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 `