Skip to content

Commit

Permalink
grant core permition
Browse files Browse the repository at this point in the history
  • Loading branch information
Pompurin404 committed Aug 4, 2024
1 parent 09ca8c2 commit 60fb73b
Show file tree
Hide file tree
Showing 8 changed files with 132 additions and 36 deletions.
27 changes: 26 additions & 1 deletion src/main/core/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ import {
mihomoWorkDir
} from '../utils/dirs'
import { generateProfile } from '../resolve/factory'
import { getAppConfig } from '../config'
import { getAppConfig, setAppConfig } from '../config'
import { safeStorage } from 'electron'
import fs from 'fs'

let child: ChildProcess

export function startCore(): void {
const corePath = mihomoCorePath(getAppConfig().core ?? 'mihomo')
grantCorePermition(corePath)
generateProfile()
checkProfile()
stopCore()
Expand Down Expand Up @@ -51,3 +53,26 @@ export function checkProfile(): void {
const corePath = mihomoCorePath(getAppConfig().core ?? 'mihomo')
execFileSync(corePath, ['-t', '-f', mihomoWorkConfigPath(), '-d', mihomoTestDir()])
}

export function grantCorePermition(corePath: string): void {
if (getAppConfig().encryptedPassword && isEncryptionAvailable()) {
const password = safeStorage.decryptString(Buffer.from(getAppConfig().encryptedPassword ?? []))
try {
if (process.platform === 'linux') {
execSync(
`echo "${password}" | sudo -S setcap cap_net_bind_service,cap_net_admin,cap_dac_override,cap_net_raw=+ep ${corePath}`
)
}
if (process.platform === 'darwin') {
execSync(`echo "${password}" | sudo -S chown root:admin ${corePath}`)
execSync(`echo "${password}" | sudo -S chmod +sx ${corePath}`)
}
} catch (e) {
setAppConfig({ encryptedPassword: undefined })
}
}
}

export function isEncryptionAvailable(): boolean {
return safeStorage.isEncryptionAvailable()
}
4 changes: 1 addition & 3 deletions src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ if (!gotTheLock) {
app.quit()
} else {
init()
startCore()

app.on('second-instance', () => {
window?.show()
window?.focusOnWebView()
Expand All @@ -51,7 +49,7 @@ if (!gotTheLock) {
app.whenReady().then(() => {
// Set app user model id for windows
electronApp.setAppUserModelId('party.mihomo.app')

startCore()
// Default open or close DevTools by F12 in development
// and ignore CommandOrControl + R in production.
// see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
Expand Down
1 change: 0 additions & 1 deletion src/main/resolve/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ export function generateProfile(): void {
const { tun: controledTun } = controledMihomoConfig
const tun = Object.assign(profileTun, controledTun)
const profile = Object.assign(currentProfile, controledMihomoConfig)
console.log('profile', profile)
profile.tun = tun
fs.writeFileSync(mihomoWorkConfigPath(), yaml.stringify(profile))
}
6 changes: 4 additions & 2 deletions src/main/utils/ipc.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { app, ipcMain } from 'electron'
import { app, ipcMain, safeStorage } from 'electron'
import {
mihomoChangeProxy,
mihomoCloseAllConnections,
Expand All @@ -25,7 +25,7 @@ import {
addProfileItem,
removeProfileItem
} from '../config'
import { restartCore } from '../core/manager'
import { isEncryptionAvailable, restartCore } from '../core/manager'
import { triggerSysProxy } from '../resolve/sysproxy'
import { changeCurrentProfile } from '../config/profile'

Expand Down Expand Up @@ -57,5 +57,7 @@ export function registerIpcMainHandlers(): void {
ipcMain.handle('removeProfileItem', (_e, id) => removeProfileItem(id))
ipcMain.handle('restartCore', restartCore)
ipcMain.handle('triggerSysProxy', (_e, enable) => triggerSysProxy(enable))
ipcMain.handle('isEncryptionAvailable', isEncryptionAvailable)
ipcMain.handle('encryptString', (_e, str) => safeStorage.encryptString(str))
ipcMain.handle('quitApp', () => app.quit())
}
41 changes: 41 additions & 0 deletions src/renderer/src/components/base/base-password-modal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import {
Modal,
ModalContent,
ModalHeader,
ModalBody,
ModalFooter,
Button,
Input
} from '@nextui-org/react'
import React, { useState } from 'react'

interface Props {
onCancel: () => void
onConfirm: (script: string) => void
}

const BasePasswordModal: React.FC<Props> = (props) => {
const { onCancel, onConfirm } = props
const [password, setPassword] = useState('')

return (
<Modal hideCloseButton isOpen={true}>
<ModalContent>
<ModalHeader className="flex">请输入root密码</ModalHeader>
<ModalBody>
<Input fullWidth type="password" value={password} onValueChange={setPassword} />
</ModalBody>
<ModalFooter>
<Button variant="light" onPress={onCancel}>
取消
</Button>
<Button color="primary" onPress={() => onConfirm(password)}>
确认
</Button>
</ModalFooter>
</ModalContent>
</Modal>
)
}

export default BasePasswordModal
81 changes: 52 additions & 29 deletions src/renderer/src/components/sider/tun-switcher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,50 +3,73 @@ import { useControledMihomoConfig } from '@renderer/hooks/use-controled-mihomo-c
import BorderSwitch from '@renderer/components/base/border-swtich'
import { TbDeviceIpadHorizontalBolt } from 'react-icons/tb'
import { useLocation, useNavigate } from 'react-router-dom'
import { patchMihomoConfig } from '@renderer/utils/ipc'
import React from 'react'
import { encryptString, patchMihomoConfig, isEncryptionAvailable } from '@renderer/utils/ipc'
import React, { useState } from 'react'
import { useAppConfig } from '@renderer/hooks/use-app-config'
import BasePasswordModal from '../base/base-password-modal'

const TunSwitcher: React.FC = () => {
const navigate = useNavigate()
const location = useLocation()
const match = location.pathname.includes('/tun')

const [openPasswordModal, setOpenPasswordModal] = useState(false)
const { appConfig, patchAppConfig } = useAppConfig()
const { controledMihomoConfig, patchControledMihomoConfig } = useControledMihomoConfig(true)
const { tun } = controledMihomoConfig || {}
const { enable } = tun || {}

const onChange = async (enable: boolean): Promise<void> => {
const encryptionAvailable = await isEncryptionAvailable()
if (!appConfig?.encryptedPassword && encryptionAvailable) {
setOpenPasswordModal(true)
return
}
if (!encryptionAvailable) {
alert('加密不可用,请手动给内核授权')
}
await patchControledMihomoConfig({ tun: { enable } })
await patchMihomoConfig({ tun: { enable } })
}

return (
<Card
className={`w-[50%] ml-1 ${match ? 'bg-primary' : ''}`}
isPressable
onPress={() => navigate('/tun')}
>
<CardBody className="pb-1 pt-0 px-0">
<div className="flex justify-between">
<Button
isIconOnly
className="bg-transparent pointer-events-none"
variant="flat"
color="default"
>
<TbDeviceIpadHorizontalBolt color="default" className="text-[24px] font-bold" />
</Button>
<BorderSwitch
isShowBorder={match && enable}
isSelected={enable}
onValueChange={onChange}
/>
</div>
</CardBody>
<CardFooter className="pt-1">
<h3 className="select-none text-md font-bold">虚拟网卡</h3>
</CardFooter>
</Card>
<>
{openPasswordModal && (
<BasePasswordModal
onCancel={() => setOpenPasswordModal(false)}
onConfirm={async (password: string) => {
const encrypted = await encryptString(password)
patchAppConfig({ encryptedPassword: encrypted })
setOpenPasswordModal(false)
}}
/>
)}
<Card
className={`w-[50%] ml-1 ${match ? 'bg-primary' : ''}`}
isPressable
onPress={() => navigate('/tun')}
>
<CardBody className="pb-1 pt-0 px-0">
<div className="flex justify-between">
<Button
isIconOnly
className="bg-transparent pointer-events-none"
variant="flat"
color="default"
>
<TbDeviceIpadHorizontalBolt color="default" className="text-[24px] font-bold" />
</Button>
<BorderSwitch
isShowBorder={match && enable}
isSelected={enable}
onValueChange={onChange}
/>
</div>
</CardBody>
<CardFooter className="pt-1">
<h3 className="select-none text-md font-bold">虚拟网卡</h3>
</CardFooter>
</Card>
</>
)
}

Expand Down
7 changes: 7 additions & 0 deletions src/renderer/src/utils/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,13 @@ export async function triggerSysProxy(enable: boolean): Promise<void> {
return await window.electron.ipcRenderer.invoke('triggerSysProxy', enable)
}

export async function isEncryptionAvailable(): Promise<boolean> {
return await window.electron.ipcRenderer.invoke('isEncryptionAvailable')
}

export async function encryptString(str: string): Promise<Buffer> {
return await window.electron.ipcRenderer.invoke('encryptString', str)
}
export async function quitApp(): Promise<void> {
return await window.electron.ipcRenderer.invoke('quitApp')
}
1 change: 1 addition & 0 deletions src/shared/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ interface IAppConfig {
userAgent?: string
delayTestUrl?: string
delayTestTimeout?: number
encryptedPassword?: Buffer
}

interface IMihomoTunConfig {
Expand Down

0 comments on commit 60fb73b

Please sign in to comment.