Browse Source

use type safe api, fix typescript errors

pull/1250/head
Bernd Storath 9 months ago
parent
commit
93e527aeb6
No known key found for this signature in database GPG Key ID: D6C85685A555540F
  1. 2
      src/app.vue
  2. 10
      src/server/api/session.delete.ts
  3. 37
      src/server/utils/WireGuard.ts
  4. 2
      src/server/utils/cmd.ts
  5. 108
      src/utils/api.ts

2
src/app.vue

@ -1590,7 +1590,7 @@ onMounted(() => {
}, 1000); }, 1000);
api api
.getuiTrafficStats() .getUITrafficStats()
.then((res) => { .then((res) => {
uiTrafficStats.value = res; uiTrafficStats.value = res;
}) })

10
src/server/api/session.delete.ts

@ -1,9 +1,9 @@
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
const session = await useSession(event, SESSION_CONFIG); const session = await useSession(event, SESSION_CONFIG);
const sessionId = session.id; const sessionId = session.id;
await session.clear(); await session.clear();
SERVER_DEBUG(`Deleted Session: ${sessionId}`); SERVER_DEBUG(`Deleted Session: ${sessionId}`);
return { success: true }; return { success: true };
}); });

37
src/server/utils/WireGuard.ts

@ -21,15 +21,15 @@ type Server = {
}; };
type Client = { type Client = {
enabled: boolean;
name: string; name: string;
publicKey: string; address: string;
privateKey: string; privateKey: string;
publicKey: string;
preSharedKey: string; preSharedKey: string;
address: string; createdAt: string;
createdAt: number; updatedAt: string;
updatedAt: Date; enabled: boolean;
allowedIPs?: string[]; allowedIPs?: never;
}; };
type Config = { type Config = {
@ -168,10 +168,10 @@ ${
updatedAt: new Date(client.updatedAt), updatedAt: new Date(client.updatedAt),
allowedIPs: client.allowedIPs, allowedIPs: client.allowedIPs,
downloadableConfig: 'privateKey' in client, downloadableConfig: 'privateKey' in client,
persistentKeepalive: null, persistentKeepalive: null as string | null,
latestHandshakeAt: null, latestHandshakeAt: null as Date | null,
transferRx: null, transferRx: null as number | null,
transferTx: null, transferTx: null as number | null,
}) })
); );
@ -265,11 +265,11 @@ Endpoint = ${WG_HOST}:${WG_CONFIG_PORT}`;
let address; let address;
for (let i = 2; i < 255; i++) { for (let i = 2; i < 255; i++) {
const client = Object.values(config.clients).find((client) => { const client = Object.values(config.clients).find((client) => {
return client.address === WG_DEFAULT_ADDRESS.replace('x', i); return client.address === WG_DEFAULT_ADDRESS.replace('x', i.toString());
}); });
if (!client) { if (!client) {
address = WG_DEFAULT_ADDRESS.replace('x', i); address = WG_DEFAULT_ADDRESS.replace('x', i.toString());
break; break;
} }
} }
@ -288,8 +288,8 @@ Endpoint = ${WG_HOST}:${WG_CONFIG_PORT}`;
publicKey, publicKey,
preSharedKey, preSharedKey,
createdAt: new Date(), createdAt: new Date().toISOString(),
updatedAt: new Date(), updatedAt: new Date().toISOString(),
enabled: true, enabled: true,
}; };
@ -305,6 +305,7 @@ Endpoint = ${WG_HOST}:${WG_CONFIG_PORT}`;
const config = await this.getConfig(); const config = await this.getConfig();
if (config.clients[clientId]) { if (config.clients[clientId]) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete config.clients[clientId]; delete config.clients[clientId];
await this.saveConfig(); await this.saveConfig();
} }
@ -314,7 +315,7 @@ Endpoint = ${WG_HOST}:${WG_CONFIG_PORT}`;
const client = await this.getClient({ clientId }); const client = await this.getClient({ clientId });
client.enabled = true; client.enabled = true;
client.updatedAt = new Date(); client.updatedAt = new Date().toISOString();
await this.saveConfig(); await this.saveConfig();
} }
@ -323,7 +324,7 @@ Endpoint = ${WG_HOST}:${WG_CONFIG_PORT}`;
const client = await this.getClient({ clientId }); const client = await this.getClient({ clientId });
client.enabled = false; client.enabled = false;
client.updatedAt = new Date(); client.updatedAt = new Date().toISOString();
await this.saveConfig(); await this.saveConfig();
} }
@ -338,7 +339,7 @@ Endpoint = ${WG_HOST}:${WG_CONFIG_PORT}`;
const client = await this.getClient({ clientId }); const client = await this.getClient({ clientId });
client.name = name; client.name = name;
client.updatedAt = new Date(); client.updatedAt = new Date().toISOString();
await this.saveConfig(); await this.saveConfig();
} }
@ -357,7 +358,7 @@ Endpoint = ${WG_HOST}:${WG_CONFIG_PORT}`;
} }
client.address = address; client.address = address;
client.updatedAt = new Date(); client.updatedAt = new Date().toISOString();
await this.saveConfig(); await this.saveConfig();
} }

2
src/server/utils/cmd.ts

@ -14,7 +14,7 @@ export function exec(
return Promise.resolve(''); return Promise.resolve('');
} }
return new Promise((resolve, reject) => { return new Promise<string>((resolve, reject) => {
childProcess.exec( childProcess.exec(
cmd, cmd,
{ {

108
src/utils/api.ts

@ -1,104 +1,51 @@
export type APIClient = {
id: string;
name: string;
enabled: boolean;
address: string;
publicKey: string;
createdAt: string;
updatedAt: string;
downloadableConfig: boolean;
persistentKeepalive: string;
latestHandshakeAt: null;
transferRx: number;
transferTx: number;
};
class API { class API {
async call({
method,
path,
body,
}: {
method: string;
path: string;
body?: Record<string, unknown>;
}) {
const res = await fetch(`./api${path}`, {
method,
headers: {
'Content-Type': 'application/json',
},
body: body ? JSON.stringify(body) : undefined,
});
if (res.status === 204) {
return undefined;
}
const json = await res.json();
if (!res.ok) {
throw new Error(json.message || res.statusText);
}
return json;
}
async getRelease() { async getRelease() {
return this.call({ return $fetch('/api/release', {
method: 'get', method: 'get',
path: '/release',
}); });
} }
async getLang() { async getLang() {
return this.call({ return $fetch('/api/lang', {
method: 'get', method: 'get',
path: '/lang',
}); });
} }
async getuiTrafficStats() { async getUITrafficStats() {
return this.call({ return $fetch('/api/ui-traffic-stats', {
method: 'get', method: 'get',
path: '/ui-traffic-stats',
}); });
} }
async getChartType() { async getChartType() {
return this.call({ return $fetch('/api/ui-chart-type', {
method: 'get', method: 'get',
path: '/ui-chart-type',
}); });
} }
async getSession() { async getSession() {
return this.call({ return $fetch('/api/session', {
method: 'get', method: 'get',
path: '/session',
}); });
} }
async createSession({ password }: { password: string | null }) { async createSession({ password }: { password: string | null }) {
return this.call({ return $fetch('/api/session', {
method: 'post', method: 'post',
path: '/session',
body: { password }, body: { password },
}); });
} }
async deleteSession() { async deleteSession() {
return this.call({ return $fetch('/api/session', {
method: 'delete', method: 'delete',
path: '/session',
}); });
} }
async getClients() { async getClients() {
return this.call({ return $fetch('/api/wireguard/client', {
method: 'get', method: 'get',
path: '/wireguard/client', }).then((clients) =>
}).then((clients: APIClient[]) =>
clients.map((client) => ({ clients.map((client) => ({
...client, ...client,
createdAt: new Date(client.createdAt), createdAt: new Date(client.createdAt),
@ -112,31 +59,27 @@ class API {
} }
async createClient({ name }: { name: string }) { async createClient({ name }: { name: string }) {
return this.call({ return $fetch('/api/wireguard/client', {
method: 'post', method: 'POST',
path: '/wireguard/client',
body: { name }, body: { name },
}); });
} }
async deleteClient({ clientId }: { clientId: string }) { async deleteClient({ clientId }: { clientId: string }) {
return this.call({ return $fetch(`/api/wireguard/client/${clientId}`, {
method: 'delete', method: 'DELETE',
path: `/wireguard/client/${clientId}`,
}); });
} }
async enableClient({ clientId }: { clientId: string }) { async enableClient({ clientId }: { clientId: string }) {
return this.call({ return $fetch(`/api/wireguard/client/${clientId}/enable`, {
method: 'post', method: 'POST',
path: `/wireguard/client/${clientId}/enable`,
}); });
} }
async disableClient({ clientId }: { clientId: string }) { async disableClient({ clientId }: { clientId: string }) {
return this.call({ return $fetch(`/api/wireguard/client/${clientId}/disable`, {
method: 'post', method: 'POST',
path: `/wireguard/client/${clientId}/disable`,
}); });
} }
@ -147,9 +90,8 @@ class API {
clientId: string; clientId: string;
name: string; name: string;
}) { }) {
return this.call({ return $fetch(`/api/wireguard/client/${clientId}/name`, {
method: 'put', method: 'PUT',
path: `/wireguard/client/${clientId}/name/`,
body: { name }, body: { name },
}); });
} }
@ -161,17 +103,15 @@ class API {
clientId: string; clientId: string;
address: string; address: string;
}) { }) {
return this.call({ return $fetch(`/api/wireguard/client/${clientId}/address`, {
method: 'put', method: 'PUT',
path: `/wireguard/client/${clientId}/address/`,
body: { address }, body: { address },
}); });
} }
async restoreConfiguration(file: string) { async restoreConfiguration(file: string) {
return this.call({ return $fetch('/api/wireguard/restore', {
method: 'put', method: 'PUT',
path: '/wireguard/restore',
body: { file }, body: { file },
}); });
} }

Loading…
Cancel
Save