Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improv: error cleaning and local state storage in $APP. #3

Merged
merged 2 commits into from
May 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 14 additions & 7 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,10 +192,13 @@ fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![start_wireguard_tunnel, stop_wireguard_tunnel, generate_public_key, is_wireguard_up, remove_windows_service, log_to_console])
.setup(| _app | {
let path = _app.path_resolver().resource_dir().expect("Unable to access resources directory.");
let wireguard_config_path_exists = fs::metadata(format!("{}\\lib\\wg0.conf", &path.display()));
let rpath = _app.path_resolver().resource_dir().expect("Unable to access resources directory.");
let apath = _app.path_resolver().app_dir().expect("Unable to access app directory...");
let wireguard_config_path_exists = fs::metadata(format!("{}\\lib\\wg0.conf", &apath.display()));

println!("Dir: {}", format!("{}\\lib\\wg0.conf", &path.display()));
fs::create_dir_all(apath.clone().join("lib"))?;

println!("Dir: {}", format!("{}\\lib\\wg0.conf", &apath.display()));

let exists_ = match wireguard_config_path_exists {
Ok(_inner) => true,
Expand All @@ -209,23 +212,27 @@ fn main() {
println!("{:?}", private_key);

write_text_file(
&path,
&apath,
(&"wg0.conf").to_string(),
format!("[Interface]\nAddress = 10.0.0.0/24\nDNS = 1.1.1.1\nListenPort = 51820\nPrivateKey = {}", private_key)
);

// let mut perms = fs::metadata(format!("{}\\lib\\wg0.conf", &apath.display()))?.permissions();
// perms.set_readonly(false);
// fs::set_permissions(format!("{}\\lib\\wg0.conf", &apath.display()), perms)?;

write_text_file(
&path,
&apath,
(&".first_time").to_string(),
"YES".to_string()
);

let in_path = format!("{}\\lib\\wg0.conf", &path.display());
let in_path = format!("{}\\lib\\wg0.conf", &apath.display());

if cfg!(target_os = "windows") {
println!("Performing first time setup on WINDOWS");

let service = runas::Command::new("lib\\wireguard.exe")
let service = runas::Command::new(format!("{}\\lib\\wireguard.exe", &rpath.display()))
.arg("/installtunnelservice")
.arg(in_path)
.status();
Expand Down
6 changes: 3 additions & 3 deletions src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"distDir": "../out",
"devPath": "http://localhost:3000",
"beforeDevCommand": "yarn dev -p 3000",
"beforeBuildCommand": "",
"beforeBuildCommand": "yarn build",
"withGlobalTauri": true
},
"tauri": {
Expand Down Expand Up @@ -50,7 +50,7 @@
"allowlist": {
"all": true,
"fs": {
"scope": ["$RESOURCE/*"]
"scope": ["$RESOURCE/*", "$APP/*"]
}
},
"windows": [
Expand All @@ -63,7 +63,7 @@
}
],
"security": {
"csp": "default-src blob: data: filesystem: ws: wss: http: https: tauri: 'unsafe-eval' 'unsafe-inline' 'self'"
"csp": "default-src blob: data: filesystem: ws: wss: http: https: tauri: 'unsafe-eval' 'unsafe-inline' 'self' upgrade-insecure-requests"
}
}
}
5 changes: 5 additions & 0 deletions src/components/importer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { resourceDir } from '@tauri-apps/api/path';

const directory = resourceDir();

export default await directory;
30 changes: 19 additions & 11 deletions src/components/tabview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,17 @@ const TabView: NextPage<{ connectionCallback: Function, tab: "servers" | "settin
const { today } = useDate();

const [ session, setSession ] = useState(null);
const [fp, setFP] = useState(null);
// const session = useSession();

useEffect(() => {
if(typeof navigator !== 'undefined') {
(async () => {
const { appDir } = await import('@tauri-apps/api/path');
setFP(await appDir() + "lib\\wg0.conf");
})();
}

const sess = JSON.parse(localStorage.getItem("reseda.safeguard"));
setSession(sess);

Expand All @@ -41,7 +49,7 @@ const TabView: NextPage<{ connectionCallback: Function, tab: "servers" | "settin
const json = await e.json();
setServerRegistry(json);
setFetching(false);
resumeConnection(connectionCallback, setConnectionTime, json, sess);
resumeConnection(connectionCallback, setConnectionTime, json, sess, fp);
})
.catch(e => {
console.log(e)
Expand All @@ -68,11 +76,11 @@ const TabView: NextPage<{ connectionCallback: Function, tab: "servers" | "settin
if(connection?.server == e.id) return;

if(connection?.connected) {
disconnect(connection, connectionCallback, session).then(() => {
connect(e, setConnectionTime, connectionCallback, session)
disconnect(connection, connectionCallback, session, fp).then(() => {
connect(e, setConnectionTime, connectionCallback, session, fp)
})
}else {
connect(e, setConnectionTime, connectionCallback, session)
connect(e, setConnectionTime, connectionCallback, session, fp)
}
}}>
<div style={{ display: 'flex', flexDirection: 'row', alignItems: "center", gap: ".6rem" }}>
Expand Down Expand Up @@ -118,9 +126,9 @@ const TabView: NextPage<{ connectionCallback: Function, tab: "servers" | "settin
</div>

<div style={{ backgroundColor: 'transparent', justifyContent: 'space-around' }}>
<Button className="text-black" onClick={() => { disconnect_pure(connection, connectionCallback, session)} }>Uninstall Service</Button>
<Button className="text-black" onClick={() => { disconnect_pure(connection, connectionCallback, session, fp)} }>Uninstall Service</Button>

<Button className="text-black" onClick={() => { disconnect(connection, connectionCallback, session)} }>Force Disconnect</Button>
<Button className="text-black" onClick={() => { disconnect(connection, connectionCallback, session, fp)} }>Force Disconnect</Button>
</div>
</div>
)
Expand Down Expand Up @@ -259,26 +267,26 @@ const TabView: NextPage<{ connectionCallback: Function, tab: "servers" | "settin
case 0:
return (
<Button style={{ flexGrow: 0, height: 'fit-content', width: '100%', backgroundColor: '#fff', padding: '.4rem 1rem', color: "#000", fontWeight: '600', fontFamily: "GT Walsheim Pro" }} icon={false} onClick={() => {
disconnect(connection, connectionCallback, session);
disconnect(connection, connectionCallback, session, fp);
}}>Connect to {"Singapore"}</Button>
)
case 1:
return (
<Button style={{ flexGrow: 0, height: 'fit-content', width: '100%', backgroundColor: '#fff', padding: '.4rem 1rem', color: "#000", fontWeight: '600', fontFamily: "GT Walsheim Pro" }} icon={false} onClick={() => {
disconnect(connection, connectionCallback, session);
disconnect(connection, connectionCallback, session, fp);
}}>Disconnect</Button>
)
case 2:
return (
<Button style={{ flexGrow: 0, height: 'fit-content', width: '100%', backgroundColor: '#fff', padding: '.4rem 1rem', color: "#000", fontWeight: '600', fontFamily: "GT Walsheim Pro" }} icon={false} onClick={() => {
disconnect(connection, connectionCallback, session);
disconnect(connection, connectionCallback, session, fp);
}}>Cancel</Button>
)
case 3:
return (
<Button style={{ flexGrow: 0, height: 'fit-content', width: '100%', backgroundColor: '#fff', padding: '.4rem 1rem', color: "#000", fontWeight: '600', fontFamily: "GT Walsheim Pro" }} icon={false} onClick={() => {
disconnect(connection, connectionCallback, session).then(e => {
if(e?.location?.id) connect(connection.location, setConnectionTime, connectionCallback, session);
disconnect(connection, connectionCallback, session, fp).then(e => {
if(e?.location?.id) connect(connection.location, setConnectionTime, connectionCallback, session, fp);
else return;
})
}}>Retry</Button>
Expand Down
6 changes: 3 additions & 3 deletions src/lib/wg-tools/src/WgConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export class WgConfig implements WgConfigObject {
}

/** Write this WgConfig object as a WireGuard config file to a file in the system */
async writeToFile(filePath?: string) {
async writeToFile(filePath: string) {
filePath = filePath || this.filePath
if (!filePath) throw new Error(`No filePath found for WgConfig`)
await writeConfig({ filePath, config: this })
Expand Down Expand Up @@ -186,8 +186,8 @@ export class WgConfig implements WgConfigObject {
}

/** Saves the config to file and restarts it unless `{ noUp: true }` is passed */
async save(opts?: { filePath?: string, noUp: boolean }) {
await this.writeToFile(opts?.filePath)
async save(opts: { filePath: string, noUp?: boolean }) {
await this.writeToFile(opts.filePath)
if (!opts?.noUp) {
await this.restart(opts?.filePath)
}
Expand Down
3 changes: 1 addition & 2 deletions src/lib/wg-tools/src/utils/getConfigFromFile.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { invoke } from '@tauri-apps/api/tauri'
import { parseConfigString } from './configParser'
import * as f from '@tauri-apps/api/fs'
import { appDir, executableDir, publicDir, resourceDir, runtimeDir } from "@tauri-apps/api/path"
const fs = f

interface Options {
Expand All @@ -21,7 +20,7 @@ export const getConfigStringFromFile = async (opts: Options) => {
* Get a wireguard config file as a parsed object
*/
export const getConfigObjectFromFile = async (opts: Options) => {
const file = fs.readTextFile(`${await resourceDir()}lib\\${opts.filePath}`)
const file = fs.readTextFile(`${opts.filePath}`)
.then(e => {
console.log(e);
const obj = parseConfigString(e)
Expand Down
5 changes: 2 additions & 3 deletions src/lib/wg-tools/src/utils/writeConfig.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as f from '@tauri-apps/api/fs'
import { appDir, executableDir, publicDir, resourceDir, runtimeDir } from "@tauri-apps/api/path"
const fs = f

import path from 'path'
Expand All @@ -21,17 +20,17 @@ interface Options {
export const writeConfig = async (opts: Options) => {
try {
const { filePath, config } = opts
const dir = path.dirname(filePath)
// await makeSureDirExists(dir)
const configString = typeof config === 'string' ? config : generateConfigString(config);

console.log(configString);

const write = fs.writeFile({
contents: configString,
path: await resourceDir() + "lib\\wg0.conf"
path: filePath
});


console.log("Written?", write, execPath);

// await invoke('write_text_file', { fileName: "wg0.conf", text: configString });
Expand Down
79 changes: 0 additions & 79 deletions src/pages/_____index.tsx

This file was deleted.

2 changes: 1 addition & 1 deletion src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export default function Home({ providers }) {
const [ authSuccess, setAuthSuccess ] = useState<"logged_out" | "logged_in" | "login_failure">("logged_out");

useEffect(() => {
if(JSON.parse(localStorage.getItem("reseda.safeguard")).email) router.push('./app');
if(JSON.parse(localStorage.getItem("reseda.safeguard"))?.email) router.push('./app');

// Create your instance
const gradient = new Gradient()
Expand Down