use indexedDB manager proxySwitch

This commit is contained in:
go0p
2025-03-04 16:07:14 +08:00
parent 1e25561fae
commit 6f82842c92
23 changed files with 1542 additions and 753 deletions
-1
View File
@@ -1,7 +1,6 @@
console.log('Options page script loaded');
import { ProxySettings } from './proxy-settings.js';
import { ProxyManager } from './proxy-manager.js';
let currentConfigs = [];
+71 -53
View File
@@ -1,72 +1,91 @@
// 代理认证管理
import { proxyStore } from '../db/proxy-store.js';
export class ProxyAuth {
static async setupAuthListener() {
try {
// 保存认证信息到 storage
const saveAuth = async (config) => {
await chrome.storage.local.set({
proxyAuth: {
username: config.username,
password: config.password,
timestamp: Date.now()
// 使用 chrome.webRequest.onAuthRequired 的非阻塞版本
chrome.webRequest.onAuthRequired.addListener(
async (details) => {
try {
// 获取认证处理器
const handlers = await proxyStore.getAuthHandlers();
const handler = handlers.find(h =>
details.challenger?.host === h.host
);
if (handler) {
// 使用 declarativeNetRequest 规则来处理认证
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: [handler.id],
addRules: [{
id: parseInt(handler.id),
priority: 1,
action: {
type: 'modifyHeaders',
requestHeaders: [
{
header: 'Proxy-Authorization',
operation: 'set',
value: 'Basic ' + btoa(`${handler.username}:${handler.password}`)
}
]
},
condition: {
domains: [handler.host],
resourceTypes: ['main_frame', 'sub_frame', 'stylesheet', 'script', 'image', 'font', 'object', 'xmlhttprequest', 'ping', 'csp_report', 'media', 'websocket', 'other']
}
}]
});
}
});
};
} catch (error) {
console.error('Auth error:', error);
}
},
{ urls: ["<all_urls>"] }
);
}
// 获取认证信息
const getAuth = async () => {
const result = await chrome.storage.local.get('proxyAuth');
return result.proxyAuth;
};
static async saveAuthHandler(host, username, password) {
const handler = {
id: Date.now().toString(),
host,
username,
password
};
await proxyStore.saveAuthHandler(handler);
await this.setupAuthListener(); // 重新设置认证规则
}
// 清除认证信息
const clearAuth = async () => {
await chrome.storage.local.remove('proxyAuth');
};
return {
saveAuth,
getAuth,
clearAuth
};
} catch (error) {
console.error('Error setting up auth listener:', error);
return null;
static async removeAuthHandler(host) {
const handlers = await proxyStore.getAuthHandlers();
const handler = handlers.find(h => h.host === host);
if (handler) {
await proxyStore.deleteAuthHandler(handler.id);
// 移除对应的认证规则
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: [parseInt(handler.id)]
});
}
}
static setupErrorHandler() {
// 在 Manifest V3 中,我们不能使用 chrome.proxy.onProxyError
// 所以我们只记录错误到 storage
try {
const logError = async (error) => {
const errors = await chrome.storage.local.get('proxyErrors') || [];
// 使用 storage 记录错误
return {
logError: async (error) => {
const errors = await proxyStore.getErrors() || [];
errors.push({
timestamp: Date.now(),
error: error.message || error
});
await chrome.storage.local.set({
proxyErrors: errors.slice(-100) // 只保留最近100条错误记录
});
};
return { logError };
} catch (error) {
console.error('Error setting up error handler:', error);
return null;
}
await proxyStore.saveErrors(errors.slice(-100)); // 只保留最近100条错误记录
}
};
}
// 设置代理认证信息
static async setProxyAuth(username, password) {
try {
await chrome.storage.local.set({
proxyAuth: {
username,
password,
timestamp: Date.now()
}
});
await proxyStore.saveAuth({ username, password, timestamp: Date.now() });
return true;
} catch (error) {
console.error('Error setting proxy auth:', error);
@@ -77,8 +96,7 @@ export class ProxyAuth {
// 获取代理认证信息
static async getProxyAuth() {
try {
const result = await chrome.storage.local.get('proxyAuth');
return result.proxyAuth || null;
return await proxyStore.getAuth();
} catch (error) {
console.error('Error getting proxy auth:', error);
return null;
@@ -88,7 +106,7 @@ export class ProxyAuth {
// 清除代理认证信息
static async clearProxyAuth() {
try {
await chrome.storage.local.remove('proxyAuth');
await proxyStore.clearAuth();
return true;
} catch (error) {
console.error('Error clearing proxy auth:', error);
+155 -71
View File
@@ -1,12 +1,17 @@
// 日志数据库管理
export class ProxyLogs {
static DB_NAME = 'yakit_proxy_logs';
static STORE_NAME = 'logs';
static VERSION = 1;
import { proxyStore } from '../db/proxy-store.js';
static async openDB() {
// 日志数据库管理
class ProxyLogs {
constructor() {
this.DB_NAME = 'proxy_extension';
this.STORE_NAME = 'proxy_logs';
this.DB_VERSION = 1;
this.MAX_LOGS = 1000; // 最多保存1000条日志
}
async initDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(this.DB_NAME, this.VERSION);
const request = indexedDB.open(this.DB_NAME, this.DB_VERSION);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
@@ -17,82 +22,161 @@ export class ProxyLogs {
const store = db.createObjectStore(this.STORE_NAME, { keyPath: 'id' });
// 创建索引
store.createIndex('timestamp', 'timestamp');
store.createIndex('url', 'url');
store.createIndex('proxyId', 'proxyId');
store.createIndex('resourceType', 'resourceType');
store.createIndex('status', 'status');
}
};
});
}
static async addLog(log) {
const db = await this.openDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction([this.STORE_NAME], 'readwrite');
const store = transaction.objectStore(this.STORE_NAME);
// 添加新日志
const request = store.add(log);
request.onsuccess = () => {
// 删除旧日志,只保留最新的 100 条
const countRequest = store.count();
countRequest.onsuccess = () => {
if (countRequest.result > 100) {
const index = store.index('timestamp');
const cursorRequest = index.openCursor();
let deleteCount = countRequest.result - 100;
cursorRequest.onsuccess = (event) => {
const cursor = event.target.result;
if (cursor && deleteCount > 0) {
store.delete(cursor.primaryKey);
deleteCount--;
cursor.continue();
}
};
async getResourceType(details) {
try {
// 首先检查请求类型
if (details.type) {
// 直接使用 Chrome 提供的类型
switch (details.type) {
case 'main_frame': return 'page';
case 'xmlhttprequest': {
// 检查请求头来区分 XHR 和 Fetch
const isFetch = details.requestHeaders?.some(
header => header.name.toLowerCase() === 'sec-fetch-mode' &&
header.value === 'cors'
);
return isFetch ? 'fetch' : 'xhr';
}
};
resolve();
};
request.onerror = () => reject(request.error);
});
}
static async getLogs(limit = 100) {
const db = await this.openDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction([this.STORE_NAME], 'readonly');
const store = transaction.objectStore(this.STORE_NAME);
const index = store.index('timestamp');
const request = index.openCursor(null, 'prev');
const logs = [];
request.onsuccess = (event) => {
const cursor = event.target.result;
if (cursor && logs.length < limit) {
logs.push(cursor.value);
cursor.continue();
} else {
resolve(logs);
case 'script': return 'script';
case 'stylesheet': return 'stylesheet';
case 'image': return 'image';
case 'media': return 'media';
case 'font': return 'font';
case 'websocket': return 'websocket';
}
}
// 根据文件扩展名和内容类型判断
const contentType = details.requestHeaders?.find(
header => header.name.toLowerCase() === 'content-type'
)?.value || '';
const url = new URL(details.url);
const pathname = url.pathname.toLowerCase();
// 检查文件扩展名
if (pathname.endsWith('.js')) return 'script';
if (pathname.endsWith('.css')) return 'stylesheet';
if (/\.(png|jpg|jpeg|gif|webp|svg|ico)$/.test(pathname)) return 'image';
if (/\.(mp3|mp4|wav|ogg|webm)$/.test(pathname)) return 'media';
if (/\.(woff|woff2|ttf|eot|otf)$/.test(pathname)) return 'font';
// 根据内容类型判断
if (contentType) {
if (contentType.includes('javascript')) return 'script';
if (contentType.includes('css')) return 'stylesheet';
if (contentType.includes('image/')) return 'image';
if (contentType.includes('audio/') || contentType.includes('video/')) return 'media';
if (contentType.includes('font/') || contentType.includes('application/font')) return 'font';
if (contentType.includes('application/json')) return 'xhr';
if (contentType.includes('application/x-www-form-urlencoded')) return 'xhr';
}
// 检查 Accept 头
const acceptHeader = details.requestHeaders?.find(
header => header.name.toLowerCase() === 'accept'
)?.value || '';
if (acceptHeader) {
if (acceptHeader.includes('application/json')) return 'xhr';
if (acceptHeader.includes('text/javascript')) return 'script';
if (acceptHeader.includes('text/css')) return 'stylesheet';
if (acceptHeader.includes('image/')) return 'image';
}
console.log('Resource type detection:', {
url: details.url,
type: details.type,
contentType,
acceptHeader,
headers: details.requestHeaders
});
return 'other';
} catch (error) {
console.error('Error determining resource type:', error);
return 'other';
}
}
async logRequest(details, proxyConfig, error = null) {
try {
// 检查是否是扩展自身的请求
if (details.url.startsWith('chrome-extension://')) {
return;
}
// 获取资源类型
const resourceType = await this.getResourceType(details);
const log = {
id: Date.now().toString(),
timestamp: Date.now(),
url: details.url,
proxyId: proxyConfig.id,
proxyName: proxyConfig.name,
status: error ? 'error' : 'success',
errorMessage: error?.message,
method: details.method,
requestHeaders: details.requestHeaders?.reduce((acc, header) => {
acc[header.name] = header.value;
return acc;
}, {}),
requestBody: details.requestBody?.raw?.[0]?.bytes
? decodeURIComponent(String.fromCharCode.apply(null, new Uint8Array(details.requestBody.raw[0].bytes)))
: null,
responseHeaders: details.responseHeaders?.reduce((acc, header) => {
acc[header.name] = header.value;
return acc;
}, {}),
timing: {
startTime: details.timeStamp,
endTime: Date.now(),
duration: Date.now() - details.timeStamp
},
protocol: details.protocol || details.type,
ip: details.ip,
fromCache: details.fromCache,
resourceType
};
request.onerror = () => reject(request.error);
});
// 使用 proxyStore 存储日志
await proxyStore.addLog(log);
this.notifyLogUpdate();
} catch (error) {
console.error('Error logging proxy request:', error);
}
}
static async clearLogs() {
const db = await this.openDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction([this.STORE_NAME], 'readwrite');
const store = transaction.objectStore(this.STORE_NAME);
const request = store.clear();
async getLogs() {
return await proxyStore.getLogs();
}
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
async clearLogs() {
await proxyStore.clearLogs();
this.notifyLogUpdate();
}
notifyLogUpdate() {
// 通知前端日志已更新
chrome.runtime.sendMessage({
action: 'PROXY_LOGS_UPDATED'
}).catch(() => {
// 忽略接收者不存在的错误
});
}
}
}
// 导出实例而不是直接使用顶层 await
export const proxyLogs = new ProxyLogs();
// 移除这些顶层 await 语句
// await proxyStore.addLog({...});
// const logs = await proxyStore.getLogs();
-87
View File
@@ -1,87 +0,0 @@
// 代理配置管理
export class ProxyManager {
static async setProxy(config) {
try {
const proxyConfig = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: config.scheme,
host: config.host,
port: config.port
},
bypassList: ["localhost", "127.0.0.1"]
}
};
await chrome.proxy.settings.set({
value: proxyConfig,
scope: 'regular'
});
// 保存当前配置
await chrome.storage.local.set({
currentProxy: {
...config,
timestamp: Date.now()
}
});
return true;
} catch (error) {
console.error('Error setting proxy:', error);
return false;
}
}
static async clearProxy() {
try {
await chrome.proxy.settings.clear({scope: 'regular'});
await chrome.storage.local.remove('currentProxy');
return true;
} catch (error) {
console.error('Error clearing proxy:', error);
return false;
}
}
static async getProxyStatus() {
try {
const settings = await chrome.proxy.settings.get({});
const currentProxy = await chrome.storage.local.get('currentProxy');
return {
enabled: settings.value.mode === "fixed_servers",
config: currentProxy.currentProxy || null
};
} catch (error) {
console.error('Error getting proxy status:', error);
return {
enabled: false,
config: null
};
}
}
static async deleteProxy(proxyId) {
try {
// 获取当前代理配置
const result = await chrome.storage.local.get(['proxyConfigs', 'currentProxy']);
const configs = result.proxyConfigs || [];
const currentProxy = result.currentProxy;
// 如果要删除的代理正在使用中,先清除代理设置
if (currentProxy && currentProxy.id === proxyId) {
await clearProxyConfig();
}
// 从配置列表中删除代理
const updatedConfigs = configs.filter(config => config.id !== proxyId);
await chrome.storage.local.set({ proxyConfigs: updatedConfigs });
return true;
} catch (error) {
console.error('Error deleting proxy:', error);
return false;
}
}
}
+21 -19
View File
@@ -1,41 +1,43 @@
import { proxyStore } from '../db/proxy-store.js';
// 代理配置存储和管理
export const ProxySettings = {
async importSettings(settings) {
export class ProxySettings {
static async importSettings(settings) {
try {
if (Array.isArray(settings) && settings.every(s => s.proxyType)) {
await chrome.storage.local.set({proxyConfigs: settings});
await proxyStore.saveProxyConfigs(settings);
return {success: true};
}
return {success: false, error: "Invalid settings format"};
} catch (error) {
return {success: false, error: error.message};
}
},
}
async exportSettings() {
static async exportSettings() {
try {
const {proxyConfigs} = await chrome.storage.local.get('proxyConfigs');
return {success: true, settings: proxyConfigs || []};
const configs = await proxyStore.getProxyConfigs();
return {success: true, settings: configs || []};
} catch (error) {
return {success: false, error: error.message};
}
},
}
async setDefaultConfigs() {
const result = await chrome.storage.local.get('proxyConfigs');
if (!result.proxyConfigs) {
const defaultConfigs = [{
static async setDefaultConfigs() {
const configs = await proxyStore.getProxyConfigs();
if (!configs || configs.length === 0) {
// 设置默认的直接连接配置
await proxyStore.saveProxyConfigs([{
id: 'direct',
name: '直接连接',
proxyType: 'direct',
enabled: false
}];
await chrome.storage.local.set({ proxyConfigs: defaultConfigs });
}]);
}
// 确保 proxyLogs 存在
const logsResult = await chrome.storage.local.get('proxyLogs');
if (!logsResult.proxyLogs) {
await chrome.storage.local.set({ proxyLogs: [] });
// 确保日志存储已初始化
const logs = await proxyStore.getLogs(); // 使用 getLogs 而不是 getProxyLogs
if (!logs || logs.length === 0) {
await proxyStore.clearLogs(); // 初始化日志存储
}
}
};
}