Files
it-tools-pro/src/tools/license/license.ts
T

318 lines
10 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 = '/buy'; // 站内支付页:下单 -> 支付 -> 当场显示卡密
// 受控功能(消耗服务器性能:翻译走服务器代理、OCR 走本机识别服务)
export const PROTECTED_TOOLS: Record<string, string> = {
'/translator': '在线翻译',
'/image-ocr': '图片OCR文字识别',
'/pdf-ocr': 'PDF文字识别',
'/ai-retouch': 'AI修图',
'/doc-convert': '文档格式转换',
'/image-tools': '图片工具',
'/pdf-tools': 'PDF工具',
'/video-tools': '视频工具',
'/audio-tools': '音频工具',
'/text-to-image': '文字生成图片',
'/ai-image-lab': 'AI图片实验室',
'/copywriting': '文案工具箱',
'/ai-gen': 'AI 生图',
'/face-swap': 'AI换脸',
'/poster-maker': 'AI海报生成',
};
export const TRIAL_MS = 30 * 60 * 1000; // 每个功能每天免费 30 分钟
const DAY_MS = 24 * 60 * 60 * 1000;
const TZ_OFFSET_MS = 8 * 60 * 60 * 1000; // 北京时间 UTC+8 —— 重置对齐自然日 0 点
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;
}
/** 当天 00:00(北京时间)对应的时间戳 */
function todayStartOf(now: number): number {
return Math.floor((now + TZ_OFFSET_MS) / DAY_MS) * DAY_MS - TZ_OFFSET_MS;
}
export function startTrial(path: string): void {
const t = readTrials();
const now = Date.now();
const start = t[path];
// 首次进入,或已跨到新的一天 → 立刻开新一天的额度
// (额度只在用户当天真的进来时才起算,不会从 0 点空耗)
if (!start || start < todayStartOf(now)) {
t[path] = now;
writeTrials(t);
}
}
export function remainingMs(path: string, now: number): number {
const start = getTrialStart(path);
if (start === null) {
return TRIAL_MS; // 尚未开始计时
}
// 起点不早于今天 0 点:昨天的起点在跨天后自动失效
const s = Math.max(start, todayStartOf(now));
return Math.max(0, TRIAL_MS - (now - s));
}
/** 下一次重置时刻(恒为次日 00:00 北京时间);未开始计时返回 null */
export function nextTrialResetAt(path: string, now: number): number | null {
if (getTrialStart(path) === null) return null;
return todayStartOf(now) + DAY_MS;
}
/** 人类可读的重置提示,恒为「明天 00:00」 */
export function trialResetHint(path: string, now: number): string {
const at = nextTrialResetAt(path, now);
if (at === null) return '';
const d = new Date(at);
return `明天 ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
}
// ====== 授权状态 ======
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;
}
}
// ---- 工具使用统计上报:任何访客(含未登录)打开工具页即计一次 ----
// 同一工具 10 分钟内只上报一次(防刷新刷量),服务端还会再做一层去重与限流。
const USAGE_THROTTLE_MS = 10 * 60 * 1000;
export function reportToolUsage(path: string): void {
try {
const tool = String(path || '').replace(/^\/+/, '').slice(0, 64);
if (!tool) {
return;
}
const key = `it-tools-usage:${tool}`;
const last = Number(localStorage.getItem(key) || 0);
if (Date.now() - last < USAGE_THROTTLE_MS) {
return;
}
localStorage.setItem(key, String(Date.now()));
let machine = '';
try {
machine = getMachineId();
}
catch {
machine = '';
}
fetch('/relay/usage', {
method: 'POST',
keepalive: true,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ machine_id: machine, tool }),
}).catch(() => {});
}
catch {
// 统计失败绝不影响功能
}
}
// ---- 在线统计心跳:打开满 1 分钟才开始上报;仅未登录访客被统计 ----
const ONLINE_DELAY_MS = 60 * 1000; // 停留超过 1 分钟才计入在线(由前端延迟首发实现)
const ONLINE_BEAT_MS = 30 * 1000; // 之后每 30s 心跳一次(后台标签被浏览器节流为 60s,服务端 90s 窗口判定)
let onlineStarted = false;
function isGuest(): boolean {
try {
return !JSON.parse(localStorage.getItem('it-tools-auth') ?? 'null');
}
catch {
return true;
}
}
export function startOnlineHeartbeat(): void {
if (onlineStarted) {
return;
}
onlineStarted = true;
const beat = () => {
try {
fetch('/relay/online', {
method: 'POST',
keepalive: true,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ machine_id: getMachineId(), guest: isGuest() }),
}).catch(() => {});
}
catch {
// 统计失败绝不影响功能
}
};
setTimeout(() => {
beat();
setInterval(beat, ONLINE_BEAT_MS);
// 登录/登出立即同步:登录后该机器被移出在线统计
window.addEventListener('it-tools-auth-changed', beat);
}, ONLINE_DELAY_MS);
}