修改图标、名称或配色会自动同步至所有已标注技能;删除标签时,原有标签备注会自动合并进单技能备注中。
为保证中国大陆无需代理即可直连且永久免费,本应用采用 Cloudflare Pages + 免费 KV 存储。上线后将下方 20 行后端函数放进 functions/api/sync.js,此处填入 /api/sync 即可实现三端实时云同步与服务端密码隐私保护。
const DEVICES_KV_KEY = "trusted_devices";
const BUNDLE_KV_KEY = "user_bundle";
const LAST_USED_TOUCH_INTERVAL_MS = 30 * 60 * 1000;
function jsonResponse(payload, status = 200, extraHeaders = {}) {
return new Response(JSON.stringify(payload), {
status,
headers: {
"Content-Type": "application/json; charset=utf-8",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-Sync-User",
"Access-Control-Allow-Methods": "GET, PUT, POST, OPTIONS",
...extraHeaders,
},
});
}
function getMaxDevices(env) {
const parsed = Number.parseInt(env.MAX_DEVICES || "5", 10);
if (!Number.isFinite(parsed)) return 5;
return Math.max(1, Math.min(20, parsed));
}
async function sha256Hex(text) {
const data = new TextEncoder().encode(text);
const digest = await crypto.subtle.digest("SHA-256", data);
return Array.from(new Uint8Array(digest))
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
function generateDeviceToken() {
const bytes = new Uint8Array(32);
crypto.getRandomValues(bytes);
const hex = Array.from(bytes)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
return `dt_${hex}`;
}
async function readDevices(env) {
try {
const raw = await env.LOL_KV.get(DEVICES_KV_KEY);
const list = raw ? JSON.parse(raw) : [];
return Array.isArray(list) ? list : [];
} catch {
return [];
}
}
async function writeDevices(env, devices) {
await env.LOL_KV.put(DEVICES_KV_KEY, JSON.stringify(devices));
}
function sanitizeDevices(devices) {
return devices.map((d) => ({
id: d.id,
name: d.name,
createdAt: d.createdAt,
lastUsedAt: d.lastUsedAt,
}));
}
async function authenticate(request, env) {
const auth = (request.headers.get("Authorization") || "").trim();
if (!auth) return { ok: false, reason: "missing_auth" };
if (auth.startsWith("Bearer ")) {
const pass = auth.slice(7);
if (!env.SYNC_PASSWORD || pass !== env.SYNC_PASSWORD) {
return { ok: false, reason: "invalid_password" };
}
const requiredUser = (env.SYNC_USERNAME || "").trim();
if (requiredUser) {
const incomingUser = (request.headers.get("X-Sync-User") || "").trim();
if (incomingUser !== requiredUser) {
return { ok: false, reason: "invalid_username" };
}
}
return { ok: true, mode: "password", deviceId: null, deviceName: null };
}
if (auth.startsWith("Device ")) {
const token = auth.slice(7).trim();
if (!token) return { ok: false, reason: "invalid_device" };
const tokenHash = await sha256Hex(token);
const devices = await readDevices(env);
const idx = devices.findIndex((d) => d.tokenHash === tokenHash);
if (idx === -1) return { ok: false, reason: "device_revoked" };
const now = Date.now();
if (!devices[idx].lastUsedAt || now - devices[idx].lastUsedAt > LAST_USED_TOUCH_INTERVAL_MS) {
devices[idx].lastUsedAt = now;
await writeDevices(env, devices);
}
return {
ok: true,
mode: "device",
deviceId: devices[idx].id,
deviceName: devices[idx].name,
};
}
return { ok: false, reason: "unsupported_auth" };
}
export async function onRequest(context) {
const { request, env } = context;
if (request.method === "OPTIONS") {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-Sync-User",
"Access-Control-Allow-Methods": "GET, PUT, POST, OPTIONS",
},
});
}
const authResult = await authenticate(request, env);
if (!authResult.ok) {
const msg =
authResult.reason === "device_revoked"
? "Device authorization revoked"
: authResult.reason === "invalid_username"
? "Invalid username"
: "Unauthorized";
return jsonResponse({ ok: false, error: msg, reason: authResult.reason }, 401);
}
if (request.method === "GET") {
const data = (await env.LOL_KV.get(BUNDLE_KV_KEY)) || "{}";
return new Response(data, {
headers: {
"Content-Type": "application/json; charset=utf-8",
"Access-Control-Allow-Origin": "*",
"X-Auth-Mode": authResult.mode,
"X-Device-Id": authResult.deviceId || "",
},
});
}
if (request.method === "PUT") {
const body = await request.text();
await env.LOL_KV.put(BUNDLE_KV_KEY, body);
return jsonResponse({ ok: true });
}
if (request.method === "POST") {
let payload = {};
try {
payload = await request.json();
} catch {
return jsonResponse({ ok: false, error: "Invalid JSON body" }, 400);
}
const action = payload.action;
const maxDevices = getMaxDevices(env);
if (action === "list_devices") {
const devices = await readDevices(env);
return jsonResponse({
ok: true,
maxDevices,
currentDeviceId: authResult.deviceId,
requireUsername: Boolean((env.SYNC_USERNAME || "").trim()),
devices: sanitizeDevices(devices),
});
}
if (action === "register_device") {
const devices = await readDevices(env);
const rawName = String(payload.deviceName || "未命名设备").trim().slice(0, 40) || "未命名设备";
const existingId = String(payload.currentDeviceId || authResult.deviceId || "").trim();
const now = Date.now();
const token = generateDeviceToken();
const tokenHash = await sha256Hex(token);
let deviceId = existingId;
let evictedName = "";
const existingIdx = deviceId ? devices.findIndex((d) => d.id === deviceId) : -1;
if (existingIdx !== -1) {
devices[existingIdx] = {
...devices[existingIdx],
name: rawName,
tokenHash,
lastUsedAt: now,
};
} else {
deviceId = `dev_${crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`;
if (devices.length >= maxDevices) {
devices.sort((a, b) => (a.lastUsedAt || a.createdAt || 0) - (b.lastUsedAt || b.createdAt || 0));
const removed = devices.shift();
if (removed) evictedName = removed.name || "";
}
devices.push({
id: deviceId,
name: rawName,
tokenHash,
createdAt: now,
lastUsedAt: now,
});
}
devices.sort((a, b) => (b.lastUsedAt || b.createdAt || 0) - (a.lastUsedAt || a.createdAt || 0));
await writeDevices(env, devices);
const saved = devices.find((d) => d.id === deviceId);
return jsonResponse({
ok: true,
token,
maxDevices,
evictedName,
device: {
id: saved.id,
name: saved.name,
createdAt: saved.createdAt,
lastUsedAt: saved.lastUsedAt,
},
devices: sanitizeDevices(devices),
});
}
if (action === "rename_device") {
const targetId = String(payload.deviceId || "").trim();
const newName = String(payload.deviceName || "").trim().slice(0, 40);
if (!targetId || !newName) {
return jsonResponse({ ok: false, error: "Missing deviceId or deviceName" }, 400);
}
const devices = await readDevices(env);
const target = devices.find((d) => d.id === targetId);
if (!target) return jsonResponse({ ok: false, error: "Device not found" }, 404);
target.name = newName;
await writeDevices(env, devices);
return jsonResponse({ ok: true, devices: sanitizeDevices(devices), maxDevices });
}
if (action === "revoke_device") {
const targetId = String(payload.deviceId || "").trim();
if (!targetId) return jsonResponse({ ok: false, error: "Missing deviceId" }, 400);
const devices = await readDevices(env);
const next = devices.filter((d) => d.id !== targetId);
await writeDevices(env, next);
return jsonResponse({ ok: true, devices: sanitizeDevices(next), maxDevices });
}
if (action === "revoke_all_devices") {
await writeDevices(env, []);
return jsonResponse({ ok: true, devices: [], maxDevices });
}
return jsonResponse({ ok: false, error: "Unknown action" }, 400);
}
return jsonResponse({ ok: false, error: "Method Not Allowed" }, 405);
}