diff --git a/components.d.ts b/components.d.ts index ff917c4..e11c35b 100644 --- a/components.d.ts +++ b/components.d.ts @@ -233,6 +233,7 @@ declare module '@vue/runtime-core' { UrlParser: typeof import('./src/tools/url-parser/url-parser.vue')['default'] UserAgentParser: typeof import('./src/tools/user-agent-parser/user-agent-parser.vue')['default'] UserAgentResultCards: typeof import('./src/tools/user-agent-parser/user-agent-result-cards.vue')['default'] + UserMenu: typeof import('./src/components/UserMenu.vue')['default'] UuidGenerator: typeof import('./src/tools/uuid-generator/uuid-generator.vue')['default'] WifiQrCodeGenerator: typeof import('./src/tools/wifi-qr-code-generator/wifi-qr-code-generator.vue')['default'] XmlFormatter: typeof import('./src/tools/xml-formatter/xml-formatter.vue')['default'] diff --git a/docker/it-tools-relay/server.py b/docker/it-tools-relay/server.py index 17b608c..5aa5f95 100644 --- a/docker/it-tools-relay/server.py +++ b/docker/it-tools-relay/server.py @@ -570,6 +570,216 @@ def activate_card(card_key: str, machine_id: str, contact_qq: str, replace: bool return code, ares + +# ================= 用户系统(注册/登录/数据云同步/文件存储) ================= +import hashlib +import hmac +import secrets +import sqlite3 +import uuid + +USER_DB = os.environ.get("USER_DB", "/app/data/users.db") +SECRET_FILE = os.environ.get("SECRET_FILE", "/app/data/.auth_secret") +USERS_ROOT = os.environ.get("USERS_ROOT", "/app/data/users") +MAX_UPLOAD = int(os.environ.get("MAX_UPLOAD_MB", "50")) * 1024 * 1024 + + +def _auth_secret(): + if not os.path.exists(SECRET_FILE): + os.makedirs(os.path.dirname(SECRET_FILE), exist_ok=True) + with open(SECRET_FILE, "w") as f: + f.write(secrets.token_hex(32)) + with open(SECRET_FILE) as f: + return f.read().strip() + + +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)") + conn.commit() + return conn + + +def _hash_pw(pw, salt): + return hashlib.pbkdf2_hmac("sha256", pw.encode(), salt.encode(), 120000).hex() + + +def _make_token(username): + exp = str(int(time.time()) + 7 * 86400) + payload = username + "." + exp + sig = hmac.new(_auth_secret().encode(), payload.encode(), hashlib.sha256).hexdigest()[:32] + return payload + "." + sig + + +def _parse_token(tok): + try: + username, exp, sig = tok.rsplit(".", 2) + payload = username + "." + exp + expect = hmac.new(_auth_secret().encode(), payload.encode(), hashlib.sha256).hexdigest()[:32] + if hmac.compare_digest(sig, expect) and int(exp) > time.time(): + return username + except Exception: + pass + return None + + +def _user_dir(username): + d = os.path.join(USERS_ROOT, username) + os.makedirs(os.path.join(d, "files"), exist_ok=True) + return d + + +def _auth_user(handler): + tok = handler.headers.get("Authorization", "") + if tok.lower().startswith("bearer "): + tok = tok[7:] + return _parse_token(tok) if tok else None + + +USER_NAME_RE = re.compile(r"^[A-Za-z0-9_\u4e00-\u9fa5-]{3,32}$") + + +def user_api(method, sub, payload, handler): + """returns (status, body_dict)""" + if method == "POST" and sub == "/register": + username = str(payload.get("username") or "").strip() + password = str(payload.get("password") or "") + if not USER_NAME_RE.match(username): + return 400, {"code": 400, "message": "用户名需 3-32 位字母/数字/下划线/中文"} + if len(password) < 6: + return 400, {"code": 400, "message": "密码至少 6 位"} + conn = _db() + try: + salt = secrets.token_hex(16) + conn.execute("INSERT INTO users VALUES (?,?,?,?)", (username, salt, _hash_pw(password, salt), time.time())) + conn.commit() + except sqlite3.IntegrityError: + return 409, {"code": 409, "message": "用户名已被注册"} + finally: + conn.close() + _user_dir(username) + return 200, {"code": 200, "message": "ok", "data": {"token": _make_token(username), "username": username}} + + if method == "POST" and sub == "/login": + username = str(payload.get("username") or "").strip() + password = str(payload.get("password") or "") + conn = _db() + row = conn.execute("SELECT salt, pw_hash FROM users WHERE username=?", (username,)).fetchone() + conn.close() + if not row or _hash_pw(password, row[0]) != row[1]: + return 401, {"code": 401, "message": "用户名或密码错误"} + _user_dir(username) + return 200, {"code": 200, "message": "ok", "data": {"token": _make_token(username), "username": username}} + + # ---- below requires auth ---- + username = _auth_user(handler) + if not username: + return 401, {"code": 401, "message": "请先登录"} + + if method == "GET" and sub == "/me": + return 200, {"code": 200, "message": "ok", "data": {"username": username}} + + if method == "GET" and sub == "/data": + path = os.path.join(_user_dir(username), "data.json") + if not os.path.exists(path): + return 200, {"code": 200, "message": "ok", "data": {"data": {}, "updated": 0}} + try: + with open(path) as f: + saved = json.load(f) + except Exception: + saved = {} + return 200, {"code": 200, "message": "ok", "data": {"data": saved.get("data", {}), "updated": saved.get("updated", 0)}} + + if method == "POST" and sub == "/data": + data = payload.get("data") + if not isinstance(data, dict): + return 400, {"code": 400, "message": "data 需为对象"} + path = os.path.join(_user_dir(username), "data.json") + tmp = path + ".tmp" + with open(tmp, "w") as f: + json.dump({"data": data, "updated": time.time()}, f, ensure_ascii=False) + os.replace(tmp, path) + return 200, {"code": 200, "message": "ok"} + + if method == "POST" and sub == "/files": + files = payload.get("_files") or {} + fields = payload.get("_fields") or {} + fobj = files.get("file") + if not fobj: + return 400, {"code": 400, "message": "缺少 file 字段"} + fname, fdata, fmime = fobj + if len(fdata) > MAX_UPLOAD: + return 413, {"code": 413, "message": "文件超过 " + str(MAX_UPLOAD // 1024 // 1024) + "MB 限制"} + if not fdata: + return 400, {"code": 400, "message": "文件为空"} + file_id = uuid.uuid4().hex[:16] + safe_name = os.path.basename(str(fname))[:120] or "file" + kind = re.sub(r"[^A-Za-z0-9_-]", "", str(fields.get("kind") or ""))[:32] + fdir = os.path.join(_user_dir(username), "files") + os.makedirs(fdir, exist_ok=True) + if kind: + fdir = os.path.join(fdir, kind) + os.makedirs(fdir, exist_ok=True) + with open(os.path.join(fdir, file_id), "wb") as f: + f.write(fdata) + conn = _db() + conn.execute("INSERT INTO files VALUES (?,?,?,?,?,?)", (file_id, username, safe_name, len(fdata), fmime, time.time())) + conn.commit() + conn.close() + return 200, {"code": 200, "message": "ok", "data": {"id": file_id, "name": safe_name, "size": len(fdata), "kind": kind}} + + if method == "GET" and sub == "/files": + conn = _db() + rows = conn.execute("SELECT id, name, size, mime, created FROM files WHERE username=? ORDER BY created DESC LIMIT 200", (username,)).fetchall() + conn.close() + files = [{"id": r[0], "name": r[1], "size": r[2], "mime": r[3], "created": int(r[4])} for r in rows] + return 200, {"code": 200, "message": "ok", "data": {"files": files}} + + if sub.startswith("/file/"): + file_id = sub[len("/file/"):] + if not re.match(r"^[A-Za-z0-9_-]{8,64}$", file_id): + return 400, {"code": 400, "message": "文件ID无效"} + conn = _db() + row = conn.execute("SELECT id, username, name, size, mime, created FROM files WHERE id=?", (file_id,)).fetchone() + conn.close() + if not row or row[1] != username: + return 404, {"code": 404, "message": "文件不存在"} + fpath = None + base = os.path.join(_user_dir(username), "files") + if os.path.exists(os.path.join(base, file_id)): + fpath = os.path.join(base, file_id) + else: + for d in os.listdir(base): + p = os.path.join(base, d, file_id) + if os.path.exists(p): + fpath = p + break + if not fpath: + return 404, {"code": 404, "message": "文件不存在"} + if method == "GET": + if not os.path.exists(fpath): + return 404, {"code": 404, "message": "文件不存在"} + with open(fpath, "rb") as f: + data = f.read() + handler.send_response(200) + handler.send_header("Content-Type", row[4] or "application/octet-stream") + handler.send_header("Content-Length", str(len(data))) + handler.send_header("Content-Disposition", "attachment; filename*=UTF-8''" + parse.quote(row[2])) + handler.end_headers() + handler.wfile.write(data) + return None, None + if method == "DELETE": + if fpath and os.path.exists(fpath): + os.remove(fpath) + conn = _db() + conn.execute("DELETE FROM files WHERE id=?", (file_id,)) + conn.commit() + conn.close() + return 200, {"code": 200, "message": "ok"} + + return 404, {"code": 404, "message": "unknown user api"} + class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" @@ -585,8 +795,45 @@ class Handler(BaseHTTPRequestHandler): self.wfile.write(body) # ---------- GET ---------- + def _handle_user(self, method): + parsed = parse.urlparse(self.path) + sub = parsed.path[len("/user"):] + payload = {} + if method == "POST": + try: + ctype = self.headers.get("Content-Type", "") + length = int(self.headers.get("Content-Length") or 0) + if length > MAX_UPLOAD + 1024 * 1024: + self._reply(413, json.dumps({"code": 413, "message": "文件过大"}, ensure_ascii=False).encode(), "application/json") + return + raw = self.rfile.read(length) if length else b"{}" + if ctype.startswith("multipart/form-data"): + env = {"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype, "CONTENT_LENGTH": str(length)} + fs = cgi.FieldStorage(fp=io.BytesIO(raw), environ=env, keep_blank_values=True) + files = {} + fields = {} + for k in fs.keys(): + item = fs[k] + if getattr(item, "filename", None): + files[k] = (item.filename, item.file.read(), item.type or "application/octet-stream") + else: + fields[k] = item.value + payload = {"_fields": fields, "_files": files} + else: + payload = json.loads(raw.decode("utf-8") or "{}") + except Exception: + self._reply(400, json.dumps({"code": 400, "message": "无效请求体"}, ensure_ascii=False).encode(), "application/json") + return + status, body = user_api(method, sub, payload, self) + if status is None: + return # response already sent (file download) + self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json") + def do_GET(self): parsed = parse.urlparse(self.path) + if parsed.path.startswith("/user"): + self._handle_user("GET") + return if parsed.path == "/auth-status": qs = parse.parse_qs(parsed.query) machine = (qs.get("machine_id") or [""])[0] @@ -637,6 +884,9 @@ class Handler(BaseHTTPRequestHandler): def do_POST(self): parsed = parse.urlparse(self.path) + if parsed.path.startswith("/user"): + self._handle_user("POST") + return if parsed.path == "/convert": self._handle_convert() return @@ -766,6 +1016,9 @@ class Handler(BaseHTTPRequestHandler): def do_DELETE(self): parsed = parse.urlparse(self.path) + if parsed.path.startswith("/user"): + self._handle_user("DELETE") + return if parsed.path.startswith("/sites/"): sub = parsed.path[len("/sites"):] status, body = sites_api("DELETE", sub, {}) diff --git a/src/components/UserMenu.vue b/src/components/UserMenu.vue new file mode 100644 index 0000000..9b3a5e8 --- /dev/null +++ b/src/components/UserMenu.vue @@ -0,0 +1,250 @@ + + + + + diff --git a/src/composable/cloud-sync.ts b/src/composable/cloud-sync.ts new file mode 100644 index 0000000..6d871ca --- /dev/null +++ b/src/composable/cloud-sync.ts @@ -0,0 +1,119 @@ +import { apiFetch, useUserAuth } from './user-auth'; + +// localStorage keys synced to the cloud +const SYNC_KEYS = [ + 'favoriteToolsName', + 'it-tools-recent-tools', + 'it-tools-bookmarks:sites', + 'menu-tool-option:collapsed-categories', +]; + +function collectLocal(): Record { + const data: Record = {}; + for (const k of SYNC_KEYS) { + const v = localStorage.getItem(k); + if (v !== null) { + data[k] = v; + } + } + // gen-history:* records + const hist: Record = {}; + for (let i = 0; i < localStorage.length; i++) { + const k = localStorage.key(i); + if (k && k.startsWith('gen-history:')) { + hist[k] = localStorage.getItem(k) ?? ''; + } + } + if (Object.keys(hist).length > 0) { + data['__gen-history'] = hist; + } + return data; +} + +function applyLocal(data: Record) { + for (const [k, v] of Object.entries(data)) { + if (k === '__gen-history') { + for (const [hk, hv] of Object.entries(v as Record)) { + localStorage.setItem(hk, hv); + } + } + else if (typeof v === 'string') { + localStorage.setItem(k, v); + } + } +} + +/** merge two string arrays parsed from JSON storage (union, server items appended) */ +function mergeJsonArrays(a: string, b: string, keyField: string | null): string { + try { + const arrA = JSON.parse(a); + const arrB = JSON.parse(b); + if (!Array.isArray(arrA) || !Array.isArray(arrB)) { + return b; + } + const seen = new Set(arrA.map((x: any) => (keyField ? x?.[keyField] : x))); + for (const item of arrB) { + const id = keyField ? item?.[keyField] : item; + if (id !== undefined && !seen.has(id)) { + arrA.push(item); + seen.add(id); + } + } + return JSON.stringify(arrA); + } + catch { + return b; + } +} + +function mergeData(server: Record, mine: Record): Record { + const out: Record = { ...server }; + for (const [k, v] of Object.entries(mine)) { + if (k === '__gen-history') { + out[k] = { ...(server[k] ?? {}), ...(v as Record) }; + } + else if (out[k] === undefined) { + out[k] = v; + } + else if (typeof v === 'string' && typeof out[k] === 'string') { + // prefer the larger/newer list per key + if (k === 'favoriteToolsName' || k === 'it-tools-recent-tools' || k === 'it-tools-bookmarks:sites') { + out[k] = mergeJsonArrays(out[k], v, k === 'it-tools-recent-tools' ? 'path' : null); + } + else { + out[k] = v; // scalar configs: local wins + } + } + } + return out; +} + +export function useCloudSync() { + const { isLoggedIn } = useUserAuth(); + + /** push local data up, pull server data down, merge both ways */ + async function syncNow(): Promise<{ ok: boolean; message: string }> { + if (!isLoggedIn.value) { + return { ok: false, message: '未登录' }; + } + const mine = collectLocal(); + const { status, body } = await apiFetch('/user/data'); + if (status !== 200) { + return { ok: false, message: body.message || '同步失败' }; + } + const server = body.data?.data ?? {}; + const merged = mergeData(server, mine); + const put = await apiFetch('/user/data', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ data: merged }), + }); + if (put.status !== 200) { + return { ok: false, message: put.body.message || '同步失败' }; + } + applyLocal(merged); + return { ok: true, message: '同步完成' }; + } + + return { syncNow, isLoggedIn }; +} diff --git a/src/composable/user-auth.ts b/src/composable/user-auth.ts new file mode 100644 index 0000000..0d4ba0f --- /dev/null +++ b/src/composable/user-auth.ts @@ -0,0 +1,98 @@ +import { computed, ref } from 'vue'; + +const TOKEN_KEY = 'it-tools-auth'; + +export interface AuthState { + token: string; + username: string; +} + +function loadState(): AuthState | null { + try { + const v = JSON.parse(localStorage.getItem(TOKEN_KEY) ?? 'null'); + if (v && typeof v.token === 'string' && typeof v.username === 'string') { + return v; + } + } + catch { /* ignore */ } + return null; +} + +const state = ref(loadState()); + +function save(s: AuthState | null) { + state.value = s; + if (s) { + localStorage.setItem(TOKEN_KEY, JSON.stringify(s)); + } + else { + localStorage.removeItem(TOKEN_KEY); + } +} + +export async function apiFetch(path: string, init: RequestInit = {}): Promise { + const headers = new Headers(init.headers); + if (state.value?.token) { + headers.set('Authorization', `Bearer ${state.value.token}`); + } + const res = await fetch(`/relay${path}`, { ...init, headers }); + const body = await res.json().catch(() => ({})); + if (res.status === 401 && path !== '/user/login' && path !== '/user/register') { + // token expired/invalid -> logout locally + save(null); + window.dispatchEvent(new CustomEvent('it-tools-auth-changed')); + } + return { status: res.status, body }; +} + +export function useUserAuth() { + const isLoggedIn = computed(() => state.value !== null); + const username = computed(() => state.value?.username ?? ''); + + async function login(u: string, p: string) { + const { status, body } = await apiFetch('/user/login', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username: u, password: p }), + }); + if (status !== 200) { + throw new Error(body.message || '登录失败'); + } + save({ token: body.data.token, username: body.data.username }); + window.dispatchEvent(new CustomEvent('it-tools-auth-changed')); + return body.data.username; + } + + async function register(u: string, p: string) { + const { status, body } = await apiFetch('/user/register', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username: u, password: p }), + }); + if (status !== 200) { + throw new Error(body.message || '注册失败'); + } + save({ token: body.data.token, username: body.data.username }); + window.dispatchEvent(new CustomEvent('it-tools-auth-changed')); + return body.data.username; + } + + function logout() { + save(null); + window.dispatchEvent(new CustomEvent('it-tools-auth-changed')); + } + + /** upload a file to the cloud (only when logged in) */ + async function cloudUpload(file: File | Blob, kind: string, name?: string): Promise<{ id: string } | null> { + if (!state.value) { + return null; + } + const fd = new FormData(); + fd.append('file', file, name ?? (file as File).name ?? 'file'); + fd.append('kind', kind); + const { status, body } = await apiFetch('/user/files', { method: 'POST', body: fd }); + return status === 200 ? body.data : null; + } + + return { isLoggedIn, username, login, register, logout, cloudUpload }; +} diff --git a/src/layouts/base.layout.vue b/src/layouts/base.layout.vue index 44e742d..c49ab27 100644 --- a/src/layouts/base.layout.vue +++ b/src/layouts/base.layout.vue @@ -14,6 +14,7 @@ import type { ToolCategory } from '@/tools/tools.types'; import { useToolStore } from '@/tools/tools.store'; import { useTracker } from '@/modules/tracker/tracker.services'; import CollapsibleToolMenu from '@/components/CollapsibleToolMenu.vue'; +import UserMenu from '@/components/UserMenu.vue'; const themeVars = useThemeVars(); const styleStore = useStyleStore(); @@ -103,6 +104,8 @@ const tools = computed(() => [ + + +import { useUserAuth } from '@/composable/user-auth'; import { licenseHeaders } from '../license/license'; import GenHistory from '@/tools/gen-history/GenHistory.vue'; import { useGenHistory } from '@/tools/gen-history/gen-history'; @@ -67,8 +68,12 @@ function onDrop(e: DragEvent) { handleFile(e.dataTransfer?.files?.[0]); } +const { cloudUpload } = useUserAuth(); + function handleFile(file?: File | null) { if (!file) return; + cloudUpload(file, 'ai-retouch').catch(() => {}); // 云端留档(登录后) + if (!file.type.startsWith('image/')) { error.value = '请选择图片文件(png/jpg/webp 等)'; return; diff --git a/src/tools/image-ocr/image-ocr.vue b/src/tools/image-ocr/image-ocr.vue index a950808..7887f0b 100644 --- a/src/tools/image-ocr/image-ocr.vue +++ b/src/tools/image-ocr/image-ocr.vue @@ -1,4 +1,5 @@