Files
it-tools-pro/src/tools/license/license.ts
T
personal82555 1c53e2b188 feat(license): 免费试用改为每24小时30分钟窗口,额度在用户进入时才开启
- 前端 startTrial/remainingMs: 距窗口起点满24h即刷新起点,额度不因用户缺席空耗
- 服务端 trial_allowed 同步同算法(TRIAL_CYCLE_H可配),前后端窗口一致,避免前端显示有额度而服务端403
- 锁定弹窗提示「明天 HH:MM 可再试」,Pricing/About/README/403文案统一为「每天/今日」
- 验证: 服务端 /check 6/6 + 前端 5/5 通过
2026-10-14 21:17:45 +08:00

247 lines
8.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { reactive } from 'vue';
// ====== 授权服务器 (CardAuth) ======
export const AUTH_BASE = 'https://auth.88531.cn/api';
export const BUY_URL = 'https://auth.88531.cn/#/shop';
// 受控功能(消耗服务器性能:翻译走服务器代理、OCR 走本机识别服务)
export const PROTECTED_TOOLS: Record<string, string> = {
'/translator': '在线翻译',
'/image-ocr': '图片OCR文字识别',
'/pdf-ocr': 'PDF文字识别',
'/ai-retouch': 'AI修图',
'/label-designer': '面单设计',
'/doc-convert': '文档格式转换',
'/image-tools': '图片工具',
'/pdf-tools': 'PDF工具',
'/video-tools': '视频工具',
'/audio-tools': '音频工具',
'/text-to-image': '文字生成图片',
'/ai-image-lab': 'AI图片实验室',
'/ai-chat': 'AI客服',
'/copywriting': '文案工具箱',
'/ai-gen': 'AI 生图',
};
export const TRIAL_MS = 30 * 60 * 1000; // 每个功能每轮免费 30 分钟
export const TRIAL_CYCLE_MS = 24 * 60 * 60 * 1000; // 每 24 小时重置一轮(买断制下给用户第二次触达机会)
const MACHINE_KEY = 'it-tools-machine-id';
const TRIAL_KEY = 'it-tools-trials';
const AUTH_CACHE_KEY = 'it-tools-auth-cache';
// ====== 机器码:13 位数字,首次生成后持久化 ======
export function getMachineId(): string {
let id = localStorage.getItem(MACHINE_KEY);
if (!id || !/^\d{10,16}$/.test(id)) {
id = `9${Date.now().toString().slice(-9)}${Math.floor(Math.random() * 1000).toString().padStart(3, '0')}`;
localStorage.setItem(MACHINE_KEY, id);
}
return id;
}
// ====== 免费试用计时(每个功能独立;以首次进入为锚点,每 24 小时滚一轮) ======
function readTrials(): Record<string, number> {
try {
return JSON.parse(localStorage.getItem(TRIAL_KEY) ?? '{}');
}
catch {
return {};
}
}
function writeTrials(t: Record<string, number>) {
localStorage.setItem(TRIAL_KEY, JSON.stringify(t));
}
export function getTrialStart(path: string): number | null {
return readTrials()[path] ?? null;
}
export function startTrial(path: string): void {
const t = readTrials();
const now = Date.now();
const start = t[path];
// 首次进入,或距本窗口起点已满一个周期 → 立刻开新窗口
// (否则额度会从上一轮起点空耗掉,用户不在场也算用过)
if (!start || now - start >= TRIAL_CYCLE_MS) {
t[path] = now;
writeTrials(t);
}
}
/** 当前轮次起点:锚定首次进入时间,每 TRIAL_CYCLE_MS 滚动一次 */
function cycleStartOf(start: number, now: number): number {
if (now <= start) return start;
return start + Math.floor((now - start) / TRIAL_CYCLE_MS) * TRIAL_CYCLE_MS;
}
export function remainingMs(path: string, now: number): number {
const start = getTrialStart(path);
if (start === null) {
return TRIAL_MS; // 尚未开始计时
}
return Math.max(0, TRIAL_MS - (now - cycleStartOf(start, now)));
}
/** 本轮已用完时,下一轮免费试用的重置时刻(ms 时间戳);未开始计时返回 null */
export function nextTrialResetAt(path: string, now: number): number | null {
const start = getTrialStart(path);
if (start === null) return null;
if (remainingMs(path, now) > 0) return null; // 本轮还有剩余,无需提示重置
return cycleStartOf(start, now) + TRIAL_CYCLE_MS;
}
/** 人类可读的重置提示,如「明天 14:23」/「今天 21:05」 */
export function trialResetHint(path: string, now: number): string {
const at = nextTrialResetAt(path, now);
if (at === null) return '';
const d = new Date(at);
const hm = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
const start = getTrialStart(path);
const cycleOfAt = cycleStartOf(start ?? now, at);
const sameDay = new Date(cycleOfAt).toDateString() === new Date(now).toDateString();
return `${sameDay ? '今天' : '明天'} ${hm}`;
}
// ====== 授权状态 ======
export const licenseState = reactive({
checking: false,
checked: false,
authorized: false,
activating: false,
activateError: '',
activateSuccess: false,
});
/** 撤销本机授权(relay 本地即时生效,并尽力同步 CardAuth) */
export async function deactivateLicense(): Promise<{ ok: boolean; msg: string }> {
try {
const res = await fetch('/relay/deactivate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ machine_id: getMachineId() }),
});
const json = await res.json().catch(() => null);
if (json?.code === 200) {
licenseState.authorized = false;
writeAuthCache(false);
return { ok: true, msg: '已撤销授权,本机回到免费试用状态' };
}
return { ok: false, msg: json?.message || '撤销失败,请稍后再试' };
}
catch {
return { ok: false, msg: '网络错误,撤销失败' };
}
}
function readAuthCache(): boolean {
try {
const c = JSON.parse(localStorage.getItem(AUTH_CACHE_KEY) ?? 'null');
return c?.authorized === true;
}
catch {
return false;
}
}
function writeAuthCache(authorized: boolean) {
localStorage.setItem(AUTH_CACHE_KEY, JSON.stringify({ authorized, at: Date.now() }));
}
/** 查询机器码授权状态:统一由本站 relay 判定(本地撤销名单 + CardAuth);
* 网络失败时回退到本地缓存(断网不锁死已购用户) */
export async function checkAuth(): Promise<boolean> {
licenseState.checking = true;
try {
const res = await fetch(`/relay/auth-status?machine_id=${encodeURIComponent(getMachineId())}`, { method: 'GET' });
const json = await res.json();
if (json?.code === 200) {
const ok = json.data?.authorized === true;
licenseState.authorized = ok;
writeAuthCache(ok);
return ok;
}
// 服务端业务错误:按未授权处理,但不覆盖缓存里的已授权
licenseState.authorized = readAuthCache();
return licenseState.authorized;
}
catch {
// 网络失败:用本地缓存
licenseState.authorized = readAuthCache();
return licenseState.authorized;
}
finally {
licenseState.checking = false;
licenseState.checked = true;
}
}
/** 受控 API 请求头:服务端 nginx auth_request 按此校验授权/试用 */
export function licenseHeaders(tool: string): Record<string, string> {
return {
'X-Machine-Id': getMachineId(),
'X-Tool': tool,
};
}
/** 激活卡密 */
export async function activateCard(cardKey: string, contactQq: string, replace = false): Promise<{ ok: boolean; msg: string }> {
const key = cardKey.trim();
if (!key) {
return { ok: false, msg: '请输入卡密' };
}
licenseState.activating = true;
licenseState.activateError = '';
licenseState.activateSuccess = false;
try {
// 走本站 relay:API Key 只存在服务端,且 relay 先用 /verify 预检卡密
// attach the logged-in account token so the card is bound to the account (follows across devices)
let authHeader = '';
try {
const auth = JSON.parse(localStorage.getItem('it-tools-auth') ?? 'null');
if (auth?.token) {
authHeader = `Bearer ${auth.token}`;
}
}
catch { /* ignore */ }
const actHeaders: Record<string, string> = { 'Content-Type': 'application/json' };
if (authHeader) {
actHeaders['Authorization'] = authHeader;
}
const res = await fetch('/relay/activate', {
method: 'POST',
headers: actHeaders,
body: JSON.stringify({
card_key: key,
machine_id: getMachineId(),
contact_qq: contactQq.trim() || getMachineId(),
replace,
}),
});
const json = await res.json();
if (json?.code === 200) {
// 激活成功 → 重新查询确认
const ok = await checkAuth();
if (ok) {
licenseState.activateSuccess = true;
return { ok: true, msg: '激活成功,全部功能已解锁' };
}
return { ok: false, msg: '激活请求已受理,但授权状态未生效,请稍后刷新重试' };
}
const msg = json?.message || '激活失败';
licenseState.activateError = msg;
return { ok: false, msg };
}
catch (e: any) {
const msg = `网络错误:${e?.message ?? e}`;
licenseState.activateError = msg;
return { ok: false, msg };
}
finally {
licenseState.activating = false;
}
}