vpn-btcpay-provisioner/app/static/js/components/WireGuardPayment.jsx
2024-12-30 06:03:07 +00:00

213 lines
6.2 KiB
JavaScript

import React, { useState, useEffect } from 'react';
import { generateKeys } from '../utils/wireguard';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { AlertCircle } from 'lucide-react';
import { Alert, AlertDescription } from '@/components/ui/alert';
const WireGuardPayment = () => {
const [keyData, setKeyData] = useState(null);
const [duration, setDuration] = useState(24);
const [price, setPrice] = useState(0);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [userId, setUserId] = useState('');
useEffect(() => {
// Generate random userId and keys when component mounts
const init = async () => {
try {
const randomId = crypto.randomUUID();
setUserId(randomId);
const keys = await generateKeys();
setKeyData(keys);
calculatePrice(duration);
} catch (err) {
setError('Failed to initialize keys');
console.error(err);
}
};
init();
}, []);
const calculatePrice = async (hours) => {
try {
const response = await fetch('/api/calculate-price', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ hours: parseInt(hours) })
});
const data = await response.json();
setPrice(data.price);
} catch (err) {
setError('Failed to calculate price');
}
};
const handleDurationChange = (event) => {
const newDuration = parseInt(event.target.value);
setDuration(newDuration);
calculatePrice(newDuration);
};
const handlePayment = async () => {
if (!keyData) {
setError('No keys generated. Please refresh the page.');
return;
}
try {
setLoading(true);
const response = await fetch('/create-invoice', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
duration,
userId,
publicKey: keyData.publicKey,
// Don't send private key to server!
configuration: {
type: 'wireguard',
publicKey: keyData.publicKey
}
})
});
if (!response.ok) {
throw new Error('Failed to create payment');
}
const data = await response.json();
// Save private key to localStorage before redirecting
localStorage.setItem(`vpn_keys_${userId}`, JSON.stringify({
privateKey: keyData.privateKey,
publicKey: keyData.publicKey,
createdAt: new Date().toISOString()
}));
window.location.href = data.checkout_url;
} catch (err) {
setError('Failed to initiate payment');
console.error(err);
} finally {
setLoading(false);
}
};
const handleRegenerateKeys = async () => {
try {
const keys = await generateKeys();
setKeyData(keys);
} catch (err) {
setError('Failed to regenerate keys');
}
};
return (
<Card className="w-full max-w-xl mx-auto">
<CardHeader>
<CardTitle>WireGuard VPN Configuration</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<label className="text-sm font-medium">Your User ID:</label>
<Input value={userId} readOnly className="font-mono text-sm" />
<p className="text-sm text-gray-500">
Save this ID - you'll need it to manage your subscription
</p>
</div>
{keyData && (
<div className="space-y-2">
<label className="text-sm font-medium">Your Public Key:</label>
<Input value={keyData.publicKey} readOnly className="font-mono text-sm" />
<Button
onClick={handleRegenerateKeys}
variant="outline"
size="sm"
className="w-full"
>
Regenerate Keys
</Button>
</div>
)}
<div className="space-y-2">
<label className="text-sm font-medium">Duration:</label>
<div className="space-y-1">
<Input
type="range"
min="1"
max="720"
value={duration}
onChange={handleDurationChange}
className="w-full"
/>
<div className="flex justify-between text-sm text-gray-500">
<Button
variant="ghost"
size="sm"
onClick={() => {
setDuration(24);
calculatePrice(24);
}}
>
1 Day
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => {
setDuration(168);
calculatePrice(168);
}}
>
1 Week
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => {
setDuration(720);
calculatePrice(720);
}}
>
30 Days
</Button>
</div>
<p className="text-center font-medium">{duration} hours</p>
</div>
</div>
<div className="text-center py-4">
<p className="text-3xl font-bold text-blue-500">{price} sats</p>
</div>
<Button
onClick={handlePayment}
disabled={loading || !keyData}
className="w-full"
>
{loading ? 'Processing...' : 'Pay with Bitcoin'}
</Button>
<div className="mt-4 text-sm text-gray-500 space-y-1">
<p> Keys are generated securely in your browser</p>
<p> Your private key never leaves your device</p>
<p> Configuration will be available after payment</p>
</div>
</CardContent>
</Card>
);
};
export default WireGuardPayment;