From 0c197a791dd95b4b72f5cf59cfce3413fbedb196 Mon Sep 17 00:00:00 2001 From: go0p Date: Mon, 14 Apr 2025 14:17:38 +0800 Subject: [PATCH] Remove ord directory from tracking --- .env | 1 - README.md | 90 - config/env.js | 104 - config/getHttpsConfig.js | 66 - config/jest/babelTransform.js | 29 - config/jest/cssTransform.js | 14 - config/jest/fileTransform.js | 40 - config/modules.js | 134 - config/paths.js | 77 - config/webpack.config.js | 758 - .../persistentCache/createEnvironmentHash.js | 9 - config/webpackDevServer.config.js | 127 - package-lock.json | 20032 ---------------- package.json | 155 - public/background.js | 84 - public/content.js | 59 - public/db/db.js | 120 - public/db/proxy-store.js | 175 - public/images/icon128.png | Bin 6704 -> 0 bytes public/images/icon16.png | Bin 1940 -> 0 bytes public/images/icon48.png | Bin 3062 -> 0 bytes public/images/yak.svg | 10 - public/images/yakitlogo.png | Bin 51526 -> 0 bytes public/index.html | 12 - public/inject.js | 38 - public/manifest.json | 74 - public/proxy.js | 559 - public/proxy/content.js | 1270 - public/proxy/links_finder.js | 213 - public/proxy/options.css | 160 - public/proxy/options.html | 11 - public/proxy/proxy-auth.js | 116 - public/proxy/proxy-logs.js | 150 - public/proxy/proxy-settings.js | 51 - public/sidepanel.html | 10 - public/socket.js | 134 - public/types/action.js | 13 - scripts/build.js | 217 - scripts/start.js | 154 - scripts/test.js | 52 - src/App.tsx | 30 - src/assets/icon/icon.tsx | 168 - src/components/AddProxyForm/index.css | 10 - src/components/AddProxyForm/index.tsx | 72 - src/components/Contro.css | 73 - src/components/Contro.tsx | 191 - src/components/EvalInTab.tsx | 81 - src/components/Proxifier.css | 113 - src/components/Proxifier.tsx | 311 - src/components/ProxySwitch/index.css | 235 - src/components/ProxySwitch/index.tsx | 311 - src/index.css | 27 - src/index.tsx | 13 - src/network/chrome.ts | 69 - .../components/ProxyLogs/LogDetail.tsx | 166 - .../components/ProxyLogs/index.tsx | 131 - .../components/ProxySettings/index.css | 65 - .../components/ProxySettings/index.tsx | 461 - .../OptionsPage/hooks/useProxyConfigs.ts | 167 - src/pages/OptionsPage/hooks/useProxyLogs.ts | 59 - src/pages/OptionsPage/index.css | 111 - src/pages/OptionsPage/index.tsx | 139 - src/pages/options.tsx | 16 - src/styles/global.css | 58 - src/types/action.ts | 24 - src/types/chrome.d.ts | 10 - src/types/chrome.ts | 19 - src/types/proxy.ts | 45 - tsconfig.json | 32 - webpack.config.js | 89 - yarn.lock | 10666 -------- 71 files changed, 39280 deletions(-) delete mode 100644 .env delete mode 100644 README.md delete mode 100644 config/env.js delete mode 100644 config/getHttpsConfig.js delete mode 100644 config/jest/babelTransform.js delete mode 100644 config/jest/cssTransform.js delete mode 100644 config/jest/fileTransform.js delete mode 100644 config/modules.js delete mode 100644 config/paths.js delete mode 100644 config/webpack.config.js delete mode 100644 config/webpack/persistentCache/createEnvironmentHash.js delete mode 100644 config/webpackDevServer.config.js delete mode 100644 package-lock.json delete mode 100644 package.json delete mode 100644 public/background.js delete mode 100644 public/content.js delete mode 100644 public/db/db.js delete mode 100644 public/db/proxy-store.js delete mode 100644 public/images/icon128.png delete mode 100644 public/images/icon16.png delete mode 100644 public/images/icon48.png delete mode 100644 public/images/yak.svg delete mode 100644 public/images/yakitlogo.png delete mode 100644 public/index.html delete mode 100644 public/inject.js delete mode 100644 public/manifest.json delete mode 100644 public/proxy.js delete mode 100644 public/proxy/content.js delete mode 100644 public/proxy/links_finder.js delete mode 100644 public/proxy/options.css delete mode 100644 public/proxy/options.html delete mode 100644 public/proxy/proxy-auth.js delete mode 100644 public/proxy/proxy-logs.js delete mode 100644 public/proxy/proxy-settings.js delete mode 100644 public/sidepanel.html delete mode 100644 public/socket.js delete mode 100644 public/types/action.js delete mode 100644 scripts/build.js delete mode 100644 scripts/start.js delete mode 100644 scripts/test.js delete mode 100644 src/App.tsx delete mode 100644 src/assets/icon/icon.tsx delete mode 100644 src/components/AddProxyForm/index.css delete mode 100644 src/components/AddProxyForm/index.tsx delete mode 100644 src/components/Contro.css delete mode 100644 src/components/Contro.tsx delete mode 100644 src/components/EvalInTab.tsx delete mode 100644 src/components/Proxifier.css delete mode 100644 src/components/Proxifier.tsx delete mode 100644 src/components/ProxySwitch/index.css delete mode 100644 src/components/ProxySwitch/index.tsx delete mode 100644 src/index.css delete mode 100644 src/index.tsx delete mode 100644 src/network/chrome.ts delete mode 100644 src/pages/OptionsPage/components/ProxyLogs/LogDetail.tsx delete mode 100644 src/pages/OptionsPage/components/ProxyLogs/index.tsx delete mode 100644 src/pages/OptionsPage/components/ProxySettings/index.css delete mode 100644 src/pages/OptionsPage/components/ProxySettings/index.tsx delete mode 100644 src/pages/OptionsPage/hooks/useProxyConfigs.ts delete mode 100644 src/pages/OptionsPage/hooks/useProxyLogs.ts delete mode 100644 src/pages/OptionsPage/index.css delete mode 100644 src/pages/OptionsPage/index.tsx delete mode 100644 src/pages/options.tsx delete mode 100644 src/styles/global.css delete mode 100644 src/types/action.ts delete mode 100644 src/types/chrome.d.ts delete mode 100644 src/types/chrome.ts delete mode 100644 src/types/proxy.ts delete mode 100644 tsconfig.json delete mode 100644 webpack.config.js delete mode 100644 yarn.lock diff --git a/.env b/.env deleted file mode 100644 index 083c815..0000000 --- a/.env +++ /dev/null @@ -1 +0,0 @@ -NODE_ENV=development \ No newline at end of file diff --git a/README.md b/README.md deleted file mode 100644 index a6f85fd..0000000 --- a/README.md +++ /dev/null @@ -1,90 +0,0 @@ -# Yet Another Chrome Extension for Yakit CyberSecurity - -This is a Chrome Extension for Yakit CyberSecurity. U can use it to... - -1. Change your proxy between Yakit and other proxy or your system. -2. As a sandbox for your Yakit Client - -# CRA: Getting Started with Create React App - -This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). - -## Available Scripts - -In the project directory, you can run: - -### `npm start` - -Runs the app in the development mode.\ -Open [http://localhost:3000](http://localhost:3000) to view it in your browser. - -The page will reload when you make changes.\ -You may also see any lint errors in the console. - -### `npm test` - -Launches the test runner in the interactive watch mode.\ -See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more -information. - -### `npm run build` - -Builds the app for production to the `build` folder.\ -It correctly bundles React in production mode and optimizes the build for the best performance. - -The build is minified and the filenames include the hashes.\ -Your app is ready to be deployed! - -See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. - -### `npm run eject` - -**Note: this is a one-way operation. Once you `eject`, you can't go back!** - -If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will -remove the single build dependency from your project. - -Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right -into your project so you have full control over them. All of the commands except `eject` will still work, but they will -point to the copied scripts so you can tweak them. At this point you're on your own. - -You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you -shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't -customize it when you are ready for it. - -## Learn More - -You can learn more in -the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). - -To learn React, check out the [React documentation](https://reactjs.org/). - -### Code Splitting - -This section has moved -here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) - -### Analyzing the Bundle Size - -This section has moved -here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) - -### Making a Progressive Web App - -This section has moved -here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) - -### Advanced Configuration - -This section has moved -here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) - -### Deployment - -This section has moved -here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) - -### `npm run build` fails to minify - -This section has moved -here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) diff --git a/config/env.js b/config/env.js deleted file mode 100644 index ffa7e49..0000000 --- a/config/env.js +++ /dev/null @@ -1,104 +0,0 @@ -'use strict'; - -const fs = require('fs'); -const path = require('path'); -const paths = require('./paths'); - -// Make sure that including paths.js after env.js will read .env variables. -delete require.cache[require.resolve('./paths')]; - -const NODE_ENV = process.env.NODE_ENV; -if (!NODE_ENV) { - throw new Error( - 'The NODE_ENV environment variable is required but was not specified.' - ); -} - -// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use -const dotenvFiles = [ - `${paths.dotenv}.${NODE_ENV}.local`, - // Don't include `.env.local` for `test` environment - // since normally you expect tests to produce the same - // results for everyone - NODE_ENV !== 'test' && `${paths.dotenv}.local`, - `${paths.dotenv}.${NODE_ENV}`, - paths.dotenv, -].filter(Boolean); - -// Load environment variables from .env* files. Suppress warnings using silent -// if this file is missing. dotenv will never modify any environment variables -// that have already been set. Variable expansion is supported in .env files. -// https://github.com/motdotla/dotenv -// https://github.com/motdotla/dotenv-expand -dotenvFiles.forEach(dotenvFile => { - if (fs.existsSync(dotenvFile)) { - require('dotenv-expand')( - require('dotenv').config({ - path: dotenvFile, - }) - ); - } -}); - -// We support resolving modules according to `NODE_PATH`. -// This lets you use absolute paths in imports inside large monorepos: -// https://github.com/facebook/create-react-app/issues/253. -// It works similar to `NODE_PATH` in Node itself: -// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders -// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored. -// Otherwise, we risk importing Node.js core modules into an app instead of webpack shims. -// https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421 -// We also resolve them to make sure all tools using them work consistently. -const appDirectory = fs.realpathSync(process.cwd()); -process.env.NODE_PATH = (process.env.NODE_PATH || '') - .split(path.delimiter) - .filter(folder => folder && !path.isAbsolute(folder)) - .map(folder => path.resolve(appDirectory, folder)) - .join(path.delimiter); - -// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be -// injected into the application via DefinePlugin in webpack configuration. -const REACT_APP = /^REACT_APP_/i; - -function getClientEnvironment(publicUrl) { - const raw = Object.keys(process.env) - .filter(key => REACT_APP.test(key)) - .reduce( - (env, key) => { - env[key] = process.env[key]; - return env; - }, - { - // Useful for determining whether we’re running in production mode. - // Most importantly, it switches React into the correct mode. - NODE_ENV: process.env.NODE_ENV || 'development', - // Useful for resolving the correct path to static assets in `public`. - // For example, . - // This should only be used as an escape hatch. Normally you would put - // images into the `src` and `import` them in code to get their paths. - PUBLIC_URL: publicUrl, - // We support configuring the sockjs pathname during development. - // These settings let a developer run multiple simultaneous projects. - // They are used as the connection `hostname`, `pathname` and `port` - // in webpackHotDevClient. They are used as the `sockHost`, `sockPath` - // and `sockPort` options in webpack-dev-server. - WDS_SOCKET_HOST: process.env.WDS_SOCKET_HOST, - WDS_SOCKET_PATH: process.env.WDS_SOCKET_PATH, - WDS_SOCKET_PORT: process.env.WDS_SOCKET_PORT, - // Whether or not react-refresh is enabled. - // It is defined here so it is available in the webpackHotDevClient. - FAST_REFRESH: process.env.FAST_REFRESH !== 'false', - } - ); - // Stringify all values so we can feed into webpack DefinePlugin - const stringified = { - 'process.env': Object.keys(raw).reduce((env, key) => { - env[key] = JSON.stringify(raw[key]); - return env; - }, {}), - }; - - return { raw, stringified }; -} - -module.exports = getClientEnvironment; diff --git a/config/getHttpsConfig.js b/config/getHttpsConfig.js deleted file mode 100644 index 013d493..0000000 --- a/config/getHttpsConfig.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -const fs = require('fs'); -const path = require('path'); -const crypto = require('crypto'); -const chalk = require('react-dev-utils/chalk'); -const paths = require('./paths'); - -// Ensure the certificate and key provided are valid and if not -// throw an easy to debug error -function validateKeyAndCerts({ cert, key, keyFile, crtFile }) { - let encrypted; - try { - // publicEncrypt will throw an error with an invalid cert - encrypted = crypto.publicEncrypt(cert, Buffer.from('test')); - } catch (err) { - throw new Error( - `The certificate "${chalk.yellow(crtFile)}" is invalid.\n${err.message}` - ); - } - - try { - // privateDecrypt will throw an error with an invalid key - crypto.privateDecrypt(key, encrypted); - } catch (err) { - throw new Error( - `The certificate key "${chalk.yellow(keyFile)}" is invalid.\n${ - err.message - }` - ); - } -} - -// Read file and throw an error if it doesn't exist -function readEnvFile(file, type) { - if (!fs.existsSync(file)) { - throw new Error( - `You specified ${chalk.cyan( - type - )} in your env, but the file "${chalk.yellow(file)}" can't be found.` - ); - } - return fs.readFileSync(file); -} - -// Get the https config -// Return cert files if provided in env, otherwise just true or false -function getHttpsConfig() { - const { SSL_CRT_FILE, SSL_KEY_FILE, HTTPS } = process.env; - const isHttps = HTTPS === 'true'; - - if (isHttps && SSL_CRT_FILE && SSL_KEY_FILE) { - const crtFile = path.resolve(paths.appPath, SSL_CRT_FILE); - const keyFile = path.resolve(paths.appPath, SSL_KEY_FILE); - const config = { - cert: readEnvFile(crtFile, 'SSL_CRT_FILE'), - key: readEnvFile(keyFile, 'SSL_KEY_FILE'), - }; - - validateKeyAndCerts({ ...config, keyFile, crtFile }); - return config; - } - return isHttps; -} - -module.exports = getHttpsConfig; diff --git a/config/jest/babelTransform.js b/config/jest/babelTransform.js deleted file mode 100644 index 5b391e4..0000000 --- a/config/jest/babelTransform.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -const babelJest = require('babel-jest').default; - -const hasJsxRuntime = (() => { - if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') { - return false; - } - - try { - require.resolve('react/jsx-runtime'); - return true; - } catch (e) { - return false; - } -})(); - -module.exports = babelJest.createTransformer({ - presets: [ - [ - require.resolve('babel-preset-react-app'), - { - runtime: hasJsxRuntime ? 'automatic' : 'classic', - }, - ], - ], - babelrc: false, - configFile: false, -}); diff --git a/config/jest/cssTransform.js b/config/jest/cssTransform.js deleted file mode 100644 index 8f65114..0000000 --- a/config/jest/cssTransform.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -// This is a custom Jest transformer turning style imports into empty objects. -// http://facebook.github.io/jest/docs/en/webpack.html - -module.exports = { - process() { - return 'module.exports = {};'; - }, - getCacheKey() { - // The output is always the same. - return 'cssTransform'; - }, -}; diff --git a/config/jest/fileTransform.js b/config/jest/fileTransform.js deleted file mode 100644 index aab6761..0000000 --- a/config/jest/fileTransform.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -const path = require('path'); -const camelcase = require('camelcase'); - -// This is a custom Jest transformer turning file imports into filenames. -// http://facebook.github.io/jest/docs/en/webpack.html - -module.exports = { - process(src, filename) { - const assetFilename = JSON.stringify(path.basename(filename)); - - if (filename.match(/\.svg$/)) { - // Based on how SVGR generates a component name: - // https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6 - const pascalCaseFilename = camelcase(path.parse(filename).name, { - pascalCase: true, - }); - const componentName = `Svg${pascalCaseFilename}`; - return `const React = require('react'); - module.exports = { - __esModule: true, - default: ${assetFilename}, - ReactComponent: React.forwardRef(function ${componentName}(props, ref) { - return { - $$typeof: Symbol.for('react.element'), - type: 'svg', - ref: ref, - key: null, - props: Object.assign({}, props, { - children: ${assetFilename} - }) - }; - }), - };`; - } - - return `module.exports = ${assetFilename};`; - }, -}; diff --git a/config/modules.js b/config/modules.js deleted file mode 100644 index d63e41d..0000000 --- a/config/modules.js +++ /dev/null @@ -1,134 +0,0 @@ -'use strict'; - -const fs = require('fs'); -const path = require('path'); -const paths = require('./paths'); -const chalk = require('react-dev-utils/chalk'); -const resolve = require('resolve'); - -/** - * Get additional module paths based on the baseUrl of a compilerOptions object. - * - * @param {Object} options - */ -function getAdditionalModulePaths(options = {}) { - const baseUrl = options.baseUrl; - - if (!baseUrl) { - return ''; - } - - const baseUrlResolved = path.resolve(paths.appPath, baseUrl); - - // We don't need to do anything if `baseUrl` is set to `node_modules`. This is - // the default behavior. - if (path.relative(paths.appNodeModules, baseUrlResolved) === '') { - return null; - } - - // Allow the user set the `baseUrl` to `appSrc`. - if (path.relative(paths.appSrc, baseUrlResolved) === '') { - return [paths.appSrc]; - } - - // If the path is equal to the root directory we ignore it here. - // We don't want to allow importing from the root directly as source files are - // not transpiled outside of `src`. We do allow importing them with the - // absolute path (e.g. `src/Components/Button.js`) but we set that up with - // an alias. - if (path.relative(paths.appPath, baseUrlResolved) === '') { - return null; - } - - // Otherwise, throw an error. - throw new Error( - chalk.red.bold( - "Your project's `baseUrl` can only be set to `src` or `node_modules`." + - ' Create React App does not support other values at this time.' - ) - ); -} - -/** - * Get webpack aliases based on the baseUrl of a compilerOptions object. - * - * @param {*} options - */ -function getWebpackAliases(options = {}) { - const baseUrl = options.baseUrl; - - if (!baseUrl) { - return {}; - } - - const baseUrlResolved = path.resolve(paths.appPath, baseUrl); - - if (path.relative(paths.appPath, baseUrlResolved) === '') { - return { - src: paths.appSrc, - }; - } -} - -/** - * Get jest aliases based on the baseUrl of a compilerOptions object. - * - * @param {*} options - */ -function getJestAliases(options = {}) { - const baseUrl = options.baseUrl; - - if (!baseUrl) { - return {}; - } - - const baseUrlResolved = path.resolve(paths.appPath, baseUrl); - - if (path.relative(paths.appPath, baseUrlResolved) === '') { - return { - '^src/(.*)$': '/src/$1', - }; - } -} - -function getModules() { - // Check if TypeScript is setup - const hasTsConfig = fs.existsSync(paths.appTsConfig); - const hasJsConfig = fs.existsSync(paths.appJsConfig); - - if (hasTsConfig && hasJsConfig) { - throw new Error( - 'You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file.' - ); - } - - let config; - - // If there's a tsconfig.json we assume it's a - // TypeScript project and set up the config - // based on tsconfig.json - if (hasTsConfig) { - const ts = require(resolve.sync('typescript', { - basedir: paths.appNodeModules, - })); - config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config; - // Otherwise we'll check if there is jsconfig.json - // for non TS projects. - } else if (hasJsConfig) { - config = require(paths.appJsConfig); - } - - config = config || {}; - const options = config.compilerOptions || {}; - - const additionalModulePaths = getAdditionalModulePaths(options); - - return { - additionalModulePaths: additionalModulePaths, - webpackAliases: getWebpackAliases(options), - jestAliases: getJestAliases(options), - hasTsConfig, - }; -} - -module.exports = getModules(); diff --git a/config/paths.js b/config/paths.js deleted file mode 100644 index f0a6cd9..0000000 --- a/config/paths.js +++ /dev/null @@ -1,77 +0,0 @@ -'use strict'; - -const path = require('path'); -const fs = require('fs'); -const getPublicUrlOrPath = require('react-dev-utils/getPublicUrlOrPath'); - -// Make sure any symlinks in the project folder are resolved: -// https://github.com/facebook/create-react-app/issues/637 -const appDirectory = fs.realpathSync(process.cwd()); -const resolveApp = relativePath => path.resolve(appDirectory, relativePath); - -// We use `PUBLIC_URL` environment variable or "homepage" field to infer -// "public path" at which the app is served. -// webpack needs to know it to put the right - - \ No newline at end of file diff --git a/public/proxy/proxy-auth.js b/public/proxy/proxy-auth.js deleted file mode 100644 index bc3229c..0000000 --- a/public/proxy/proxy-auth.js +++ /dev/null @@ -1,116 +0,0 @@ -// 代理认证管理 -import { proxyStore } from '../db/proxy-store.js'; - -export class ProxyAuth { - static async setupAuthListener() { - // 使用 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: [""] } - ); - } - - static async saveAuthHandler(host, username, password) { - const handler = { - id: Date.now().toString(), - host, - username, - password - }; - await proxyStore.saveAuthHandler(handler); - await this.setupAuthListener(); // 重新设置认证规则 - } - - 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() { - // 使用 storage 记录错误 - return { - logError: async (error) => { - const errors = await proxyStore.getErrors() || []; - errors.push({ - timestamp: Date.now(), - error: error.message || error - }); - await proxyStore.saveErrors(errors.slice(-100)); // 只保留最近100条错误记录 - } - }; - } - - // 设置代理认证信息 - static async setProxyAuth(username, password) { - try { - await proxyStore.saveAuth({ username, password, timestamp: Date.now() }); - return true; - } catch (error) { - console.error('Error setting proxy auth:', error); - return false; - } - } - - // 获取代理认证信息 - static async getProxyAuth() { - try { - return await proxyStore.getAuth(); - } catch (error) { - console.error('Error getting proxy auth:', error); - return null; - } - } - - // 清除代理认证信息 - static async clearProxyAuth() { - try { - await proxyStore.clearAuth(); - return true; - } catch (error) { - console.error('Error clearing proxy auth:', error); - return false; - } - } -} \ No newline at end of file diff --git a/public/proxy/proxy-logs.js b/public/proxy/proxy-logs.js deleted file mode 100644 index 885b3bf..0000000 --- a/public/proxy/proxy-logs.js +++ /dev/null @@ -1,150 +0,0 @@ -import { proxyStore } from '../db/proxy-store.js'; - -// 日志数据库管理 -class ProxyLogs { - 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'; - } - 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 - }; - - // 使用 proxyStore 存储日志 - await proxyStore.addLog(log); - this.notifyLogUpdate(); - } catch (error) { - console.error('Error logging proxy request:', error); - } - } - - async getLogs() { - return await proxyStore.getLogs(); - } - - async clearLogs() { - await proxyStore.clearLogs(); - this.notifyLogUpdate(); - } - - notifyLogUpdate() { - // 通知前端日志已更新 - chrome.runtime.sendMessage({ - action: 'PROXY_LOGS_UPDATED' - }).catch(() => { - // 忽略接收者不存在的错误 - }); - } -} - -export const proxyLogs = new ProxyLogs(); \ No newline at end of file diff --git a/public/proxy/proxy-settings.js b/public/proxy/proxy-settings.js deleted file mode 100644 index c2ccba4..0000000 --- a/public/proxy/proxy-settings.js +++ /dev/null @@ -1,51 +0,0 @@ -import { proxyStore } from '../db/proxy-store.js'; - -// 代理配置存储和管理 -export class ProxySettings { - static async importSettings(settings) { - try { - if (Array.isArray(settings) && settings.every(s => s.proxyType)) { - await proxyStore.saveProxyConfigs(settings); - return {success: true}; - } - return {success: false, error: "Invalid settings format"}; - } catch (error) { - return {success: false, error: error.message}; - } - } - - static async exportSettings() { - try { - const configs = await proxyStore.getProxyConfigs(); - return {success: true, settings: configs || []}; - } catch (error) { - return {success: false, error: error.message}; - } - } - - static async setDefaultConfigs() { - const configs = await proxyStore.getProxyConfigs(); - if (!configs || configs.length === 0) { - // 设置默认的直接连接配置 - await proxyStore.saveProxyConfigs([ - { - id: 'direct', - name: '直接连接', - proxyType: 'direct', - enabled: false - }, - { - id: 'system', - name: '系统代理', - proxyType: 'system', - enabled: false - } - ]); - } - // 确保日志存储已初始化 - const logs = await proxyStore.getLogs(); - if (!logs || logs.length === 0) { - await proxyStore.clearLogs(); - } - } -} \ No newline at end of file diff --git a/public/sidepanel.html b/public/sidepanel.html deleted file mode 100644 index ac4cc51..0000000 --- a/public/sidepanel.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - My Sidepanel - - -

