vpn-btcpay-provisioner/app/static/js/utils/wireguard.js
2024-12-30 06:03:07 +00:00

54 lines
1.4 KiB
JavaScript

// Base64 encoding/decoding utilities
const b64 = {
encode: array => btoa(String.fromCharCode.apply(null, array)),
decode: str => Uint8Array.from(atob(str), c => c.charCodeAt(0))
};
async function generateKeyPair() {
// Generate a random key pair using Web Crypto API
const keyPair = await window.crypto.subtle.generateKey(
{
name: 'X25519',
namedCurve: 'X25519',
},
true,
['deriveKey', 'deriveBits']
);
// Export keys in raw format
const privateKey = await window.crypto.subtle.exportKey('raw', keyPair.privateKey);
const publicKey = await window.crypto.subtle.exportKey('raw', keyPair.publicKey);
// Convert to base64
return {
privateKey: b64.encode(new Uint8Array(privateKey)),
publicKey: b64.encode(new Uint8Array(publicKey))
};
}
export async function generateWireGuardConfig(serverPublicKey, serverEndpoint, address) {
const keys = await generateKeyPair();
return {
keys,
config: `[Interface]
PrivateKey = ${keys.privateKey}
Address = ${address}
DNS = 1.1.1.1
[Peer]
PublicKey = ${serverPublicKey}
Endpoint = ${serverEndpoint}
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25`
};
}
export async function generateKeys() {
try {
return await generateKeyPair();
} catch (error) {
console.error('Failed to generate WireGuard keys:', error);
throw error;
}
}