From 70e03feca6a5ef8008416c646772f8b714b15342 Mon Sep 17 00:00:00 2001 From: personal82555 Date: Mon, 12 Oct 2026 12:32:13 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=8E=88=E6=9D=83=E5=85=B3=E8=81=94?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E8=B4=A6=E5=8F=B7=20=E2=80=94=20=E7=99=BB?= =?UTF-8?q?=E5=BD=95=E8=AE=B0=E5=BD=95=E8=AE=BE=E5=A4=87,=20=E6=BF=80?= =?UTF-8?q?=E6=B4=BB=E6=97=B6=E5=8D=A1=E5=AF=86=E5=AD=98=E8=B4=A6=E5=8F=B7?= =?UTF-8?q?,=20=E6=8D=A2=E8=AE=BE=E5=A4=87=E7=99=BB=E5=BD=95=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E6=8E=88=E6=9D=83(=E6=9C=80=E5=A4=9A10=E5=8F=B0),=20?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E4=B8=AD=E5=BF=83=E6=98=BE=E7=A4=BA=E6=8E=88?= =?UTF-8?q?=E6=9D=83=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docker/it-tools-relay/server.py | 79 ++++++++++++++++++++++++++++++++- src/composable/user-auth.ts | 5 ++- src/pages/UserCenter.page.vue | 38 ++++++++++++++++ src/tools/license/license.ts | 15 ++++++- 4 files changed, 133 insertions(+), 4 deletions(-) diff --git a/docker/it-tools-relay/server.py b/docker/it-tools-relay/server.py index 7ad2a97..c30eea8 100644 --- a/docker/it-tools-relay/server.py +++ b/docker/it-tools-relay/server.py @@ -480,9 +480,33 @@ def check(machine: str, tool: str) -> int: return 200 if trial_allowed(machine, tool) else 403 if query_authorized(machine): return 200 + # account-level license: this device belongs to a logged-in user whose card is active + if _account_license_ok(machine): + return 200 return 200 if trial_allowed(machine, tool) else 403 +def _account_license_ok(machine: str) -> bool: + """True when this device logged into an account holding an active card.""" + try: + conn = _db() + rows = conn.execute("SELECT card_key, origin_machine, bound_machines FROM users").fetchall() + conn.close() + except Exception: + return False + for card_key, origin, bm_json in rows: + if not card_key or not origin: + continue + try: + machines = json.loads(bm_json or "[]") + except Exception: + machines = [] + if machine in machines: + if origin == machine or query_authorized(origin): + return True + return False + + # ---- card activation (server-side key) ---- _auth_state: dict = {"token": None} @@ -604,10 +628,47 @@ def _db(): conn = sqlite3.connect(USER_DB) conn.execute("CREATE TABLE IF NOT EXISTS users (username TEXT PRIMARY KEY, salt TEXT, pw_hash TEXT, created REAL)") conn.execute("CREATE TABLE IF NOT EXISTS files (id TEXT PRIMARY KEY, username TEXT, name TEXT, size INTEGER, mime TEXT, created REAL)") + for stmt in ( + "ALTER TABLE users ADD COLUMN card_key TEXT DEFAULT ''", + "ALTER TABLE users ADD COLUMN origin_machine TEXT DEFAULT ''", + "ALTER TABLE users ADD COLUMN bound_machines TEXT DEFAULT '[]'", + ): + try: + conn.execute(stmt) + except sqlite3.OperationalError: + pass conn.commit() return conn +def _bind_machine(username: str, machine: str): + """remember devices that logged into this account (max 10)""" + if not machine or not MACHINE_RE.match(machine): + return + conn = _db() + row = conn.execute("SELECT bound_machines FROM users WHERE username=?", (username,)).fetchone() + try: + machines = json.loads(row[0] or "[]") if row else [] + except Exception: + machines = [] + if machine in machines: + machines.remove(machine) + machines.insert(0, machine) + conn.execute("UPDATE users SET bound_machines=? WHERE username=?", (json.dumps(machines[:10]), username)) + conn.commit() + conn.close() + + +def _save_user_license(username: str, card_key: str, machine: str): + """store the card bound to this account after a successful activation""" + conn = _db() + conn.execute("UPDATE users SET card_key=?, origin_machine=? WHERE username=?", + (card_key, machine, username)) + conn.commit() + conn.close() + _bind_machine(username, machine) + + def _hash_pw(pw, salt): return hashlib.pbkdf2_hmac("sha256", pw.encode(), salt.encode(), 120000).hex() @@ -666,6 +727,10 @@ def verify_turnstile(token: str) -> bool: USER_NAME_RE = re.compile(r"^[A-Za-z0-9_\u4e00-\u9fa5-]{3,32}$") +def _req_machine(handler): + return handler.headers.get("X-Machine-Id", "") if handler else "" + + def user_api(method, sub, payload, handler): """returns (status, body_dict)""" if method == "POST" and sub == "/register": @@ -687,6 +752,7 @@ def user_api(method, sub, payload, handler): finally: conn.close() _user_dir(username) + _bind_machine(username, _req_machine(handler)) return 200, {"code": 200, "message": "ok", "data": {"token": _make_token(username), "username": username}} if method == "POST" and sub == "/login": @@ -700,6 +766,7 @@ def user_api(method, sub, payload, handler): if not row or _hash_pw(password, row[0]) != row[1]: return 401, {"code": 401, "message": "用户名或密码错误"} _user_dir(username) + _bind_machine(username, _req_machine(handler)) return 200, {"code": 200, "message": "ok", "data": {"token": _make_token(username), "username": username}} # ---- below requires auth ---- @@ -872,7 +939,7 @@ class Handler(BaseHTTPRequestHandler): return authorized = False if machine not in _load_revoked(): - authorized = query_authorized(machine) + authorized = query_authorized(machine) or _account_license_ok(machine) body = {"code": 200, "message": "ok", "data": {"authorized": authorized}} self._reply(200, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json") return @@ -1128,6 +1195,16 @@ class Handler(BaseHTTPRequestHandler): return status, body = activate_card(card_key, machine_id, contact_qq, replace=replace) + if status == 200: + # bind card to the logged-in account so it follows the user across devices + tok = self.headers.get("Authorization", "") + if tok.lower().startswith("bearer "): + acc = _parse_token(tok[7:]) + if acc: + try: + _save_user_license(acc, card_key, machine_id) + except Exception: + pass self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json") return diff --git a/src/composable/user-auth.ts b/src/composable/user-auth.ts index 55d4dfc..4aaa4c3 100644 --- a/src/composable/user-auth.ts +++ b/src/composable/user-auth.ts @@ -1,4 +1,5 @@ import { computed, ref } from 'vue'; +import { licenseHeaders } from '@/tools/license/license'; const TOKEN_KEY = 'it-tools-auth'; @@ -52,7 +53,7 @@ export function useUserAuth() { async function login(u: string, p: string, cfToken = '') { const { status, body } = await apiFetch('/user/login', { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: { 'Content-Type': 'application/json', ...licenseHeaders() }, body: JSON.stringify({ username: u, password: p, cf_token: cfToken }), }); if (status !== 200) { @@ -66,7 +67,7 @@ export function useUserAuth() { async function register(u: string, p: string, cfToken = '') { const { status, body } = await apiFetch('/user/register', { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: { 'Content-Type': 'application/json', ...licenseHeaders() }, body: JSON.stringify({ username: u, password: p, cf_token: cfToken }), }); if (status !== 200) { diff --git a/src/pages/UserCenter.page.vue b/src/pages/UserCenter.page.vue index 6c160a8..3accafc 100644 --- a/src/pages/UserCenter.page.vue +++ b/src/pages/UserCenter.page.vue @@ -9,6 +9,23 @@ useHead({ title: '用户中心 - IT-TOOLS-PRO' }); const { isLoggedIn, username } = useUserAuth(); +// ---- 授权状态 ---- +const licensed = ref(null); +async function loadLicense() { + try { + const { getMachineId } = await import('@/tools/license/license'); + const res = await fetch(`/relay/auth-status?machine_id=${getMachineId()}`); + const b = await res.json(); + licensed.value = !!b?.data?.authorized; + } + catch { + licensed.value = null; + } +} +if (isLoggedIn.value) { + loadLicense(); +} + // ============ 数据(优先云端,回退本地) ============ const favTools = ref([]); const recentTools = ref<{ path: string; name: string; at: number }[]>([]); @@ -144,6 +161,9 @@ function removeBookmark(i: number) {
云端已同步 {{ fmtTime(syncAt) }}
+
+ {{ licensed ? '✓ 授权已关联账号' : '未授权(试用中)' }} +
= { 'Content-Type': 'application/json' }; + if (authHeader) { + actHeaders['Authorization'] = authHeader; + } const res = await fetch('/relay/activate', { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: actHeaders, body: JSON.stringify({ card_key: key, machine_id: getMachineId(),