commit 5915f03f07e35c2969a0f9d0a514d3986c422616 Author: Kitteh Date: Thu Apr 15 13:01:58 2021 +0100 Initial Commit. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..897cb9f --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +node_modules +package-lock.json +dist \ No newline at end of file diff --git a/.jshintrc b/.jshintrc new file mode 100644 index 0000000..76d41ad --- /dev/null +++ b/.jshintrc @@ -0,0 +1,22 @@ +{ + "esversion": 8, + "browser": true, + "onevar": true, + "passfail": false, + "white": true, + "maxerr": 100, + "predef": [ + "define", + "require", + "console", + "ClipboardJS", + "UIkit", + "Prism", + "CodeJar", + "moment" + ], + "indent": 2, + "globals": { + + } +} \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..aa7fbff --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,33 @@ +VaultUI Copyright (2021) (Z & Kitteh)(“Licensor”) + +Hippocratic License Version Number: 2.1. + +Purpose. The purpose of this License is for the Licensor named above to permit the Licensee (as defined below) broad permission, if consistent with Human Rights Laws and Human Rights Principles (as each is defined below), to use and work with the Software (as defined below) within the full scope of Licensor’s copyright and patent rights, if any, in the Software, while ensuring attribution and protecting the Licensor from liability. + +Permission and Conditions. The Licensor grants permission by this license (“License”), free of charge, to the extent of Licensor’s rights under applicable copyright and patent law, to any person or entity (the “Licensee”) obtaining a copy of this software and associated documentation files (the “Software”), to do everything with the Software that would otherwise infringe (i) the Licensor’s copyright in the Software or (ii) any patent claims to the Software that the Licensor can license or becomes able to license, subject to all of the following terms and conditions: + +* Acceptance. This License is automatically offered to every person and entity subject to its terms and conditions. Licensee accepts this License and agrees to its terms and conditions by taking any action with the Software that, absent this License, would infringe any intellectual property right held by Licensor. + +* Notice. Licensee must ensure that everyone who gets a copy of any part of this Software from Licensee, with or without changes, also receives the License and the above copyright notice (and if included by the Licensor, patent, trademark and attribution notice). Licensee must cause any modified versions of the Software to carry prominent notices stating that Licensee changed the Software. For clarity, although Licensee is free to create modifications of the Software and distribute only the modified portion created by Licensee with additional or different terms, the portion of the Software not modified must be distributed pursuant to this License. If anyone notifies Licensee in writing that Licensee has not complied with this Notice section, Licensee can keep this License by taking all practical steps to comply within 30 days after the notice. If Licensee does not do so, Licensee’s License (and all rights licensed hereunder) shall end immediately. + +* Compliance with Human Rights Principles and Human Rights Laws. + + 1. Human Rights Principles. + + (a) Licensee is advised to consult the articles of the United Nations Universal Declaration of Human Rights and the United Nations Global Compact that define recognized principles of international human rights (the “Human Rights Principles”). Licensee shall use the Software in a manner consistent with Human Rights Principles. + + (b) Unless the Licensor and Licensee agree otherwise, any dispute, controversy, or claim arising out of or relating to (i) Section 1(a) regarding Human Rights Principles, including the breach of Section 1(a), termination of this License for breach of the Human Rights Principles, or invalidity of Section 1(a) or (ii) a determination of whether any Law is consistent or in conflict with Human Rights Principles pursuant to Section 2, below, shall be settled by arbitration in accordance with the Hague Rules on Business and Human Rights Arbitration (the “Rules”); provided, however, that Licensee may elect not to participate in such arbitration, in which event this License (and all rights licensed hereunder) shall end immediately. The number of arbitrators shall be one unless the Rules require otherwise. + + Unless both the Licensor and Licensee agree to the contrary: (1) All documents and information concerning the arbitration shall be public and may be disclosed by any party; (2) The repository referred to under Article 43 of the Rules shall make available to the public in a timely manner all documents concerning the arbitration which are communicated to it, including all submissions of the parties, all evidence admitted into the record of the proceedings, all transcripts or other recordings of hearings and all orders, decisions and awards of the arbitral tribunal, subject only to the arbitral tribunal's powers to take such measures as may be necessary to safeguard the integrity of the arbitral process pursuant to Articles 18, 33, 41 and 42 of the Rules; and (3) Article 26(6) of the Rules shall not apply. + + 2. Human Rights Laws. The Software shall not be used by any person or entity for any systems, activities, or other uses that violate any Human Rights Laws. “Human Rights Laws” means any applicable laws, regulations, or rules (collectively, “Laws”) that protect human, civil, labor, privacy, political, environmental, security, economic, due process, or similar rights; provided, however, that such Laws are consistent and not in conflict with Human Rights Principles (a dispute over the consistency or a conflict between Laws and Human Rights Principles shall be determined by arbitration as stated above). Where the Human Rights Laws of more than one jurisdiction are applicable or in conflict with respect to the use of the Software, the Human Rights Laws that are most protective of the individuals or groups harmed shall apply. + + 3. Indemnity. Licensee shall hold harmless and indemnify Licensor (and any other contributor) against all losses, damages, liabilities, deficiencies, claims, actions, judgments, settlements, interest, awards, penalties, fines, costs, or expenses of whatever kind, including Licensor’s reasonable attorneys’ fees, arising out of or relating to Licensee’s use of the Software in violation of Human Rights Laws or Human Rights Principles. + +* Failure to Comply. Any failure of Licensee to act according to the terms and conditions of this License is both a breach of the License and an infringement of the intellectual property rights of the Licensor (subject to exceptions under Laws, e.g., fair use). In the event of a breach or infringement, the terms and conditions of this License may be enforced by Licensor under the Laws of any jurisdiction to which Licensee is subject. Licensee also agrees that the Licensor may enforce the terms and conditions of this License against Licensee through specific performance (or similar remedy under Laws) to the extent permitted by Laws. For clarity, except in the event of a breach of this License, infringement, or as otherwise stated in this License, Licensor may not terminate this License with Licensee. + +* Enforceability and Interpretation. If any term or provision of this License is determined to be invalid, illegal, or unenforceable by a court of competent jurisdiction, then such invalidity, illegality, or unenforceability shall not affect any other term or provision of this License or invalidate or render unenforceable such term or provision in any other jurisdiction; provided, however, subject to a court modification pursuant to the immediately following sentence, if any term or provision of this License pertaining to Human Rights Laws or Human Rights Principles is deemed invalid, illegal, or unenforceable against Licensee by a court of competent jurisdiction, all rights in the Software granted to Licensee shall be deemed null and void as between Licensor and Licensee. Upon a determination that any term or provision is invalid, illegal, or unenforceable, to the extent permitted by Laws, the court may modify this License to affect the original purpose that the Software be used in compliance with Human Rights Principles and Human Rights Laws as closely as possible. The language in this License shall be interpreted as to its fair meaning and not strictly for or against any party. + +* Disclaimer. TO THE FULL EXTENT ALLOWED BY LAW, THIS SOFTWARE COMES “AS IS,” WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED, AND LICENSOR AND ANY OTHER CONTRIBUTOR SHALL NOT BE LIABLE TO ANYONE FOR ANY DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THIS LICENSE, UNDER ANY KIND OF LEGAL CLAIM. + +This Hippocratic License is an Ethical Source license (https://ethicalsource.dev) and is offered for use by licensors and licensees at their own risk, on an “AS IS” basis, and with no warranties express or implied, to the maximum extent permitted by Laws. diff --git a/package.json b/package.json new file mode 100644 index 0000000..3cd3a3a --- /dev/null +++ b/package.json @@ -0,0 +1,20 @@ +{ + "devDependencies": { + "clipboard": "^2.0.8", + "codejar": "^3.4.0", + "css-loader": "^5.2.1", + "date-fns": "^2.21.1", + "html-webpack-plugin": "^5.3.1", + "less": "^4.1.1", + "less-loader": "^8.1.0", + "mini-css-extract-plugin": "^1.4.1", + "moment": "^2.29.1", + "node-sass": "^5.0.0", + "prismjs": "^1.23.0", + "sass-loader": "^11.0.1", + "uikit": "^3.6.19", + "webpack": "^5.32.0", + "webpack-cli": "^4.6.0", + "webpack-dev-server": "^3.11.2" + } +} diff --git a/src/PageState.js b/src/PageState.js new file mode 100644 index 0000000..b4c2a8d --- /dev/null +++ b/src/PageState.js @@ -0,0 +1,77 @@ +import { Page } from "./types/Page.js"; +import { + getKeyByObjectPropertyValue, +} from "./utils.js"; + +export class PageState extends Page { + constructor() { + super(); + this._currentPage = new Page(); + } + + // NOTE: When a item in the page state isn't a string (e.g it is a array or object), + // you need to add helper methods to mutate it or else it wont save. + // example: currentSecretPath is a array so when you try to .push() to it + // it will modify the object that was getted from this class + // then when you try to access it again, there will be a different object. + // I guess you could make another class that emulates a Array or Map + // by using a bunch of functions and modifying localStorage in order to remove some of + // the clunkyness of this approach, but for now, this works. + + get currentBaseMount() { + return localStorage.getItem('currentBaseMount') || ""; + } + set currentBaseMount(value) { + return localStorage.setItem('currentBaseMount', value); + } + + + // Since this is a array we can't act directly on it so we need + // functions to do the same modifications. + // See the note at the start o + popCurrentSecretPath() { + let secPath = this.currentSecretPath; + secPath.pop(); + this.currentSecretPath = secPath; + } + pushCurrentSecretPath(...args) { + let secPath = this.currentSecretPath; + secPath.push(...args); + this.currentSecretPath = secPath; + } + get currentSecretPath() { + return JSON.parse(localStorage.getItem('currentSecretPath') || "[]"); + } + set currentSecretPath(value) { + return localStorage.setItem('currentSecretPath', JSON.stringify(value)); + } + + get currentSecretVersion() { + return localStorage.getItem('currentSecretVersion') || "0"; + } + set currentSecretVersion(value) { + return localStorage.setItem('currentSecretVersion', value); + } + + get currentSecret() { + return localStorage.getItem('currentSecret') || ""; + } + set currentSecret(value) { + return localStorage.setItem('currentSecret', value); + } + + get currentMountType() { + return localStorage.getItem('currentMountType') || ""; + } + set currentMountType(value) { + return localStorage.setItem('currentMountType', value); + } + get currentPage() { + let curPage = localStorage.getItem('currentPage') || "HOME"; + return pages[curPage]; + } + set currentPage(value) { + let key = getKeyByObjectPropertyValue(pages, value); + localStorage.setItem('currentPage', key); + } +} \ No newline at end of file diff --git a/src/api.js b/src/api.js new file mode 100644 index 0000000..2d90592 --- /dev/null +++ b/src/api.js @@ -0,0 +1,304 @@ + +import { getAPIURL, getToken, removeDoubleSlash } from "./utils.js"; + +export const DoesNotExistError = new Error("Does not exist."); + +export async function lookupSelf() { + const request = new Request(getAPIURL() + "/v1/auth/token/lookup-self", { + headers: { + "X-Vault-Token": getToken(), + } + }); + return fetch(request).then(response => { + return response.json(); + }).then(data => { + if ("data" in data) { + return data.data; + } else if ("errors" in data) { + throw new Error(data.errors[0]); + } + }); +} + +export async function renewSelf() { + const request = new Request(getAPIURL() + "/v1/auth/token/renew-self", { + method: 'POST', + headers: { + "X-Vault-Token": getToken(), + 'Content-Type': 'application/json' + }, + body: JSON.stringify({}) + }); + return fetch(request).then(response => { + return response.json(); + }).then(data => { + if ("errors" in data) { + throw new Error(data.errors[0]); + } + }); +} + +export async function usernameLogin(username, password) { + const request = new Request(getAPIURL() + `/v1/auth/userpass/login/${username}`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ "username": username, "password": password }) + }); + return fetch(request).then(response => { + return response.json(); + }).then(data => { + if ("auth" in data) { + return data.auth.client_token; + } else if ("errors" in data) { + throw new Error(data.errors[0]); + } + }); +} + +export async function getMounts() { + const request = new Request(getAPIURL() + "/v1/sys/internal/ui/mounts", { + headers: { + "X-Vault-Token": getToken(), + } + }); + return fetch(request).then(response => { + return response.json(); + }).then(data => { + return data.data.secret; + }); +} + +export async function getSealStatus() { + const request = new Request(getAPIURL() + "/v1/sys/seal-status"); + return fetch(request).then(response => { + return response.json(); + }).then(data => { + return data; + }); +} + +export async function submitUnsealKey(key) { + const request = new Request(getAPIURL() + "/v1/sys/unseal", { + method: "POST", + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + "key": key + }) + }); + let response = await fetch(request); + if (!response.ok) { + let json = await response.json(); + throw new Error(json.errors[0]); + } +} + +export async function getCapabilities(baseMount, secretPath, name) { + const request = new Request(getAPIURL() + "/v1/sys/capabilities-self", { + method: "POST", + headers: { + 'Content-Type': 'application/json', + "X-Vault-Token": getToken(), + }, + body: JSON.stringify( + { + "paths": [removeDoubleSlash(baseMount + secretPath.join("/") + "/" + name)] + } + ) + }); + return fetch(request).then(response => { + return response.json(); + }).then(data => { + return data.capabilities; + }); +} + +export async function getSecrets(baseMount, secretPath) { + let secretURL = ""; + if (pageState.currentMountType == "kv-v2") { + secretURL = `/v1/${baseMount}/metadata/${secretPath.join("")}?list=true`; + } else { + // cubbyhole and v1 are identical + secretURL = `/v1/${baseMount}/${secretPath.join("")}?list=true`; + } + const request = new Request(getAPIURL() + secretURL, { + headers: { + "X-Vault-Token": getToken(), + } + }); + return fetch(request).then(response => { + if (response.status == 404) { + throw DoesNotExistError; + } + return response.json(); + }).then(data => { + return data.data.keys; + }); + +} + +export async function getSecretMetadata(baseMount, secretPath, name) { + const request = new Request(getAPIURL() + `/v1/${baseMount}/metadata/${secretPath.join("")}/${name}`, { + headers: { + "X-Vault-Token": getToken(), + } + }); + + return fetch(request).then(response => { + return response.json(); + }).then(data => { + return data.data; + }); +} + +export async function undeleteSecret(baseMount, secretPath, name, version) { + let secretURL = `/v1/${baseMount}/undelete/${secretPath.join("")}/${name}`; + secretURL = removeDoubleSlash(secretURL).replace(/\/$/, ""); + let request = new Request(getAPIURL() + secretURL, { + method: "POST", + headers: { + 'X-Vault-Token': getToken(), + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ "versions": [version] }) + }); + let response = await fetch(request); + if (!response.ok) { + let json = await response.json(); + throw new Error(json.errors[0]); + } +} + + +export async function getSecret(baseMount, secretPath, name, version = "0") { + let secretURL = ""; + if (pageState.currentMountType == "kv-v2") { + secretURL = `/v1/${baseMount}/data/${secretPath.join("")}/${name}`; + if (version != 0) secretURL += `?version=${version}`; + } else { + secretURL = `/v1/${baseMount}/${secretPath.join("")}/${name}`; + } + const request = new Request(getAPIURL() + secretURL, { + headers: { + "X-Vault-Token": getToken(), + } + }); + + return fetch(request).then(response => { + return response.json(); + }).then(data => { + return pageState.currentMountType == "kv-v2" ? data.data.data : data.data; + }); +} + +export async function deleteSecret(baseMount, secretPath, name, version) { + let secretURL = ""; + + let request; + + if (pageState.currentMountType == "kv-v2" && version != "0") { + secretURL = `/v1/${baseMount}/delete/${secretPath.join("")}/${name}`; + secretURL = removeDoubleSlash(secretURL).replace(/\/$/, ""); + request = new Request(getAPIURL() + secretURL, { + method: "POST", + headers: { + 'X-Vault-Token': getToken(), + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ "versions": [version] }) + }); + } else { + if (pageState.currentMountType == "kv-v2") { + secretURL = `/v1/${baseMount}/metadata/${secretPath.join("")}/${name}`; + } else { + secretURL = `/v1/${baseMount}/${secretPath.join("")}/${name}`; + } + secretURL = removeDoubleSlash(secretURL).replace(/\/$/, ""); + request = new Request(getAPIURL() + secretURL, { + method: "DELETE", + headers: { + 'X-Vault-Token': getToken() + }, + }); + } + + + let response = await fetch(request); + if (!response.ok) { + let json = await response.json(); + throw new Error(json.errors[0]); + } +} + +export async function createOrUpdateSecret(baseMount, secretPath, name, data) { + let secretURL = ""; + let APIData = {}; + + if (pageState.currentMountType == "kv-v2") { + secretURL = `/v1/${baseMount}/data/${secretPath.join("")}/${name}`; + APIData = { "data": data }; + } else { + secretURL = `/v1/${baseMount}/${secretPath.join("")}/${name}`; + APIData = data; + } + + secretURL = removeDoubleSlash(secretURL).replace(/\/$/, ""); + const request = new Request(getAPIURL() + secretURL, { + method: "POST", + headers: { + 'Content-Type': 'application/json', + 'X-Vault-Token': getToken() + }, + body: JSON.stringify(APIData, null, 0) + }); + let response = await fetch(request); + if (!response.ok) { + let json = await response.json(); + throw new Error(json.errors[0]); + } +} + +export async function getTOTPKeys(baseMount) { + const request = new Request(getAPIURL() + `/v1/${baseMount}/keys?list=true`, { + headers: { + "X-Vault-Token": getToken(), + } + }); + return fetch(request).then(response => { + return response.json(); + }).then(data => { + return data.data.keys; + }); +} + +export async function getTOTPCode(baseMount, name) { + const request = new Request(getAPIURL() + `/v1/${baseMount}/code/${name}`, { + headers: { + "X-Vault-Token": getToken(), + } + }); + return fetch(request).then(response => { + return response.json(); + }).then(data => { + return data.data.code; + }); +} + +export async function addNewTOTP(baseMount, parms) { + const request = new Request(getAPIURL() + removeDoubleSlash(`/v1/${baseMount}/keys/${parms.name}`), { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Vault-Token': getToken() + }, + body: JSON.stringify(parms) + }); + let response = await fetch(request); + if (!response.ok) { + let json = await response.json(); + throw new Error(json.errors[0]); + } +} diff --git a/src/elements/CopyableInputBox.js b/src/elements/CopyableInputBox.js new file mode 100644 index 0000000..c19d58d --- /dev/null +++ b/src/elements/CopyableInputBox.js @@ -0,0 +1,40 @@ +import ClipboardJS from "clipboard"; +import UIkit from 'uikit/dist/js/uikit.min.js'; + +import { makeFormIcon, makeElement } from "../htmlUtils.js"; +import { MarginInline } from "./MarginInline.js"; + +export function CopyableInputBox(text, copyable = true) { + let inputBoxDiv = makeElement({ tag: "div" }); + let inputBoxCopyButton = null; + if (copyable) { + inputBoxCopyButton = makeFormIcon("copy"); + let clipboard = new ClipboardJS(inputBoxCopyButton); + clipboard.on('success', _ => { + UIkit.notification("Copied to clipboard.", { status: 'success', timeout: 600 }); + }); + } + + let inputBoxInput = makeElement({ + tag: "input", + class: ["uk-input"], + attributes: { "readonly": true, "type": "text" }, + }); + + let inputBoxInner = MarginInline([ + inputBoxCopyButton, + inputBoxInput + ]); + inputBoxDiv.appendChild(inputBoxInner); + + inputBoxDiv.setText = function (text) { + inputBoxInput.value = `${text}`; + if (copyable) { + inputBoxCopyButton.dataset.clipboardText = `${text}`; + } + }; + inputBoxDiv.setText(text); + + + return inputBoxDiv; +} \ No newline at end of file diff --git a/src/elements/Margin.js b/src/elements/Margin.js new file mode 100644 index 0000000..33af061 --- /dev/null +++ b/src/elements/Margin.js @@ -0,0 +1,9 @@ +import { makeElement } from "../htmlUtils.js"; + +export function Margin(children) { + return makeElement({ + tag: "div", + class: "uk-margin", + children: children + }); +} \ No newline at end of file diff --git a/src/elements/MarginInline.js b/src/elements/MarginInline.js new file mode 100644 index 0000000..2125c21 --- /dev/null +++ b/src/elements/MarginInline.js @@ -0,0 +1,13 @@ +import { makeElement } from "../htmlUtils.js"; + +export function MarginInline(children) { + return makeElement({ + tag: "div", + class: "uk-margin", + children: makeElement({ + tag: "div", + class: "uk-inline", + children: children + }) + }); +} \ No newline at end of file diff --git a/src/htmlUtils.js b/src/htmlUtils.js new file mode 100644 index 0000000..ae2de21 --- /dev/null +++ b/src/htmlUtils.js @@ -0,0 +1,40 @@ +export function makeElement(elementInfo) { + if ("condition" in elementInfo) { if (!elementInfo.condition) { return null; } } + let element = document.createElement(elementInfo.tag); + if ("class" in elementInfo) { + if (Array.isArray(elementInfo.class)) { + element.classList.add(...elementInfo.class); + } else { + element.classList.add(elementInfo.class); + } + } + if ("id" in elementInfo) element.id = elementInfo.id; + if ("html" in elementInfo) element.innerHTML = elementInfo.html; + if ("onclick" in elementInfo) element.onclick = elementInfo.onclick; + if ("attributes" in elementInfo) setElementAttributes(element, elementInfo.attributes); + if ("text" in elementInfo) element.innerText = elementInfo.text; + if ("children" in elementInfo) { + if (Array.isArray(elementInfo.children)) { + elementInfo.children.forEach(child => { + if (child != null) element.appendChild(child); + }); + } else { + if (elementInfo.children != null) element.appendChild(elementInfo.children); + } + } + if ("thenRun" in elementInfo) { + elementInfo.thenRun(element); + } + + return element; +} + +export function setElementAttributes(element, attributes) { + for (let key of Object.getOwnPropertyNames(attributes)) { + element.setAttribute(key, attributes[key]); + } +} + +export function makeFormIcon(icon) { + return makeElement({ tag: "a", class: "uk-form-icon", attributes: { "uk-icon": `icon: ${icon}` } }); +} \ No newline at end of file diff --git a/src/main.js b/src/main.js new file mode 100644 index 0000000..b4e41d0 --- /dev/null +++ b/src/main.js @@ -0,0 +1,90 @@ +'use strict'; + +import "./scss/main.scss"; +import UIkit from 'uikit/dist/js/uikit.min.js'; +import Icons from 'uikit/dist/js/uikit-icons.min.js'; +UIkit.use(Icons); + +import Prism from "prismjs"; +import "prismjs/components/prism-json"; +Prism.highlightAll(); + + +import { + changePage, + renderPage, +} from "./pageUtils.js"; +import { PageState } from "./PageState.js"; + +import { + HomePage, + TOTPViewPage, + NewTOTPPage, + LoginPage, + SetVaultURLPage, + UnsealPage, + KeyValueViewPage, + KeyValueSecretsPage, + KeyValueVersionsPage, + KeyValueNewPage, + KeyValueDeletePage, + KeyValueSecretsEditPage, + PwGenPage, +} from "./pages"; + +import { getSealStatus } from './api.js'; + +const pages = { + HOME: new HomePage(), + TOTP: new TOTPViewPage(), + NEW_TOTP: new NewTOTPPage(), + LOGIN: new LoginPage(), + SET_VAULT_URL: new SetVaultURLPage(), + UNSEAL: new UnsealPage(), + KEY_VALUE_VIEW: new KeyValueViewPage(), + KEY_VALUE_SECRETS: new KeyValueSecretsPage(), + KEY_VALUE_VERSIONS: new KeyValueVersionsPage(), + KEY_VALUE_NEW_SECRET: new KeyValueNewPage(), + KEY_VALUE_DELETE: new KeyValueDeletePage(), + KEY_VALUE_SECRETS_EDIT: new KeyValueSecretsEditPage(), + PW_GEN: new PwGenPage(), +}; + +var pageState = new PageState(); +window.pageState = pageState; +window.pages = pages; +// when making static html, make changePage global so it can be used with onclick +window.changePage = changePage; + +document.addEventListener('DOMContentLoaded', function () { + document.body.innerHTML += ` + +
+
+

