earshelf / source /src /pro.ts
WilburDev's picture
Deploy 2026-11-20T20:26Z
b1876f7 verified
Raw History Blame Contribute Delete
6.89 kB
// "Pro" unlock: the access code from the Gumroad receipt (a Gumroad license key), checked from the browser and
// remembered on this device.
// Free: FREE_MINUTES of listening on this device, any voice, any book (the built-in sample does not count).
// Pro: unlimited listening.
//
// SWITCHED ON since 2026-11-20 (Gumroad product published). Tests and previews can turn it off with
// localStorage['earshelf.pro'] = 'off' (or on with 'on'). Nothing here runs a server; any check in the browser can be
// bypassed by a technical user, which is accepted: paying must be easier than cracking.
export const PRO = {
enabled: true,
// Gumroad product "EarShelf Pro" (license keys on), published 2026-11-20
productId: 'ZWjOGDzBDsua-Kv6BhBvaA==',
checkoutUrl: 'https://webixtech.gumroad.com/l/earshelf-pro',
price: 'US$29',
guaranteeDays: 30,
recheckDays: 30, // re-verify a saved key this often (offline keeps working until it can)
};
const VERIFY_URL = 'https://api.gumroad.com/v2/licenses/verify';
const KEY = 'earshelf.license';
export interface License {
key: string;
email: string;
verifiedAt: number;
/** definite "no" answers in a row (Pro is removed at the second) */
fails?: number;
}
export function paywallOn(): boolean {
try {
const v = localStorage.getItem('earshelf.pro');
if (v === 'on') return true;
if (v === 'off') return false;
} catch {
/* storage blocked */
}
return PRO.enabled;
}
export function savedLicense(): License | null {
try {
const raw = localStorage.getItem(KEY);
const l = raw ? (JSON.parse(raw) as License) : null;
return l && typeof l.key === 'string' ? l : null;
} catch {
return null;
}
}
export function isPro(): boolean {
return !!savedLicense();
}
/** Free listening on this device before the paywall: minutes of real playback, any voice, any book. */
export const FREE_MINUTES = 7;
const TRIAL = 'earshelf.trial';
/** Seconds of free listening (tests shrink it with localStorage['earshelf.freeSec']). */
export function freeSeconds(): number {
try {
const t = Number(localStorage.getItem('earshelf.freeSec'));
if (t > 0) return t;
} catch {
/* storage blocked */
}
return FREE_MINUTES * 60;
}
/** Seconds already listened for free on this device. */
export function trialUsed(): number {
try {
const n = Number(localStorage.getItem(TRIAL));
return Number.isFinite(n) && n > 0 ? n : 0;
} catch {
return 0;
}
}
/** Add listening time (seconds). Never goes down; the larger of two stores wins (see main.ts). */
export function addTrial(sec: number, floor = 0) {
const v = Math.max(trialUsed() + Math.max(0, sec), floor);
try {
localStorage.setItem(TRIAL, String(Math.round(v * 10) / 10));
} catch {
/* storage blocked */
}
return v;
}
export function trialLeft(): number {
return Math.max(0, freeSeconds() + bonusSeconds() - trialUsed());
}
/* A one-time surprise: a day after the free minutes ran out, 2 more minutes ("the next page is on us"). */
const GATE_AT = 'earshelf.gateAt';
const BONUS = 'earshelf.bonus';
export const BONUS_SECONDS = 120;
function bonusSeconds(): number {
try {
return Number(localStorage.getItem(BONUS)) || 0;
} catch {
return 0;
}
}
/** Remember when the paywall first stopped playback. */
export function noteGate(now = Date.now()) {
try {
if (!localStorage.getItem(GATE_AT)) localStorage.setItem(GATE_AT, String(now));
} catch {
/* storage blocked */
}
}
/** Gives the bonus once, 24 h or more after the first stop. True when it was just given. */
export function grantBonus(now = Date.now()): boolean {
try {
const at = Number(localStorage.getItem(GATE_AT)) || 0;
if (!at || localStorage.getItem(BONUS) || isPro() || !paywallOn() || now - at < 86_400_000) return false;
localStorage.setItem(BONUS, String(trialUsed() - freeSeconds() + BONUS_SECONDS)); // 2 minutes from wherever the count is
return true;
} catch {
return false;
}
}
/** Does this book count against the free minutes? (the built-in sample never does) */
export function counts(book: { format: string } | null): boolean {
return !!book && book.format !== 'sample' && paywallOn() && !isPro();
}
/** May playback go on? False only when the free minutes are used up on a metered book. */
export function mayListen(book: { format: string } | null): boolean {
return !counts(book) || trialLeft() > 0;
}
export type VerifyResult = { ok: true; license: License } | { ok: false; reason: 'invalid' | 'refunded' | 'network' };
/** Ask Gumroad whether a key is valid for this product. Does not count as a new use of the key. */
export async function verifyKey(key: string, fetcher: typeof fetch = fetch): Promise<VerifyResult> {
const k = key.replace(/\s+/g, ''); // pasted from an email: stray spaces and line breaks
if (!k) return { ok: false, reason: 'invalid' };
let res: Response;
try {
res = await fetcher(VERIFY_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ product_id: PRO.productId, license_key: k, increment_uses_count: 'false' }),
});
} catch {
return { ok: false, reason: 'network' };
}
let data: any = null;
try {
data = await res.json();
} catch {
/* not JSON */
}
// a Wi-Fi login page, proxy or rate limit is not an answer about the key
if (!data || typeof data !== 'object' || res.status === 408 || res.status === 429 || res.status >= 500) return { ok: false, reason: 'network' };
if (!data.success) return { ok: false, reason: 'invalid' };
const p = data.purchase || {};
if (p.refunded || p.chargebacked || p.disputed) return { ok: false, reason: 'refunded' };
return { ok: true, license: { key: k, email: String(p.email || ''), verifiedAt: Date.now() } };
}
export function storeLicense(l: License | null) {
try {
if (l) localStorage.setItem(KEY, JSON.stringify(l));
else localStorage.removeItem(KEY);
} catch {
/* storage blocked */
}
}
/**
* Re-check a saved key now and then. A network failure keeps Pro (offline use must keep working);
* only a definite "invalid" or "refunded" answer removes it.
*/
export async function recheck(now = Date.now(), fetcher: typeof fetch = fetch): Promise<'kept' | 'removed' | 'skipped'> {
const l = savedLicense();
if (!l) return 'skipped';
if (now - l.verifiedAt < PRO.recheckDays * 86_400_000) return 'skipped';
const r = await verifyKey(l.key, fetcher);
if (r.ok) {
storeLicense({ ...r.license, verifiedAt: now, fails: 0 });
return 'kept';
}
if (r.reason === 'network') return 'kept';
if (r.reason === 'invalid' && !l.fails) {
storeLicense({ ...l, fails: 1, verifiedAt: now - PRO.recheckDays * 86_400_000 + 86_400_000 }); // ask again tomorrow
return 'kept';
}
storeLicense(null);
return 'removed';
}