All sites sidepanel extension

-

This side panel is enabled on all sites

- - \ No newline at end of file diff --git a/public/socket.js b/public/socket.js deleted file mode 100644 index a80344a..0000000 --- a/public/socket.js +++ /dev/null @@ -1,134 +0,0 @@ -export const ActionType = { - CONNECT: 'connect', - SEND_MESSAGE: 'send_message', - DISCONNECT: 'disconnect', - STATUS: 'status', - PROXY_STATUS: 'proxy_status', - SET_PROXY: 'set_proxy', - CLEAR_PROXY: 'clear_proxy', - INJECT_SCRIPT: 'yakit_inject_script', - TO_EXTENSION_PAGE: "yakit_to_extension_page", - BADGE_COUNT: "yakit_badge", -} - -export class WebSocketManager { - constructor() { - this.socket = null; - this.intervalId = null; - } - - connectWebsocket(url, port) { - this.disconnectWebsocket(); - this.socket = new WebSocket(url); - - this.socket.onopen = () => { - chrome.runtime.sendMessage({action: ActionType.STATUS, connected: true, port: port}); - this.startHeartbeat(); - }; - - this.socket.onmessage = (event) => { - console.log("event", event) - this.handleMessage(event.data); - }; - - this.socket.onclose = () => { - chrome.runtime.sendMessage({action: ActionType.STATUS, connected: false}); - }; - - this.socket.onerror = (error) => { - console.error("WebSocket Error:", error); - }; - } - - sendMessage(message) { - if (this.isConnected()) { - try { - console.log("发射", message) - this.socket.send(JSON.stringify(message)); - } catch (e) { - console.error("Error sending message:", e); - } - } else { - console.error("WebSocket is not connected."); - } - } - - disconnectWebsocket() { - if (this.socket) { - try { - this.socket.close(); - chrome.runtime.sendMessage({action: ActionType.STATUS, connected: false}); - } catch (e) { - console.error("Error closing websocket:", e); - } - this.socket = null; - this.stopHeartbeat(); - } - } - - startHeartbeat() { - this.intervalId = setInterval(() => this.heartbeat(), 25000); - } - - stopHeartbeat() { - if (this.intervalId) { - clearInterval(this.intervalId); - this.intervalId = null; - } - } - - heartbeat() { - if (this.isConnected()) { - try { - this.socket.send(JSON.stringify({"type": "heartbeat"})); - } catch (e) { - console.error("Error sending heartbeat:", e); - } - } else { - this.disconnectWebsocket(); - } - } - - isConnected() { - return this.socket && this.socket.readyState === WebSocket.OPEN; - } - - handleMessage(message) { - message = JSON.parse(message); - if (message && message.type === "eval") { - (async () => { - const [tab] = await getTab(); - await injectScriptAndSendMessage(tab.id, { - type: ActionType.INJECT_SCRIPT, - value: { - mode: "CONTENT_EVAL_CODE", code: message.code, - } - }); - })(); - } - } -} - -const getTab = async () => { - return chrome.tabs.query({active: true, lastFocusedWindow: true}) -} - -export const injectScriptAndSendMessage = async (tabId, message) => { - try { - // 注入 JS 脚本 - await chrome.scripting.executeScript({ - target: {tabId: tabId}, - files: ['content.js'] - }); - - // 发送消息 - const response = await chrome.tabs.sendMessage(tabId, message); - - console.log("response", response); - if (response && response.action === ActionType.TO_EXTENSION_PAGE) { - await chrome.runtime.sendMessage(response); - } - } catch (err) { - console.error('Script or CSS injection failed:', err); - } -} \ No newline at end of file diff --git a/public/types/action.js b/public/types/action.js deleted file mode 100644 index cbca12a..0000000 --- a/public/types/action.js +++ /dev/null @@ -1,13 +0,0 @@ -// 这个是插件 background 中使用的 action 类型 -// 和前端的 action 要保持一致 -export const ProxyActionType = { - SET_PROXY_CONFIG: "SET_PROXY_CONFIG", - CLEAR_PROXY_CONFIG: "CLEAR_PROXY_CONFIG", - GET_PROXY_STATUS: "GET_PROXY_STATUS", - GET_PROXY_LOGS: "GET_PROXY_LOGS", - CLEAR_PROXY_LOGS: "CLEAR_PROXY_LOGS", - GET_PROXY_CONFIGS: "GET_PROXY_CONFIGS", - ADD_PROXY_CONFIG: "ADD_PROXY_CONFIG", - UPDATE_PROXY_CONFIG: "UPDATE_PROXY_CONFIG", - OPEN_OPTIONS_PAGE: "OPEN_OPTIONS_PAGE", -}; \ No newline at end of file diff --git a/scripts/build.js b/scripts/build.js deleted file mode 100644 index 8a9acaa..0000000 --- a/scripts/build.js +++ /dev/null @@ -1,217 +0,0 @@ -'use strict'; - -// Do this as the first thing so that any code reading it knows the right env. -process.env.BABEL_ENV = 'production'; -process.env.NODE_ENV = 'production'; - -// Makes the script crash on unhandled rejections instead of silently -// ignoring them. In the future, promise rejections that are not handled will -// terminate the Node.js process with a non-zero exit code. -process.on('unhandledRejection', err => { - throw err; -}); - -// Ensure environment variables are read. -require('../config/env'); - -const path = require('path'); -const chalk = require('react-dev-utils/chalk'); -const fs = require('fs-extra'); -const bfj = require('bfj'); -const webpack = require('webpack'); -const configFactory = require('../config/webpack.config'); -const paths = require('../config/paths'); -const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); -const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); -const printHostingInstructions = require('react-dev-utils/printHostingInstructions'); -const FileSizeReporter = require('react-dev-utils/FileSizeReporter'); -const printBuildError = require('react-dev-utils/printBuildError'); - -const measureFileSizesBeforeBuild = - FileSizeReporter.measureFileSizesBeforeBuild; -const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild; -const useYarn = fs.existsSync(paths.yarnLockFile); - -// These sizes are pretty large. We'll warn for bundles exceeding them. -const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024; -const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024; - -const isInteractive = process.stdout.isTTY; - -// Warn and crash if required files are missing -if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { - process.exit(1); -} - -const argv = process.argv.slice(2); -const writeStatsJson = argv.indexOf('--stats') !== -1; - -// Generate configuration -const config = configFactory('production'); - -// We require that you explicitly set browsers and do not fall back to -// browserslist defaults. -const { checkBrowsers } = require('react-dev-utils/browsersHelper'); -checkBrowsers(paths.appPath, isInteractive) - .then(() => { - // First, read the current file sizes in build directory. - // This lets us display how much they changed later. - return measureFileSizesBeforeBuild(paths.appBuild); - }) - .then(previousFileSizes => { - // Remove all content but keep the directory so that - // if you're in it, you don't end up in Trash - fs.emptyDirSync(paths.appBuild); - // Merge with the public folder - copyPublicFolder(); - // Start the webpack build - return build(previousFileSizes); - }) - .then( - ({ stats, previousFileSizes, warnings }) => { - if (warnings.length) { - console.log(chalk.yellow('Compiled with warnings.\n')); - console.log(warnings.join('\n\n')); - console.log( - '\nSearch for the ' + - chalk.underline(chalk.yellow('keywords')) + - ' to learn more about each warning.' - ); - console.log( - 'To ignore, add ' + - chalk.cyan('// eslint-disable-next-line') + - ' to the line before.\n' - ); - } else { - console.log(chalk.green('Compiled successfully.\n')); - } - - console.log('File sizes after gzip:\n'); - printFileSizesAfterBuild( - stats, - previousFileSizes, - paths.appBuild, - WARN_AFTER_BUNDLE_GZIP_SIZE, - WARN_AFTER_CHUNK_GZIP_SIZE - ); - console.log(); - - const appPackage = require(paths.appPackageJson); - const publicUrl = paths.publicUrlOrPath; - const publicPath = config.output.publicPath; - const buildFolder = path.relative(process.cwd(), paths.appBuild); - printHostingInstructions( - appPackage, - publicUrl, - publicPath, - buildFolder, - useYarn - ); - }, - err => { - const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true'; - if (tscCompileOnError) { - console.log( - chalk.yellow( - 'Compiled with the following type errors (you may want to check these before deploying your app):\n' - ) - ); - printBuildError(err); - } else { - console.log(chalk.red('Failed to compile.\n')); - printBuildError(err); - process.exit(1); - } - } - ) - .catch(err => { - if (err && err.message) { - console.log(err.message); - } - process.exit(1); - }); - -// Create the production build and print the deployment instructions. -function build(previousFileSizes) { - console.log('Creating an optimized production build...'); - - const compiler = webpack(config); - return new Promise((resolve, reject) => { - compiler.run((err, stats) => { - let messages; - if (err) { - if (!err.message) { - return reject(err); - } - - let errMessage = err.message; - - // Add additional information for postcss errors - if (Object.prototype.hasOwnProperty.call(err, 'postcssNode')) { - errMessage += - '\nCompileError: Begins at CSS selector ' + - err['postcssNode'].selector; - } - - messages = formatWebpackMessages({ - errors: [errMessage], - warnings: [], - }); - } else { - messages = formatWebpackMessages( - stats.toJson({ all: false, warnings: true, errors: true }) - ); - } - if (messages.errors.length) { - // Only keep the first error. Others are often indicative - // of the same problem, but confuse the reader with noise. - if (messages.errors.length > 1) { - messages.errors.length = 1; - } - return reject(new Error(messages.errors.join('\n\n'))); - } - if ( - process.env.CI && - (typeof process.env.CI !== 'string' || - process.env.CI.toLowerCase() !== 'false') && - messages.warnings.length - ) { - // Ignore sourcemap warnings in CI builds. See #8227 for more info. - const filteredWarnings = messages.warnings.filter( - w => !/Failed to parse source map/.test(w) - ); - if (filteredWarnings.length) { - console.log( - chalk.yellow( - '\nTreating warnings as errors because process.env.CI = true.\n' + - 'Most CI servers set it automatically.\n' - ) - ); - return reject(new Error(filteredWarnings.join('\n\n'))); - } - } - - const resolveArgs = { - stats, - previousFileSizes, - warnings: messages.warnings, - }; - - if (writeStatsJson) { - return bfj - .write(paths.appBuild + '/bundle-stats.json', stats.toJson()) - .then(() => resolve(resolveArgs)) - .catch(error => reject(new Error(error))); - } - - return resolve(resolveArgs); - }); - }); -} - -function copyPublicFolder() { - fs.copySync(paths.appPublic, paths.appBuild, { - dereference: true, - filter: file => file !== paths.appHtml, - }); -} diff --git a/scripts/start.js b/scripts/start.js deleted file mode 100644 index 4104798..0000000 --- a/scripts/start.js +++ /dev/null @@ -1,154 +0,0 @@ -'use strict'; - -// Do this as the first thing so that any code reading it knows the right env. -process.env.BABEL_ENV = 'development'; -process.env.NODE_ENV = 'development'; - -// Makes the script crash on unhandled rejections instead of silently -// ignoring them. In the future, promise rejections that are not handled will -// terminate the Node.js process with a non-zero exit code. -process.on('unhandledRejection', err => { - throw err; -}); - -// Ensure environment variables are read. -require('../config/env'); - -const fs = require('fs'); -const chalk = require('react-dev-utils/chalk'); -const webpack = require('webpack'); -const WebpackDevServer = require('webpack-dev-server'); -const clearConsole = require('react-dev-utils/clearConsole'); -const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); -const { - choosePort, - createCompiler, - prepareProxy, - prepareUrls, -} = require('react-dev-utils/WebpackDevServerUtils'); -const openBrowser = require('react-dev-utils/openBrowser'); -const semver = require('semver'); -const paths = require('../config/paths'); -const configFactory = require('../config/webpack.config'); -const createDevServerConfig = require('../config/webpackDevServer.config'); -const getClientEnvironment = require('../config/env'); -const react = require(require.resolve('react', { paths: [paths.appPath] })); - -const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1)); -const useYarn = fs.existsSync(paths.yarnLockFile); -const isInteractive = process.stdout.isTTY; - -// Warn and crash if required files are missing -if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { - process.exit(1); -} - -// Tools like Cloud9 rely on this. -const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000; -const HOST = process.env.HOST || '0.0.0.0'; - -if (process.env.HOST) { - console.log( - chalk.cyan( - `Attempting to bind to HOST environment variable: ${chalk.yellow( - chalk.bold(process.env.HOST) - )}` - ) - ); - console.log( - `If this was unintentional, check that you haven't mistakenly set it in your shell.` - ); - console.log( - `Learn more here: ${chalk.yellow('https://cra.link/advanced-config')}` - ); - console.log(); -} - -// We require that you explicitly set browsers and do not fall back to -// browserslist defaults. -const { checkBrowsers } = require('react-dev-utils/browsersHelper'); -checkBrowsers(paths.appPath, isInteractive) - .then(() => { - // We attempt to use the default port but if it is busy, we offer the user to - // run on a different port. `choosePort()` Promise resolves to the next free port. - return choosePort(HOST, DEFAULT_PORT); - }) - .then(port => { - if (port == null) { - // We have not found a port. - return; - } - - const config = configFactory('development'); - const protocol = process.env.HTTPS === 'true' ? 'https' : 'http'; - const appName = require(paths.appPackageJson).name; - - const useTypeScript = fs.existsSync(paths.appTsConfig); - const urls = prepareUrls( - protocol, - HOST, - port, - paths.publicUrlOrPath.slice(0, -1) - ); - // Create a webpack compiler that is configured with custom messages. - const compiler = createCompiler({ - appName, - config, - urls, - useYarn, - useTypeScript, - webpack, - }); - // Load proxy config - const proxySetting = require(paths.appPackageJson).proxy; - const proxyConfig = prepareProxy( - proxySetting, - paths.appPublic, - paths.publicUrlOrPath - ); - // Serve webpack assets generated by the compiler over a web server. - const serverConfig = { - ...createDevServerConfig(proxyConfig, urls.lanUrlForConfig), - host: HOST, - port, - }; - const devServer = new WebpackDevServer(serverConfig, compiler); - // Launch WebpackDevServer. - devServer.startCallback(() => { - if (isInteractive) { - clearConsole(); - } - - if (env.raw.FAST_REFRESH && semver.lt(react.version, '16.10.0')) { - console.log( - chalk.yellow( - `Fast Refresh requires React 16.10 or higher. You are using React ${react.version}.` - ) - ); - } - - console.log(chalk.cyan('Starting the development server...\n')); - openBrowser(urls.localUrlForBrowser); - }); - - ['SIGINT', 'SIGTERM'].forEach(function (sig) { - process.on(sig, function () { - devServer.close(); - process.exit(); - }); - }); - - if (process.env.CI !== 'true') { - // Gracefully exit when stdin ends - process.stdin.on('end', function () { - devServer.close(); - process.exit(); - }); - } - }) - .catch(err => { - if (err && err.message) { - console.log(err.message); - } - process.exit(1); - }); diff --git a/scripts/test.js b/scripts/test.js deleted file mode 100644 index a38c855..0000000 --- a/scripts/test.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -// Do this as the first thing so that any code reading it knows the right env. -process.env.BABEL_ENV = 'test'; -process.env.NODE_ENV = 'test'; -process.env.PUBLIC_URL = ''; - -// Makes the script crash on unhandled rejections instead of silently -// ignoring them. In the future, promise rejections that are not handled will -// terminate the Node.js process with a non-zero exit code. -process.on('unhandledRejection', err => { - throw err; -}); - -// Ensure environment variables are read. -require('../config/env'); - -const jest = require('jest'); -const execSync = require('child_process').execSync; -let argv = process.argv.slice(2); - -function isInGitRepository() { - try { - execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' }); - return true; - } catch (e) { - return false; - } -} - -function isInMercurialRepository() { - try { - execSync('hg --cwd . root', { stdio: 'ignore' }); - return true; - } catch (e) { - return false; - } -} - -// Watch unless on CI or explicitly running all tests -if ( - !process.env.CI && - argv.indexOf('--watchAll') === -1 && - argv.indexOf('--watchAll=false') === -1 -) { - // https://github.com/facebook/create-react-app/issues/5210 - const hasSourceControl = isInGitRepository() || isInMercurialRepository(); - argv.push(hasSourceControl ? '--watch' : '--watchAll'); -} - - -jest.run(argv); diff --git a/src/App.tsx b/src/App.tsx deleted file mode 100644 index 627befd..0000000 --- a/src/App.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import React from "react"; -// import "./App.css"; -import {ConfigProvider} from "antd"; -import {Contro} from "@components/Contro"; -import {Proxifier} from "@components/Proxifier"; -import {EvalInTab} from "@components/EvalInTab"; -import {ProxySwitch} from "@components/ProxySwitch"; -import './styles/global.css'; - -function App() { - return ( - -
- {/**/} - {/* */} - - - {/* */} -
-
- ); -} - -export default App; diff --git a/src/assets/icon/icon.tsx b/src/assets/icon/icon.tsx deleted file mode 100644 index cc04997..0000000 --- a/src/assets/icon/icon.tsx +++ /dev/null @@ -1,168 +0,0 @@ -import Icon from "@ant-design/icons"; -import { CustomIconComponentProps } from "@ant-design/icons/lib/components/Icon"; -import React from "react"; - -interface IconProps extends CustomIconComponentProps { - onClick: (e: React.MouseEvent) => void; - ref?: any; -} - -const X = () => ( - - - -); -/** - * @description Icon/Outline/x - */ -export const XIcon = (props: Partial) => { - return ; -}; - -const Check = () => ( - - - -); -/** - * @description Icon/Outline/check - */ -export const CheckIcon = (props: Partial) => { - return ; -}; - -const PencilAlt = () => ( - - - -); -/** - * @description Icon/Outline/pencil-alt - */ -export const PencilAltIcon = (props: Partial) => { - return ; -}; - -const Refresh = () => ( - - - -); -/** - * @description Icon/Outline/refresh - */ -export const RefreshIcon = (props: Partial) => { - return ; -}; - -const Exit = () => ( - - - -); -/** - * @description 退出 - */ -export const ExitIcon = (props: Partial) => { - return ; -}; - -const PlusSm = () => ( - - - -); -/** - * @description Icon/Outline/plus-sm - */ -export const PlusSmIcon = (props: Partial) => { - return ; -}; - -const Trash = () => ( - - - -); -/** - * @description Icon/Outline/trash - */ -export const TrashIcon = (props: Partial) => { - return ; -}; diff --git a/src/components/AddProxyForm/index.css b/src/components/AddProxyForm/index.css deleted file mode 100644 index 9bb13ab..0000000 --- a/src/components/AddProxyForm/index.css +++ /dev/null @@ -1,10 +0,0 @@ -.add-proxy-form { - padding: 24px; -} - -.form-buttons { - display: flex; - justify-content: flex-end; - gap: 8px; - margin-top: 24px; -} \ No newline at end of file diff --git a/src/components/AddProxyForm/index.tsx b/src/components/AddProxyForm/index.tsx deleted file mode 100644 index a08e01a..0000000 --- a/src/components/AddProxyForm/index.tsx +++ /dev/null @@ -1,72 +0,0 @@ -import React from 'react'; -import { Form, Input, Select, InputNumber, Button, message } from 'antd'; -import { ProxyActionType } from '@/types/action'; -import './index.css'; - -interface EditFormData { - name: string; - proxyType: string; - scheme?: string; - host?: string; - port?: number; - pacScript?: string; -} - -export const AddProxyForm: React.FC = () => { - const [form] = Form.useForm(); - - // 初始化表单 - React.useEffect(() => { - form.setFieldsValue({ - name: '', - proxyType: 'fixed_servers', - scheme: 'http', - host: '127.0.0.1', - port: 8080 - }); - }, []); - - const handleSave = async () => { - try { - const values = await form.validateFields(); - const newConfig = { - id: Date.now().toString(), - ...values, - enabled: false - }; - - const response = await chrome.runtime.sendMessage({ - action: ProxyActionType.ADD_PROXY_CONFIG, - config: newConfig - }); - - if (response.success) { - message.success('添加成功'); - window.close(); // 关闭窗口 - } - } catch (error) { - console.error('Failed to add proxy:', error); - message.error('添加失败'); - } - }; - - return ( -
-
- {/* 表单项与之前相同 */} - - - - -
-
- ); -}; \ No newline at end of file diff --git a/src/components/Contro.css b/src/components/Contro.css deleted file mode 100644 index 77c8f68..0000000 --- a/src/components/Contro.css +++ /dev/null @@ -1,73 +0,0 @@ -.Contro { - display: flex; - align-items: center; - height: 40px; - padding: 8px 16px; - font-size: 12px; -} - -.Contro-error-bg { - background-color: rgba(244, 115, 107, .10); -} - -.Contro-success-bg { - background-color: rgba(86, 201, 145, .10); -} - -.Contro-cont-input { - height: 24px; - margin-right: 8px; -} - -.Contro-lable { - color: #85899E; -} - -.Contro-cont { - display: flex; - justify-content: space-between; - align-items: center; - flex: 1; -} - -.Contro-cont-text-error { - color: #F6544A; -} - -.Contro-cont-text-success { - color: #56C991; -} - -.Contro-handle-icon { - display: flex; - align-items: center; -} - -.Contro-handle-icon svg { - cursor: pointer; -} - -.contro-handle-icon-check { - margin-left: 8px; -} - -.icon-p { - display: inline-block; - padding: 4px; -} - -.icon-p svg { - color: #85899E; -} - -.Contro-cont span.anticon:hover { - background: #F0F1F3; -} - -.grey-icon svg { - color: #85899E; -} - -.icon-active:active svg { - color: #F28B44; -} diff --git a/src/components/Contro.tsx b/src/components/Contro.tsx deleted file mode 100644 index 4f92995..0000000 --- a/src/components/Contro.tsx +++ /dev/null @@ -1,191 +0,0 @@ -import React, {useEffect, useMemo, useRef, useState} from "react"; -import {Divider, Tooltip, Input} from "antd"; -import classNames from "classnames"; -import { - CheckIcon, - ExitIcon, - PencilAltIcon, - RefreshIcon, - XIcon, -} from "@assets/icon/icon"; -import {wsc} from "@network/chrome"; -import "./Contro.css"; - -interface ControProps { -} - -export const Contro: React.FC = () => { - const [isEdit, setIsEdit] = useState(false); - const [connected, setConnected] = useState(false); - const [autoFindFailedReason, setAutoFindFailedReason] = useState(""); - const [enginePort, setEnginePort] = useState(""); - const [enginePortTemp, setEnginePortTemp] = useState(enginePort); - const enginePortRef = useRef(enginePort); - - useEffect(() => { - enginePortRef.current = enginePort; - }, [enginePort]); - - useEffect(() => { - const yakitConnectInfo = localStorage.getItem("yakit-connect"); - if (!yakitConnectInfo) { - findPort(11212, 11222); - } else { - const {port, connected} = JSON.parse(yakitConnectInfo); - setConnected(connected); - setEnginePort(port + ""); - setAutoFindFailedReason(""); - } - - wsc.onWSCMessage((message) => { - if (message.action === wsc.ActionType.STATUS) { - if (message.connected === false) { - handleConnectFail(); - } else { - localStorage.setItem( - "yakit-connect", - JSON.stringify({connected: true, port: message.port}) - ); - setEnginePort(message.port + ""); - setConnected(true); - setAutoFindFailedReason(""); - } - } - }); - }, []); - - const findPort = (port: number, max: number) => { - const ws = new WebSocket(`ws://127.0.0.1:${port}`); - ws.onclose = (e: CloseEvent) => { - if (enginePortRef.current) { - handleConnectFail(); - return; - } - if (e.reason !== `FoundYakitWebSocketController` && port + 1 <= max) { - setTimeout(() => findPort(port + 1, max), 200); - } - - if (port + 1 > max) { - setConnected(false); - setEnginePort(""); - setAutoFindFailedReason("Cannot found Yakit"); - localStorage.setItem("yakit-connect", ""); - } - }; - ws.onopen = () => { - setConnected(true); - setEnginePort(port + ""); - ws.close(1000, "FoundYakitWebSocketController"); - connectPort(port); - }; - }; - - const handleConnectFail = () => { - setConnected(false); - setAutoFindFailedReason("Yakit WebSocket Controller Connect Fail"); - localStorage.setItem("yakit-connect", ""); - }; - - const connectPort = (port: number) => { - setAutoFindFailedReason(""); - wsc.connect(port); - }; - - const safeConnected = useMemo(() => { - return connected && enginePort; - }, [connected, enginePort]); - - const failConnected = useMemo(() => { - return !connected && autoFindFailedReason; - }, [connected, autoFindFailedReason]); - - return ( - <> - {safeConnected || failConnected ? ( -
-
Yakit 引擎连接状态:
-
- {isEdit ? ( - <> - { - const value = e.target.value; - setEnginePortTemp(value); - }} - /> -
- { - setIsEdit(false); - }} - /> - { - if (enginePortTemp) { - setIsEdit(false); - setEnginePort(enginePortTemp); - connectPort(Number(enginePortTemp)); - } - }} - /> -
- - ) : ( - <> -
- {safeConnected && "已连接(" + enginePort + ")"} - {failConnected && - (enginePort - ? autoFindFailedReason + "(" + enginePort + ")" - : autoFindFailedReason)} -
-
- - { - setIsEdit(true); - setEnginePortTemp(enginePort); - }} - /> - - - {safeConnected && ( - wsc.disconnect()}/> - )} - {failConnected && ( - { - if (enginePort) { - connectPort(Number(enginePort)); - } else { - findPort(11212, 11222); - } - }} - /> - )} -
- - )} -
-
- ) : null} - - ); -}; diff --git a/src/components/EvalInTab.tsx b/src/components/EvalInTab.tsx deleted file mode 100644 index e094e75..0000000 --- a/src/components/EvalInTab.tsx +++ /dev/null @@ -1,81 +0,0 @@ -import React, {useEffect, useState} from "react"; -import {Button, Input} from "antd"; -import TextArea from "antd/lib/input/TextArea"; -import {wsc} from "@network/chrome"; - -interface EvalInTabProps { -} - -export const EvalInTab: React.FC = () => { - const [funcName, setFuncName] = useState(""); - const [inputArgsData, setInputArgsData] = useState(""); - const [code, setCode] = useState(""); - - useEffect(() => { - wsc.onWSCMessage((message) => { - console.log("message from content script:", message) - if (message.action === wsc.ActionType.TO_EXTENSION_PAGE) { - console.log("eval in tab:", message.result); - // alert("from content script: " + JSON.stringify(message.result)); - // 发送结果 - wsc.sendMessage({"type": "chrome-extension", res: message.result}) - } - }); - }, []); - - const handleClick = async () => { - try { - const [tab] = await wsc.getTab(); - await chrome.runtime.sendMessage({ - action: wsc.ActionType.INJECT_SCRIPT, - tabId: tab.id, - value: {mode: "CONTENT_CALL_FUNCTION", fn_name: funcName, args: inputArgsData}, - }); - } catch (error) { - console.log("error:", error) - } - }; - - const handleInputChange = (event: React.ChangeEvent) => { - setInputArgsData(event.target.value); - }; - - - const handleEvalCodeClick = async () => { - try { - const [tab] = await wsc.getTab(); - await chrome.runtime.sendMessage({ - action: wsc.ActionType.INJECT_SCRIPT, - tabId: tab.id, - value: { - mode: "CONTENT_EVAL_CODE", - code: code, - }, - }); - } catch (error) { - } - } - - return ( -
- setFuncName(e.target.value)} - placeholder="Enter function name" - > -