Title

+
+
+
+
+ `; + window.pageContent = document.querySelector("#pageContent"); + renderPage(); + + setInterval(async () => { + if (pageState.currentPage != pages.UNSEAL) { + let sealStatus = await getSealStatus(); + if (sealStatus.sealed) { + changePage(pages.UNSEAL); + return; + } + } + }, 5000); +}, false); \ No newline at end of file diff --git a/src/pageUtils.js b/src/pageUtils.js new file mode 100644 index 0000000..8ddc42d --- /dev/null +++ b/src/pageUtils.js @@ -0,0 +1,103 @@ +import UIkit from 'uikit/dist/js/uikit.min.js'; +import { makeElement } from "./htmlUtils.js"; + + +export function setErrorText(text) { + let errorTextElement = document.querySelector("#errorText"); + if (errorTextElement) { + document.querySelector("#errorText").innerText = `Error: ${text}`; + } + UIkit.notification({ + message: `Error: ${text}`, + status: 'danger', + pos: 'top-center', + timeout: 2000 + }); +} + +export function changePage(page) { + if (pageState.currentPage) { + pageState.currentPage.cleanup(); + } + pageState.currentPage = page; + renderPage(); +} + +export function renderPage() { + console.log("Rendering Page: ", pageState.currentPage.name); + document.querySelector("#pageContent").innerHTML = ""; + setPageTitle(pageState.currentPage.name); + pageState.currentPage.render(); +} + +export function setPageTitle(title) { + let pageTitle = document.getElementById("pageTitle"); + pageTitle.innerHTML = ""; + if (typeof title === "string" || title instanceof String) { + pageTitle.innerText = title; + } else { + pageTitle.appendChild(title); + } +} + +function currentTitleSecretText() { + let currentSecretText = pageState.currentSecret + " "; + if (pageState.currentPage == pages.KEY_VALUE_SECRETS_EDIT) currentSecretText += "(edit)"; + if (pageState.currentPage == pages.KEY_VALUE_DELETE) currentSecretText += "(delete)"; + if (pageState.currentPage == pages.KEY_VALUE_VERSIONS) currentSecretText += "(versions)"; + if (pageState.currentPage == pages.NEW_TOTP) currentSecretText += "(new)"; + if (pageState.currentSecretVersion != "0") currentSecretText += `(v${pageState.currentSecretVersion})`; + return currentSecretText; +} + +export function setTitleElement(pageState) { + const titleElement = makeElement({ + tag: "div", + children: [ + makeElement({ + tag: "a", + text: pageState.currentBaseMount + " ", + onclick: _ => { + pageState.currentSecretPath = []; + pageState.currentSecret = ""; + pageState.currentSecretVersion = "0"; + + if (pageState.currentMountType.startsWith("kv") || pageState.currentMountType == "cubbyhole") { + changePage(pages.KEY_VALUE_VIEW); + } else { + changePage(pages.TOTP); + } + } + }), + ...pageState.currentSecretPath.map(function (secretPath, index, secretPaths) { + return makeElement({ + tag: "a", + text: secretPath + " ", + onclick: _ => { + if (pageState.currentMountType.startsWith("kv")) { + pageState.currentSecretPath = secretPaths.slice(0, index + 1); + changePage(pages.KEY_VALUE_VIEW); + } + } + }); + }), + makeElement({ + tag: "span", + condition: pageState.currentSecret.length != 0, + text: currentTitleSecretText() + }) + ] + }); + setPageTitle(titleElement); + return titleElement; +} + +export function setPageContent(content) { + let pageContent = document.getElementById("pageContent"); + if (typeof content === "string" || content instanceof String) { + pageContent.innerHTML = content; + } else { + pageContent.innerHTML = ""; + pageContent.appendChild(content); + } +} \ No newline at end of file diff --git a/src/pages/Home.js b/src/pages/Home.js new file mode 100644 index 0000000..4dd7140 --- /dev/null +++ b/src/pages/Home.js @@ -0,0 +1,156 @@ +import { Page } from "../types/Page.js"; +import { setErrorText, changePage } from "../pageUtils.js"; +import { getAPIURL, getToken } from "../utils.js"; +import { makeElement } from "../htmlUtils.js"; +import { getSealStatus, lookupSelf, getMounts, renewSelf } from "../api.js"; +import formatDistance from 'date-fns/formatDistance'; + + +export class HomePage extends Page { + constructor() { + super(); + } + async render() { + pageContent.innerHTML = ""; + if (!getAPIURL()) { + changePage(pages.SET_VAULT_URL); + return; + } + if (!getToken()) { + localStorage.removeItem("token"); + changePage(pages.LOGIN); + return; + } + let sealStatus = await getSealStatus(); + if (sealStatus.sealed) { + changePage(pages.UNSEAL); + return; + } + + + const textList = makeElement({ + tag: "ul", + class: "uk-nav", + children: [ + makeElement({ + tag: "li", + children: makeElement({ + tag: "span", + text: `VaultURL: ${getAPIURL()}` + }) + }), + makeElement({ + tag: "li", + children: makeElement({ + tag: "a", + text: "Log Out", + onclick: () => { + localStorage.removeItem("token"); + changePage(pageState.currentPage); + } + }) + }), + makeElement({ + tag: "li", + children: makeElement({ + tag: "a", + text: "Renew Lease", + onclick: () => { + renewSelf().then(() => { + changePage(pages.HOME); + }).catch(e => { + setErrorText(e.message); + }); + } + }) + }), + makeElement({ + tag: "li", + children: makeElement({ + tag: "a", + text: "Password Generator", + onclick: () => { + changePage(pages.PW_GEN); + } + }) + }) + ] + }); + pageContent.appendChild(textList); + + try { + let selfTokenInfo = await lookupSelf(); + let expireTime = formatDistance(new Date(), new Date(selfTokenInfo.expire_time)); + textList.appendChild(makeElement({ + tag: "li", + text: `Your token expires in ${expireTime}` + })); + } catch (e) { + setErrorText(e.message); + if (e.message == "permission denied") { + localStorage.removeItem("token"); + changePage(pages.LOGIN); + } + } + + pageState.currentBaseMount = ""; + pageState.currentSecretPath = []; + pageState.currentSecret = ""; + pageState.currentSecretVersion = "0"; + + const navList = makeElement({ tag: "ul", class: ["uk-nav", "uk-nav-default", "uk-margin-top"] }); + pageContent.appendChild(navList); + + navList.appendChild(makeElement({ + tag: "li", + children: makeElement({ + tag: "a", + text: "Cubbyhole - /cubbyhole", + onclick: _ => { + pageState.currentBaseMount = "/cubbyhole"; + pageState.currentMountType = "cubbyhole"; + changePage(pages.KEY_VALUE_VIEW); + } + }) + })); + + let mounts = await getMounts(); + // sort it by secretPath so it's in alphabetical order consistantly. + const mountsMap = new Map(Object.entries(mounts).sort()); + + mountsMap.forEach(function (mount, baseMount) { + if (typeof mount != 'object') return; + if (mount == null) return; + if (!("type" in mount)) return; + if (!(["kv", "totp"].includes(mount.type))) return; + + let mountType = mount.type == "kv" ? "kv-v" + String(mount.options.version) : mount.type; + + let linkText = ""; + let linkPage; + if (mount.type == "kv") { + linkText = `K/V (v${mount.options.version}) - ${baseMount}`; + linkPage = pages.KEY_VALUE_VIEW; + } else if (mount.type == "totp") { + linkText = `TOTP - ${baseMount}`; + linkPage = pages.TOTP; + } + + navList.appendChild(makeElement({ + tag: "li", + children: makeElement({ + tag: "a", + text: linkText, + onclick: _ => { + pageState.currentBaseMount = baseMount; + pageState.currentMountType = mountType; + changePage(linkPage); + } + }) + })); + }); + } + get name() { + return "Home"; + } +} \ No newline at end of file diff --git a/src/pages/KeyValueDelete.js b/src/pages/KeyValueDelete.js new file mode 100644 index 0000000..432308b --- /dev/null +++ b/src/pages/KeyValueDelete.js @@ -0,0 +1,45 @@ +import { Page } from "../types/Page.js"; +import { deleteSecret } from "../api.js"; +import { setPageContent, setTitleElement } from "../pageUtils.js"; +import { makeElement } from "../htmlUtils.js"; + +export class KeyValueDeletePage extends Page { + constructor() { + super(); + } + goBack() { + if (pageState.currentSecretVersion != "0") { + pageState.currentSecretVersion = "0"; + changePage(pages.KEY_VALUE_SECRETS); + } else { + pageState.currentSecret = ""; + changePage(pages.KEY_VALUE_VIEW); + } + } + render() { + setTitleElement(pageState); + setPageContent(makeElement({ + tag: "div", + children: [ + makeElement({ + tag: "h5", + text: "Are you sure you want to delete this?" + }), + makeElement({ + tag: "button", + class: ["uk-button", "uk-button-danger"], + text: "Delete", + onclick: _ => { + deleteSecret(pageState.currentBaseMount, pageState.currentSecretPath, pageState.currentSecret, pageState.currentSecretVersion).then(() => { + this.goBack(); + }); + } + }), + ] + })); + } + + get name() { + return "K/V Delete"; + } +} \ No newline at end of file diff --git a/src/pages/KeyValueNew.js b/src/pages/KeyValueNew.js new file mode 100644 index 0000000..2cac8c0 --- /dev/null +++ b/src/pages/KeyValueNew.js @@ -0,0 +1,83 @@ +import { Page } from "../types/Page.js"; +import { createOrUpdateSecret } from "../api.js"; +import { setPageContent, setTitleElement, setErrorText } from "../pageUtils.js"; +import { makeElement } from "../htmlUtils.js"; + +export class KeyValueNewPage extends Page { + constructor() { + super(); + } + goBack() { + changePage(pages.KEY_VALUE_VIEW); + } + render() { + setTitleElement(pageState); + this.addKVNewForm = makeElement({ + tag: "form", + id: "addKVNewForm", + children: [ + makeElement({ + tag: "div", + class: "uk-margin", + children: makeElement({ + tag: "input", + class: ["uk-input", "uk-form-width-medium"], + attributes: { + required: true, + type: "text", + placeholder: "Relative Path", + name: "path" + } + }) + }), + makeElement({ + tag: "p", + id: "errorText", + class: "uk-text-danger" + }), + makeElement({ + tag: "button", + class: ["uk-button", "uk-button-primary"], + text: "Create Empty Secret", + attributes: { + type: "submit", + } + }) + ] + }); + setPageContent(this.addKVNewForm); + + this.addKVNewForm.addEventListener("submit", function (e) { + e.preventDefault(); + pageState.currentPage.newKVSecretHandleForm(); + }); + } + + newKVSecretHandleForm() { + let formData = new FormData(this.addKVNewForm); + let path = formData.get("path"); + let splitPath = path.split("/"); + let keyData = {}; + + if (["kv-v1", "cubbyhole"].includes(pageState.currentMountType)) { + keyData = { "key": "value" }; + } + + createOrUpdateSecret( + pageState.currentBaseMount, + pageState.currentSecretPath, + splitPath[splitPath.length - 1], + keyData + ).then(_ => { + changePage(pages.KEY_VALUE_VIEW); + return; + }).catch(e => { + setErrorText(e.message); + }); + } + + + get name() { + return "K/V New"; + } +} \ No newline at end of file diff --git a/src/pages/KeyValueSecrets.js b/src/pages/KeyValueSecrets.js new file mode 100644 index 0000000..b6c8dfc --- /dev/null +++ b/src/pages/KeyValueSecrets.js @@ -0,0 +1,156 @@ +import { Page } from "../types/Page.js"; +import { getSecret, undeleteSecret, getCapabilities } from "../api.js"; +import { setPageContent, setTitleElement } from "../pageUtils.js"; +import { CopyableInputBox } from "../elements/CopyableInputBox.js"; +import { makeElement } from "../htmlUtils.js"; + +import Prism from "prismjs"; + + + + + +export class KeyValueSecretsPage extends Page { + constructor() { + super(); + } + goBack() { + if (pageState.currentSecretVersion != "0") { + pageState.currentSecretVersion = "0"; + changePage(pages.KEY_VALUE_VERSIONS); + + } else { + pageState.currentSecret = ""; + changePage(pages.KEY_VALUE_VIEW); + } + + } + async render() { + setTitleElement(pageState); + setPageContent(makeElement({ + tag: "div", + children: [ + makeElement({ + tag: "p", + id: "buttonsBlock" + }), + makeElement({ + tag: "p", + text: "Loading..", + id: "loadingText" + }), + makeElement({ + tag: "div", + id: "kvList" + }), + ] + })); + + let buttonsBlock = document.querySelector("#buttonsBlock"); + let kvList = document.querySelector("#kvList"); + let isSecretNestedJson = false; + let caps = await getCapabilities(pageState.currentBaseMount, pageState.currentSecretPath, pageState.currentSecret); + if (caps.includes("delete")) { + let deleteButtonText = "Delete"; + if (pageState.currentMountType == "kv-v2" && pageState.currentSecretVersion == "0") { + deleteButtonText = `Delete All Versions`; + } else if (pageState.currentMountType == "kv-v2" && pageState.currentSecretVersion != "0") { + deleteButtonText = `Delete Version ${pageState.currentSecretVersion}`; + } + buttonsBlock.appendChild(makeElement({ + tag: "button", + id: "deleteButton", + class: ["uk-button", "uk-button-danger"], + onclick: _ => { changePage(pages.KEY_VALUE_DELETE); }, + text: deleteButtonText + })); + } + if (caps.includes("update")) { + if (pageState.currentSecretVersion == "0") { + buttonsBlock.appendChild(makeElement({ + tag: "button", + id: "editButton", + class: ["uk-button", "uk-margin", "uk-button-primary"], + onclick: _ => { changePage(pages.KEY_VALUE_SECRETS_EDIT); }, + text: "Edit" + })); + } + } + if (pageState.currentMountType == "kv-v2") { + buttonsBlock.appendChild(makeElement({ + tag: "button", + id: "versionsButton", + class: ["uk-button", "uk-button-secondary"], + onclick: _ => { changePage(pages.KEY_VALUE_VERSIONS); }, + text: "Versions" + })); + } + + getSecret( + pageState.currentBaseMount, + pageState.currentSecretPath, + pageState.currentSecret, + pageState.currentSecretVersion + ).then(secretInfo => { + if (secretInfo == null && pageState.currentMountType == "kv-v2") { + document.querySelector("#buttonsBlock").remove(); + document.getElementById("loadingText").remove(); + + kvList.appendChild(makeElement({ + tag: "p", + text: "This secret version has been soft deleted but remains restorable, do you want to restore it?" + })); + + kvList.appendChild(makeElement({ + tag: "button", + text: "Restore Secret Version", + id: "restoreButton", + class: ["uk-button", "uk-button-primary"], + onclick: () => { + undeleteSecret( + pageState.currentBaseMount, + pageState.currentSecretPath, + pageState.currentSecret, + pageState.currentSecretVersion + ).then(resp => { + changePage(pageState.currentPage); + }); + }, + })); + return; + } + + const secretsMap = new Map(Object.entries(secretInfo).sort()); + + for (let [key, value] of secretsMap) { + if (typeof value == 'object') isSecretNestedJson = true; + } + + if (isSecretNestedJson) { + let jsonText = JSON.stringify(Object.fromEntries(secretsMap), null, 4); + kvList.appendChild(makeElement({ + tag: "pre", + class: ["code-block", "language-json", "line-numbers"], + html: Prism.highlight(jsonText, Prism.languages.json, 'json') + })); + } else { + secretsMap.forEach(function (value, key) { + let kvListElement = this.makeKVListElement(key, value); + kvList.appendChild(kvListElement); + }, this); + } + document.getElementById("loadingText").remove(); + }); + } + makeKVListElement(key, value) { + return makeElement({ + tag: "div", + class: ["uk-grid", "uk-grid-small", "uk-text-left"], + children: [CopyableInputBox(key), CopyableInputBox(value)] + }); + } + + get name() { + return "K/V Secret"; + } +} \ No newline at end of file diff --git a/src/pages/KeyValueSecretsEdit.js b/src/pages/KeyValueSecretsEdit.js new file mode 100644 index 0000000..fc74dab --- /dev/null +++ b/src/pages/KeyValueSecretsEdit.js @@ -0,0 +1,71 @@ +import { Page } from "../types/Page.js"; +import { getSecret, createOrUpdateSecret } from "../api.js"; +import { verifyJSONString } from "../utils.js"; +import { setPageContent, setTitleElement, setErrorText } from "../pageUtils.js"; +import { CodeJar } from "codejar"; +import { makeElement } from "../htmlUtils.js"; + +export class KeyValueSecretsEditPage extends Page { + constructor() { + super(); + } + goBack() { + changePage(pages.KEY_VALUE_SECRETS); + } + render() { + setTitleElement(pageState); + let loadingText = makeElement({ tag: "p", text: "Loading.." }); + let editor = makeElement({ + tag: "div", + class: ["editor", "language-json"] + }); + let saveButton = makeElement({ + tag: "button", + class: ["uk-button", "uk-button-primary"], + text: "Save" + }); + setPageContent(makeElement({ + tag: "div", + children: [ + loadingText, + editor, + makeElement({ + tag: "p", + id: "errorText", + class: ["uk-text-danger", "uk-margin-top"] + }), + saveButton + ] + })); + getSecret(pageState.currentBaseMount, pageState.currentSecretPath, pageState.currentSecret).then(secretInfo => { + loadingText.remove(); + + const secretsJSON = JSON.stringify(Object.fromEntries(new Map(Object.entries(secretInfo).sort())), null, 4); + + let jar = CodeJar(editor, () => { }, { tab: ' '.repeat(4) }); + jar.updateCode(secretsJSON); + saveButton.onclick = function () { + if (!verifyJSONString(jar.toString())) { + setErrorText("Invalid JSON"); + return; + } + createOrUpdateSecret( + pageState.currentBaseMount, + pageState.currentSecretPath, + pageState.currentSecret, + JSON.parse(jar.toString()) + ).then(resp => { + changePage(pages.KEY_VALUE_SECRETS); + return; + }).catch(e => { + setErrorText(e.message); + }); + }; + }); + } + + + get name() { + return "K/V Secrets Edit"; + } +} \ No newline at end of file diff --git a/src/pages/KeyValueVersions.js b/src/pages/KeyValueVersions.js new file mode 100644 index 0000000..cc179a5 --- /dev/null +++ b/src/pages/KeyValueVersions.js @@ -0,0 +1,48 @@ +import { Page } from "../types/Page.js"; +import { getSecretMetadata } from "../api.js"; +import { setPageContent, setTitleElement } from "../pageUtils.js"; +import { makeElement } from "../htmlUtils.js"; + +export class KeyValueVersionsPage extends Page { + constructor() { + super(); + } + goBack() { + changePage(pages.KEY_VALUE_SECRETS); + } + async render() { + setTitleElement(pageState); + + let versionsList = makeElement({ + tag: "ul", + id: "versionsList", + class: ["uk-nav", "uk-nav-default"] + }); + setPageContent(versionsList); + + let metadata = await getSecretMetadata( + pageState.currentBaseMount, + pageState.currentSecretPath, + pageState.currentSecret + ); + + new Map(Object.entries(metadata.versions)).forEach((_, ver) => { + versionsList.appendChild(makeElement({ + tag: "li", + children: makeElement({ + tag: "a", + text: `v${ver}`, + onclick: _ => { + pageState.currentSecretVersion = ver; + changePage(pages.KEY_VALUE_SECRETS); + } + }) + })); + }); + + } + + get name() { + return "K/V Versions"; + } + } \ No newline at end of file diff --git a/src/pages/KeyValueView.js b/src/pages/KeyValueView.js new file mode 100644 index 0000000..2fc50dc --- /dev/null +++ b/src/pages/KeyValueView.js @@ -0,0 +1,80 @@ +import { Page } from "../types/Page.js"; +import { DoesNotExistError, getSecrets } from "../api.js"; +import { setErrorText, setTitleElement } from "../pageUtils.js"; +import { makeElement } from "../htmlUtils.js"; + +export class KeyValueViewPage extends Page { + constructor() { + super(); + } + goBack() { + if (pageState.currentSecretPath.length != 0) { + pageState.popCurrentSecretPath(); + changePage(pages.KEY_VALUE_VIEW); + } else { + changePage(pages.HOME); + } + } + async render() { + pageState.currentSecret = ""; + + setTitleElement(pageState); + + let newButton = makeElement({ + tag: "button", + text: "New", + class: ["uk-button", "uk-button-primary", "uk-margin-bottom"], + onclick: () => { + changePage(pages.KEY_VALUE_NEW_SECRET); + } + }); + pageContent.appendChild(newButton); + + try { + let res = await getSecrets(pageState.currentBaseMount, pageState.currentSecretPath); + + pageContent.appendChild(makeElement({ + tag: "ul", + class: ["uk-nav", "uk-nav-default"], + children: [ + ...res.map(function (secret) { + return makeElement({ + tag: "li", + children: makeElement({ + tag: "a", + text: secret, + onclick: _ => { + if (secret.endsWith("/")) { + pageState.pushCurrentSecretPath(secret); + changePage(pages.KEY_VALUE_VIEW); + } else { + pageState.currentSecret = secret; + changePage(pages.KEY_VALUE_SECRETS); + } + } + }) + }); + }) + ] + })); + } catch (e) { + if (e == DoesNotExistError) { + // getSecrets also 404's on no keys so dont go all the way back. + if (pageState.currentSecretPath.length != 0) { + return this.goBack(); + } else { + pageContent.appendChild(makeElement({ + tag: "p", + text: "You seem to have no secrets here, would you like to create one?" + })); + } + } else { + setErrorText(e.message); + } + }; + } + + get name() { + return "K/V View"; + } +} diff --git a/src/pages/Login.js b/src/pages/Login.js new file mode 100644 index 0000000..513a4b2 --- /dev/null +++ b/src/pages/Login.js @@ -0,0 +1,149 @@ +import { Page } from "../types/Page.js"; +import { lookupSelf, usernameLogin } from "../api.js"; +import { setPageContent, setErrorText } from "../pageUtils.js"; +import { makeElement } from "../htmlUtils.js"; +import { Margin } from "../elements/Margin.js"; +import { MarginInline } from "../elements/MarginInline.js"; + +export class LoginPage extends Page { + constructor() { + super(); + } + render() { + let tokenLoginForm = makeElement({ + tag: "form", + children: [ + Margin(makeElement({ + tag: "input", + class: ["uk-input", "uk-form-width-medium"], + attributes: { + required: true, + type: "password", + placeholder: "Token", + name: "token" + } + })), + MarginInline(makeElement({ + tag: "button", + class: ["uk-button", "uk-button-primary"], + text: "Log In", + attributes: { + type: "submit" + } + })) + ] + }); + + let usernameLoginForm = makeElement({ + tag: "form", + children: [ + Margin(makeElement({ + tag: "input", + id: "usernameInput", + class: ["uk-input", "uk-form-width-medium"], + attributes: { + required: true, + type: "text", + placeholder: "Username", + name: "username" + } + })), + Margin(makeElement({ + tag: "input", + id: "passwordInput", + class: ["uk-input", "uk-form-width-medium"], + attributes: { + required: true, + type: "password", + placeholder: "Password", + name: "password" + } + })), + MarginInline(makeElement({ + tag: "button", + class: ["uk-button", "uk-button-primary"], + text: "Log In", + attributes: { + type: "submit" + } + })) + ] + }); + + setPageContent(makeElement({ + tag: "div", + children: [ + makeElement({ + tag: "ul", + class: ["uk-subnav", "uk-subnav-pill"], + attributes: { "uk-switcher": "" }, + children: [ + makeElement({ + tag: "li", + id: "tokenInput", + children: makeElement({ + tag: "a", + text: "Token" + }) + }), + makeElement({ + tag: "li", + children: makeElement({ + tag: "a", + text: "Username" + }) + }) + ] + }), + makeElement({ + tag: "p", + id: "errorText", + class: "uk-text-danger" + }), + makeElement({ + tag: "ul", + class: ["uk-switcher", "uk-margin"], + children: [ + makeElement({ + tag: "li", + children: tokenLoginForm + }), + makeElement({ + tag: "li", + children: usernameLoginForm + }) + ] + }) + ] + })); + + tokenLoginForm.addEventListener("submit", function (e) { + e.preventDefault(); + let formData = new FormData(tokenLoginForm); + const token = formData.get("token"); + localStorage.setItem('token', token); + lookupSelf().then(res => { + changePage(pages.HOME); + }).catch(e => { + document.getElementById("tokenInput").classList.add("uk-form-danger"); + setErrorText(e.message); + }); + }); + usernameLoginForm.addEventListener("submit", function (e) { + e.preventDefault(); + let formData = new FormData(usernameLoginForm); + usernameLogin(formData.get("username"), formData.get("password")).then(res => { + localStorage.setItem("token", res); + changePage(pages.HOME); + }).catch(e => { + document.getElementById("usernameInput").classList.add("uk-form-danger"); + document.getElementById("passwordInput").classList.add("uk-form-danger"); + setErrorText(e.message); + }); + }); + } + + get name() { + return "Login"; + } +} \ No newline at end of file diff --git a/src/pages/NewTOTP.js b/src/pages/NewTOTP.js new file mode 100644 index 0000000..558202b --- /dev/null +++ b/src/pages/NewTOTP.js @@ -0,0 +1,92 @@ +import { Page } from "../types/Page.js"; +import { addNewTOTP } from "../api.js"; +import { setTitleElement, setPageContent, setErrorText, changePage } from "../pageUtils.js"; +import { makeElement } from "../htmlUtils.js"; +import { Margin } from "../elements/Margin.js"; +import { MarginInline } from "../elements/MarginInline.js"; + +export class NewTOTPPage extends Page { + constructor() { + super(); + } + goBack() { + changePage(pages.TOTP); + } + render() { + setTitleElement(pageState); + + let totpForm = makeElement({ + tag: "form", + children: [ + Margin(makeElement({ + tag: "input", + class: ["uk-input", "uk-form-width-medium"], + attributes: { + required: true, + type: "text", + placeholder: "TOTP Name", + name: "name" + } + })), + makeElement({ + tag: "p", + text: "You need either a key or a URI, URI prefered. Just scan the QR code and copy the UI." + }), + Margin(makeElement({ + tag: "input", + class: ["uk-input", "uk-form-width-medium"], + attributes: { + required: true, + type: "text", + placeholder: "URI", + name: "uri" + } + })), + Margin(makeElement({ + tag: "input", + class: ["uk-input", "uk-form-width-medium"], + attributes: { + required: true, + type: "text", + placeholder: "Key", + name: "key" + } + })), + makeElement({ + tag: "p", + id: "errorText", + class: "uk-text-danger" + }), + MarginInline(makeElement({ + tag: "button", + class: ["uk-button", "uk-button-primary"], + text: "Add", + attributes: { + type: "submit" + } + })) + ] + + }); + setPageContent(totpForm); + + totpForm.addEventListener("submit", function (e) { + e.preventDefault(); + let formData = new FormData(totpForm); + let parms = { + url: formData.get("uri"), + key: formData.get("key"), + name: formData.get("name"), + generate: false + }; + addNewTOTP(pageState.currentBaseMount, parms).then(res => { + changePage(pages.TOTP); + }).catch(e => { + setErrorText(`API Error: ${e.message}`); + }); + }); + } + get name() { + return "Create New TOTP"; + } +} \ No newline at end of file diff --git a/src/pages/PwGen.js b/src/pages/PwGen.js new file mode 100644 index 0000000..9386a54 --- /dev/null +++ b/src/pages/PwGen.js @@ -0,0 +1,56 @@ +import { Page } from "../types/Page.js"; +import { setPageContent } from "../pageUtils.js"; +import { makeElement } from "../htmlUtils.js"; + +import { CopyableInputBox } from "../elements/CopyableInputBox.js"; + +function random() { + const { + crypto, + Uint32Array + } = window; + + if (typeof (crypto === null || crypto === void 0 ? void 0 : crypto.getRandomValues) === 'function' && typeof Uint32Array === 'function') { + return window.crypto.getRandomValues(new Uint32Array(1))[0] / 4294967295; + } + + return Math.random(); +} + + +function genPw(len) { + let pw = ""; + const pwArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&'()*+,-./:;<=>?@[\]^_{|}~".split(''); + for (let i = 0; i < len; i++) { + pw = pw.concat(pwArray[Math.floor(random() * pwArray.length)]); + } + return pw; +} + + +export class PwGenPage extends Page { + constructor() { + super(); + } + async render() { + let inputBox = CopyableInputBox(genPw(24)); + setPageContent(makeElement({ + tag: "div", + children: [ + inputBox, + makeElement({ + tag: "button", + text: "Gen New Password", + class: ["uk-button", "uk-button-primary", "uk-margin-bottom"], + onclick: () => { + inputBox.setText(genPw(24)); + } + }) + ] + })); + } + + get name() { + return "Password Generator"; + } +} \ No newline at end of file diff --git a/src/pages/SetVaultURL.js b/src/pages/SetVaultURL.js new file mode 100644 index 0000000..072a6ae --- /dev/null +++ b/src/pages/SetVaultURL.js @@ -0,0 +1,53 @@ +import { Page } from "../types/Page.js"; +import { setPageContent, changePage } from "../pageUtils.js"; +import { makeElement } from "../htmlUtils.js"; + +export class SetVaultURLPage extends Page { + constructor() { + super(); + } + render() { + setPageContent(makeElement({ + tag: "form", + id: "setVaultURLForm", + children: [ + makeElement({ + tag: "div", + class: "uk-margin", + children: makeElement({ + tag: "input", + class: ["uk-input", "uk-form-width-medium"], + attributes: { + required: true, + type: "text", + placeholder: "Vault URL", + name: "vaultURL" + } + }) + }), + makeElement({ + tag: "p", + id: "errorText", + class: "uk-text-danger" + }), + makeElement({ + tag: "button", + class: ["uk-button", "uk-button-primary"], + text: "Set", + attributes: { + type: "submit", + } + }) + ] + })); + document.getElementById("setVaultURLForm").addEventListener("submit", function (e) { + e.preventDefault(); + let formData = new FormData(document.querySelector('#setVaultURLForm')); + localStorage.setItem('apiurl', formData.get("vaultURL")); + changePage(pages.HOME); + }); + } + get name() { + return "Set Vault URL"; + } +} diff --git a/src/pages/TOTPView.js b/src/pages/TOTPView.js new file mode 100644 index 0000000..cf38899 --- /dev/null +++ b/src/pages/TOTPView.js @@ -0,0 +1,70 @@ +import { Page } from "../types/Page.js"; +import { getTOTPKeys, getTOTPCode } from "../api.js"; +import { setTitleElement, setPageContent } from "../pageUtils.js"; +import { CopyableInputBox } from "../elements/CopyableInputBox.js"; +import { makeElement } from "../htmlUtils.js"; + +export class TOTPViewPage extends Page { + constructor() { + super(); + this.refreshers = []; + } + render() { + setTitleElement(pageState); + let totpList = makeElement({ tag: "div" }); + setPageContent(makeElement({ + tag: "div", + children: [ + makeElement({ + tag: "a", + text: "Add new TOTP", + onclick: _ => { changePage(pages.NEW_TOTP); } + }), + makeElement({ + tag: "p", + id: "loadingText", + text: "Loading TOTP Codes..", + }), + makeElement({tag: "br"}), + makeElement({tag: "br"}), + totpList + ] + })); + + + getTOTPKeys(pageState.currentBaseMount, pageState.currentSecretPath).then(res => { + res.forEach(function (totpKeyName) { + let totpListElement = this.makeTOTPListElement(totpKeyName); + totpList.appendChild(totpListElement); + let totpRefresher = async function (totpKeyName, totpListElement) { + totpListElement.setCode(await getTOTPCode(pageState.currentBaseMount, totpKeyName)); + }; + totpRefresher(totpKeyName, totpListElement); + this.refreshers.push(setInterval(totpRefresher, 3000, totpKeyName, totpListElement)); + }, this); + document.getElementById("loadingText").remove(); + }); + } + + cleanup() { + this.refreshers.forEach(refresher => clearInterval(refresher)); + } + + makeTOTPListElement(totpKeyName) { + let totpKeyBox = CopyableInputBox(totpKeyName, false); + let totpValueBox = CopyableInputBox("Loading.."); + + let gridElement = makeElement({ + tag: "div", + class: ["uk-grid", "uk-grid-small", "uk-text-expand"], + children: [totpKeyBox, totpValueBox] + }); + + gridElement.setCode = totpValueBox.setText; + + return gridElement; + } + get name() { + return "TOTP"; + } +} \ No newline at end of file diff --git a/src/pages/Unseal.js b/src/pages/Unseal.js new file mode 100644 index 0000000..a63abc0 --- /dev/null +++ b/src/pages/Unseal.js @@ -0,0 +1,91 @@ +import { Page } from "../types/Page.js"; +import { submitUnsealKey, getSealStatus } from "../api.js"; +import { setPageContent, setErrorText, changePage } from "../pageUtils.js"; +import { makeElement } from "../htmlUtils.js"; +import { Margin } from "../elements/Margin.js"; +import { MarginInline } from "../elements/MarginInline.js"; + +export class UnsealPage extends Page { + constructor() { + super(); + } + async render() { + this.unsealKeyForm = makeElement({ + tag: "form", + children: [ + MarginInline(makeElement({ + tag: "input", + class: ["uk-input", "uk-form-width-medium"], + attributes: { + required: true, + type: "password", + placeholder: "Key", + name: "key" + } + })), + MarginInline(makeElement({ + tag: "button", + class: ["uk-button", "uk-button-primary"], + text: "Submit Key" + })), + ] + }); + + this.unsealProgress = makeElement({ + tag: "progress", + class: "uk-progress", + attributes: {value: "0", max: "0"} + }); + this.unsealProgressText = makeElement({ + tag: "p", + text: "Keys: 0/0", + }); + + setPageContent(makeElement({ + tag: "div", + children: [ + this.unsealProgress, + makeElement({ + tag: "p", + id: "errorText", + class: ["uk-text-danger", "uk-margin-top"] + }), + this.unsealProgressText, + this.unsealKeyForm + ] + })); + this.unsealKeyForm.addEventListener("submit", function (e) { + e.preventDefault(); + pageState.currentPage.handleKeySubmit(); + }); + this.updateSealProgress(await getSealStatus()); + } + updateSealProgress(data) { + let progress = data.progress; + let keysNeeded = data.t; + let text = this.unsealProgressText; + text.innerText = `Keys: ${progress}/${keysNeeded}`; + let progressBar = this.unsealProgress; + progressBar.value = progress; + progressBar.max = keysNeeded; + if (!data.sealed) { + progressBar.value = keysNeeded; + changePage(pages.HOME); + } + } + + async handleKeySubmit() { + let formData = new FormData(this.unsealKeyForm); + + submitUnsealKey(formData.get("key")).then(resp => { + getSealStatus().then(data => { + this.updateSealProgress(data); + }); + }).catch(e => { + setErrorText(e.message); + }); + } + get name() { + return "Unseal"; + } +} \ No newline at end of file diff --git a/src/pages/index.js b/src/pages/index.js new file mode 100644 index 0000000..66749aa --- /dev/null +++ b/src/pages/index.js @@ -0,0 +1,13 @@ +export { HomePage } from "./Home.js"; +export { TOTPViewPage } from "./TOTPView.js"; +export { NewTOTPPage } from "./NewTOTP.js"; +export { LoginPage } from "./Login.js"; +export { SetVaultURLPage } from "./SetVaultURL.js"; +export { UnsealPage } from "./Unseal.js"; +export { KeyValueViewPage } from "./KeyValueView.js"; +export { KeyValueSecretsPage } from "./KeyValueSecrets.js"; +export { KeyValueVersionsPage } from "./KeyValueVersions.js"; +export { KeyValueNewPage } from "./KeyValueNew.js"; +export { KeyValueDeletePage } from "./KeyValueDelete.js"; +export { KeyValueSecretsEditPage } from "./KeyValueSecretsEdit.js"; +export { PwGenPage } from "./PwGen.js"; \ No newline at end of file diff --git a/src/scss/main.scss b/src/scss/main.scss new file mode 100644 index 0000000..85c922c --- /dev/null +++ b/src/scss/main.scss @@ -0,0 +1,14 @@ +.editor { + background-color: #3B4252; + padding: 1em; + margin: .5em 0; + overflow: auto; +} +.code-block { + padding-top: 10px !important; + padding-right: 10px !important; + padding-bottom: 10px !important; + padding-left: 10px !important; +} +@import "./prism-nord.scss"; +@import "./uikit.scss"; \ No newline at end of file diff --git a/src/scss/prism-nord.scss b/src/scss/prism-nord.scss new file mode 100644 index 0000000..659f461 --- /dev/null +++ b/src/scss/prism-nord.scss @@ -0,0 +1,116 @@ +code[class*="language-"], +pre[class*="language-"] { + color: #f8f8f2; + background: none; + font-family: "Fira Code", Consolas, Monaco, "Andale Mono", "Ubuntu Mono", + monospace; + text-align: left; + white-space: pre; + word-spacing: normal; + word-break: normal; + word-wrap: normal; + line-height: 1.5; + -moz-tab-size: 4; + -o-tab-size: 4; + tab-size: 4; + -webkit-hyphens: none; + -moz-hyphens: none; + -ms-hyphens: none; + hyphens: none; +} + +pre[class*="language-"] { + padding: 1em; + margin: 0.5em 0; + overflow: auto; + border-radius: 0.3em; +} + +:not(pre) > code[class*="language-"], +pre[class*="language-"] { + background: #3b4252; +} + +:not(pre) > code[class*="language-"] { + padding: 0.1em; + border-radius: 0.3em; + white-space: normal; +} + +.token.comment, +.token.prolog, +.token.doctype, +.token.cdata { + color: #636f88; +} + +.token.punctuation { + color: #81a1c1; +} + +.namespace { + opacity: 0.7; +} + +.token.property, +.token.tag, +.token.constant, +.token.symbol, +.token.deleted { + color: #81a1c1; +} + +.token.number { + color: #b48ead; +} + +.token.boolean { + color: #81a1c1; +} + +.token.selector, +.token.attr-name, +.token.string, +.token.char, +.token.builtin, +.token.inserted { + color: #a3be8c; +} + +.token.operator, +.token.entity, +.token.url, +.language-css .token.string, +.style .token.string, +.token.variable { + color: #81a1c1; +} + +.token.atrule, +.token.attr-value, +.token.function, +.token.class-name { + color: #88c0d0; +} + +.token.keyword { + color: #81a1c1; +} + +.token.regex, +.token.important { + color: #ebcb8b; +} + +.token.important, +.token.bold { + font-weight: bold; +} + +.token.italic { + font-style: italic; +} + +.token.entity { + cursor: help; +} diff --git a/src/scss/uikit.scss b/src/scss/uikit.scss new file mode 100644 index 0000000..b5fb6a0 --- /dev/null +++ b/src/scss/uikit.scss @@ -0,0 +1,74 @@ +$global-color: #D8DEE9 !default; +$global-emphasis-color: #E5E9F0 !default; +$global-muted-color: #E5E9F0 !default; + +$global-link-color: #5E81AC !default; +$global-link-hover-color: #88C0D0 !default; + +$global-inverse-color: #fff !default; + +$global-background: #2E3440 !default; + +$global-muted-background: #3B4252 !default; +$global-primary-background: #434C5E !default; +$global-secondary-background: #4C566A !default; + +$global-success-background: #A3BE8C !default; +$global-warning-background: #D08770 !default; +$global-danger-background: #BF616A !default; + + +$button-primary-background: #5E81AC; + +// Keep these in same order as https://github.com/uikit/uikit/blob/develop/src/less/components/_import.less +@import "uikit/src/scss/variables.scss"; +@import "uikit/src/scss/mixins.scss"; +@import "uikit/src/scss/components/base.scss"; + +// Elements +@import "uikit/src/scss/components/link.scss"; +@import "uikit/src/scss/components/heading.scss"; +@import "uikit/src/scss/components/list.scss"; +@import "uikit/src/scss/components/icon.scss"; +@import "uikit/src/scss/components/form.scss"; +@import "uikit/src/scss/components/button.scss"; +@import "uikit/src/scss/components/progress.scss"; + +// Layout +@import "uikit/src/scss/components/section.scss"; +@import "uikit/src/scss/components/container.scss"; +@import "uikit/src/scss/components/tile.scss"; +@import "uikit/src/scss/components/card.scss"; + +// Common +@import "uikit/src/scss/components/spinner.scss"; +@import "uikit/src/scss/components/alert.scss"; + +// JavaScript +@import "uikit/src/scss/components/slider.scss"; +@import "uikit/src/scss/components/notification.scss"; + + +// Other +@import "uikit/src/scss/components/grid.scss"; + +@import "uikit/src/scss/components/nav.scss"; +@import "uikit/src/scss/components/navbar.scss"; +@import "uikit/src/scss/components/tab.scss"; + +// Utils + +@import "uikit/src/scss/components/width.scss"; +@import "uikit/src/scss/components/height.scss"; +@import "uikit/src/scss/components/text.scss"; +@import "uikit/src/scss/components/column.scss"; +@import "uikit/src/scss/components/cover.scss"; +@import "uikit/src/scss/components/background.scss"; +@import "uikit/src/scss/components/align.scss"; +@import "uikit/src/scss/components/svg.scss"; +@import "uikit/src/scss/components/utility.scss"; +@import "uikit/src/scss/components/flex.scss"; +@import "uikit/src/scss/components/margin.scss"; +@import "uikit/src/scss/components/padding.scss"; +@import "uikit/src/scss/components/position.scss"; +@import "uikit/src/scss/components/inverse.scss"; \ No newline at end of file diff --git a/src/types/Page.js b/src/types/Page.js new file mode 100644 index 0000000..fa3cadf --- /dev/null +++ b/src/types/Page.js @@ -0,0 +1,15 @@ +import {changePage} from "../pageUtils.js"; + +export class Page { + constructor() { } + render() { + } + get name() { + return "Page"; + } + goBack() { + changePage(pages.HOME); + } + cleanup() { + } +} \ No newline at end of file diff --git a/src/utils.js b/src/utils.js new file mode 100644 index 0000000..040e76e --- /dev/null +++ b/src/utils.js @@ -0,0 +1,27 @@ +export function removeDoubleSlash(str) { + return str.replace(/\/\/+/g, "/"); +} + +export function getKeyByObjectPropertyValue(map, searchValue) { + for (let key of Object.getOwnPropertyNames(map)) { + if (map[key] === searchValue) + return key; + } +} + +export function verifyJSONString(str) { + try { + JSON.parse(str); + } catch (e) { + return false; + } + return true; +} + +export function getToken() { + return localStorage.getItem('token'); +} + +export function getAPIURL() { + return localStorage.getItem('apiurl'); +} \ No newline at end of file diff --git a/webpack.config.js b/webpack.config.js new file mode 100644 index 0000000..5c4f7cf --- /dev/null +++ b/webpack.config.js @@ -0,0 +1,32 @@ +const path = require('path'); +const MiniCssExtractPlugin = require('mini-css-extract-plugin'); +const HtmlWebpackPlugin = require('html-webpack-plugin'); + +module.exports = { + mode: process.env.WEBPACK_MODE || "production", + entry: './src/main.js', + output: { + path: path.resolve(__dirname, 'dist'), + filename: 'bundle.js', + }, + plugins: [new MiniCssExtractPlugin(), new HtmlWebpackPlugin({ title: "VaultUI" })], + devServer: { + open: 'microsoft-edge-dev', + }, + resolve: { + modules: ['node_modules'], + }, + module: { + rules: [ + { + test: /\.(sa|sc|c)ss$/, + use: [ + MiniCssExtractPlugin.loader, + "css-loader", + "sass-loader" + ], + }, + + ], + }, +}; \ No newline at end of file