pssecret-web/app.js
2025-01-09 13:31:40 +01:00

79 lines
2.6 KiB
JavaScript

import config from './config.js';
import { generateKey, encryptData, decryptData, exportKey, importKey } from './crypto.js';
const textarea = document.getElementById('secretInput');
const shareButton = document.getElementById('shareButton');
const spinner = document.getElementById('spinner');
async function handleShare() {
if (!textarea.value.trim()) return;
try {
spinner.classList.remove('hidden');
// Generate encryption key and encrypt data
const key = await generateKey();
const encryptedData = await encryptData(textarea.value, key);
// Send encrypted data to server
const response = await fetch(`${config.API_BASE_URL}/secret`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ data: encryptedData })
});
const { key: secretKey } = await response.json();
const exportedKey = await exportKey(key);
// Create sharing URL
const combinedData = `${secretKey}::${exportedKey}`;
const encodedData = btoa(combinedData);
const shareUrl = `${window.location.origin}/${encodedData}`;
textarea.value = shareUrl;
} catch (error) {
console.error('Sharing failed:', error);
} finally {
spinner.classList.add('hidden');
}
}
async function handlePageLoad() {
const path = window.location.pathname.substring(1);
if (!path) return;
try {
// Try to decode the URL
const decodedData = atob(path);
const [secretKey, encryptionKeyData] = decodedData.split('::');
if (!secretKey || !encryptionKeyData) return;
spinner.classList.remove('hidden');
// Fetch the secret
const response = await fetch(`${config.API_BASE_URL}/secret/${secretKey}`);
if (response.status === 404) {
textarea.value = "Oops, your secret could not be found. Have you already retrieved it?";
return;
}
const { data: encryptedData } = await response.json();
// Decrypt the data
const key = await importKey(encryptionKeyData);
const decryptedData = await decryptData(encryptedData, key);
textarea.value = decryptedData;
} catch (error) {
console.error('Loading secret failed:', error);
} finally {
spinner.classList.add('hidden');
}
}
shareButton.addEventListener('click', handleShare);
window.addEventListener('load', handlePageLoad);