Compare commits
No commits in common. "9daefc9d2dcbf8568392d5806a823f88be9feb41" and "e3805b1a04cd9484eea8d0d5296825c4e8cec2f2" have entirely different histories.
9daefc9d2d
...
e3805b1a04
8 changed files with 429 additions and 504 deletions
15
main.go
15
main.go
|
@ -22,20 +22,7 @@ func run() error {
|
|||
return err
|
||||
}
|
||||
|
||||
go func() {
|
||||
ticker := time.Tick(20 * time.Second)
|
||||
for {
|
||||
<-ticker
|
||||
|
||||
err := storage.ClearExpired()
|
||||
if err != nil {
|
||||
log.Printf("Failed to clear expired passwords: %s", err)
|
||||
continue
|
||||
}
|
||||
|
||||
log.Printf("Cleared expired passwords.")
|
||||
}
|
||||
}()
|
||||
defer storage.Close()
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("GET /", routes.ServeFiles(embedFS, "static"))
|
||||
|
|
|
@ -1,52 +0,0 @@
|
|||
/** Upload a password to the server
|
||||
* @param {string} password Encryptes password
|
||||
* @param {Promise<number>} expiresIn Number of seconds in which the password will expire
|
||||
*/
|
||||
async function uploadPassword(password, expiresIn) {
|
||||
const res = await fetch("/api/password", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
password: password,
|
||||
"expires-in": expiresIn,
|
||||
}),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const msg = await res.text();
|
||||
throw new Error(`Failed to upload password: ${res.status}: ${msg}`);
|
||||
}
|
||||
|
||||
const json = await res.json();
|
||||
return json.id;
|
||||
}
|
||||
|
||||
/** Check if the server knows about the password
|
||||
* @param {string} id Password ID
|
||||
* @returns {Promise<bool>}
|
||||
*/
|
||||
async function hasPassword(id) {
|
||||
const res = await fetch(`/api/password/${id}`, {
|
||||
method: "HEAD",
|
||||
});
|
||||
if (res.status == 404) {
|
||||
return false;
|
||||
}
|
||||
if (res.status == 204) {
|
||||
return true;
|
||||
}
|
||||
|
||||
throw new Error(`Failed to check if password exists: ${res.status}: ${msg}`);
|
||||
}
|
||||
/** Get a password from the server
|
||||
* @param {string} id Password ID
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async function getPassword(id) {
|
||||
const res = await fetch(`/api/password/${id}`);
|
||||
if (!res.ok) {
|
||||
const msg = await res.text();
|
||||
throw new Error(`Failed to get password: ${res.status}: ${msg}`);
|
||||
}
|
||||
|
||||
const json = await res.json();
|
||||
return json.password;
|
||||
}
|
108
static/crypto.js
108
static/crypto.js
|
@ -1,108 +0,0 @@
|
|||
const ALGORITHM_NAME = "AES-GCM";
|
||||
const ALGORITHM_LENGTH = 256;
|
||||
const IV_LENGTH = 16;
|
||||
|
||||
const TEXT_ENCODER = new TextEncoder();
|
||||
const TEXT_DECODER = new TextDecoder();
|
||||
|
||||
/** Coverts an ArrayBuffer into a Base64 encoded string
|
||||
* @param {ArrayBuffer} buffer
|
||||
* @returns {string}
|
||||
*/
|
||||
function bufferToBase64(buffer) {
|
||||
let binary = "";
|
||||
const bytes = new Uint8Array(buffer);
|
||||
const len = bytes.byteLength;
|
||||
for (let i = 0; i < len; i++) {
|
||||
binary += String.fromCharCode(bytes[i]);
|
||||
}
|
||||
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
/** Converts a Base64 encoded string into an ArrayBuffer
|
||||
* @param {string} base64
|
||||
* @returns {ArrayBuffer}
|
||||
*/
|
||||
function base64ToBuffer(base64) {
|
||||
const binaryString = atob(base64);
|
||||
const len = binaryString.length;
|
||||
const bytes = new Uint8Array(len);
|
||||
for (let i = 0; i < len; i++) {
|
||||
bytes[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
/** Generates an key and encrypts "password" using it
|
||||
* @param {Promise<string>} password
|
||||
*/
|
||||
async function encryptPassword(password) {
|
||||
const iv = new Uint8Array(IV_LENGTH);
|
||||
window.crypto.getRandomValues(iv);
|
||||
|
||||
const key = await window.crypto.subtle.generateKey(
|
||||
{
|
||||
name: ALGORITHM_NAME,
|
||||
length: ALGORITHM_LENGTH,
|
||||
},
|
||||
true,
|
||||
["encrypt", "decrypt"],
|
||||
);
|
||||
|
||||
const encryptedPassword = await window.crypto.subtle.encrypt(
|
||||
{
|
||||
name: ALGORITHM_NAME,
|
||||
iv: iv,
|
||||
},
|
||||
key,
|
||||
TEXT_ENCODER.encode(password),
|
||||
);
|
||||
|
||||
const exportedKey = await window.crypto.subtle.exportKey("raw", key);
|
||||
|
||||
const encodedPassword = bufferToBase64(encryptedPassword);
|
||||
const encodedKey = bufferToBase64(exportedKey);
|
||||
const encodedIv = bufferToBase64(iv.buffer);
|
||||
|
||||
return {
|
||||
password: encodedPassword,
|
||||
key: encodedKey,
|
||||
iv: encodedIv,
|
||||
};
|
||||
}
|
||||
|
||||
/** Decodes to key and iv and decryptes the password
|
||||
* @param {string} password
|
||||
* @param {string} key
|
||||
* @param {string} iv
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async function decryptPassword(password, key, iv) {
|
||||
const decodedPassword = base64ToBuffer(password);
|
||||
const decodedKey = base64ToBuffer(key);
|
||||
const decodedIv = base64ToBuffer(iv);
|
||||
|
||||
const cryptoKey = await window.crypto.subtle.importKey(
|
||||
"raw",
|
||||
decodedKey,
|
||||
{
|
||||
name: ALGORITHM_NAME,
|
||||
length: ALGORITHM_LENGTH,
|
||||
},
|
||||
true,
|
||||
["encrypt", "decrypt"],
|
||||
);
|
||||
|
||||
const decryptedPassword = await window.crypto.subtle.decrypt(
|
||||
{
|
||||
name: ALGORITHM_NAME,
|
||||
iv: decodedIv,
|
||||
},
|
||||
cryptoKey,
|
||||
decodedPassword,
|
||||
);
|
||||
|
||||
return TEXT_DECODER.decode(decryptedPassword);
|
||||
}
|
|
@ -7,11 +7,11 @@
|
|||
<!--<link rel="icon" href="favicon.png" />-->
|
||||
<title>PassED</title>
|
||||
|
||||
<script src="/crypto.js"></script>
|
||||
<script src="/api.js"></script>
|
||||
<script src="/index.js" defer></script>
|
||||
<link rel="stylesheet" href="/pico.min.css" />
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<nav class="container-fluid">
|
||||
<ul>
|
||||
<li>
|
||||
|
@ -27,10 +27,14 @@
|
|||
</nav>
|
||||
|
||||
<main class="container">
|
||||
<article>
|
||||
<header>Enter Password</header>
|
||||
<noscript>
|
||||
<h1>This website requires JavaScript to function.</h1>
|
||||
</noscript>
|
||||
|
||||
<form id="enter-password">
|
||||
<article>
|
||||
<header>Enter your password</header>
|
||||
|
||||
<form id="password">
|
||||
<label>
|
||||
Password
|
||||
<textarea name="password"></textarea>
|
||||
|
@ -50,51 +54,61 @@
|
|||
<button type="submit">Generate URL</button>
|
||||
</form>
|
||||
</article>
|
||||
</main>
|
||||
|
||||
<dialog id="url-dialog">
|
||||
<dialog id="url">
|
||||
<article>
|
||||
<header>Password URL</header>
|
||||
|
||||
<fieldset role="group">
|
||||
<input id="url" readonly autofocus />
|
||||
<input id="password-url" readonly autofocus />
|
||||
<button id="url-copy">Copy</button>
|
||||
</fieldset>
|
||||
|
||||
<footer>
|
||||
<button id="url-close">Close</button>
|
||||
</footer>
|
||||
<button id="share-another">Share Another</button>
|
||||
</article>
|
||||
</dialog>
|
||||
|
||||
<dialog id="view-dialog">
|
||||
<dialog id="confirm-view">
|
||||
<article>
|
||||
<header>View Password</header>
|
||||
|
||||
<textarea readonly id="view-password" input></textarea>
|
||||
|
||||
<footer>
|
||||
<button id="view-close">Close</button>
|
||||
</footer>
|
||||
<p class="pico-color-red-500">
|
||||
You may only reveal the password once.
|
||||
</p>
|
||||
<button id="confirm-view">OK</button>
|
||||
</article>
|
||||
</dialog>
|
||||
|
||||
<dialog id="confirm-view-dialog">
|
||||
<dialog id="view">
|
||||
<article>
|
||||
<header>View Password</header>
|
||||
<header>Password</header>
|
||||
|
||||
<p>You may only reveal the password once.</p>
|
||||
|
||||
<footer>
|
||||
<button id="view-cancel" class="secondary">
|
||||
Cancel
|
||||
</button>
|
||||
<button id="view-confirm">Confirm</button>
|
||||
</footer>
|
||||
<textarea id="password" readonly></textarea>
|
||||
</article>
|
||||
</dialog>
|
||||
|
||||
<dialog id="not-found">
|
||||
<dialog id="loading">
|
||||
<article>
|
||||
<header>Loading...</header>
|
||||
</article>
|
||||
</dialog>
|
||||
|
||||
<dialog id="error">
|
||||
<article>
|
||||
<header>Error</header>
|
||||
|
||||
<label>
|
||||
Something went horribly wrong..
|
||||
<textarea id="error-message" readonly></textarea>
|
||||
</label>
|
||||
|
||||
<form method="get" action="/">
|
||||
<button type="submit">Close</button>
|
||||
</form>
|
||||
</article>
|
||||
</dialog>
|
||||
|
||||
<dialog id="password-ne">
|
||||
<article>
|
||||
<header>Password does not exist</header>
|
||||
|
||||
|
@ -103,26 +117,11 @@
|
|||
before or never even existed in the first place.
|
||||
</p>
|
||||
|
||||
<footer>
|
||||
<button id="not-found-close" class="secondary">Close</button>
|
||||
</footer>
|
||||
</article>
|
||||
</dialog>
|
||||
|
||||
<dialog id="loading-dialog">
|
||||
<h1>Loading...</h1>
|
||||
</dialog>
|
||||
|
||||
<dialog id="error-dialog">
|
||||
<article>
|
||||
<header>Error</header>
|
||||
|
||||
<textarea id="error" readonly></textarea>
|
||||
|
||||
<footer>
|
||||
<button id="error-reload">Reload the page</button>
|
||||
</footer>
|
||||
<form method="get" action="/">
|
||||
<button type="submit">Close</button>
|
||||
</form>
|
||||
</article>
|
||||
</dialog>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
|
|
418
static/index.js
418
static/index.js
|
@ -1,199 +1,269 @@
|
|||
const loadingDialog = {
|
||||
dialog: document.querySelector("dialog#loading-dialog"),
|
||||
init() {
|
||||
this.dialog.addEventListener("cancel", (ev) => {
|
||||
ev.preventDefault();
|
||||
});
|
||||
},
|
||||
show() {
|
||||
this.dialog.showModal();
|
||||
},
|
||||
close() {
|
||||
this.dialog.close();
|
||||
},
|
||||
};
|
||||
/*
|
||||
Welcome to the magic behind PassED!
|
||||
This file is responsible for encrypting passwords in the browser and to only send encrypted passwords to the server.
|
||||
|
||||
const errorDialog = {
|
||||
dialog: document.querySelector("dialog#error-dialog"),
|
||||
error: document.querySelector("textarea#error"),
|
||||
reload: document.querySelector("button#error-reload"),
|
||||
init() {
|
||||
this.dialog.addEventListener("close", (ev) => {
|
||||
window.location.reload();
|
||||
});
|
||||
- https://git.1e99.eu/1e99/passed
|
||||
- https://discord.gg/NuGxJKtDKS
|
||||
*/
|
||||
|
||||
this.reload.addEventListener("click", (ev) => {
|
||||
window.location.href = "/";
|
||||
});
|
||||
},
|
||||
show(err) {
|
||||
this.error.value = err;
|
||||
console.error(err);
|
||||
this.dialog.showModal();
|
||||
},
|
||||
};
|
||||
const ALGORITHM_NAME = "AES-GCM";
|
||||
const ALGORITHM_LENGTH = 256;
|
||||
const IV_LENGTH = 16;
|
||||
|
||||
const urlDialog = {
|
||||
dialog: document.querySelector("dialog#url-dialog"),
|
||||
url: document.querySelector("input#url"),
|
||||
urlCopy: document.querySelector("button#url-copy"),
|
||||
close: document.querySelector("button#url-close"),
|
||||
init() {
|
||||
this.dialog.addEventListener("close", (ev) => {});
|
||||
const TEXT_ENCODER = new TextEncoder();
|
||||
const TEXT_DECODER = new TextDecoder();
|
||||
|
||||
this.urlCopy.addEventListener("click", (ev) => {
|
||||
this.url.select();
|
||||
this.url.setSelectionRange(0, 99999);
|
||||
navigator.clipboard.writeText(this.url.value);
|
||||
});
|
||||
const ACTIVE_PAGE = "page-active";
|
||||
|
||||
this.close.addEventListener("click", (ev) => {
|
||||
this.dialog.close();
|
||||
});
|
||||
},
|
||||
show(url) {
|
||||
this.url.value = url;
|
||||
this.dialog.showModal();
|
||||
},
|
||||
};
|
||||
|
||||
const notFoundDialog = {
|
||||
dialog: document.querySelector("dialog#not-found"),
|
||||
close: document.querySelector("button#not-found-close"),
|
||||
init() {
|
||||
this.dialog.addEventListener("close", (ev) => {
|
||||
window.location.search = "";
|
||||
});
|
||||
|
||||
this.close.addEventListener("click", (ev) => {
|
||||
window.location.search = "";
|
||||
});
|
||||
},
|
||||
show() {
|
||||
this.dialog.showModal();
|
||||
},
|
||||
};
|
||||
|
||||
const viewDialog = {
|
||||
dialog: document.querySelector("dialog#view-dialog"),
|
||||
password: document.querySelector("textarea#view-password"),
|
||||
close: document.querySelector("button#view-close"),
|
||||
init() {
|
||||
this.dialog.addEventListener("close", (ev) => {
|
||||
window.location.search = "";
|
||||
});
|
||||
|
||||
this.close.addEventListener("click", (ev) => {
|
||||
this.dialog.close();
|
||||
});
|
||||
},
|
||||
show(password) {
|
||||
this.password.value = password;
|
||||
this.dialog.showModal();
|
||||
},
|
||||
};
|
||||
|
||||
const confirmViewDialog = {
|
||||
dialog: document.querySelector("dialog#confirm-view-dialog"),
|
||||
cancel: document.querySelector("button#view-cancel"),
|
||||
confirm: document.querySelector("button#view-confirm"),
|
||||
resolve: null,
|
||||
reject: null,
|
||||
init() {
|
||||
this.dialog.addEventListener("cancel", (ev) => {
|
||||
this.dialog.close();
|
||||
this.resolve(false);
|
||||
});
|
||||
|
||||
this.cancel.addEventListener("click", (ev) => {
|
||||
this.dialog.close();
|
||||
this.resolve(false);
|
||||
});
|
||||
|
||||
this.confirm.addEventListener("click", (ev) => {
|
||||
this.dialog.close();
|
||||
this.resolve(true);
|
||||
});
|
||||
},
|
||||
show() {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.resolve = resolve;
|
||||
this.reject = reject;
|
||||
this.dialog.showModal();
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
async function viewPassword() {
|
||||
try {
|
||||
loadingDialog.show();
|
||||
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const id = params.get("id");
|
||||
const key = params.get("key");
|
||||
const iv = params.get("iv");
|
||||
|
||||
const exists = await hasPassword(id);
|
||||
if (!exists) {
|
||||
notFoundDialog.show();
|
||||
return;
|
||||
/** Coverts an ArrayBuffer into a Base64 encoded string
|
||||
* @param {ArrayBuffer} buffer
|
||||
* @returns {string}
|
||||
*/
|
||||
function bufferToBase64(buffer) {
|
||||
let binary = "";
|
||||
const bytes = new Uint8Array(buffer);
|
||||
const len = bytes.byteLength;
|
||||
for (let i = 0; i < len; i++) {
|
||||
binary += String.fromCharCode(bytes[i]);
|
||||
}
|
||||
|
||||
const shouldView = await confirmViewDialog.show();
|
||||
if (!shouldView) {
|
||||
// This is needed for the redirect, otherwise the user won't get redirected
|
||||
setTimeout(() => (window.location.search = ""), 0);
|
||||
return;
|
||||
}
|
||||
|
||||
const encrypted = await getPassword(id);
|
||||
const password = await decryptPassword(encrypted, key, iv);
|
||||
|
||||
viewDialog.show(password);
|
||||
} catch (error) {
|
||||
errorDialog.show(error);
|
||||
} finally {
|
||||
loadingDialog.close();
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
const enterPassword = document.querySelector("form#enter-password");
|
||||
/** Converts a Base64 encoded string into an ArrayBuffer
|
||||
* @param {string} base64
|
||||
* @returns {ArrayBuffer}
|
||||
*/
|
||||
function base64ToBuffer(base64) {
|
||||
const binaryString = atob(base64);
|
||||
const len = binaryString.length;
|
||||
const bytes = new Uint8Array(len);
|
||||
for (let i = 0; i < len; i++) {
|
||||
bytes[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
|
||||
enterPassword.addEventListener("submit", async (ev) => {
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
/** Generates an key and encrypts "password" using it
|
||||
* @param {string} password
|
||||
*/
|
||||
async function encryptPassword(password) {
|
||||
const iv = new Uint8Array(IV_LENGTH);
|
||||
window.crypto.getRandomValues(iv);
|
||||
|
||||
const key = await window.crypto.subtle.generateKey(
|
||||
{
|
||||
name: ALGORITHM_NAME,
|
||||
length: ALGORITHM_LENGTH,
|
||||
},
|
||||
true,
|
||||
["encrypt", "decrypt"],
|
||||
);
|
||||
|
||||
const encryptedPassword = await window.crypto.subtle.encrypt(
|
||||
{
|
||||
name: ALGORITHM_NAME,
|
||||
iv: iv,
|
||||
},
|
||||
key,
|
||||
TEXT_ENCODER.encode(password),
|
||||
);
|
||||
|
||||
const exportedKey = await window.crypto.subtle.exportKey("raw", key);
|
||||
|
||||
const encodedPassword = bufferToBase64(encryptedPassword);
|
||||
const encodedKey = bufferToBase64(exportedKey);
|
||||
const encodedIv = bufferToBase64(iv.buffer);
|
||||
|
||||
return {
|
||||
password: encodedPassword,
|
||||
key: encodedKey,
|
||||
iv: encodedIv,
|
||||
};
|
||||
}
|
||||
|
||||
/** Decodes to key and iv and decryptes the password
|
||||
* @param {string} password
|
||||
* @param {string} key
|
||||
* @param {string} iv
|
||||
*/
|
||||
async function decryptPassword(password, key, iv) {
|
||||
const decodedPassword = base64ToBuffer(password);
|
||||
const decodedKey = base64ToBuffer(key);
|
||||
const decodedIv = base64ToBuffer(iv);
|
||||
|
||||
const cryptoKey = await window.crypto.subtle.importKey(
|
||||
"raw",
|
||||
decodedKey,
|
||||
{
|
||||
name: ALGORITHM_NAME,
|
||||
length: ALGORITHM_LENGTH,
|
||||
},
|
||||
true,
|
||||
["encrypt", "decrypt"],
|
||||
);
|
||||
|
||||
const decryptedPassword = await window.crypto.subtle.decrypt(
|
||||
{
|
||||
name: ALGORITHM_NAME,
|
||||
iv: decodedIv,
|
||||
},
|
||||
cryptoKey,
|
||||
decodedPassword,
|
||||
);
|
||||
|
||||
return TEXT_DECODER.decode(decryptedPassword);
|
||||
}
|
||||
|
||||
function showError(error) {
|
||||
const errorDialog = document.querySelector("dialog#error");
|
||||
const errorMessage = document.querySelector("textarea#error-message");
|
||||
|
||||
errorMessage.value = error;
|
||||
errorDialog.showModal();
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
function init() {
|
||||
const passwordForm = document.querySelector("form#password");
|
||||
const loadingDialog = document.querySelector("dialog#loading");
|
||||
const urlDialog = document.querySelector("dialog#url");
|
||||
const urlCopy = document.querySelector("button#url-copy");
|
||||
const passwordUrl = document.querySelector("input#password-url");
|
||||
const shareAnother = document.querySelector("button#share-another");
|
||||
|
||||
passwordForm.addEventListener("submit", async (ev) => {
|
||||
try {
|
||||
loadingDialog.show();
|
||||
loadingDialog.showModal();
|
||||
ev.preventDefault();
|
||||
const data = new FormData(ev.target);
|
||||
|
||||
const password = await encryptPassword(data.get("password"));
|
||||
const id = await uploadPassword(
|
||||
password.password,
|
||||
parseInt(data.get("expires-in")),
|
||||
);
|
||||
const encrypted = await encryptPassword(data.get("password"));
|
||||
|
||||
const res = await fetch("/api/password", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
password: encrypted.password,
|
||||
"expires-in": parseInt(data.get("expires-in")),
|
||||
}),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const msg = await res.text();
|
||||
throw new Error(`Failed to upload password: ${res.status}: ${msg}`);
|
||||
}
|
||||
|
||||
const json = await res.json();
|
||||
|
||||
const params = new URLSearchParams();
|
||||
params.set("id", id);
|
||||
params.set("key", password.key);
|
||||
params.set("iv", password.iv);
|
||||
params.set("id", json.id);
|
||||
params.set("key", encrypted.key);
|
||||
params.set("iv", encrypted.iv);
|
||||
|
||||
const url = new URL(window.location);
|
||||
url.search = params.toString();
|
||||
urlDialog.show(url.toString());
|
||||
passwordUrl.value = url.toString();
|
||||
|
||||
urlDialog.showModal();
|
||||
passwordUrl.select();
|
||||
} catch (error) {
|
||||
errorDialog.show(error);
|
||||
showError(error);
|
||||
} finally {
|
||||
loadingDialog.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
loadingDialog.init();
|
||||
errorDialog.init();
|
||||
urlDialog.init();
|
||||
notFoundDialog.init();
|
||||
viewDialog.init();
|
||||
confirmViewDialog.init();
|
||||
|
||||
const query = window.location.search;
|
||||
if (query.trim() != "") {
|
||||
viewPassword();
|
||||
loadingDialog.addEventListener("close", (ev) => ev.preventDefault());
|
||||
shareAnother.addEventListener("click", (ev) => {
|
||||
passwordForm.reset();
|
||||
passwordUrl.value = "";
|
||||
urlDialog.close();
|
||||
});
|
||||
urlCopy.addEventListener("click", async (ev) => {
|
||||
passwordUrl.select();
|
||||
passwordUrl.setSelectionRange(0, 99999);
|
||||
await navigator.clipboard.writeText(passwordUrl.value);
|
||||
});
|
||||
}
|
||||
|
||||
async function confirmViewPassword(params) {
|
||||
const confirmDialog = document.querySelector("dialog#confirm-view");
|
||||
const confirm = document.querySelector("button#confirm-view");
|
||||
const loadingDialog = document.querySelector("dialog#loading");
|
||||
const passwordNEDialog = document.querySelector("dialog#password-ne");
|
||||
|
||||
try {
|
||||
loadingDialog.showModal();
|
||||
|
||||
const res = await fetch(`/api/password/${params.get("id")}`, {
|
||||
method: "HEAD",
|
||||
});
|
||||
console.log(res.status);
|
||||
if (res.status == 404) {
|
||||
loadingDialog.close();
|
||||
passwordNEDialog.showModal();
|
||||
console.log("Return");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const msg = await res.text();
|
||||
throw new Error(
|
||||
`Failed to check if password exists: ${res.status}: ${msg}`,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
}
|
||||
|
||||
loadingDialog.close();
|
||||
confirmDialog.showModal();
|
||||
|
||||
confirm.addEventListener("click", (ev) => {
|
||||
confirmDialog.close();
|
||||
viewPassword(params);
|
||||
});
|
||||
}
|
||||
|
||||
async function viewPassword(params) {
|
||||
const viewDialog = document.querySelector("dialog#view");
|
||||
const password = document.querySelector("textarea#password");
|
||||
const loadingDialog = document.querySelector("dialog#loading");
|
||||
|
||||
try {
|
||||
loadingDialog.showModal();
|
||||
|
||||
const res = await fetch(`/api/password/${params.get("id")}`);
|
||||
if (!res.ok) {
|
||||
const msg = await res.text();
|
||||
throw new Error(`Failed to load password: ${res.status}: ${msg}`);
|
||||
}
|
||||
|
||||
const json = await res.json();
|
||||
|
||||
const decrypted = await decryptPassword(
|
||||
json.password,
|
||||
params.get("key"),
|
||||
params.get("iv"),
|
||||
);
|
||||
|
||||
password.value = decrypted;
|
||||
viewDialog.showModal();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
loadingDialog.close();
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("load", () => {
|
||||
const query = window.location.search;
|
||||
if (query.trim() != "") {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
confirmViewPassword(params);
|
||||
}
|
||||
|
||||
init();
|
||||
});
|
||||
|
|
|
@ -8,21 +8,23 @@ import (
|
|||
"time"
|
||||
)
|
||||
|
||||
func NewDirStore(path string) Store {
|
||||
func NewDirStore(clearInterval time.Duration, path string) Store {
|
||||
store := &dir{
|
||||
clearInterval: clearInterval,
|
||||
timeLayout: time.RFC3339Nano,
|
||||
path: path,
|
||||
close: make(chan bool),
|
||||
}
|
||||
|
||||
go store.clearExpired()
|
||||
return store
|
||||
}
|
||||
|
||||
type dir struct {
|
||||
clearInterval time.Duration
|
||||
timeLayout string
|
||||
path string
|
||||
}
|
||||
|
||||
type dirEntry struct {
|
||||
Password []byte
|
||||
ExpiresAt time.Time
|
||||
close chan bool
|
||||
}
|
||||
|
||||
func (store *dir) Create(password []byte, expiresAt time.Time) (string, error) {
|
||||
|
@ -44,7 +46,7 @@ func (store *dir) Create(password []byte, expiresAt time.Time) (string, error) {
|
|||
|
||||
defer file.Close()
|
||||
|
||||
entry := dirEntry{
|
||||
entry := entry{
|
||||
Password: password,
|
||||
ExpiresAt: expiresAt,
|
||||
}
|
||||
|
@ -77,7 +79,7 @@ func (store *dir) Get(id string) ([]byte, error) {
|
|||
|
||||
defer file.Close()
|
||||
|
||||
var entry dirEntry
|
||||
var entry entry
|
||||
err = gob.NewDecoder(file).Decode(&entry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -96,12 +98,26 @@ func (store *dir) Delete(id string) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (store *dir) ClearExpired() error {
|
||||
func (store *dir) Close() error {
|
||||
store.close <- true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *dir) clearExpired() error {
|
||||
ticker := time.NewTicker(store.clearInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-store.close:
|
||||
return nil
|
||||
case <-ticker.C:
|
||||
// TODO: Error handling?
|
||||
now := time.Now()
|
||||
|
||||
entries, err := os.ReadDir(store.path)
|
||||
if err != nil {
|
||||
return err
|
||||
continue
|
||||
}
|
||||
|
||||
for _, file := range entries {
|
||||
|
@ -113,28 +129,25 @@ func (store *dir) ClearExpired() error {
|
|||
0,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
continue
|
||||
}
|
||||
|
||||
defer file.Close()
|
||||
|
||||
var entry dirEntry
|
||||
var entry entry
|
||||
err = gob.NewDecoder(file).Decode(&entry)
|
||||
if err != nil {
|
||||
return err
|
||||
continue
|
||||
}
|
||||
|
||||
if now.After(entry.ExpiresAt) {
|
||||
// Close file early as we need to delete it
|
||||
file.Close()
|
||||
err = store.Delete(id)
|
||||
if err != nil {
|
||||
return err
|
||||
store.Delete(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *dir) getPath(id string) string {
|
||||
|
|
|
@ -5,23 +5,23 @@ import (
|
|||
"time"
|
||||
)
|
||||
|
||||
func NewRamStore() Store {
|
||||
func NewRamStore(clearInterval time.Duration) Store {
|
||||
store := &ram{
|
||||
passwords: make(map[string]ramEntry),
|
||||
clearInterval: clearInterval,
|
||||
passwords: make(map[string]entry),
|
||||
lock: sync.Mutex{},
|
||||
close: make(chan bool),
|
||||
}
|
||||
|
||||
go store.clearExpired()
|
||||
return store
|
||||
}
|
||||
|
||||
type ram struct {
|
||||
passwords map[string]ramEntry
|
||||
clearInterval time.Duration
|
||||
passwords map[string]entry
|
||||
lock sync.Mutex
|
||||
}
|
||||
|
||||
type ramEntry struct {
|
||||
Password []byte
|
||||
ExpiresAt time.Time
|
||||
close chan bool
|
||||
}
|
||||
|
||||
func (store *ram) Create(password []byte, expiresAt time.Time) (string, error) {
|
||||
|
@ -35,7 +35,7 @@ func (store *ram) Create(password []byte, expiresAt time.Time) (string, error) {
|
|||
continue
|
||||
}
|
||||
|
||||
store.passwords[id] = ramEntry{
|
||||
store.passwords[id] = entry{
|
||||
Password: password,
|
||||
ExpiresAt: expiresAt,
|
||||
}
|
||||
|
@ -63,19 +63,30 @@ func (store *ram) Delete(id string) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (store *ram) ClearExpired() error {
|
||||
func (store *ram) Close() error {
|
||||
store.close <- true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *ram) clearExpired() error {
|
||||
ticker := time.NewTicker(store.clearInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-store.close:
|
||||
return nil
|
||||
case <-ticker.C:
|
||||
store.lock.Lock()
|
||||
defer store.lock.Unlock()
|
||||
time := time.Now()
|
||||
|
||||
for id, password := range store.passwords {
|
||||
if time.After(password.ExpiresAt) {
|
||||
err := store.Delete(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
store.Delete(id)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
store.lock.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -14,11 +14,16 @@ var (
|
|||
ErrFull = errors.New("storage is filled")
|
||||
)
|
||||
|
||||
type entry struct {
|
||||
Password []byte
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
type Store interface {
|
||||
Create(password []byte, expiresAt time.Time) (string, error)
|
||||
Get(id string) ([]byte, error)
|
||||
Delete(id string) error
|
||||
ClearExpired() error
|
||||
Close() error
|
||||
}
|
||||
|
||||
func NewStore() (Store, error) {
|
||||
|
@ -27,7 +32,7 @@ func NewStore() (Store, error) {
|
|||
|
||||
switch storeType {
|
||||
case "ram":
|
||||
return NewRamStore(), nil
|
||||
return NewRamStore(20 * time.Second), nil
|
||||
case "dir":
|
||||
path := os.Getenv("PASSED_STORE_DIR_PATH")
|
||||
if path == "" {
|
||||
|
@ -35,11 +40,11 @@ func NewStore() (Store, error) {
|
|||
path = "passwords"
|
||||
}
|
||||
|
||||
return NewDirStore(path), nil
|
||||
return NewDirStore(60*time.Second, path), nil
|
||||
|
||||
default:
|
||||
log.Printf("No PASSED_STORE_TYPE provided, defaulting to memory store.")
|
||||
return NewRamStore(), nil
|
||||
return NewRamStore(20 * time.Second), nil
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue