diff --git a/.github/ISSUE_TEMPLATE/add-your-dashboard-to-the-showcase----.md b/.github/ISSUE_TEMPLATE/add-your-dashboard-to-the-showcase----.md new file mode 100644 index 00000000..d6cf344c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/add-your-dashboard-to-the-showcase----.md @@ -0,0 +1,20 @@ +--- +name: "Add your Dashboard to the Showcase \U0001F5BC️" +about: Share a screenshot of your dashboard to the Readme showcase! +title: "[SHOWCASE_REQUEST]" +labels: '' +assignees: '' + +--- + +Please read the instructions here first: +https://github.com/Lissy93/dashy/blob/master/docs/showcase.md#submitting-your-dashboard + +### Complete the Following +- **Title of Dashboard**: +- **Link to Screenshot**: +- **Would you like your name/ username included**: Yes/ No +- **Link to your Website/ Profile/ Twitter** (optional) +- **Description** (optional) + +Either attach your screenshot here, or include a link to the CDN / image hosting service. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 98f2ab52..6041f6e0 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,18 +1,23 @@ -**Please check the type of change your PR introduces**: -- [ ] Bugfix -- [ ] Feature -- [ ] Code style update (formatting, renaming) -- [ ] Refactoring (no functional changes, no api changes) -- [ ] Build related changes -- [ ] Documentation content changes -- [ ] Other (please describe): +*Thank you for contributing to Dashy! So that your PR can be handled effectively, please populate the following fields (delete sections that are not applicable)* -**Issue Number** (if applicable): +**Category**: +> One of: Bugfix / Feature / Code style update / Refactoring Only / Build related changes / Documentation / Other (please specify) -**Briefly outline your changes**: +**Overview** +> Briefly outline your new changes... + +**Issue Number** _(if applicable)_ #00 + +**New Vars** _(if applicable)_ +> If you've added any new build scripts, environmental variables, config file options, dependency or devDependency, please outline here + +**Screenshot** _(if applicable)_ +> If you've introduced any significant UI changes, please include a screenshot + +**Code Quality Checklist** _(Please complete)_ +- [ ] All changes are backwards compatible +- [ ] All lint checks and tests are passing +- [ ] There are no (new) build warnings or errors +- [ ] _(If a new config option is added)_ Attribute is outlined in the schema and documented +- [ ] _(If a new dependency is added)_ Package is essential, and has been checked out for security or performance -**Before submitting, please ensure that**: -- [ ] Must be backwards compatible -- [ ] All lint checks and tests must pass -- [ ] If a new option in the the config file is added, it needs to be added into the schema, and documented in the configuring guide -- [ ] If a new dependency is required, it must be essential, and it must be thoroughly checked out for security or efficiency issues diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..05cc619f --- /dev/null +++ b/LICENSE @@ -0,0 +1,17 @@ +Licensed under MIT X11. Copyright © 2021 Alicia Sykes + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the “Software”), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWAREOR THE USE +OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index c92f9369..d8e1a2a4 100644 --- a/README.md +++ b/README.md @@ -2,53 +2,73 @@

Dashy

Dashy helps you organize your self-hosted services, by making them all accessible from a single place

-

- -

-

+[![Awesome Self-Hosted](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/awesome-selfhosted/awesome-selfhosted#personal-dashboards) +![Docker Pulls](https://img.shields.io/docker/pulls/lissy93/dashy?logo=docker&style=flat-square) +![Stars](https://flat.badgen.net/github/stars/lissy93/dashy?icon=github) +![GitHub Status](https://flat.badgen.net/github/status/lissy93/dashy?icon=github) +![License MIT](https://img.shields.io/badge/License-MIT-09be48?style=flat-square&logo=opensourceinitiative) +![Current Version](https://img.shields.io/github/package-json/v/lissy93/dashy?style=flat-square&logo=azurepipelines&color=00af87) +[![Known Vulnerabilities](https://snyk.io/test/github/lissy93/dashy/badge.svg)](https://snyk.io/test/github/lissy93/dashy) ## Features 🌈 - Instant search by name, domain and tags - just start typing - Full keyboard shortcuts for navigation, searching and launching - Multiple color themes, with easy method for adding more -- Customizable layout options, and item sizes -- Quickly preview a website, by holding down the Alt key while clicking, to open it in a resizable pop-up modal +- Easy to customize every part of your dashboard, layout, icon sizes and colors etc - Many options for icons, including full Font-Awesome support and the ability to auto-fetch icon from URLs favicon -- Additional info for each item visible on hover (including opening method icon and description as a tooltip) -- Option for full-screen background image, custom nav-bar links, and custom footer text -- User settings stored in local storage and applied on load +- Option to show service status for each of your apps / links, for basic availability and uptime monitoring +- Multiple ways of opening apps, either in your browser, a pop-up modal or workspace view +- Option for full-screen background image, custom nav-bar links, html footer, title, and more - Encrypted cloud backup and restore feature available +- Optional authentication, requiring user to log in - Easy single-file YAML-based configuration - Small bundle size, fully responsive UI and PWA makes the app easy to use on any device - Plus lots more... -**Live Demos**: [Demo 1](https://dashy-demo-1.as93.net) ┆ [Demo 2](https://dashy-demo-2.as93.net) ┆ [Demo 3](https://dashy-demo-3.as93.net) +## Demo ⚡ -**Spin up your own demo**: [![One-Click Deploy with PWD](https://img.shields.io/badge/Play--with--Docker-Deploy-2496ed?style=flat-square&logo=docker)](https://labs.play-with-docker.com/?stack=https://raw.githubusercontent.com/Lissy93/dashy/master/docker-compose.yml) +> For more examples of Dashy in action, see: [**The Showcase**](./docs/showcase.md) + +#### Live Demos +[Demo 1](https://dashy-demo-1.as93.net) ┆ [Demo 2](https://dashy-demo-2.as93.net) ┆ [Demo 3](https://dashy-demo-3.as93.net) + +#### Spin up your own Demo +- 1-Click Deploy: [![One-Click Deploy with PWD](https://img.shields.io/badge/Play--with--Docker-Deploy-2496ed?style=flat-square&logo=docker)](https://labs.play-with-docker.com/?stack=https://raw.githubusercontent.com/Lissy93/dashy/master/docker-compose.yml) +- Or on your own machine: `docker run -p 8080:80 lissy93/dashy` + +#### Recording +

+ Demo +

+ +#### User Showcase +Are using Dashy? Want to share your dashboard here too - [Submit your Screenshots to the Showcase](./docs/showcase.md#submitting-your-dashboard)! -**Screenshots** ![Screenshots](https://i.ibb.co/r5T3MwM/dashy-screenshots.png) -**Recording** -

- Demo -

+**[⬆️ Back to Top](#dashy)** --- ## Getting Started 🛫 -> For full setup instructions, see: [**Getting Started**](./docs/getting-started.md) +> For full setup instructions, see: [**Deployment**](./docs/deployment.md) #### Deploying from Docker Hub 🐳 You will need [Docker](https://docs.docker.com/get-docker/) installed on your system +``` +docker run -p 8080:80 lissy93/dashy +``` + +Or + ```docker docker run -d \ -p 4000:80 \ @@ -57,8 +77,8 @@ docker run -d \ --restart=always \ lissy93/dashy:latest ``` -After making changes to your configuration file, you will need to run: `docker exec -it [container-id] yarn build` to rebuild. You can also run other commands, such as `yarn validate-config` this way too. Container ID can be found by running `docker ps`. Healthchecks are pre-configured to monitor the uptime and response times of Dashy, and the status of which can be seen in the container logs, e.g. `docker inspect --format "{{json .State.Health }}" [container-id]`. +You can also build the Docker container from source, by cloning the repo, cd'ing into it and running `docker build .` and `docker compose up`. #### Deploying from Source 🚀 You will need both [git](https://git-scm.com/downloads) and the latest or LTS version of [Node.js](https://nodejs.org/) installed on your system @@ -69,14 +89,35 @@ You will need both [git](https://git-scm.com/downloads) and the latest or LTS ve - Build: `yarn build` - Run: `yarn start` -After making changes to your configuration file, you will need to run: `yarn build` to rebuild. - #### Deploy to the Cloud -Dashy supports 1-Click deployments on several popular cloud platforms (with more on the way!). To get started, just click a link below: -- [Deploy to Netlify](https://app.netlify.com/start/deploy?repository=https://github.com/lissy93/dashy) -- [Deploy to Heroku](https://heroku.com/deploy?template=https://github.com/Lissy93/dashy) -- [Deploy with PWD](https://labs.play-with-docker.com/?stack=https://raw.githubusercontent.com/Lissy93/dashy/master/docker-compose.yml) +Dashy supports 1-Click deployments on several popular cloud platforms. To spin up a new instance, just click a link below: +- [ Deploy to Netlify](https://app.netlify.com/start/deploy?repository=https://github.com/lissy93/dashy) +- [ Deploy to Heroku](https://heroku.com/deploy?template=https://github.com/Lissy93/dashy) +- [ Deploy to Vercel](https://vercel.com/new/project?template=https://github.com/lissy93/dashy) +- [ Deploy to Render](https://render.com/deploy?repo=https://github.com/lissy93/dashy/tree/deploy_render) +- [ Deploy to PWD](https://labs.play-with-docker.com/?stack=https://raw.githubusercontent.com/Lissy93/dashy/master/docker-compose.yml) + +#### Basic Commands + +The following commands can be run on Dashy. + +- `yarn build` - Builds the project for production, and outputs it into `./dist` +- `yarn start` - Starts a web server, and serves up the production site from `./dist` +- `yarn validate-config` - Parses and validates your `conf.yml` against Dashy's [schema](https://github.com/Lissy93/dashy/blob/master/src/utils/ConfigSchema.json) +- `yarn health-check` - Checks the health and status of Dashy's Node server +- `yarn pm2-start` - Starts the app using the [PM2](https://pm2.keymetrics.io/) process manager +- `yarn dev` - Starts the development server with hot reloading, linting, testing and verbose messaging +- `yarn lint` - Lints code to ensure it follows a consistent neat style +- `yarn test` - Runs tests, and outputs results +- `yarn install` - Install all dependencies + +If you are using Docker, than precede each command with `docker exec -it [container-id]`, where container id can be found by running `docker ps`, e.g. `docker exec -it 92490c12baff yarn build`. +If you prefer [`NPM`](https://docs.npmjs.com), then just replace `yarn` with `npm run` in the following commands. + +In Docker, [healthchecks](https://docs.docker.com/engine/reference/builder/#healthcheck) are pre-configured to monitor the uptime and response times of Dashy, and the status of which will show in your Docker monitoring app, or the `docker ps` command, or the container logs, using: `docker inspect --format "{{json .State.Health }}" [container-id]`. + +**[⬆️ Back to Top](#dashy)** --- @@ -86,21 +127,25 @@ Dashy supports 1-Click deployments on several popular cloud platforms (with more Dashy is configured with a single [YAML](https://yaml.org/) file, located at `./public/conf.yml` (or `./app/public/conf.yml` for Docker). Any other optional user-customizable assets are also located in the `./public/` directory, e.g. `favicon.ico`, `manifest.json`, `robots.txt` and `web-icons/*`. If you are using Docker, the easiest way to method is to mount a Docker volume (e.g. `-v /root/my-local-conf.yml:/app/public/conf.yml`) -In the production environment, the app needs to be rebuilt in order for changes to take effect. This can be done with `yarn build`, or `docker exec -it [container-id] yarn build` if you are using Docker (where container ID can be found by running `docker ps`). +In the production environment, the app needs to be rebuilt in order for changes to take effect. This should happen automatically, but can also be triggered by running `yarn build`, or `docker exec -it [container-id] yarn build` if you are using Docker (where container ID can be found by running `docker ps`). You can check that your config matches Dashy's [schema](https://github.com/Lissy93/dashy/blob/master/src/utils/ConfigSchema.json) before deploying, by running `yarn validate-config.` +It is now possible also possible to update Dashy's config directly through the UI, and have changes written to disk. You can disable this feature by setting: `appConfig.allowConfigEdit: false`. If you are using users within Dashy, then you need to be logged in to a user of `type: admin` in order to modify the configuration globally. You can also trigger a rebuild of the app through the UI (Settings --> Rebuild). + You may find these [example config](https://gist.github.com/Lissy93/000f712a5ce98f212817d20bc16bab10) helpful for getting you started +**[⬆️ Back to Top](#dashy)** + --- ## Theming 🎨 -> For full configuration documentation, see: [**Theming**](./docs/theming.md) +> For full theming documentation, see: [**Theming**](./docs/theming.md)

- Example Themes + Example Themes

@@ -108,11 +153,34 @@ The app comes with a number of built-in themes, but it's also easy to write you' You can also apply custom CSS overrides directly through the UI (Under Config menu --> Custom CSS), or specify it in your config file under `appConfig.customCss`. If you have a lot of custom styles, you can pass in the path to a stylesheet, in `appConfig.externalStyleSheet`. +**[⬆️ Back to Top](#dashy)** + +--- + +## Icons 🧸 + +> For full iconography documentation, see: [**Icons**](./docs/icons.md) + +Both sections and items can have an icon associated with them, and defined under the `icon` attribute. There are many options for icons, including Font Awesome support, automatic fetching from favicon, programmatically generated icons and direct local or remote URLs. + +

+ +

+ +- **Favicon**: Set `icon: favicon` to fetch a services icon automatically from the URL of the corresponding application +- **Font-Awesome**: To use any font-awesome icon, specify the category, followed by the icon name, e.g. `fas fa-rocket` or `fab fa-monero`. You can also use Pro icons if you have a license key, just set it under `appConfig.fontAwesomeKey` +- **Generative**: Setting `icon: generative`, will generate a unique for a given service, based on it's URL or IP +- **Emoji**: Use an emoji as a tile icon, by putting the emoji's code as the icon attribute. Emojis can be specified either as emojis (`🚀`), unicode (`'U+1F680'`) or shortcode (`':rocket:'`). +- **URL**: You can also pass in a URL to an icon asset, hosted either locally or using any CDN service. E.g. `icon: https://i.ibb.co/710B3Yc/space-invader-x256.png`. +- **Local Image**: To use a local image, store it in `./public/item-icons/` (or create a volume in Docker: `-v /local/image/directory:/app/public/item-icons/`) , and reference it by name and extension - e.g. set `icon: image.png` to use `./public/item-icon/image.png`. You can also use sub-folders here if you have a lot of icons, to keep them organized. + +**[⬆️ Back to Top](#dashy)** + --- ## Cloud Backup & Sync ☁ -> For full documentation, see: [**Cloud Backup & Sync**](./docs/backup-restore.md) +> For full backup documentation, see: [**Cloud Backup & Sync**](./docs/backup-restore.md) Dashy has an **optional** built-in feature for securely backing up your config to a hosted cloud service, and then restoring it on another instance. This feature is totally optional, and if you do not enable it, then Dashy will not make any external network requests. @@ -120,6 +188,136 @@ This is useful not only for backing up your configuration off-site, but it also All data is encrypted before being sent to the backend. In Dashy, this is done in [`CloudBackup.js`](https://github.com/Lissy93/dashy/blob/master/src/utils/CloudBackup.js), using [crypto.js](https://github.com/brix/crypto-js)'s AES method, using the users chosen password as the key. The data is then sent to a [Cloudflare worker](https://developers.cloudflare.com/workers/learning/how-workers-works) (a platform for running serverless functions), and stored in a [KV](https://developers.cloudflare.com/workers/learning/how-kv-works) data store. +**[⬆️ Back to Top](#dashy)** + +--- + +## Authentication 💂 + +> For full authentication documentation, see: [**Authentication**](./docs/authentication.md) + +Dashy has a built-in login feature, which can be used for basic access control. To enable this feature, add an `auth` attribute under `appConfig`, containing an array of users, each with a username, SHA-256 hashed password and optional user type. + +```yaml +appConfig: + auth: + - user: alicia + hash: 4D1E58C90B3B94BCAD9848ECCACD6D2A8C9FBC5CA913304BBA5CDEAB36FEEFA3 +``` +At present, access control is handled on the frontend, and therefore in security-critical situations, it is recommended to use an alternate method for authentication, such as [Authelia](https://www.authelia.com/), a VPN or web server and firewall rules. + +

+ Example login screen, using Vapourwave theme +

+ + +**[⬆️ Back to Top](#dashy)** + +--- + +## Status Indicators 🚦 + +> For full monitoring documentation, see: [**Status Indicators**](./docs/status-indicators.md) + +Dashy has an optional feature that can display a small icon next to each of your running services, indicating it's current status. This is useful if you are using Dashy as your homelab's start page, as it gives you an overview of the health of each of your running services. Hovering over the indicator will show additional information, including average response time and an error message for services which are down. + +By default, this feature is off, but you can enable it globally by setting `appConfig.statusCheck: true`, or enable/ disable it for an individual item, with `item[n].statusCheck`. You can also specify an time interval in seconds under `appConfig.statusCheckInterval`, which will determine how often to recheck services, if this value is `0`, then status is only checked on initial page load, this is default behavior. + +

+ Status Checks demo +

+ +**[⬆️ Back to Top](#dashy)** + +--- + +## Opening Methods 🖱️ + +One of the primary purposes of Dashy is to make launching commonly used apps and services as quick as possible. To aid in this, there are several different options on how items can be opened. You can configure your preference by setting the `target` property of any item, to one of the following values: +- `sametab` - The app will be launched in the current tab +- `newtab` - The app will be launched in a new tab +- `modal` - Launch app in a resizable/ movable popup modal on the current page +- `workspace` - Changes to Workspace view, and launches app + +Even if the target is not set (or is set to `sametab`), you can still launch any given app in an alternative method: Alt + Click will open the modal, and Ctrl + Click will open in a new tab. You can also right-click on any item to see all options (as seen in the screenshot below). This custom context menu can be disabled by setting `appConfig.disableContextMenu: true`. + +

+ +

+ +The modal and workspace views work by rendering the target application in an iframe. For this to work, the HTTP response header [`X-Frame-Options`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options) for a given application needs to be set to `ALLOW`. If you are getting a `Refused to Connect` error then this header is set to `DENY` (or `SAMEORIGIN` and it's on a different host). + +Here's a quick demo of the workspace view: +

+ Workspace view demo +

+ +**[⬆️ Back to Top](#dashy)** + +--- + +## Config Editor ⚙️ + +From the Settings Menu in Dashy, you can download, backup, edit and rest your config. An interactive editor makes editing the config file easy, it will tell you if you've got any errors. After making your changes, you can either apply them locally, or export into your main config file. After saving to the config file to the disk, the app will need to be rebuilt. This will happen automatically, but may take a few minutes. You can also manually trigger a rebuild from the Settings Menu. A full list of available config options can be found [here](./docs/configuring.md). It's recommend to make a backup of your configuration, as you can then restore it into a new instance of Dashy, without having to set it up again. [json2yaml](https://www.json2yaml.com/) is very useful for converting between YAML to JSON and visa versa. + +

+ Workspace view demo +

+ +**[⬆️ Back to Top](#dashy)** + +--- + +## Sections & Items 🗃️ + +Dashy is made up of a series of sections, each containing a series of items. + +A section an be collapsed by clicking on it's name. This will cause only the title button to be visible until clicked, which is useful for particularly long sections, or those containing less-used apps. The collapse state for each section will be remembered for the next time you visit. + +From the UI, you can also choose a layout, either `grid`, `horizontal` or `vertical`, as well as set the size for items, either `small`, `medium` or `large`, and of course set a theme using the dropdown. All settings specified here will be stored in your browsers local storage, and so won't persist across devices, if you require this then you must set these in the config file instead. + +Within each section, you can set custom layout properties with under `displayData`. For example, you can make a given section double the width by making is span 2 columns with `cols: 2`, or specify how many rows it should span with `rows`. You can also set the layout for items within a given section here, for example, use `itemCountX` to define how many items will be on each row within the section. Sections can also have a custom color, specified as a hex code and defined using the `color` attribute. For full options for items, see the [`section.displayData` docs](https://github.com/Lissy93/dashy/blob/master/docs/configuring.md#sectiondisplaydata-optional) + +Items also have some optional config attributes. As well as `title`, `description`, `URL` and `icon`, you can also specify a specific opening method (`target`), and configure status checks (`statusCheck: true/false`, `statusCheckUrl` and `statusCheckHeaders`), and modify appearance with `color` and `backgroundColor`. For full options for items, see the [`section.item` docs](https://github.com/Lissy93/dashy/blob/master/docs/configuring.md#sectionitem) + + +**[⬆️ Back to Top](#dashy)** + +--- + +## Setting Dashboard Info 🌳 + +Page settings are defined under [`pageInfo`](https://github.com/Lissy93/dashy/blob/master/docs/configuring.md#pageinfo). Here you can set things like title, sub-title, navigation links, footer text, etc + +Custom links for the navigation menu are defined under [`pageInfo.navLinks`](https://github.com/Lissy93/dashy/blob/master/docs/configuring.md#pageinfonavlinks-optional). + +You can display either custom text or HTML in the footer, using the `pageInfo.footerText` attribute. + +It's also possible to hide parts of the page that you do not need (e.g. navbar, footer, search, heading, etc). This is done using the [`appConfig.hideComponents`](https://github.com/Lissy93/dashy/blob/master/docs/configuring.md#appconfighidecomponents-optional) attribute. + +For example, a `pageInfo` section might look something like this: + +```yaml +pageInfo: + title: Home Lab + description: Dashy + navLinks: + - title: Home + path: / + - title: Server Monitoring + path: https://server-start.local + - title: Start Page + path: https://start-page.local + footerText: 'Built with Dashy, by Alicia Sykes, 2021' +``` + +**[⬆️ Back to Top](#dashy)** + --- ## Developing 🧱 @@ -134,6 +332,8 @@ Hot reload is enabled, so changes will be detected automatically, triggering the If you are new to Vue.js or web development and want to learn more, [here are some resources](docs/developing.md#resources-for-beginners) to help get you started. Dashy is a pretty straight-forward application, so would make an ideal candidate for your first PR! +**[⬆️ Back to Top](#dashy)** + --- ## Contributing 😇 @@ -142,7 +342,7 @@ If you are new to Vue.js or web development and want to learn more, [here are so Pull requests are welcome, and would by much appreciated! -Some ideas for PRs include: bug fixes, improve the docs, add new themes, implement a new widget, add or improve the display options, improve or refactor the code, or implement a new feature. +Some ideas for PRs include: bug fixes, improve the docs, submit a screenshot of your dashboard to the showcase, add new themes, implement a new widget, add or improve the display options, improve or refactor the code, or implement a new feature. Before you submit your pull request, please ensure the following: - Must be backwards compatible @@ -151,6 +351,16 @@ Before you submit your pull request, please ensure the following: - If a new dependency is required, it must be essential, and it must be thoroughly checked out for security or efficiency issues - Your pull request will need to be up-to-date with master, and the PR template must be filled in +### Repo Status + +![Open PRs](https://flat.badgen.net/github/open-prs/lissy93/dashy?icon=github) +![Total PRs](https://flat.badgen.net/github/prs/lissy93/dashy?icon=github) +![GitHub commit activity](https://img.shields.io/github/commit-activity/m/lissy93/dashy?style=flat-square) +![Last Commit](https://flat.badgen.net/github/last-commit/lissy93/dashy?icon=github) +![Contributors](https://flat.badgen.net/github/contributors/lissy93/dashy?icon=github) + +**[⬆️ Back to Top](#dashy)** + --- ## Support 🙋‍♀️ @@ -164,24 +374,35 @@ If you've found a bug, or something that isn't working as you'd expect, please r - [Ask a Question 🤷‍♀️](https://github.com/Lissy93/dashy/issues/new?assignees=Lissy93&labels=%F0%9F%A4%B7%E2%80%8D%E2%99%82%EF%B8%8F+Question&template=question------.md&title=%5BQUESTION%5D) - [Share Feedback 🌈](https://github.com/Lissy93/dashy/issues/new?assignees=&labels=%F0%9F%8C%88+Feedback&template=share-feedback---.md&title=%5BFEEDBACK%5D) +[**Issue Status**](https://isitmaintained.com/project/lissy93/dashy) ![Resolution Time](http://isitmaintained.com/badge/resolution/lissy93/dashy.svg) ![Open Issues](http://isitmaintained.com/badge/open/lissy93/dashy.svg) ![Closed Issues](https://badgen.net/github/closed-issues/lissy93/dashy) + + For more general questions about any of the technologies used, [StackOverflow](https://stackoverflow.com/questions/) may be more helpful first port of info If you need to get in touch securely with the author (me, Alicia Sykes), drop me a message at: - **Email**: `alicia at omg dot lol` - **Public Key** [`0688 F8D3 4587 D954 E9E5 1FB8 FEDB 68F5 5C02 83A7`](https://keybase.io/aliciasykes/pgp_keys.asc?fingerprint=0688f8d34587d954e9e51fb8fedb68f55c0283a7) +**[⬆️ Back to Top](#dashy)** + --- ## Documentation 📘 -- [Getting Started](/docs/getting-started.md) +- [Deployment](/docs/deployment.md) - [Configuring](/docs/configuring.md) - [Developing](/docs/developing.md) - [Contributing](/docs/contributing.md) - [User Guide](/docs/user-guide.md) - [Troubleshooting](/docs/troubleshooting.md) - [Backup & Restore](/docs/backup-restore.md) +- [Status Indicators](/docs/status-indicators.md) - [Theming](/docs/theming.md) +- [Icons](/docs/icons.md) +- [Authentication](/docs/authentication.md) +- [Showcase](/docs/showcase.md) + +**[⬆️ Back to Top](#dashy)** --- @@ -189,9 +410,7 @@ For more general questions about any of the technologies used, [StackOverflow](h ### Contributors 👥 -![Auto-generated contributors](https://raw.githubusercontent.com/Lissy93/dashy/03fbaf35ff4653d16a622cfce00a1347c13d0192/docs/assets/CONTRIBUTORS.svg) - -_(^^ It's lonely here all by myself - submit a PR to become listed as a contributor!)_ +![Auto-generated contributors](https://raw.githubusercontent.com/Lissy93/dashy/master/docs/assets/CONTRIBUTORS.svg) ### Dependencies 🔗 @@ -224,7 +443,10 @@ The 1-Click deploy demo uses [Play-with-Docker Labs](https://play-with-docker.co ### Alternatives 🙌 -There are a few self-hosted web apps, that serve a similar purpose to Dashy. If you're looking for a dashboard, and Dashy doesn't meet your needs, I highly recommend you check these projects out! Including, but not limited to: [HomeDash2](https://lamarios.github.io/Homedash2), [Homer](https://github.com/bastienwirtz/homer) (`Apache License 2.0`), [Organizr](https://organizr.app/) (`GPL-3.0 License`) and [Heimdall](https://github.com/linuxserver/Heimdall) (`MIT License`) +There are a few self-hosted web apps, that serve a similar purpose to Dashy. If you're looking for a dashboard, and Dashy doesn't meet your needs, I highly recommend you check these projects out! +[HomeDash2](https://lamarios.github.io/Homedash2), [Homer](https://github.com/bastienwirtz/homer) (`Apache License 2.0`), [Organizr](https://organizr.app/) (`GPL-3.0 License`) and [Heimdall](https://github.com/linuxserver/Heimdall) (`MIT License`) + +**[⬆️ Back to Top](#dashy)** --- ## License 📜 @@ -249,6 +471,16 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWAREOR THE OR OTHER DEALINGS IN THE SOFTWARE. ``` +**TDLR;** _You can do whatever you like with Dashy: use it in private or commercial settings,_ +_redistribute and modify it. But you must display this license and credit the author._ +_There is no warranty that this app will work as expected, and the author cannot be held_ +_liable for anything that goes wrong._ +For more info, see TLDR Legal's [Explanation of MIT](https://tldrlegal.com/license/mit-license) + +![Octocat](https://github.githubassets.com/images/icons/emoji/octocat.png?v8) + +**[⬆️ Back to Top](#dashy)** + --- Dashy - A feature-rich dashboard for your homelab 🚀 | Product Hunt diff --git a/docker-compose.yml b/docker-compose.yml index 0a8ab5b8..17aacb7a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -12,14 +12,18 @@ services: # - /root/my-config.yml:/app/public/conf.yml ports: - 4000:80 + # Set any environmental variables + environment: + - NODE_ENV=production # Specify your user ID and group ID. You can find this by running `id -u` and `id -g` - # environment: # - UID=1000 # - GID=1000 + # Specify restart policy restart: unless-stopped + # Configure healthchecks healthcheck: - test: ['CMD', 'node', '/app/bin/healthcheck'] + test: ['CMD', 'node', '/app/services/healthcheck'] interval: 1m30s timeout: 10s retries: 3 - start_period: 40s \ No newline at end of file + start_period: 40s diff --git a/docs/assets/CONTRIBUTORS.svg b/docs/assets/CONTRIBUTORS.svg index 4776780a..4a3cf1a8 100644 --- a/docs/assets/CONTRIBUTORS.svg +++ b/docs/assets/CONTRIBUTORS.svg @@ -6,4 +6,7 @@ + + + \ No newline at end of file diff --git a/docs/assets/config-editor-demo.gif b/docs/assets/config-editor-demo.gif new file mode 100644 index 00000000..09fcd584 Binary files /dev/null and b/docs/assets/config-editor-demo.gif differ diff --git a/docs/assets/status-check-demo.gif b/docs/assets/status-check-demo.gif new file mode 100644 index 00000000..43422a02 Binary files /dev/null and b/docs/assets/status-check-demo.gif differ diff --git a/docs/assets/workspace-demo.gif b/docs/assets/workspace-demo.gif new file mode 100644 index 00000000..c6e186ae Binary files /dev/null and b/docs/assets/workspace-demo.gif differ diff --git a/docs/authentication.md b/docs/authentication.md new file mode 100644 index 00000000..4cba3e5b --- /dev/null +++ b/docs/authentication.md @@ -0,0 +1,177 @@ +# Authentication + +- [Built-In Login Feature](#authentication) + - [Setting Up Authentication](#setting-up-authentication) + - [Hash Password](#hash-password) + - [Logging In and Out](#logging-in-and-out) + - [Security](#security) +- [Alternative Authentication Methods](#alternative-authentication-methods) + - [VPN](#vpn) + - [IP-Based Access](#ip-based-access) + - [Web Server Authentication](#web-server-authentication) + - [OAuth Services](#oauth-services) + - [Auth on Cloud Hosting Services](#static-site-hosting-providers) + +Dashy has a basic login page included, and frontend authentication. You can enable this by adding users to the `auth` section under `appConfig` in your `conf.yml`. If this section is not specified, then no authentication will be required to access the app, and it the homepage will resolve to your dashboard. + +## Setting Up Authentication +The `auth` property takes an array of users. Each user needs to include a username, hash and optional user type (`admin` or `normal`). The hash property is a [SHA-256 Hash](https://en.wikipedia.org/wiki/SHA-2) of your desired password. + +For example: +```yaml +appConfig: + auth: + - user: alicia + hash: 4D1E58C90B3B94BCAD9848ECCACD6D2A8C9FBC5CA913304BBA5CDEAB36FEEFA3 + type: admin + - user: edward + hash: 5E884898DA28047151D0E56F8DC6292773603D0D6AABBDD62A11EF721D1542D8 + type: admin +``` +## Hash Password +Dashy uses [SHA-256 Hash](https://en.wikipedia.org/wiki/Sha-256), a 64-character string, which you can generate using an online tool, such as [this one](https://passwordsgenerator.net/sha256-hash-generator/) or [CyberChef](https://gchq.github.io/CyberChef/) (which can be self-hosted/ ran locally). + +A hash is a one-way cryptographic function, meaning that it is easy to generate a hash for a given password, but very hard to determine the original password for a given hash. This means, that so long as your password is long, strong and unique, it is safe to store it's hash in the clear. Having said that, you should never reuse passwords, hashes can be cracked by iterating over known password lists, generating a hash of each. + +## Logging In and Out +Once authentication is enabled, so long as there is no valid token in cookie storage, the application will redirect the user to the login page. When the user enters credentials in the login page, they will be checked, and if valid, then a token will be generated, and they can be redirected to the home page. If credentials are invalid, then an error message will be shown, and they will remain on the login page. Once in the application, to log out the user can click the logout button (in the top-right), which will clear cookie storage, causing them to be redirected back to the login page. + +## Security +Since all authentication is happening entirely on the client-side, it is vulnerable to manipulation by an adversary. An attacker could look at the source code, find the function used generate the auth token, then decode the minified JavaScript to find the hash, and manually generate a token using it, then just insert that value as a cookie using the console, and become a logged in user. Therefore, if you need secure authentication for your app, it is strongly recommended to implement this using your web server, or use a VPN to control access to Dashy. The purpose of the login page is merely to prevent immediate unauthorized access to your homepage. + +Addressing this is on the todo list, and there are several potential solutions: +1. Encrypt all site data against the users password, so that an attacker can not physically access any data without the correct decryption key +2. Use a backend service to handle authentication and configuration, with no user data returned from the server until the correct credentials are provided. However, this would require either Dashy to be run using it's Node.js server, or the use of an external service +3. Implement authentication using a self-hosted identity management solution, such as [Keycloak for Vue](https://www.keycloak.org/securing-apps/vue) + +**[⬆️ Back to Top](#authentication)** + +--- + +## Alternative Authentication Methods + +If you are self-hosting Dashy, and require secure authentication to prevent unauthorized access, you have several options: +- [Authentication Server](#authentication-server) - Put Dashy behind a self-hosted auth server +- [VPN](#vpn) - Use a VPN to tunnel into the network where Dashy is running +- [IP-Based Access](#ip-based-access) - Disallow access from all IP addresses, except your own +- [Web Server Authentication](#web-server-authentication) - Enable user control within your web server or proxy +- [OAuth Services](#oauth-services) - Implement a user management system using a cloud provider +- [Password Protection (for cloud providers)](#static-site-hosting-providers) - Enable password-protection on your site + +### Authentication Server +##### Authelia +[Authelia](https://www.authelia.com/) is an open-source full-featured authentication server, which can be self-hosted and either on bare metal, in a Docker container or in a Kubernetes cluster. It allows for fine-grained access control rules based on IP, path, users etc, and supports 2FA, simple password access or bypass policies for your domains. + +- `git clone https://github.com/authelia/authelia.git` +- `cd authelia/examples/compose/lite` +- Modify the `users_database.yml` the default username and password is authelia +- Modify the `configuration.yml` and `docker-compose.yml` with your respective domains and secrets +- `docker-compose up -d` + +For more information, see the [Authelia docs](https://www.authelia.com/docs/) + +### VPN +A catch-all solution to accessing services running from your home network remotely is to use a VPN. It means you do not need to worry about implementing complex authentication rules, or trusting the login implementation of individual applications. However it can be inconvenient to use on a day-to-day basis, and some public and corporate WiFi block VPN connections. Two popular VPN protocols are [OpenVPN](https://openvpn.net/) and [WireGuard](https://www.wireguard.com/) + +### IP-Based Access +If you have a static IP or use a VPN to access your running services, then you can use conditional access to block access to Dashy from everyone except users of your pre-defined IP address. This feature is offered by most cloud providers, and supported by most web servers. + +##### Apache +In Apache, this is configured in your `.htaccess` file in Dashy's root folder, and should look something like: +``` +Order Deny,Allow +Deny from all +Allow from [your-ip] +``` + +##### NGINX +In NGINX you can specify [control access](https://docs.nginx.com/nginx/admin-guide/security-controls/controlling-access-proxied-http/) rules for a given site in your `nginx.conf` or hosts file. For example: +``` +server { + listen 80; + server_name www.dashy.example.com; + location / { + root /path/to/dashy/; + passenger_enabled on; + allow [your-ip]; + deny all; + } + } +``` + +##### Caddy +In Caddy, [Request Matchers](https://caddyserver.com/docs/caddyfile/matchers) can be used to filter requests +``` +dashy.site { + @public_networks not remote_ip [your-ip] + respond @public_networks "Access denied" 403 +} +``` + +### Web Server Authentication +Most web servers make password protecting certain apps very easy. Note that you should also set up HTTPS and have a valid certificate in order for this to be secure. + +##### Apache +First crate a `.htaccess` file in Dashy's route directory. Specify the auth type and path to where you want to store the password file (usually the same folder). For example: +``` +AuthType Basic +AuthName "Please Sign into Dashy" +AuthUserFile /path/dashy/.htpasswd +require valid-user +``` + +Then create a `.htpasswd` file in the same directory. List users and their hashed passwords here, with one user on each line, and a colon between username and password (e.g. `[username]:[hashed-password]`). You will need to generate an MD5 hash of your desired password, this can be done with an [online tool](https://www.web2generators.com/apache-tools/htpasswd-generator). Your file will look something like: +``` +alicia:$apr1$jv0spemw$RzOX5/GgY69JMkgV6u16l0 +``` + +##### NGINX +NGINX has an [authentication module](https://nginx.org/en/docs/http/ngx_http_auth_basic_module.html) which can be used to add passwords to given sites, and is fairly simple to set up. Similar to above, you will need to create a `.htpasswd` file. Then just enable auth and specify the path to that file, for example: +``` +location / { + auth_basic "closed site"; + auth_basic_user_file conf/htpasswd; +} +``` +##### Caddy +Caddy has a [basic-auth](https://caddyserver.com/docs/caddyfile/directives/basicauth) directive, where you specify a username and hash. The password hash needs to be base-64 encoded, the [`caddy hash-password`](https://caddyserver.com/docs/command-line#caddy-hash-password) command can help with this. For example: +``` +basicauth /secret/* { + alicia JDJhJDEwJEVCNmdaNEg2Ti5iejRMYkF3MFZhZ3VtV3E1SzBWZEZ5Q3VWc0tzOEJwZE9TaFlZdEVkZDhX +} +``` + +For more info about implementing a single sign on for all your apps with Caddy, see [this tutorial](https://joshstrange.com/securing-your-self-hosted-apps-with-single-signon/) + +##### Lighttpd +You can use the [mod_auth](https://doc.lighttpd.net/lighttpd2/mod_auth.html) module to secure your site with Lighttpd. Like with Apache, you need to first create a password file listing your usersnames and hashed passwords, but in Lighttpd, it's usually called `.lighttpdpassword`. + +Then in your `lighttpd.conf` file (usually in the `/etc/lighttpd/` directory), load in the mod_auth module, and configure it's directives. For example: +``` +server.modules += ( "mod_auth" ) +auth.debug = 2 +auth.backend = "plain" +auth.backend.plain.userfile = "/home/lighttpd/.lighttpdpassword" + +$HTTP["host"] == "dashy.my-domain.net" { + server.document-root = "/home/lighttpd/dashy.my-domain.net/http" + server.errorlog = "/var/log/lighttpd/dashy.my-domain.net/error.log" + accesslog.filename = "/var/log/lighttpd/dashy.my-domain.net/access.log" + auth.require = ( + "/docs/" => ( + "method" => "basic", + "realm" => "Password protected area", + "require" => "user=alicia" + ) + ) +} +``` +Restart your web server for changes to take effect. + +### OAuth Services +There are also authentication services, such as [Ory.sh](https://www.ory.sh/), [Okta](https://developer.okta.com/), [Auth0](https://auth0.com/), [Firebase](https://firebase.google.com/docs/auth/). Implementing one of these solutions would involve some changes to the [`Auth.js`](https://github.com/Lissy93/dashy/blob/master/src/utils/Auth.js) file, but should be fairly straight forward. + +### Static Site Hosting Providers +If you are hosting Dashy on a cloud platform, you will probably find that it has built-in support for password protected access to web apps. For more info, see the relevant docs for your provider, for example: [Netlify Password Protection](https://docs.netlify.com/visitor-access/password-protection/), [Cloudflare Access](https://www.cloudflare.com/teams/access/), [AWS Cognito](https://aws.amazon.com/cognito/), [Azure Authentication](https://docs.microsoft.com/en-us/azure/app-service/scenario-secure-app-authentication-app-service) and [Vercel Password Protection](https://vercel.com/docs/platform/projects#password-protection). + +**[⬆️ Back to Top](#authentication)** diff --git a/docs/backup-restore.md b/docs/backup-restore.md index 11c578e9..2c6b2158 100644 --- a/docs/backup-restore.md +++ b/docs/backup-restore.md @@ -49,6 +49,20 @@ Maximum of 24mb of storage per user. Please do not repeatedly hit the endpoint, - Add your `zone_id` (found in the Overview tab of your desired domain on Cloudflare) - Add your `route`, which should be a domain or host, supporting a wildcard +```toml +name = "dashy-worker" +type = "javascript" + +workers_dev = true +route = "example.com/*" +zone_id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +account_id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + +kv_namespaces = [ + { binding = "DASHY_CLOUD_BACKUP", id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } +] +``` + #### Complete `index.js` - Write code to handle your requests, and interact with any other data sources in this file - Generally, this is done within an event listener for 'fetch', and returns a promise @@ -66,7 +80,7 @@ async function handleRequest(request) { } ``` -- For the code used for Dashy's cloud service, see [here](https://notes.aliciasykes.com/p/j2F1deljv1) +- For the code used for Dashy's cloud service, see [here](https://gist.github.com/Lissy93/d19b43d50f30e02fa25f349cf5cb5ed8#file-index-js) #### Commands diff --git a/docs/configuring.md b/docs/configuring.md index e6d4474c..0da72148 100644 --- a/docs/configuring.md +++ b/docs/configuring.md @@ -1,20 +1,26 @@ -## Configuring +# Configuring All app configuration is specified in [`/public/conf.yml`](https://github.com/Lissy93/dashy/blob/master/public/conf.yml) which is in [YAML Format](https://yaml.org/) format. -If you're new to YAML, it's pretty straight-forward. The format is exactly the same as that of JSON, but instead of using curley braces, structure is denoted using whitespace. This [quick guide](https://linuxhandbook.com/yaml-basics/) should get you up to speed in a few minutes, for more advanced topics take a look at this [Wikipedia article](https://en.wikipedia.org/wiki/YAML) and for some practicle examples, the [Azure pipelines schema](https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=azure-devops&tabs=schema%2Cparameter-schema) may be useful. - -You may find it helpful to look at some sample config files to get you started, a collection of which can be found [here](https://gist.github.com/Lissy93/000f712a5ce98f212817d20bc16bab10). - -There's a couple of things to remember, before getting started: -- After modifying your config, you will need to run `yarn build` to recompile the application +Tips: +- You may find it helpful to look at some sample config files to get you started, a collection of which can be found [here](https://gist.github.com/Lissy93/000f712a5ce98f212817d20bc16bab10) - You can check that your config file fits the schema, by running `yarn validate-config` -- Any changes made locally through the UI need to be exported into this file, in order for them to persist across devices +- After modifying your config, the app needs to be recompiled, by running `yarn build` - this happens automatically whilst the app is running +- It is recommended to make and keep a backup of your config file. You can download your current config through the UI either from the Config menu, or using the `/download` endpoint. +- All fields are optional, unless otherwise stated. -All fields are optional, unless otherwise stated. +### About YAML +If you're new to YAML, it's pretty straight-forward. The format is exactly the same as that of JSON, but instead of using curly braces, structure is denoted using whitespace. This [quick guide](https://linuxhandbook.com/yaml-basics/) should get you up to speed in a few minutes, for more advanced topics take a look at this [Wikipedia article](https://en.wikipedia.org/wiki/YAML) and for some practicle examples, the [Azure pipelines schema](https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=azure-devops&tabs=schema%2Cparameter-schema) may be useful. +### Config Saving Methods +When updating the config through the JSON editor in the UI, you have two save options: **Local** or **Write to Disk**. +- Changes saved locally will only be applied to the current user through the browser, and will not apply to other instances - you either need to use the cloud sync feature, or manually update the conf.yml file. +- On the other-hand, if you choose to write changes to disk, then your main `conf.yml` file will be updated, and changes will be applied to all users, and visible across all devices. For this functionality to work, you must be running Dashy with using the Docker container, or the Node server. A backup of your current configuration will also be saved in the same directory. -#### Top-Level Fields +### Preventing Changes being Written to Disk +To disallow any changes from being written to disk via the UI config editor, set `appConfig.allowConfigEdit: false`. If you are using users, and have setup `auth` within Dashy, then only users with `type: admin` will be able to write config changes to disk. + +### Top-Level Fields **Field** | **Type** | **Required**| **Description** --- | --- | --- | --- @@ -22,7 +28,9 @@ All fields are optional, unless otherwise stated. **`appConfig`** | `object` | _Optional_ | Settings related to how the app functions, including API keys and global styles. See [`appConfig`](#appconfig-optional) **`sections`** | `array` | Required | An array of sections, each containing an array of items, which will be displayed as links. See [`section`](#section) -#### `PageInfo` +**[⬆️ Back to Top](#configuring)** + +### `PageInfo` **Field** | **Type** | **Required**| **Description** --- | --- | --- | --- @@ -31,27 +39,65 @@ All fields are optional, unless otherwise stated. **`navLinks`** | `array` | _Optional_ | Optional list of a maximum of 6 links, which will be displayed in the navigation bar. See [`navLinks`](#pageinfonavlinks-optional) **`footerText`** | `string` | _Optional_ | Text to display in the footer (note that this will override the default footer content). This can also include HTML and inline CSS -#### `pageInfo.navLinks` _(optional)_ +**[⬆️ Back to Top](#configuring)** + +### `pageInfo.navLinks` _(optional)_ **Field** | **Type** | **Required**| **Description** --- | --- | --- | --- **`title`** | `string` | Required | The text to display on the link button **`path`** | `string` | Required | The URL to navigate to when clicked. Can be relative (e.g. `/about`) or absolute (e.g. `https://example.com` or `http://192.168.1.1`) -#### `appConfig` _(optional)_ +**[⬆️ Back to Top](#configuring)** + +### `appConfig` _(optional)_ **Field** | **Type** | **Required**| **Description** --- | --- | --- | --- +**`statusCheck`** | `boolean` | _Optional_ | When set to `true`, Dashy will ping each of your services and display their status as a dot next to each item. This can be overridden by setting `statusCheck` under each item. Defaults to `false` +**`statusCheckInterval`** | `boolean` | _Optional_ | The number of seconds between checks. If set to `0` then service will only be checked on initial page load, which is usually the desired functionality. If value is less than `10` you may experience a hit in performance. Defaults to `0` **`backgroundImg`** | `string` | _Optional_ | Path to an optional full-screen app background image. This can be either remote (http) or local (/). Note that this will slow down initial load **`enableFontAwesome`** | `boolean` | _Optional_ | Where `true` is enabled, if left blank font-awesome will be enabled only if required by 1 or more icons **`fontAwesomeKey`** | `string` | _Optional_ | If you have a font-awesome key, then you can use it here and make use of premium icons. It is a 10-digit alpha-numeric string from you're FA kit URL (e.g. `13014ae648`) +**`faviconApi`** | `string` | _Optional_ | Only applicable if you are using favicons for item icons. Specifies which service to use to resolve favicons. Set to `local` to do this locally, without using an API. Services running locally will use this option always. Available options are: `local`, `faviconkit`, `google`, `clearbit`, `webmasterapi` and `allesedv`. Defaults to `faviconkit`. See [Icons](/docs/icons.md#favicons) for more info +**`auth`** | `array` | _Optional_ | An array of objects containing usernames and hashed passwords. If this is not provided, then authentication will be off by default, and you will not need any credentials to access the app. Note authentication is done on the client side, and so if your instance of Dashy is exposed to the internet, it is recommend to configure your web server to handle this. See [`auth`](#appconfigauth-optional) +**`layout`** | `string` | _Optional_ | App layout, either `horizontal`, `vertical`, `auto` or `sidebar`. Defaults to `auto`. This specifies the layout and direction of how sections are positioned on the home screen. This can also be modified from the UI. +**`iconSize`** | `string` | _Optional_ | The size of link items / icons. Can be either `small`, `medium,` or `large`. Defaults to `medium`. This can also be set directly from the UI. **`theme`** | `string` | _Optional_ | The default theme for first load (you can change this later from the UI) **`cssThemes`** | `string[]` | _Optional_ | An array of custom theme names which can be used in the theme switcher dropdown **`externalStyleSheet`** | `string` or `string[]` | _Optional_ | Either a URL to an external stylesheet or an array or URLs, which can be applied as themes within the UI **`customCss`** | `string` | _Optional_ | Raw CSS that will be applied to the page. This can also be set from the UI. Please minify it first. -**`showSplashScreen`** | `boolean` | _Optional_ | Should display a splash screen while the app is loading. Defaults to false, except on first load +**`hideComponents`** | `object` | _Optional_ | A list of key page components (header, footer, search, settings, etc) that are present by default, but can be removed using this option. See [`appConfig.hideComponents`](#appconfighideComponents-optional) +**`allowConfigEdit`** | `boolean` | _Optional_ | Should prevent / allow the user to write configuration changes to the conf.yml from the UI. When set to `false`, the user can only apply changes locally using the config editor within the app, whereas if set to `true` then changes can be written to disk directly through the UI. Defaults to `true`. Note that if authentication is enabled, the user must be of type `admin` in order to apply changes globally. +**`disableServiceWorker`** | `boolean` | _Optional_ | Service workers cache web applications to improve load times and offer basic offline functionality, and are enabled by default in Dashy. The service worker can sometimes cause older content to be cached, requiring the app to be hard-refreshed. If you do not want SW functionality, or are having issues with caching, set this property to `true` to disable all service workers. +**`disableContextMenu`** | `boolean` | _Optional_ | If set to `true`, the custom right-click context menu will be disabled. Defaults to `false`. -#### `section` +**[⬆️ Back to Top](#configuring)** + +### `appConfig.auth` _(optional)_ + +**Field** | **Type** | **Required**| **Description** +--- | --- | --- | --- +**`user`** | `string` | Required | Username to log in with +**`hash`** | `string` | Required | A SHA-256 hashed password +**`type`** | `string` | _Optional_ | The user type, either admin or normal + +**[⬆️ Back to Top](#configuring)** + +### `appConfig.hideComponents` _(optional)_ + +**Field** | **Type** | **Required**| **Description** +--- | --- | --- | --- +**`hideHeading`** | `boolean` | _Optional_ | If set to `true`, the page title & sub-title will not be visible. Defaults to `false` +**`hideNav`** | `boolean` | _Optional_ | If set to `true`, the navigation menu will not be visible. Defaults to `false` +**`hideSearch`** | `boolean` | _Optional_ | If set to `true`, the search bar will not be visible. Defaults to `false` +**`hideSettings`** | `boolean` | _Optional_ | If set to `true`, the settings menu will not be visible. Defaults to `false` +**`hideFooter`** | `boolean` | _Optional_ | If set to `true`, the footer will not be visible. Defaults to `false` +**`hideSplashScreen`** | `boolean` | _Optional_ | If set to `true`, splash screen will not be visible while the app loads. Defaults to `true` (except on first load, when the loading screen is always shown) + +**[⬆️ Back to Top](#configuring)** + +### `section` **Field** | **Type** | **Required**| **Description** --- | --- | --- | --- @@ -60,7 +106,9 @@ All fields are optional, unless otherwise stated. **`items`** | `array` | Required | An array of items to be displayed within the section. See [`item`](#sectionitem) **`displayData`** | `object` | _Optional_ | Meta-data to optionally overide display settings for a given section. See [`displayData`](#sectiondisplaydata-optional) -#### `section.item` +**[⬆️ Back to Top](#configuring)** + +### `section.item` **Field** | **Type** | **Required**| **Description** --- | --- | --- | --- @@ -68,11 +116,16 @@ All fields are optional, unless otherwise stated. **`description`** | `string` | _Optional_ | Additional info about an item, which is shown in the tooltip on hover, or visible on large tiles **`url`** | `string` | Required | The URL / location of web address for when the item is clicked **`icon`** | `string` | _Optional_ | The icon for a given item. Can be a font-awesome icon, favicon, remote URL or local URL. See [`item.icon`](#sectionicon-and-sectionitemicon) -**`target`** | `string` | _Optional_ | The opening method for when the item is clicked, either `newtab`, `sametab` or `iframe`. Where `newtab` will open the link in a new tab, `sametab` will open it in the current tab, and `iframe` will open a pop-up modal with the content displayed within that iframe. Note that for the iframe to load, you must have set the CORS headers to either allow `*` ot allow the domain that you are hosting Dashy on, for some websites and self-hosted services, this is already set. +**`target`** | `string` | _Optional_ | The opening method for when the item is clicked, either `newtab`, `sametab`, `modal` or `workspace`. Where `newtab` will open the link in a new tab, `sametab` will open it in the current tab, and `modal` will open a pop-up modal with the content displayed within that iframe. Note that for the iframe to load, you must have set the CORS headers to either allow `*` ot allow the domain that you are hosting Dashy on, for some websites and self-hosted services, this is already set. +**`statusCheck`** | `boolean` | _Optional_ | When set to `true`, Dashy will ping the URL associated with the current service, and display its status as a dot next to the item. The value here will override `appConfig.statusCheck` so you can turn off or on checks for a given service. Defaults to `appConfig.statusCheck`, falls back to `false` +**`statusCheckUrl`** | `string` | _Optional_ | If you've enabled `statusCheck`, and want to use a different URL to what is defined under the item, then specify it here +**`statusCheckHeaders`** | `object` | _Optional_ | If you're endpoint requires any specific headers for the status checking, then define them here **`color`** | `string` | _Optional_ | An optional color for the text and font-awesome icon to be displayed in. Note that this will override the current theme and so may not display well **`backgroundColor`** | `string` | _Optional_ | An optional background fill color for the that given item. Again, this will override the current theme and so might not display well against the background -#### `section.displayData` _(optional)_ +**[⬆️ Back to Top](#configuring)** + +### `section.displayData` _(optional)_ **Field** | **Type** | **Required**| **Description** --- | --- | --- | --- @@ -82,18 +135,21 @@ All fields are optional, unless otherwise stated. **`itemSize`** | `string` | _Optional_ | Specify the size for items within this group, either `small`, `medium` or `large`. Note that this will overide any settings specified through the UI **`rows`** | `number` | _Optional_ | Height of the section, specified as the number of rows it should span vertically, e.g. `2`. Defaults to `1`. Max is `5`. **`cols`** | `number` | _Optional_ | Width of the section, specified as the number of columns the section should span horizontally, e.g. `2`. Defaults to `1`. Max is `5`. -**`layout`** | `string` | _Optional_ | Specify which CSS layout will be used to responsivley place items. Can be either `auto` (which uses flex layout), or `grid`. If `grid` is selected, then `itemCountX` and `itemCountY` may also be set. Defaults to `auto` -**`itemCountX`** | `number` | _Optional_ | The number of items to display per row / horizontally. If not set, it will be calculated automatically based on available space. Can only be set if `layout` is set to `grid`. Must be a whole number between `1` and `12` -**`itemCountY`** | `number` | _Optional_ | The number of items to display per column / vertically. If not set, it will be calculated automatically based on available space. If `itemCountX` is set, then `itemCountY` can be calculated automatically. Can only be set if `layout` is set to `grid`. Must be a whole number between `1` and `12` +**`sectionLayout`** | `string` | _Optional_ | Specify which CSS layout will be used to responsivley place items. Can be either `auto` (which uses flex layout), or `grid`. If `grid` is selected, then `itemCountX` and `itemCountY` may also be set. Defaults to `auto` +**`itemCountX`** | `number` | _Optional_ | The number of items to display per row / horizontally. If not set, it will be calculated automatically based on available space. Can only be set if `sectionLayout` is set to `grid`. Must be a whole number between `1` and `12` +**`itemCountY`** | `number` | _Optional_ | The number of items to display per column / vertically. If not set, it will be calculated automatically based on available space. If `itemCountX` is set, then `itemCountY` can be calculated automatically. Can only be set if `sectionLayout` is set to `grid`. Must be a whole number between `1` and `12` -#### `section.icon` and `section.item.icon` +**[⬆️ Back to Top](#configuring)** + +### `section.icon` and `section.item.icon` **Field** | **Type** | **Required**| **Description** --- | --- | --- | --- -**`icon`** | `string` | _Optional_ | The icon for a given item or section. Can be a font-awesome icon, favicon, remote URL or local URL. If set to `favicon`, the icon will be automatically fetched from the items website URL. To use font-awesome, specify the category, followed by the icon name, e.g. `fas fa-rocket`, `fab fa-monero` or `fal fa-duck` - note that to use pro icons, you mut specify `appConfig.fontAwesomeKey`. You can also use hosted any by specifying it's URL, e.g. `https://i.ibb.co/710B3Yc/space-invader-x256.png`. To use a local image, first store it in `./public/item-icons/` (or `-v /app/public/item-icons/` in Docker) , and reference it by name and extension - e.g. set `image.png` to use `./public/item-icon/image.png`, you can also use sub-folders if you have a lot of icons, to keep them organised. +**`icon`** | `string` | _Optional_ | The icon for a given item or section. Can be a font-awesome icon, favicon, remote URL or local URL. If set to `favicon`, the icon will be automatically fetched from the items website URL. To use font-awesome, specify the category, followed by the icon name, e.g. `fas fa-rocket`, `fab fa-monero` or `fal fa-duck` - note that to use pro icons, you mut specify `appConfig.fontAwesomeKey`. If set to `generative`, then a unique icon is generated from the apps URL or IP. You can also use hosted any by specifying it's URL, e.g. `https://i.ibb.co/710B3Yc/space-invader-x256.png`. To use a local image, first store it in `./public/item-icons/` (or `-v /app/public/item-icons/` in Docker) , and reference it by name and extension - e.g. set `image.png` to use `./public/item-icon/image.png`, you can also use sub-folders if you have a lot of icons, to keep them organised. +**[⬆️ Back to Top](#configuring)** -#### Example +### Example ```yaml --- @@ -125,3 +181,10 @@ sections: # An array of sections ``` For more example config files, see: [this gist](https://gist.github.com/Lissy93/000f712a5ce98f212817d20bc16bab10) + +If you need any help, feel free to [Raise an Issue](https://github.com/Lissy93/dashy/issues/new?assignees=Lissy93&labels=%F0%9F%A4%B7%E2%80%8D%E2%99%82%EF%B8%8F+Question&template=question.md&title=%5BQUESTION%5D) or [Start a Discussion](https://github.com/Lissy93/dashy/discussions) + +Happy Configuring 🤓🔧 + +**[⬆️ Back to Top](#configuring)** + diff --git a/docs/contributing.md b/docs/contributing.md index 7d225eb7..b3393ca2 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -83,6 +83,9 @@ on how to create a pull request.. 8. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/) with a clear title and description. +You can use emojis in your commit message, to indicate the category of the task. +For a reference of what each emoji means in the context of commits, see [gitmoji.dev](https://gitmoji.dev/). + #### Testing the Production App For larger pull requests, please also check that it works as expected in a production environment. @@ -128,7 +131,8 @@ Click one of the links below, to open an issue: ### Contributors -![Auto-generated contributors](https://raw.githubusercontent.com/Lissy93/dashy/03fbaf35ff4653d16a622cfce00a1347c13d0192/docs/assets/CONTRIBUTORS.svg) +![Auto-generated contributors](https://raw.githubusercontent.com/Lissy93/dashy/master/docs/assets/CONTRIBUTORS.svg) + ### Star-Gazers Over Time diff --git a/docs/deployment.md b/docs/deployment.md new file mode 100644 index 00000000..4cae89a2 --- /dev/null +++ b/docs/deployment.md @@ -0,0 +1,372 @@ +# Deployment + +- [Running the App](#running-the-app) + - [Deploy with Docker](#deploy-with-docker) + - [Deploy from Source](#deploy-from-source) + - [Deploy to Cloud Service](#deploy-to-cloud-service) +- [Usage](#usage) + - [Providing Assets](#providing-assets) + - [Basic Commands](#basic-commands) + - [Healthchecks](#healthchecks) + - [Monitoring](#logs-and-performance) + - [Auto Starting](#auto-starting-at-system-boot) +- [Updating](#updating) + - [Updating Docker Container](#updating-docker-container) + - [Automating Docker Updates](#automatic-docker-updates) + - [Updating from Source](#updating-dashy-from-source) +- [Web Server Configuration](#web-server-configuration) + - [NGINX](#nginx) + - [Apache](#apache) + +## Running the App + +### Deploy with Docker + +The quickest way to get started on any system is with Docker, and Dashy is available though [Docker Hub](https://hub.docker.com/r/lissy93/dashy). You will need [Docker](https://docs.docker.com/get-docker/) installed on your system. + +To configure Dashy with your own services, and customize it to your liking, you will need to write a config file, and pass it to the Docker container as a volume. + +```docker +docker run -d \ + -p 8080:80 \ + -v /root/my-local-conf.yml:/app/public/conf.yml \ + --name my-dashboard \ + --restart=always \ + lissy93/dashy:latest +``` + +Explanation of the above options: +- `-d` Detached mode (not running in the foreground of your terminal) +- `-p` The port that should be exposed, and the port it should be mapped to in your host system `[host-port][container-port]` +- `-v` Specify volumes, to pass data from your host system to the container, in the format of `[host-path]:[container-path]` +- `--name` Give your container a human-readable name +- `--restart=always` Spin up the container when the daemon starts, or after it has been stopped +- `lissy93/dashy:latest` This last option is the image the container should be built from + +For all available options, and to learn more, see the [Docker Run Docs](https://docs.docker.com/engine/reference/commandline/run/) + +You can also build and deploy the Docker container from source. +- Get the code: `git clone git@github.com:Lissy93/dashy.git && cd dashy` +- Edit the `./public/conf.yml` file and take a look at the `docker-compose.yml` +- Start the container: `docker compose up` + +### Other Container Engines + +Docker isn't the only host application capable of running standard Linux containers - [Podman](http://podman.io) is another popular option. Unlike Docker, Podman does not rely on a daemon to be running on your host system. This means there is no single point of failure and it can also support rootless containers, which is perfect for Dashy as it does not require any sudo privileges. Podman was developed by RedHat, and it's source code is written in Go, and published on [GitHub](https://github.com/containers/podman). + +Installation of the podman is really easy, as it's repository is available for most package managers (for example; Arch: `sudo pacman -S podman`, Debian/ Ubuntu: `sudo apt-get install podman`, Gentoo: `sudo emerge app-emulation/podman`, and MacOS: `brew install podman`). For more info, check out the [podman installation docs](https://podman.io/getting-started/installation). If you are using Windows, then take a look at Brent Baude's article on [Running Podman on WSL](https://www.redhat.com/sysadmin/podman-windows-wsl2). Since it's CLI is pretty much identical to that of Dockers, Podman's learning curve is very shallow. + +To run Dashy with Podman, just replace `docker` with `podman` in the above instructions. E.g. `podman run -p 8080:80 lissy93/dashy` + +It's worth noting that Podman isn't the only container running alternative, there's also [`rkt`](https://www.openshift.com/learn/topics/rkt), [`runc`](https://github.com/opencontainers/runc), [`containerd`](https://containerd.io/) and [`cri-o`](https://cri-o.io/). Dashy has not been tested with any of these engines, but it should work just fine. + + +### Deploy from Source +If you do not want to use Docker, you can run Dashy directly on your host system. For this, you will need both [git](https://git-scm.com/downloads) and the latest or LTS version of [Node.js](https://nodejs.org/) installed. + +1. Get Code: `git clone git@github.com:Lissy93/dashy.git` and `cd dashy` +2. Configuration: Fill in you're settings in `./public/conf.yml` +3. Install dependencies: `yarn` +4. Build: `yarn build` +5. Run: `yarn start` + +### Deploy to Cloud Service + +Dashy supports 1-Click deployments on several popular cloud platforms. + +#### Netlify +[![Deploy to Netlify](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/lissy93/dashy) + +[Netlify](https://www.netlify.com/) offers Git-based serverless cloud hosting for web applications. Their services are free to use for personal use, and they support deployment from both public and private repos, as well as direct file upload. The free plan also allows you to use your own custom domain or sub-domain, and is easy to setup. + +To deploy Dashy to Netlify, use the following link +``` +https://app.netlify.com/start/deploy?repository=https://github.com/lissy93/dashy +``` + +#### Heroku +[![Deploy to Heroku](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/Lissy93/dashy) + +[Heroku](https://www.heroku.com/) is a fully managed cloud platform as a service. You define app settings in a Procfile and app.json, which specifying how the app should be build and how the server should be started. Heroku is free to use for unlimited, non-commercial, single dyno apps, and supports custom domains. Heroku's single-dyno service is not as quite performant as some other providers, and the app will have a short wake-up time when not visited for a while + +To deploy Dashy to Heroku, use the following link +``` +https://heroku.com/deploy?template=https://github.com/Lissy93/dashy +``` + +#### Cloudflare Workers +[![Deploy to Cloudflare Workers](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/lissy93/dashy/tree/deploy_cloudflare) + +[Cloudflare Workers](https://workers.cloudflare.com/) is a simple yet powerful service for running cloud functions and hosting web content. It requires a Cloudflare account, but is completely free for smaller projects, and very reasonably priced ($0.15/million requests per month) for large applications. You can use your own domain, and applications are protected with Cloudflare's state of the art DDoS protection. For more info, see the docs on [Worker Sites](https://developers.cloudflare.com/workers/platform/sites) + +To deploy Dashy to Cloudflare, use the following link +``` +https://deploy.workers.cloudflare.com/?url=https://github.com/lissy93/dashy/tree/deploy_cloudflare +``` + +#### Vercel +[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/project?template=https://github.com/lissy93/dashy) + +[Vercel](https://vercel.com/) is a performance-focused platform for hosting static frontend apps. It comes bundled with some useful tools for monitoring and anaylzing application performance and other metrics. Vercel is free for personal use, allows for custom domains and has very reasonable limits. + +To deploy Dashy to Vercel, use the following link +``` +https://vercel.com/new/project?template=https://github.com/lissy93/dashy +``` + +#### DigitalOcean +[![Deploy to DO](https://www.deploytodo.com/do-btn-blue.svg)](https://cloud.digitalocean.com/apps/new?repo=https://github.com/lissy93/dashy/tree/deploy_digital-ocean&refcode=3838338e7f79) + +[DigitalOcan](https://www.digitalocean.com/) is a cloud service providing affordable developer-friendly virtual machines from $5/month. But they also have an app platform, where you can run web apps, static sites, APIs and background workers. CDN-backed static sites are free for personal use. + +``` +https://cloud.digitalocean.com/apps/new?repo=https://github.com/lissy93/dashy/tree/deploy_digital-ocean +``` + +#### Platform.sh +[![Deploy to Platform.sh](https://platform.sh/images/deploy/deploy-button-lg-blue.svg)](https://console.platform.sh/projects/create-project/?template=https://github.com/lissy93/dashy&utm_campaign=deploy_on_platform?utm_medium=button&utm_source=affiliate_links&utm_content=https://github.com/lissy93/dashy) + +[Platform.sh](https://platform.sh) is an end-to-end solution for developing and deploying applications. It is geared towards enterprise users with large teams, and focuses on allowing applications to scale up and down. Unlike the above providers, Platform.sh is not free, although you can deploy a test app to it without needing a payment method + +To deploy Dashy to Platform.sh, use the following link +``` +https://console.platform.sh/projects/create-project/?template=https://github.com/lissy93/dashy +``` + +#### Render +[![Deploy to Render](https://render.com/images/deploy-to-render-button.svg)](https://render.com/deploy?repo=https://github.com/lissy93/dashy/tree/deploy_render) + +[Render](https://render.com) is cloud provider that provides easy deployments for static sites, Docker apps, web services, databases and background workers. Render is great for developing applications, and very easy to use. Static sites are free, and services start at $7/month. Currently there are only 2 server locations - Oregon, USA and Frankfurt, Germany. For more info, see the [Render Docs](https://render.com/docs) + +To deploy Dashy to Render, use the following link +``` +https://render.com/deploy?repo=https://github.com/lissy93/dashy/tree/deploy_render +``` + +#### Scalingo +[![Deploy on Scalingo](https://cdn.scalingo.com/deploy/button.svg)](https://my.scalingo.com/deploy?source=https://github.com/lissy93/dashy#master) + +[Scalingo](https://scalingo.com/) is a scalable container-based cloud platform as a service. It's focus is on compliance and uptime, and is geared towards enterprise users. Scalingo is also not free, although they do have a 3-day free trial that does not require a payment method + +To deploy Dashy to Scalingo, use the following link +``` +https://my.scalingo.com/deploy?source=https://github.com/lissy93/dashy#master +``` + +#### Play-with-Docker +[![Try in PWD](https://raw.githubusercontent.com/play-with-docker/stacks/cff22438/assets/images/button.png)](https://labs.play-with-docker.com/?stack=https://raw.githubusercontent.com/Lissy93/dashy/master/docker-compose.yml) + +[Play with Docker](https://labs.play-with-docker.com/) is a community project by Marcos Liljedhal and Jonathan Leibiusky and sponsored by Docker, intended to provide a hands-on learning environment. Their labs let you quickly spin up a Docker container or stack, and test out the image in a temporary, sandboxed environment. There's no need to sign up, and it's completely free. + +To run Dashy in PWD, use the following URL: +``` +https://labs.play-with-docker.com/?stack=https://raw.githubusercontent.com/Lissy93/dashy/master/docker-compose.yml +``` + +#### Surge.sh +[Surge.sh](http://surge.sh/) is quick and easy static web publishing platform for frontend-apps. + +Surge supports [password-protected projects](https://surge.sh/help/adding-password-protection-to-a-project). You can also [add a custom domain](https://surge.sh/help/adding-a-custom-domain) and then [force HTTPS by default](https://surge.sh/help/using-https-by-default) and optionally [set a custom SSL certificate](https://surge.sh/help/securing-your-custom-domain-with-ssl) + +To deploy Dashy to Surge.sh, first clone and cd into Dashy, install dependencies, and then use the following commands +``` +yarn add -g surge +yarn build +surge ./dist +``` + +**[⬆️ Back to Top](#deployment)** + +--- + +## Usage +### Providing Assets +Although not essential, you will most likely want to provide several assets to Dashy. All web assets can be found in the `/public` directory. + +- `./public/conf.yml` - As mentioned, this is your main application config file +- `./public/item-icons` - If you're using your own icons, you can choose to store them locally for better load time, and this is the directory to put them in. You can also use sub-folders here to keep things organized. You then reference these assets relative this the direcroties path, for example: to use `./public/item-icons/networking/netdata.png` as an icon for one of your links, you would set `icon: networking/netdata.png` +- Also within `./public` you'll find standard website assets, including `favicon.ico`, `manifest.json`, `robots.txt`, etc. There's no need to modify these, but you can do so if you wish. + +### Basic Commands + +Now that you've got Dashy running, there are a few commands that you need to know. + +The following commands are defined in the [`package.json`](https://github.com/Lissy93/dashy/blob/master/package.json#L5) file, and are run with `yarn`. If you prefer, you can use NPM, just replace instances of `yarn` with `npm run`. If you are using Docker, then you will need to precede each command with `docker exec -it [container-id]`, where container ID can be found by running `docker ps`. For example `docker exec -it 26c156c467b4 yarn build`. + +- **`yarn build`** - In the interest of speed, the application is pre-compiled, this means that the config file is read during build-time, and therefore the app needs to rebuilt for any new changes to take effect. Luckily this is very straight forward. Just run `yarn build` or `docker exec -it [container-id] yarn build` +- **`yarn validate-config`** - If you have quite a long configuration file, you may wish to check that it's all good to go, before deploying the app. This can be done with `yarn validate-config` or `docker exec -it [container-id] yarn validate-config`. Your config file needs to be in `/public/conf.yml` (or within your Docker container at `/app/public/conf.yml`). This will first check that your YAML is valid, and then validates it against Dashy's [schema](https://github.com/Lissy93/dashy/blob/master/src/utils/ConfigSchema.js). +- **`yarn health-check`** - Checks that the application is up and running on it's specified port, and outputs current status and response times. Useful for integrating into your monitoring service, if you need to maintain high system availability +- **`yarn build-watch`** - If you find yourself making frequent changes to your configuration, and do not want to have to keep manually rebuilding, then this option is for you. It will watch for changes to any files within the projects root, and then trigger a rebuild. Note that if you are developing new features, then `yarn dev` would be more appropriate, as it's significantly faster at recompiling (under 1 second), and has hot reloading, linting and testing integrated +- **`yarn build-and-start`** - Builds the app, runs checks and starts the production server. Commands are run in parallel, and so is faster than running them in independently +- **`yarn pm2-start`** - Starts the Node server using [PM2](https://pm2.keymetrics.io/), a process manager for Node.js applications, that helps them stay alive. PM2 has some built-in basic monitoring features, and an optional [management solution](https://pm2.io/). If you are running the app on bare metal, it is recommended to use this start command + +### Healthchecks + +Healthchecks are configured to periodically check that Dashy is up and running correctly on the specified port. By default, the health script is called every 5 minutes, but this can be modified with the `--health-interval` option. You can check the current container health with: `docker inspect --format "{{json .State.Health }}" [container-id]`, and a summary of health status will show up under `docker ps`. You can also manually request the current application status by running `docker exec -it [container-id] yarn health-check`. You can disable healthchecks altogether by adding the `--no-healthcheck` flag to your Docker run command. + +To restart unhealthy containers automatically, check out [Autoheal](https://hub.docker.com/r/willfarrell/autoheal/). This image watches for unhealthy containers, and automatically triggers a restart. This is a stand in for Docker's `--exit-on-unhealthy` that was proposed, but [not merged](https://github.com/moby/moby/pull/22719). + +### Logs and Performance + +##### Container Logs +You can view logs for a given Docker container with `docker logs [container-id]`, add the `--follow` flag to stream the logs. For more info, see the [Logging Documentation](https://docs.docker.com/config/containers/logging/). There's also [Dozzle](https://dozzle.dev/), a useful tool, that provides a web interface where you can stream and query logs from all your running containers from a single web app. + +##### Container Performance +You can check the resource usage for your running Docker containers with `docker stats` or `docker stats [container-id]`. For more info, see the [Stats Documentation](https://docs.docker.com/engine/reference/commandline/stats/). There's also [cAdvisor](https://github.com/google/cadvisor), a useful web app for viewing and analyzing resource usage and performance of all your running containers. + +##### Management Apps +You can also view logs, resource usage and other info as well as manage your entire Docker workflow in third-party Docker management apps. For example [Portainer](https://github.com/portainer/portainer) an all-in-one open source management web UI for Docker and Kubernetes, or [LazyDocker](https://github.com/jesseduffield/lazydocker) a terminal UI for Docker container management and monitoring. + +##### Advanced Logging and Monitoring +Docker supports using [Prometheus](https://prometheus.io/) to collect logs, which can then be visualized using a platform like [Grafana](https://grafana.com/). For more info, see [this guide](https://docs.docker.com/config/daemon/prometheus/). If you need to route your logs to a remote syslog, then consider using [logspout](https://github.com/gliderlabs/logspout). For enterprise-grade instances, there are managed services, that make monitoring container logs and metrics very easy, such as [Sematext](https://sematext.com/blog/docker-container-monitoring-with-sematext/) with [Logagent](https://github.com/sematext/logagent-js). + +### Auto-Starting at System Boot + +You can use Docker's [restart policies](https://docs.docker.com/engine/reference/run/#restart-policies---restart) to instruct the container to start after a system reboot, or restart after a crash. Just add the `--restart=always` flag to your Docker compose script or Docker run command. For more information, see the docs on [Starting Containers Automatically](https://docs.docker.com/config/containers/start-containers-automatically/). + +For Podman, you can use `systemd` to create a service that launches your container, [the docs](https://podman.io/blogs/2018/09/13/systemd.html) explains things further. A similar approach can be used with Docker, if you need to start containers after a reboot, but before any user interaction. + +To restart the container after something within it has crashed, consider using [`docker-autoheal`](https://github.com/willfarrell/docker-autoheal) by @willfarrell, a service that monitors and restarts unhealthy containers. For more info, see the [Healthchecks](#healthchecks) section above. + +### Securing + +##### SSL + +Enabling HTTPS with an SSL certificate is recommended if you hare hosting Dashy anywhere other than your home. This will ensure that all traffic is encrypted in transit. + +[Let's Encrypt](https://letsencrypt.org/docs/) is a global Certificate Authority, providing free SSL/TLS Domain Validation certificates in order to enable secure HTTPS access to your website. They have good browser/ OS [compatibility](https://letsencrypt.org/docs/certificate-compatibility/) with their ISRG X1 and DST CA X3 root certificates, support [Wildcard issuance](https://community.letsencrypt.org/t/acme-v2-production-environment-wildcards/55578) done via ACMEv2 using the DNS-01 and have [Multi-Perspective Validation](https://letsencrypt.org/2020/02/19/multi-perspective-validation.html). Let's Encrypt provide [CertBot](https://certbot.eff.org/) an easy app for generating and setting up an SSL certificate + +[ZeroSSL](https://zerossl.com/) is another popular certificate issuer, they are free for personal use, and also provide easy-to-use tools for getting things setup. + + +If you're hosting Dashy behind Cloudflare, then they offer [free and easy SSL](https://www.cloudflare.com/en-gb/learning/ssl/what-is-an-ssl-certificate/). + +If you're not so comfortable on the command line, then you can use a tool like [SSL For Free](https://www.sslforfree.com/) to generate your Let's Encrypt or ZeroSSL certificate, and support shared hosting servers. They also provide step-by-step tutorials on setting up your certificate on most common platforms. If you are using shared hosting, you may find [this tutorial](https://www.sitepoint.com/a-guide-to-setting-up-lets-encrypt-ssl-on-shared-hosting/) helpful. + +##### Authentication +Dashy has [basic authentication](/docs/authentication.md) built in, however at present this is handled on the front-end, and so where security is critical, it is recommended to use an alternative method. See [here](/docs/authentication.md#alternative-authentication-methods) for options regarding securing Dashy. + + +**[⬆️ Back to Top](#deployment)** + +--- +## Updating + +Dashy is under active development, so to take advantage of the latest features, you may need to update your instance every now and again. + +### Updating Docker Container +1. Pull latest image: `docker pull lissy93/dashy:latest` +2. Kill off existing container + - Find container ID: `docker ps` + - Stop container: `docker stop [container_id]` + - Remove container: `docker rm [container_id]` +3. Spin up new container: `docker run [params] lissy93/dashy` + +### Automatic Docker Updates + +You can automate the above process using [Watchtower](https://github.com/containrrr/watchtower). +Watchtower will watch for new versions of a given image on Docker Hub, pull down your new image, gracefully shut down your existing container and restart it with the same options that were used when it was deployed initially. + +To get started, spin up the watchtower container: + +``` +docker run -d \ + --name watchtower \ + -v /var/run/docker.sock:/var/run/docker.sock \ + containrrr/watchtower +``` + +For more information, see the [Watchtower Docs](https://containrrr.dev/watchtower/) + +### Updating Dashy from Source +1. Navigate into directory: `cd ./dashy` +2. Stop your current instance +3. Pull latest code: `git pull origin master` +4. Re-build: `yarn build` +5. Start: `yarn start` + +**[⬆️ Back to Top](#deployment)** + +--- + +## Web Server Configuration + +_The following section only applies if you are not using Docker, and would like to use your own web server_ + +Dashy ships with a pre-configured Node.js server, in [`server.js`](https://github.com/Lissy93/dashy/blob/master/server.js) which serves up the contents of the `./dist` directory on a given port. You can start the server by running `node server`. Note that the app must have been build (run `yarn build`), and you need [Node.js](https://nodejs.org) installed. + +If you wish to run Dashy from a sub page (e.g. `example.com/dashy`), then just set the `BASE_URL` environmental variable to that page name (in this example, `/dashy`), before building the app, and the path to all assets will then resolve to the new path, instead of `./`. + +However, since Dashy is just a static web application, it can be served with whatever server you like. The following section outlines how you can configure a web server. + +Note, that if you choose not to use `server.js` to serve up the app, you will loose access to the following features: +- Loading page, while the app is building +- Writing config file to disk from the UI +- Website status indicators, and ping checks + +### NGINX + +Create a new file in `/etc/nginx/sites-enabled/dashy` + +``` +server { + listen 80; + listen [::]:80; + + root /var/www/dashy/html; + index index.html; + + server_name your-domain.com www.your-domain.com; + + location / { + try_files $uri $uri/ =404; + } +} +``` +Then upload the build contents of Dashy's dist directory to that location. +For example: `scp -r ./dist/* [username]@[server_ip]:/var/www/dashy/html` + +### Apache + +Copy Dashy's dist folder to your apache server, `sudo cp -r ./dashy/dist /var/www/html/dashy`. + +In your Apache config, `/etc/apche2/apache2.conf` add: +``` + + Options Indexes FollowSymLinks + AllowOverride All + Require all granted + +``` + +Add a `.htaccess` file within `/var/www/html/dashy/.htaccess`, and add: +``` +Options -MultiViews +RewriteEngine On +RewriteCond %{REQUEST_FILENAME} !-f +RewriteRule ^ index.html [QSA,L] +``` + +Then restart Apache, with `sudo systemctl restart apache2` + +### cPanel +1. Login to your WHM +2. Open 'Feature Manager' on the left sidebar +3. Under 'Manage feature list', click 'Edit' +4. Find 'Application manager' in the list, enable it and hit 'Save' +5. Log into your users cPanel account, and under 'Software' find 'Application Manager' +6. Click 'Register Application', fill in the form using the path that Dashy is located, and choose a domain, and hit 'Save' +7. The application should now show up in the list, click 'Ensure dependencies', and move the toggle switch to 'Enabled' +8. If you need to change the port, click 'Add environmental variable', give it the name 'PORT', choose a port number and press 'Save'. +9. Dashy should now be running at your selected path an on a given port + +**[⬆️ Back to Top](#deployment)** + +--- + +## Authentication + +Dashy has built-in authentication and login functionality. However, since this is handled on the client-side, if you are using Dashy in security-critical situations, it is recommended to use an alternate method for authentication, such as [Authelia](https://www.authelia.com/), a VPN or web server and firewall rules. For more info, see **[Authentication Docs](/docs/authentication.md)**. + + +**[⬆️ Back to Top](#deployment)** diff --git a/docs/developing.md b/docs/developing.md index c56476dc..de600bfd 100644 --- a/docs/developing.md +++ b/docs/developing.md @@ -47,6 +47,26 @@ Note: - If you are using NPM, replace `yarn` with `npm run` - If you are using Docker, precede each command with `docker exec -it [container-id]`. Container ID can be found by running `docker ps` +### Environmental Variables +- `PORT` - The port in which the application will run (defaults to `4000` for the Node.js server, and `80` within the Docker container) +- `NODE_ENV` - Which environment to use, either `production`, `development` or `test` +- `VUE_APP_DOMAIN` - The URL where Dashy is going to be accessible from. This should include the protocol, hostname and (if not 80 or 443), then the port too, e.g. `https://localhost:3000`, `http://192.168.1.2:4002` or `https://dashy.mydomain.com` + +All environmental variables are optional. Currently there are not many environmental variables used, as most of the user preferences are stored under `appConfig` in the `conf.yml` file. + +If you do add new variables, ensure that there is always a fallback (define it in [`defaults.js`](https://github.com/Lissy93/dashy/blob/master/src/utils/defaults.js)), so as to not cause breaking changes. Don't commit your `.env` file to git, but instead take a few moments to document what you've added under the appropriate section. Try and follow the concepts outlined in the [12 factor app](https://12factor.net/config), as these are good practices. + +Any environmental variables used by the frontend are preceded with `VUE_APP_`. Vue will merge the contents of your `.env` file into the app in a similar way to the ['dotenv'](https://github.com/motdotla/dotenv) package, where any variables that you set on your system will always take preference over the contents of any `.env` file. + +### Environment Modes +Both the Node app and Vue app supports several environments: `production`, `development` and `test`. You can set the environment using the `NODE_ENV` variable (either with your OS, in the Docker script or in an `.env` file - see [Environmental Variables](#environmental-variables) above). + +The production environment will build the app in full, minifying and streamlining all assets. This means that building takes longer, but the app will then run faster. Whereas the dev environment creates a webpack configuration which enables HMR, doesn't hash assets or create vendor bundles in order to allow for fast re-builds when running a dev server. It supports sourcemaps and other debugging tools, re-compiles and reloads quickly but is not optimized, and so the app will not be as snappy as it could be. The test environment is intended for test running servers, it ignores assets that aren't needed for testing, and focuses on running all the E2E, regression and unit tests. For more information, see [Vue CLI Environment Modes](https://cli.vuejs.org/guide/mode-and-env.html#modes). + +By default: +- `production` is used by `yarn build` (or `vue-cli-service build`) and `yarn build-and-start` and `yarn pm2-start` +- `development` is used by `yarn dev` (or `vue-cli-service serve`) +- `test` is used by `yarn test` (or `vue-cli-service test:unit`) ### Resources for Beginners New to Web Development? Glad you're here! Dashy is a pretty simple app, so it should make a good candidate for your first PR. Presuming that you already have a basic knowledge of JavaScript, the following articles should point you in the right direction for getting up to speed with the technologies used in this project: - [Introduction to Vue.js](https://v3.vuejs.org/guide/introduction.html) @@ -79,7 +99,6 @@ The most significant things to note are: For the full styleguide, see: [github.com/airbnb/javascript](https://github.com/airbnb/javascript) - ### Frontend Components All frontend code is located in the `./src` directory, which is split into 5 sub-folders: @@ -122,6 +141,9 @@ Running `yarn upgrade` will updated all dependencies based on the ranges specifi #### Performance - Lighthouse The easiest method of checking performance is to use Chromium's build in auditing tool, Lighthouse. To run the test, open Developer Tools (usually F12) --> Lighthouse and click on the 'Generate Report' button at the bottom. +#### Dependencies - BundlePhobia +[BundlePhobia](https://bundlephobia.com/) is a really useful app that lets you analyze the cost of adding any particular dependency to an application + ### Directory Structure #### Files in the Root: `./` diff --git a/docs/getting-started.md b/docs/getting-started.md deleted file mode 100644 index 0cf405e2..00000000 --- a/docs/getting-started.md +++ /dev/null @@ -1,169 +0,0 @@ -# Getting Started - -- [Deployment](#deployment) - - [Deploy with Docker](#deploy-with-docker) - - [Deploy from Source](#deploy-from-source) - - [Deploy to Cloud Service](#deploy-to-cloud-service) -- [Usage](#usage) - - [Providing Assets](#providing-assets) - - [Basic Commands](#basic-commands) - - [Healthchecks](#healthchecks) - - [Monitoring](#logs-and-performance) -- [Updating](#updating) - - [Updating Docker Container](#updating-docker-container) - - [Automating Docker Updates](#automatic-docker-updates) - - [Updating from Source](#updating-dashy-from-source) - -## Deployment - -### Deploy with Docker - -The quickest way to get started on any system is with Docker, and Dashy is available though [Docker Hub](https://hub.docker.com/r/lissy93/dashy). You will need [Docker](https://docs.docker.com/get-docker/) installed on your system. - -To configure Dashy with your own services, and customize it to your liking, you will need to write a config file, and pass it to the Docker container as a volume. - -```docker -docker run -d \ - -p 8080:80 \ - -v /root/my-local-conf.yml:/app/public/conf.yml \ - --name my-dashboard \ - --restart=always \ - lissy93/dashy:latest -``` - -Explanation of the above options: -- `-d` Detached mode (not running in the foreground of your terminal) -- `-p` The port that should be exposed, and the port it should be mapped to in your host system `[host-port][container-port]` -- `-v` Specify volumes, to pass data from your host system to the container, in the format of `[host-path]:[container-path]` -- `--name` Give your container a human-readable name -- `--restart=always` Spin up the container when the daemon starts, or after it has been stopped -- `lissy93/dashy:latest` This last option is the image the container should be built from - -For all available options, and to learn more, see the [Docker Run Docs](https://docs.docker.com/engine/reference/commandline/run/) - -You can also build and deploy the Docker container from source. -- Get the code: `git clone git@github.com:Lissy93/dashy.git && cd dashy` -- Edit the `./public/conf.yml` file and take a look at the `docker-compose.yml` -- Start the container: `docker compose up` - - -### Deploy from Source -If you do not want to use Docker, you can run Dashy directly on your host system. For this, you will need both [git](https://git-scm.com/downloads) and the latest or LTS version of [Node.js](https://nodejs.org/) installed. - -1. Get Code: `git clone git@github.com:Lissy93/dashy.git` and `cd dashy` -2. Configuration: Fill in you're settings in `./public/conf.yml` -3. Install dependencies: `yarn` -4. Build: `yarn build` -5. Run: `yarn start` - -### Deploy to Cloud Service - -Dashy supports 1-Click deployments on several popular cloud platforms. - -#### Netlify -[![Deploy to Netlify](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/lissy93/dashy) - -[Netlify](https://www.netlify.com/) offers Git-based serverless cloud hosting for web applications. Their services are free to use for personal use, and they support deployment from both public and private repos, as well as direct file upload. - -To deploy Dashy to Netlify, use the following link -``` -https://app.netlify.com/start/deploy?repository=https://github.com/lissy93/dashy -``` - -#### Heroku -[![Deploy to Heroku](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/Lissy93/dashy) - -[Heroku](https://www.heroku.com/) is a fully managed cloud platform as a service. You define app settings in a Procfile and app.json, which specifying how the app should be build and how the server should be started. Heroku is free to use for unlimited, non-commercial, single dyno apps. - -To deploy Dashy to Heroku, use the following link -``` -https://heroku.com/deploy?template=https://github.com/Lissy93/dashy -``` - -#### Play-with-Docker -[![Try in PWD](https://raw.githubusercontent.com/play-with-docker/stacks/cff22438/assets/images/button.png)](https://labs.play-with-docker.com/?stack=https://raw.githubusercontent.com/Lissy93/dashy/master/docker-compose.yml) - -[Play with Docker](https://labs.play-with-docker.com/) is a community project by Marcos Liljedhal and Jonathan Leibiusky and sponsored by Docker, intended to provide a hands-on learning environment. Their labs let you quickly spin up a Docker container or stack, and test out the image in a temporary, sandboxed environment. There's no need to sign up, and it's completely free. - -To run Dashy in PWD, use the following URL: -``` -https://labs.play-with-docker.com/?stack=https://raw.githubusercontent.com/Lissy93/dashy/master/docker-compose.yml -``` -**[⬆️ Back to Top](#getting-started)** - ---- - -## Usage -### Providing Assets -Although not essential, you will most likely want to provide several assets to Dashy. All web assets can be found in the `/public` directory. - -- `./public/conf.yml` - As mentioned, this is your main application config file -- `./public/item-icons` - If you're using your own icons, you can choose to store them locally for better load time, and this is the directory to put them in. You can also use sub-folders here to keep things organized. You then reference these assets relative this the direcroties path, for example: to use `./public/item-icons/networking/netdata.png` as an icon for one of your links, you would set `icon: networking/netdata.png` -- Also within `./public` you'll find standard website assets, including `favicon.ico`, `manifest.json`, `robots.txt`, etc. There's no need to modify these, but you can do so if you wish. - -### Basic Commands - -Now that you've got Dashy running, there are a few commands that you need to know. - -The following commands are defined in the [`package.json`](https://github.com/Lissy93/dashy/blob/master/package.json#L5) file, and are run with `yarn`. If you prefer, you can use NPM, just replace instances of `yarn` with `npm run`. If you are using Docker, then you will need to precede each command with `docker exec -it [container-id]`, where container ID can be found by running `docker ps`. For example `docker exec -it 26c156c467b4 yarn build`. - -- **`yarn build`** - In the interest of speed, the application is pre-compiled, this means that the config file is read during build-time, and therefore the app needs to rebuilt for any new changes to take effect. Luckily this is very straight forward. Just run `yarn build` or `docker exec -it [container-id] yarn build` -- **`yarn validate-config`** - If you have quite a long configuration file, you may wish to check that it's all good to go, before deploying the app. This can be done with `yarn validate-config` or `docker exec -it [container-id] yarn validate-config`. Your config file needs to be in `/public/conf.yml` (or within your Docker container at `/app/public/conf.yml`). This will first check that your YAML is valid, and then validates it against Dashy's [schema](https://github.com/Lissy93/dashy/blob/master/src/utils/ConfigSchema.js). -- **`yarn health-check`** - Checks that the application is up and running on it's specified port, and outputs current status and response times. Useful for integrating into your monitoring service, if you need to maintain high system availability -- **`yarn build-watch`** - If you find yourself making frequent changes to your configuration, and do not want to have to keep manually rebuilding, then this option is for you. It will watch for changes to any files within the projects root, and then trigger a rebuild. Note that if you are developing new features, then `yarn dev` would be more appropriate, as it's significantly faster at recompiling (under 1 second), and has hot reloading, linting and testing integrated -- **`yarn build-and-start`** - Builds the app, runs checks and starts the production server. Commands are run in parallel, and so is faster than running them in independently - -### Healthchecks - -Healthchecks are configured to periodically check that Dashy is up and running correctly on the specified port. By default, the health script is called every 5 minutes, but this can be modified with the `--health-interval` option. You can check the current container health with: `docker inspect --format "{{json .State.Health }}" [container-id]`, and a summary of health status will show up under `docker ps`. You can also manually request the current application status by running `docker exec -it [container-id] yarn health-check`. You can disable healthchecks altogether by adding the `--no-healthcheck` flag to your Docker run command. - -To restart unhealthy containers automatically, check out [Autoheal](https://hub.docker.com/r/willfarrell/autoheal/). This image watches for unhealthy containers, and automatically triggers a restart. This is a stand in for Docker's `--exit-on-unhealthy` that was proposed, but [not merged](https://github.com/moby/moby/pull/22719). - -### Logs and Performance - -You can view logs for a given Docker container with `docker logs [container-id]`, add the `--follow` flag to stream the logs. For more info, see the [Logging Documentation](https://docs.docker.com/config/containers/logging/). [Dozzle](https://dozzle.dev/) is a useful tool, that provides a web interface where you can stream and query logs from all your running containers from a single web app. - -You can check the resource usage for your running Docker containers with `docker stats` or `docker stats [container-id]`. For more info, see the [Stats Documentation](https://docs.docker.com/engine/reference/commandline/stats/). [cAdvisor](https://github.com/google/cadvisor) is a useful web app for viewing and analyzing resource usage and performance of your running containers. - -You can also view logs, resource usage and other info as well as manage your Docker workflow in third-party Docker management apps. For example [Portainer](https://github.com/portainer/portainer) an all-in-one management web UI for Docker and Kubernetes, or [LazyDocker](https://github.com/jesseduffield/lazydocker) a terminal UI for Docker container management and monitoring. - -**[⬆️ Back to Top](#getting-started)** - ---- -## Updating - -Dashy is under active development, so to take advantage of the latest features, you may need to update your instance every now and again. - -### Updating Docker Container -1. Pull latest image: `docker pull lissy93/dashy:latest` -2. Kill off existing container - - Find container ID: `docker ps` - - Stop container: `docker stop [container_id]` - - Remove container: `docker rm [container_id]` -3. Spin up new container: `docker run [params] lissy93/dashy` - -### Automatic Docker Updates - -You can automate the above process using [Watchtower](https://github.com/containrrr/watchtower). -Watchtower will watch for new versions of a given image on Docker Hub, pull down your new image, gracefully shut down your existing container and restart it with the same options that were used when it was deployed initially. - -To get started, spin up the watchtower container: - -``` -docker run -d \ - --name watchtower \ - -v /var/run/docker.sock:/var/run/docker.sock \ - containrrr/watchtower -``` - -For more information, see the [Watchtower Docs](https://containrrr.dev/watchtower/) - -### Updating Dashy from Source -1. Navigate into directory: `cd ./dashy` -2. Stop your current instance -3. Pull latest code: `git pull origin master` -4. Re-build: `yarn build` -5. Start: `yarn start` - - -**[⬆️ Back to Top](#getting-started)** \ No newline at end of file diff --git a/docs/icons.md b/docs/icons.md new file mode 100644 index 00000000..8cac264f --- /dev/null +++ b/docs/icons.md @@ -0,0 +1,78 @@ +## Icons + +Both sections and items can have an icon, which is specified using the `icon` attribute. Using icons improves the aesthetics of your UI and makes the app more intuitive to use. There are several options when it comes to setting icons, and this article outlines each of them + +- [Font Awesome Icons](#font-awesome) +- [Auto-Fetched Favicons](#favicons) +- [Generative Icons](#generative-icons) +- [Emoji Icons](#emoji-icons) +- [Icons by URL](#icons-by-url) +- [Local Icons](#local-icons) +- [No Icon](#no-icon) + +

+ +

+ +### Font Awesome +You can use any [Font Awesome Icon](https://fontawesome.com/icons) simply by specifying it's identifier. This is in the format of `[category] [name]` and can be found on the page for any given icon on the Font Awesome site. For example: `fas fa-rocket`, `fab fa-monero` or `fas fa-unicorn`. + +Font-Awesome has a wide variety of free icons, but you can also use their pro icons if you have a membership. To do so, you need to specify your license key under: `appConfig.fontAwesomeKey`. This is usually a 10-digit string, for example `13014ae648`. + +

+ +

+ +### Favicons +Dashy can auto-fetch the favicon for a given service using it's URL. Just set `icon: favicon` to use this feature. If the services URL is a local IP, then Dashy will attempt to find the favicon from `http://[ip]/favicon.ico`. This has two issues, favicons are not always hosted at the same location for every service, and often the default favicon is a low resolution. Therefore to fix this, for remote services an API is used to return a high-quality icon for any online service. + +

+ +

+ +The default favicon API is [Favicon Kit](https://faviconkit.com/), a free and reliable service for returning images from any given URL. However several other API's are supported. To change the API used, under `appConfig`, set `faviconApi` to one of the following values: + +- `faviconkit` - [faviconkit.com](https://faviconkit.com/) (Recommend) +- `google` - Official Google favicon API service, good support for all sites, but poor quality +- `clearbit` - [Clearbit](https://clearbit.com/logo) returns high-quality logos from mainstream websites +- `webmasterapi` - [WebMasterAPI](https://www.webmasterapi.com/get-favicons) +- `allesedv` - [allesedv.com](https://favicon.allesedv.com/) is a highly efficient IPv6-enabled service + +You can also force Dashy to always get favicons from the root of the domain, and not use an external service, by setting `appConfig.faviconApi` to `local`. + +### Generative Icons +Uses a unique and programmatically generated icon for a given service. This is particularly useful when you have a lot of similar services with a different IP or port, and no specific icon. These icons are generated with [ipsicon.io](https://ipsicon.io/). To use this option, just set an item's to: `icon: generative`. + +

+ +

+ +### Emoji Icons +You can use almost any emoji as an icon for items or sections. You can specify the emoji either by pasting it directly, using it's unicode ( e.g. `'U+1F680'`) or shortcode (e.g. `':rocket:'`). You can find these codes for any emoji using [Emojipedia](https://emojipedia.org/) (near the bottom of emoji each page), or for a quick reference to emoji shortcodes, check out [emojis.ninja](https://emojis.ninja/) by @nomanoff. + +

+ +

+ +The following example shows the unicode options available, all three will render the 🚀 emoji. + +```yaml +items: +- title: Shortcode + icon: ':rocket:' +- title: Unicode + icon: 'U+1F680' +- title: Emoji + icon: 🚀 +``` + +### Icons by URL +You can also set an icon by passing in a valid URL pointing to the icons location. For example `icon: https://i.ibb.co/710B3Yc/space-invader-x256.png`, this can be in .png, .jpg or .svg format, and hosted anywhere- so long as it's accessible from where you are hosting Dashy. The icon will be automatically scaled to fit, however loading in a lot of large icons may have a negative impact on performance, especially if you visit Dashy from new devices often. + +### Local Icons +You may also want to store your icons locally, bundled within Dashy so that there is no reliance on outside services. This can be done by putting the icons within Dashy's `./public/item-icons/` directory. If you are using Docker, then the easiest option is to map a volume from your host system, for example: `-v /local/image/directory:/app/public/item-icons/`. To reference an icon stored locally, just specify it's name and extension. For example, if my icon was stored in `/app/public/item-icons/maltrail.png`, then I would just set `icon: maltrail.png`. + +You can also use sub-folders within the `item-icons` directory to keep things organised. You would then specify an icon with it's folder name slash image name. For example: `networking/monit.png` + +### No Icon +If you don't wish for a given item or section to have an icon, just leave out the `icon` attribute. diff --git a/docs/readme.md b/docs/readme.md index 1f9607fc..96802a47 100644 --- a/docs/readme.md +++ b/docs/readme.md @@ -1,12 +1,13 @@ - - ## Contents -- [Getting Started](/docs/getting-started.md) +- [Deployment](/docs/deployment.md) - [Configuring](/docs/configuring.md) - [Developing](/docs/developing.md) - [Contributing](/docs/contributing.md) - [User Guide](/docs/user-guide.md) - [Troubleshooting](/docs/troubleshooting.md) - [Backup & Restore](/docs/backup-restore.md) +- [Status Indicators](/docs/status-indicators.md) - [Theming](/docs/theming.md) +- [Icons](/docs/icons.md) +- [Authentication](/docs/authentication.md) diff --git a/docs/showcase.md b/docs/showcase.md new file mode 100644 index 00000000..b0307226 --- /dev/null +++ b/docs/showcase.md @@ -0,0 +1,92 @@ +# *Dashy Showcase* 🌟 + +| 💗 Do you use Dashy? Got a sweet dashboard? Submit it to the showcase! 👉 [See How](#submitting-your-dashboard) | +|-| + +### Home Lab 2.0 + +![screenshot-homelab](https://raw.githubusercontent.com/Lissy93/dashy/master/docs/showcase/1-home-lab-material.png) + +--- + +### Networking Services +> By [@Lissy93](https://github.com/lissy93) + +![screenshot-networking-services](https://raw.githubusercontent.com/Lissy93/dashy/master/docs/showcase/2-networking-services-minimal-dark.png) + +--- + +### Homelab & VPS dashboard +> By [@shadowking001](https://github.com/shadowking001) + +![screenshot-shadowking001-dashy](https://raw.githubusercontent.com/Lissy93/dashy/master/docs/showcase/8-shadowking001s-dashy.png) + +--- + +### NAS Home Dashboard +> By [@cerealconyogurt](https://github.com/cerealconyogurt) + +![screenshot-networking-services](https://raw.githubusercontent.com/Lissy93/dashy/master/docs/showcase/6-nas-home-dashboard.png) + +--- + +### CFT Toolbox + +![screenshot-cft-toolbox](https://raw.githubusercontent.com/Lissy93/dashy/master/docs/showcase/3-cft-toolbox.png) + +--- + +### Bookmarks + +![screenshot-bookmarks](https://raw.githubusercontent.com/Lissy93/dashy/master/docs/showcase/4-bookmarks-colourful.png) + +--- + +### Project Management + +![screenshot-project-managment](https://raw.githubusercontent.com/Lissy93/dashy/master/docs/showcase/5-project-managment.png) + +--- + +### Ground Control +> By [@dtctek](https://github.com/dtctek) + +![screenshot-ground-control](https://raw.githubusercontent.com/Lissy93/dashy/master/docs/showcase/7-ground-control-dtctek.png) + +--- + +### Yet Another Homelab + +![screenshot-yet-another-homelab](https://raw.githubusercontent.com/Lissy93/dashy/master/docs/showcase/9-home-lab-oblivion.png) + +--- + +## Submitting your Dashboard + +#### How to Submit +- [Open an Issue](https://git.io/Jceik) +- [Open a PR](https://github.com/Lissy93/dashy/compare) + +#### What to Include +Please include the following information: +- A single high-quality screenshot of your Dashboard +- A short title (it doesn't have to be particularly imaginative) +- An optional description, you could include details on anything interesting or unique about your dashboard, or say how you use it, and why it's awesome +- Optionally leave your name or username, with a link to your GitHub, Twitter or Website + +#### Template + +If you're submitting a pull request, please use a format similar to this: + +``` +### [Dashboard Name] (required) + +> Submitted by [@username](https://github.com/user) (optional) + +![dashboard-screenshot](/docs/showcase/screenshot-name.jpg) (required) + +[An optional text description, or any interesting details] (optional) + +--- + +``` diff --git a/docs/showcase/1-home-lab-material.png b/docs/showcase/1-home-lab-material.png new file mode 100644 index 00000000..605a520c Binary files /dev/null and b/docs/showcase/1-home-lab-material.png differ diff --git a/docs/showcase/2-networking-services-minimal-dark.png b/docs/showcase/2-networking-services-minimal-dark.png new file mode 100644 index 00000000..6986f60c Binary files /dev/null and b/docs/showcase/2-networking-services-minimal-dark.png differ diff --git a/docs/showcase/3-cft-toolbox.png b/docs/showcase/3-cft-toolbox.png new file mode 100644 index 00000000..a728a8a9 Binary files /dev/null and b/docs/showcase/3-cft-toolbox.png differ diff --git a/docs/showcase/4-bookmarks-colourful.png b/docs/showcase/4-bookmarks-colourful.png new file mode 100644 index 00000000..a29563f4 Binary files /dev/null and b/docs/showcase/4-bookmarks-colourful.png differ diff --git a/docs/showcase/5-project-managment.png b/docs/showcase/5-project-managment.png new file mode 100644 index 00000000..e8567f5f Binary files /dev/null and b/docs/showcase/5-project-managment.png differ diff --git a/docs/showcase/6-nas-home-dashboard.png b/docs/showcase/6-nas-home-dashboard.png new file mode 100644 index 00000000..01bb57ff Binary files /dev/null and b/docs/showcase/6-nas-home-dashboard.png differ diff --git a/docs/showcase/7-ground-control-dtctek.png b/docs/showcase/7-ground-control-dtctek.png new file mode 100644 index 00000000..671117f5 Binary files /dev/null and b/docs/showcase/7-ground-control-dtctek.png differ diff --git a/docs/showcase/8-shadowking001s-dashy.png b/docs/showcase/8-shadowking001s-dashy.png new file mode 100644 index 00000000..7f48b0c8 Binary files /dev/null and b/docs/showcase/8-shadowking001s-dashy.png differ diff --git a/docs/showcase/9-home-lab-oblivion.png b/docs/showcase/9-home-lab-oblivion.png new file mode 100644 index 00000000..ec1a26f6 Binary files /dev/null and b/docs/showcase/9-home-lab-oblivion.png differ diff --git a/docs/status-indicators.md b/docs/status-indicators.md new file mode 100644 index 00000000..8f2a8469 --- /dev/null +++ b/docs/status-indicators.md @@ -0,0 +1,76 @@ +# Status Indicators + +Dashy has an optional feature that can display a small icon next to each of your running services, indicating it's current status. This is useful if you are using Dashy as your homelab's start page, as it gives you an overview of the health of each of your running services. + +

+ +

+ +## Enabling Status Indicators +By default, this feature is off. If you do not want this feature, just don't add the `statusCheck` to your conf.yml file, then no requests will be made. + +To enable status checks, you can either turn it on for all items, by setting `appConfig.statusCheck: true`, like: +```yaml +appConfig: + statusCheck: true +``` + +Or you can enable/ disable it on a per-item basis, with the `item[n].statusCheck` attribute +```yaml +sections: +- name: Firewall + items: + - title: OPNsense + description: Firewall Central Management + icon: networking/opnsense.png + url: https://192.168.1.1 + statusCheck: false + - title: MalTrail + description: Malicious traffic detection system + icon: networking/maltrail.png + url: http://192.168.1.1:8338 + statusCheck: true + - title: Ntopng + description: Network traffic probe and network use monitor + icon: networking/ntop.png + url: http://192.168.1.1:3001 + statusCheck: true +``` + +## Continuous Checking +By default, with status indicators enabled Dashy will check an applications status on page load, and will not keep indicators updated. This is usually desirable behavior. However, if you do want the status indicators to continue to poll your running services, this can be enabled by setting the `statusCheckInterval` attribute. Here you define an interval in seconds, and Dashy will poll your apps every x seconds. Note that if this number is very low (below 5 seconds), you may notice the app running slightly slower. + +The following example, will instruct Dashy to continuously check the status of your services every 20 seconds + +``` +appConfig: + statusCheck: true + statusCheckInterval: 20 +``` + +## Using a Different Endpoint +By default, the status checker will use the URL of each application being checked. In some situations, you may want to use a different endpoint for status checking. Similarly, some services provide a dedicated path for uptime monitoring. + +You can set the `statusCheckUrl` property on any given item in order to do this. The status checker will then ping that endpoint, instead of the apps main `url` property. + +## Setting Custom Headers +If your service is responding with an error, despite being up and running, it is most likely because custom headers for authentication, authorization or encoding are required. You can define these headers under the `statusCheckHeaders` property for any service. It should be defined as an object format, with the name of header as the key, and header content as the value. +For example, `statusCheckHeaders: { 'X-Custom-Header': 'foobar' }` + +## Troubleshooting Failing Status Checks +If the status is always returning an error, despite the service being online, then it is most likely an issue with access control, and should be fixed with the correct headers. Hover over the failing status to see the error code and response, in order to know where to start with addressing it. +If your service requires requests to include any authorization in the headers, then use the `statusCheckHeaders` property, as described above. +If you are still having issues, it may be because your target application is blocking requests from Dashy's IP. This is a [CORS error](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), and can be fixed by setting the headers on your target app, to include: +``` +Access-Control-Allow-Origin: https://location-of-dashy/ +Vary: Origin +``` +For further troubleshooting, use an application like [Postman](https://postman.com) to diagnose the issue. + +## How it Works + +When Dashy is loaded, items with `statusCheck` enabled will make a request, to `https://[your-host-name]/ping?url=[address-or-servce]`, which in turn will ping that running service, and respond with a status code. Response time is calculated from the difference between start and end time of the request. + +When the response completes, an indicator will display next to each item. The color denotes the status: Yellow while waiting for the response to return, green if request was successful, red if it failed, and grey if it was unable to make the request all together. + +All requests are made straight from your server, there is no intermediary. So providing you are hosting Dashy yourself, and are checking the status of other self-hosted services, there shouldn't be any privacy concerns. Requests are made asynchronously, so this won't have any impact on page load speeds. However recurring requests (using `statusCheckInterval`) may run more slowly if the interval between requests is very short. diff --git a/docs/theming.md b/docs/theming.md index aebce0c2..a87783c0 100644 --- a/docs/theming.md +++ b/docs/theming.md @@ -4,7 +4,7 @@ By default Dashy comes with 20 built in themes, which can be applied from the dr ![Built-in Themes](https://i.ibb.co/GV3wRss/Dashy-Themes.png) -You can also add your own themes, apply custom CSS, and modify colors. +You can also add your own themes, apply custom styles, and modify colors. You can customize Dashy by writing your own CSS, which can be loaded either as an external stylesheet, set directly through the UI, or specified in the config file. Most styling options can be set through CSS variables, which are outlined below. @@ -25,7 +25,7 @@ You can now create a block to target you're theme with `html[data-theme='my-them ```css html[data-theme='tiger'] { --primary: #f58233; - --item-group-background: #0b1021; + --background: #0b1021; } ``` @@ -33,17 +33,20 @@ Finally, from the UI use the theme dropdown menu to select your new theme, and y You can also set `appConfig.theme` to pre-select a default theme, which will be applied immediately after deployment. -### Setting Custom CSS +### Adding your own Theme + +User-defined styles and custom themes should be defined in `./src/styles/user-defined-themes.scss`. If you're using Docker, you can pass your own stylesheet in using the `--volume` flag. E.g. `v ./my-themes.scss:/app/src/styles/user-defined-themes.scss`. Don't forget to pass your theme name into `appConfig.cssThemes` so that it shows up on the theme-switcher dropdown. + +### Setting Custom CSS in the UI Custom CSS can be developed, tested and applied directly through the UI. Although you will need to make note of your changes to apply them across instances. -This can be done from the Config menu (spanner icon in the top-right), under the Custom Styles tab. This is then associated with `appConfig.customCss` in local storage. Any styles set this way can be synced across instances using the cloud backup and sync feature. - -It's also possible to set CSS in the config file under `appConfig.customCss`. However this approach is not very neat, and if you do do it, first minify / compress your CSS and wrap in quotes, to ensure it does not cause any validation errors. +This can be done from the Config menu (spanner icon in the top-right), under the Custom Styles tab. This is then associated with `appConfig.customCss` in local storage. Styles can also be directly applied to this attribute in the config file, but this may get messy very quickly if you have a lot of CSS. ### Loading External Stylesheets -The URI of a stylesheet, either local or hosted on a remote CDN can be passed into the config file. The attribute `appConfig.externalStyleSheet` accepts either a string, or an array of strings. This is handled in [`ThemeHelper.js`](https://github.com/Lissy93/dashy/blob/master/src/utils/ThemeHelper.js). +The URI of a stylesheet, either local or hosted on a remote CDN can be passed into the config file. The attribute `appConfig.externalStyleSheet` accepts either a string, or an array of strings. You can also pass custom font stylesheets here, they must be in a CSS format (for example, `https://fonts.googleapis.com/css2?family=Cutive+Mono`). +This is handled in [`ThemeHelper.js`](https://github.com/Lissy93/dashy/blob/master/src/utils/ThemeHelper.js). For example: @@ -63,6 +66,14 @@ Some UI components have a color option, that can be set in the config file, to f - `item.color` - Font and icon color for a given item - `item.backgroundColor` - Background color for a given icon +### Typography + +Essential fonts bundled within the app are located within `./src/assets/fonts/`. All optional fonts that are used by themes are stored in `./public/fonts/`, if you want to add your own font, this is where you should put it. As with assets, if you're using Docker then using a volume to link a directory on your host system with this path within the container will make management much easier. + +Fonts which are not being used by the current theme are **not** fetched on page load. They are instead only loaded into the application if and when they are required. So having multiple themes with various typefaces shouldn't have any negative impact on performance. + +Full credit to the typographers behind each of the included fonts. Specifically: Matt McInerney, Christian Robertson, Haley Fiege, Peter Hull, Cyreal and the legendary Vernon Adams + ### CSS Variables All colors as well as other variable values (such as borders, border-radius, shadows) are specified as CSS variables. This makes theming the application easy, as you only need to change a given color or value in one place. You can find all variables in [`color-palette.scss`](https://github.com/Lissy93/dashy/blob/master/src/styles/color-palette.scss) and the themes which make use of these color variables are specified in [`color-themes.scss`](https://github.com/Lissy93/dashy/blob/master/src/styles/color-themes.scss) @@ -108,10 +119,21 @@ You can target specific elements on the UI with these variables. All are optiona - `--config-settings-background` - The text color for text within the settings container. Defaults to `--background-darker` - `--scroll-bar-color` - Color of the scroll bar thumb. Defaults to `--primary` - `--scroll-bar-background` Color of the scroll bar blank space. Defaults to `--background-darker` +- `--highlight-background` Fill color for text highlighting. Defaults to `--primary` +- `--highlight-color` Text color for selected/ highlighted text. Defaults to `--background` - `--toast-background` - Background color for the toast info popup. Defaults to `--primary` - `--toast-color` - Text, icon and border color in the toast info popup. Defaults to `--background` - `--welcome-popup-background` - Background for the info pop-up shown on first load. Defaults to `--background-darker` - `--welcome-popup-text-color` - Text color for the welcome pop-up. Defaults to `--primary` +- `--side-bar-background` - Background color of the sidebar used in the workspace view. Defaults to `--background-darker` +- `--side-bar-color` - Color of icons and text within the sidebar. Defaults to `--primary` +- `--status-check-tooltip-background` - Background color for status check tooltips. Defaults to `--background-darker` +- `--status-check-tooltip-color` - Text color for the status check tooltips. Defaults to `--primary` +- `--code-editor-color` - Text color used within raw code editors. Defaults to `--black` +- `--code-editor-background` - Background color for raw code editors. Defaults to `--white` +- `--context-menu-color` - Text color for right-click context menu over items. Defaults to `--primary` +- `--context-menu-background` - Background color of right-click context menu. Defaults to `--background` +- `--context-menu-secondary-color` - Border and outline color for context menu. Defaults to `--background-darker` #### Non-Color Variables - `--outline-color` - Used to outline focused or selected elements diff --git a/docs/user-guide.md b/docs/user-guide.md index 9c4ae7f5..60d2c549 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -1,6 +1,19 @@ - ## User Guide +This article outlines how to use the application. If you are instead looking for deployment instructions, see [Deployment](/docs/deployment.md) and [Configuring](/docs/configuring.md) + +### Contents +- [Searching](#searching) +- [Keyboard Shortcuts](#keyboard-shortcuts) +- [Theme Switching](#theme-switching) +- [Visual Options](#visual-options) +- [Opening Items](#opening-items) +- [Sections and Items](#sections-and-items) +- [Icons](#icons) +- [Metadata](#metadata) +- [Editing Config](#editing-config) +- [Managing Config Data](#managing-config-data) + ### Searching A key requirement for any start page is being able to quickly and effectively find the item your looking for. For Dashy, a lot of thought was put into the most intuitive method to filter links. @@ -13,16 +26,22 @@ The following properties are used to filter items by: - URL - Only the base URL is searched, the protocol and parameters are omitted - Description +**[⬆️ Back to Top](#user-guide)** + ### Keyboard Shortcuts Many people find using the keyboard significantly more efficient than having to reach for the mouse. And so Dashy has a series of keybindings and shortcuts to enable you to navigate through items quickly. Once you've searched for a given item, you can then tab through the list (or Shift + Tab to go backwards) until you've found the item you're looking for. You can also use the arrow keys to navigate up, down, left and right through the grid. To launch an item, just hit enter. You can also open an item in a new tab with Ctrl + Enter, or open the item in a pop-up modal with Alt + Enter. To close an open popup item, or any open menus, just hit Esc. +**[⬆️ Back to Top](#user-guide)** + ### Theme Switching You can change the current theme using the dropdown menu in the upper-right-hand quadrant. Your selected theme will be stored in local storage, and applied next time you load the page. For more information on customizing the look and feel of Dashy, see [Themeing Docs](/docs/theming.md) +**[⬆️ Back to Top](#user-guide)** + ### Visual Options There are several pre-built layout options to choose from depending on your requirements. Like the theme these options will be remembered in browser storage and applied on load. @@ -33,6 +52,8 @@ Next there's icon size. This changes the size of the item and it's icon. It can ![layout-options](https://i.ibb.co/NnzF82t/available-layout-options.png) +**[⬆️ Back to Top](#user-guide)** + ### Opening Items There are three methods of opening items. Clicking (or hitting Enter on a selected item) will use the default method, specified in the config file, under `item.target`. You can use Ctrl + Click or Ctrl + Enter to open and item in a new tab. @@ -41,9 +62,11 @@ You can also use Alt + Click or Alt + Enter, to open an item in a popup window. ![Example of a pop-up opened item](https://i.ibb.co/zSnznFF/dashy-popup.png) +**[⬆️ Back to Top](#user-guide)** + ### Sections and Items -The main content in Dashy is split into sections, which contain icons. You can have as many sections as you need, and each section can have an unlimited amount of icons. Visually, the grid layout works better when sections have a similar number of icons. +The main content in Dashy is defined as an array of sections, each of which contains an array of items. You can have as many sections as you need, and each section can have an unlimited amount of items. If you are using the grid layout, then it works better, visually if each of your sections have similar number of items. Sections are collapsible, which is useful for those sections which contain less used applications, or are particularly long. The collapse state of a given section is remembered (stored in local storage), and applied on load. @@ -73,22 +96,30 @@ Sections also have several optional properties, which are specified under `secti └─────────────────────────────────────────────────────┘ ``` +**[⬆️ Back to Top](#user-guide)** + ### Icons -Both sections and items can have an icon associated with them. There are several options for specifying icons. You can let the icon be automatically resolved and fetched from the items associated URL, by just setting the icon to `favicon`. You can use a font-awesome icon, by specifying it's name and category. Or you can pass in a URL, either to a locally hosted or remote image. For local images, you can put them in `./public/item-icons/` and then reference them just by the file name. +Both sections and items can have an icon associated with them. There are several options for specifying icons. You can let the icon be automatically resolved and fetched from the items associated URL, by setting it's value to `favicon`. You can use a font-awesome icon, by specifying it's name and category, e.g. `fas fa-rocket`. Or you can pass in a URL, either to a locally hosted or remote image. For local images, you can put them in `./public/item-icons/` and then reference them just by the file name. + +**[⬆️ Back to Top](#user-guide)** ### Metadata Basic site information, displayed in the header and footer can be set from the UI. This includes: title, sub-title, footer text, and nav-bar links. Click the wrench icon in the upper-right corner, then go to the Site Metadata tab. Fill in your new data, and hit save. The page will be refreshed, and your changes will appear. These settings are stored under `pageInfo` in the config, and if set through the UI, will only be applied locally. +**[⬆️ Back to Top](#user-guide)** + ### Editing Config The config file can be edited from the UI, but take note that changes are only applied locally. You will need to either export this data into your conf.yml, or use the cloud backup and sync feature. To make changes to the config file, click the wrench icon in the upper-left hand corner. Then go to the Config tab. Here you'll find a JSON editor. You can switch from tree mode to plain-text mode if you find that easier. And parsing or validation issues will be displayed at the bottom of the screen. +**[⬆️ Back to Top](#user-guide)** + ### Managing Config Data You can download, backup or reset local config data directly from the UI. To apply config to Dashy on other devices, you will need to either download the config file, or use the cloud backup and sync feature. To download config, click the Wrench icon, in the upper-right hand corner, and then go to Download. Similarly, for cloud backup, click the Cloud icon in the upper right corner, and fill in the required fields. For detailed instructions, and technical information about backup and sync, please see the [Cloud Backup Documentation](/docs/backup-restore.md). You can also Reset all local settings from the config menu. This will not effect any data saved in your systems `conf.yml` file. - +**[⬆️ Back to Top](#user-guide)** diff --git a/package.json b/package.json index e70245f1..a812fda0 100644 --- a/package.json +++ b/package.json @@ -1,27 +1,29 @@ { "name": "Dashy", - "version": "0.1.0", + "version": "1.3.9", "license": "MIT", "main": "server", "scripts": { "start": "node server", "dev": "vue-cli-service serve", "build": "vue-cli-service build", - "lint": "vue-cli-service lint --fix", - "build-watch": "vue-cli-service build --watch", - "build-and-start": "npm-run-all --parallel build start", + "lint": "vue-cli-service lint", + "pm2-start": "npx pm2 start server.js", + "build-watch": "vue-cli-service build --watch --mode production", + "build-and-start": "npm-run-all --parallel build-watch start", "validate-config": "node src/utils/ConfigValidator", - "health-check": "node bin/healthcheck" + "health-check": "node services/healthcheck" }, "dependencies": { "ajv": "^8.5.0", "axios": "^0.21.1", + "body-parser": "^1.19.0", "connect": "^3.7.0", "crypto-js": "^4.0.0", "highlight.js": "^11.0.0", "js-yaml": "^4.1.0", "npm-run-all": "^4.1.5", - "prismjs": "^1.23.0", + "prismjs": "^1.24.1", "register-service-worker": "^1.6.2", "remedial": "^1.0.8", "serve-static": "^1.14.1", @@ -30,7 +32,7 @@ "vue": "^2.6.10", "vue-cli-plugin-yaml": "^1.0.2", "vue-js-modal": "^2.0.0-rc.6", - "vue-material-tabs": "^0.0.7", + "vue-material-tabs": "^0.1.2", "vue-prism-editor": "^1.2.2", "vue-router": "^3.0.3", "vue-select": "^3.11.2", @@ -46,10 +48,12 @@ "eslint": "^7.24.0", "eslint-config-airbnb": "^18.0.1", "eslint-plugin-vue": "^7.9.0", + "progress-bar-webpack-plugin": "^2.1.0", "sass": "^1.18.0", "sass-loader": "^7.1.0", "vue-svg-loader": "^0.16.0", - "vue-template-compiler": "^2.6.10" + "vue-template-compiler": "^2.6.10", + "webpack-build-notifier": "^2.3.0" }, "gitHooks": { "pre-commit": "yarn lint" diff --git a/public/favicon.ico b/public/favicon.ico index 638b826f..8352d15b 100644 Binary files a/public/favicon.ico and b/public/favicon.ico differ diff --git a/public/fonts/AllertaStencil-Regular.ttf b/public/fonts/AllertaStencil-Regular.ttf new file mode 100644 index 00000000..f8104ecf Binary files /dev/null and b/public/fonts/AllertaStencil-Regular.ttf differ diff --git a/public/fonts/Audiowide-Regular.ttf b/public/fonts/Audiowide-Regular.ttf new file mode 100644 index 00000000..e5d242b3 Binary files /dev/null and b/public/fonts/Audiowide-Regular.ttf differ diff --git a/public/fonts/CutiveMono-Regular.ttf b/public/fonts/CutiveMono-Regular.ttf new file mode 100644 index 00000000..e5bcf884 Binary files /dev/null and b/public/fonts/CutiveMono-Regular.ttf differ diff --git a/public/fonts/FrancoisOne-Regular.ttf b/public/fonts/FrancoisOne-Regular.ttf new file mode 100644 index 00000000..7d646fa1 Binary files /dev/null and b/public/fonts/FrancoisOne-Regular.ttf differ diff --git a/public/fonts/Podkova-Medium.ttf b/public/fonts/Podkova-Medium.ttf new file mode 100644 index 00000000..c5e5bf1e Binary files /dev/null and b/public/fonts/Podkova-Medium.ttf differ diff --git a/public/fonts/Roboto-Light.ttf b/public/fonts/Roboto-Light.ttf new file mode 100644 index 00000000..0e977514 Binary files /dev/null and b/public/fonts/Roboto-Light.ttf differ diff --git a/public/fonts/Sniglet-Regular.ttf b/public/fonts/Sniglet-Regular.ttf new file mode 100644 index 00000000..f62bffe1 Binary files /dev/null and b/public/fonts/Sniglet-Regular.ttf differ diff --git a/public/fonts/VT323-Regular.ttf b/public/fonts/VT323-Regular.ttf new file mode 100644 index 00000000..e8385811 Binary files /dev/null and b/public/fonts/VT323-Regular.ttf differ diff --git a/public/index.html b/public/index.html index c6fb3383..4a291177 100644 --- a/public/index.html +++ b/public/index.html @@ -7,7 +7,8 @@ - + + Dashy diff --git a/public/manifest.json b/public/manifest.json index 1c006cc5..a0447af2 100644 --- a/public/manifest.json +++ b/public/manifest.json @@ -1,6 +1,14 @@ { - "name": "Dashy", + "name": "Dashy Web", "short_name": "Dashy", + "description": "A Dashboard for your Homelab", + "scope": "/", + "start_url": "./index.html", + "display": "standalone", + "background_color": "#0b1021", + "theme_color": "#4DBA87", + "lang": "en-GB", + "orientation": "portrait-primary", "icons": [ { "src": "./web-icons/windows10/SmallTile.scale-100.png", @@ -507,8 +515,42 @@ "sizes": "16x16" } ], - "start_url": "./index.html", - "display": "standalone", - "background_color": "#0b1021", - "theme_color": "#4DBA87" + "screenshots": [ + { + "src": "./web-icons/screenshots/dashy-scrsht-1.png", + "sizes": "1523x1347", + "type": "image/png", + "label": "Dashy example homelab with Callisto theme" + }, + { + "src": "./web-icons/screenshots/dashy-scrsht-2.png", + "sizes": "1264x861", + "type": "image/png", + "label": "Example, Networking services with Minimal Dark theme and a Horizontal layout" + }, + { + "src": "./web-icons/screenshots/dashy-scrsht-3.png", + "sizes": "1303x864", + "type": "image/png", + "label": "Dashy example homelab with Material theme and auto-fetched favicons" + }, + { + "src": "./web-icons/screenshots/dashy-scrsht-4.png", + "sizes": "1273x865", + "type": "image/png", + "label": "Dashy CFT Toolbox using Matrix theme" + }, + { + "src": "./web-icons/screenshots/dashy-scrsht-5.png", + "sizes": "1146x851", + "type": "image/png", + "label": "Dashy as a Bookmark Manager, with Dracula theme and Font-Awesome icons" + }, + { + "src": "./web-icons/screenshots/dashy-scrsht-6.png", + "sizes": "1147x872", + "type": "image/png", + "label": "Dashy example homelab with Nord theme" + } + ] } \ No newline at end of file diff --git a/public/web-icons/dashy-logo.png b/public/web-icons/dashy-logo.png new file mode 100644 index 00000000..78fabd25 Binary files /dev/null and b/public/web-icons/dashy-logo.png differ diff --git a/public/web-icons/favicon-32x32.png b/public/web-icons/favicon-32x32.png new file mode 100644 index 00000000..1c0a2979 Binary files /dev/null and b/public/web-icons/favicon-32x32.png differ diff --git a/public/web-icons/favicon-64x64.png b/public/web-icons/favicon-64x64.png new file mode 100644 index 00000000..369f1c60 Binary files /dev/null and b/public/web-icons/favicon-64x64.png differ diff --git a/public/web-icons/screenshots/dashy-scrsht-1.png b/public/web-icons/screenshots/dashy-scrsht-1.png new file mode 100644 index 00000000..d5f3cd3f Binary files /dev/null and b/public/web-icons/screenshots/dashy-scrsht-1.png differ diff --git a/public/web-icons/screenshots/dashy-scrsht-2.png b/public/web-icons/screenshots/dashy-scrsht-2.png new file mode 100644 index 00000000..bfaab618 Binary files /dev/null and b/public/web-icons/screenshots/dashy-scrsht-2.png differ diff --git a/public/web-icons/screenshots/dashy-scrsht-3.png b/public/web-icons/screenshots/dashy-scrsht-3.png new file mode 100644 index 00000000..605a520c Binary files /dev/null and b/public/web-icons/screenshots/dashy-scrsht-3.png differ diff --git a/public/web-icons/screenshots/dashy-scrsht-4.png b/public/web-icons/screenshots/dashy-scrsht-4.png new file mode 100644 index 00000000..a728a8a9 Binary files /dev/null and b/public/web-icons/screenshots/dashy-scrsht-4.png differ diff --git a/public/web-icons/screenshots/dashy-scrsht-5.png b/public/web-icons/screenshots/dashy-scrsht-5.png new file mode 100644 index 00000000..9a61a2dc Binary files /dev/null and b/public/web-icons/screenshots/dashy-scrsht-5.png differ diff --git a/public/web-icons/screenshots/dashy-scrsht-6.png b/public/web-icons/screenshots/dashy-scrsht-6.png new file mode 100644 index 00000000..8402f0a1 Binary files /dev/null and b/public/web-icons/screenshots/dashy-scrsht-6.png differ diff --git a/server.js b/server.js index 9bdbca41..102cbb25 100644 --- a/server.js +++ b/server.js @@ -1,74 +1,92 @@ -/* eslint-disable no-console */ -/* This is a simple Node.js http server, that is used to serve up the contents of ./dist */ -const connect = require('connect'); -const serveStatic = require('serve-static'); +/** + * Note: The app must first be built (yarn build) before this script is run + * This is the main entry point for the application, a simple server that + * runs some checks, and then serves up the app from the ./dist directory + * Also includes some routes for status checks/ ping and config saving + * */ +/* Include required node dependencies */ +const serveStatic = require('serve-static'); +const connect = require('connect'); const util = require('util'); const dns = require('dns'); const os = require('os'); +const bodyParser = require('body-parser'); -require('./src/utils/ConfigValidator'); +/* Include helper functions and route handlers */ +const pingUrl = require('./services/ping'); // Used by the status check feature, to ping services +const saveConfig = require('./services/save-config'); // Saves users new conf.yml to file-system +const printMessage = require('./services/print-message'); // Function to print welcome msg on start +const rebuild = require('./services/rebuild-app'); // A script to programmatically trigger a build +require('./src/utils/ConfigValidator'); // Include and kicks off the config file validation script +/* Checks if app is running within a container, from env var */ const isDocker = !!process.env.IS_DOCKER; /* Checks env var for port. If undefined, will use Port 80 for Docker, or 4000 for metal */ const port = process.env.PORT || (isDocker ? 80 : 4000); +/* Attempts to get the users local IP, used as part of welcome message */ const getLocalIp = () => { const dnsLookup = util.promisify(dns.lookup); return dnsLookup(os.hostname()); }; -const overComplicatedMessage = (ip) => { - let msg = ''; - const chars = { - RESET: '\x1b[0m', - CYAN: '\x1b[36m', - GREEN: '\x1b[32m', - BLUE: '\x1b[34m', - BRIGHT: '\x1b[1m', - BR: '\n', - }; - const stars = (count) => new Array(count).fill('*').join(''); - const line = (count) => new Array(count).fill('━').join(''); - const blanks = (count) => new Array(count).fill(' ').join(''); - if (isDocker) { - const containerId = process.env.HOSTNAME || undefined; - msg = `${chars.BLUE}${stars(91)}${chars.BR}${chars.RESET}` - + `${chars.CYAN}Welcome to Dashy! 🚀${chars.RESET}${chars.BR}` - + `${chars.GREEN}Your new dashboard is now up and running ` - + `${containerId ? `in container ID ${containerId}` : 'with Docker'}${chars.BR}` - + `${chars.GREEN}After updating your config file, run ` - + `'${chars.BRIGHT}docker exec -it ${containerId || '[container-id]'} yarn build` - + `${chars.RESET}${chars.GREEN}' to rebuild${chars.BR}` - + `${chars.BLUE}${stars(91)}${chars.BR}${chars.RESET}`; - } else { - msg = `${chars.GREEN}┏${line(75)}┓${chars.BR}` - + `┃ ${chars.CYAN}Welcome to Dashy! 🚀${blanks(55)}${chars.GREEN}┃${chars.BR}` - + `┃ ${chars.CYAN}Your new dashboard is now up and running at ${chars.BRIGHT}` - + `http://${ip}:${port}${chars.RESET}${blanks(18 - ip.length)}${chars.GREEN}┃${chars.BR}` - + `┃ ${chars.CYAN}After updating your config file, run '${chars.BRIGHT}yarn build` - + `${chars.RESET}${chars.CYAN}' to rebuild the app${blanks(6)}${chars.GREEN}┃${chars.BR}` - + `┗${line(75)}┛${chars.BR}${chars.BR}`; - } - return msg; -}; - -/* eslint no-console: 0 */ +/* Gets the users local IP and port, then calls to print welcome message */ const printWelcomeMessage = () => { getLocalIp().then(({ address }) => { const ip = address || 'localhost'; - console.log(overComplicatedMessage(ip)); + console.log(printMessage(ip, port, isDocker)); // eslint-disable-line no-console }); }; +/* Just console.warns an error */ +const printWarning = (msg, error) => { + console.warn(`\x1b[103m\x1b[34m${msg}\x1b[0m\n`, error || ''); // eslint-disable-line no-console +}; + +/* A middleware function for Connect, that filters requests based on method type */ +const method = (m, mw) => (req, res, next) => (req.method === m ? mw(req, res, next) : next()); + try { connect() + .use(bodyParser.json()) + // Serves up the main built application to the root .use(serveStatic(`${__dirname}/dist`)) + // During build, a custom page will be served before the app is available .use(serveStatic(`${__dirname}/public`, { index: 'default.html' })) + // This root returns the status of a given service - used for uptime monitoring + .use('/ping', (req, res) => { + try { + pingUrl(req.url, async (results) => { + await res.end(results); + }); + } catch (e) { + printWarning(`Error running ping check for ${req.url}\n`, e); + } + }) + // POST Endpoint used to save config, by writing conf.yml to disk + .use('/config-manager/save', method('POST', (req, res) => { + try { + saveConfig(req.body, (results) => { + res.end(results); + }); + } catch (e) { + res.end(JSON.stringify({ success: false, message: e })); + } + })) + // GET endpoint to trigger a build, and respond with success status and output + .use('/config-manager/rebuild', (req, res) => { + rebuild().then((response) => { + res.end(JSON.stringify(response)); + }).catch((response) => { + res.end(JSON.stringify(response)); + }); + }) + // Finally, initialize the server then print welcome message .listen(port, () => { - try { printWelcomeMessage(); } catch (e) { console.log('Dashy is Starting...'); } + try { printWelcomeMessage(); } catch (e) { printWarning('Dashy is Starting...'); } }); } catch (error) { - console.log('Sorry, an error occurred ', error); + printWarning('Sorry, a critical error occurred ', error); } diff --git a/bin/healthcheck.js b/services/healthcheck.js similarity index 76% rename from bin/healthcheck.js rename to services/healthcheck.js index e315a14b..f9540ad0 100644 --- a/bin/healthcheck.js +++ b/services/healthcheck.js @@ -1,37 +1,36 @@ -/** - * An endpoint for confirming that the application is up and running - * Used for better Docker healthcheck results - * Note that exiting with code 1 indicates failure, and 0 is success - */ - -const http = require('http'); - -/* Location of the server to test */ -const port = process.env.PORT || !!process.env.IS_DOCKER ? 80 : 4000; -const host = process.env.HOST || '0.0.0.0'; -const timeout = 2000; - -const requestOptions = { host, port, timeout }; - -const startTime = new Date(); - -console.log(`[${startTime}] Running health check...`); - -/* Starts quick HTTP server, attempts to send GET to app, then exists with appropriate exit code */ -const healthCheck = http.request(requestOptions, (response) => { - const totalTime = (new Date() - startTime) / 1000; - const status = response.statusCode; - const color = status === 200 ? '\x1b[32m' : '\x1b[31m'; - const message = `${color}Status: ${status}\nRequest took ${totalTime} seconds\n\x1b[0m---`; - console.log(message); - if (status == 200) { process.exit(0); } - else { process.exit(1); } -}); - -/* If the server is not running, then print the error code, and exit with 1 */ -healthCheck.on('error', (err) => { - console.error(`\x1b[31mHealthceck Failed, Error: ${'\033[4m'}${err.code}\x1b[0m`); - process.exit(1); -}); - -healthCheck.end(); \ No newline at end of file +/** + * An endpoint for confirming that the application is up and running + * Used for better Docker healthcheck results + * Note that exiting with code 1 indicates failure, and 0 is success + */ + +const http = require('http'); + +/* Location of the server to test */ +const port = process.env.PORT || !!process.env.IS_DOCKER ? 80 : 4000; +const host = process.env.HOST || '0.0.0.0'; +const timeout = 2000; + +const requestOptions = { host, port, timeout }; + +const startTime = new Date(); // Initialize timestamp to calculate time taken + +console.log(`[${startTime}] Running health check...`); + +/* Starts quick HTTP server, attempts to send GET to app, then exists with appropriate exit code */ +const healthCheck = http.request(requestOptions, (response) => { + const totalTime = (new Date() - startTime) / 1000; + const status = response.statusCode; + const color = status === 200 ? '\x1b[32m' : '\x1b[31m'; + const message = `${color}Status: ${status}\nRequest took ${totalTime} seconds\n\x1b[0m---`; + console.log(message); // Print out healthcheck response + process.exit(status === 200 ? 0 : 1); // Exit with 0 (success), if response is 200 okay +}); + +/* If the server is not running, then print the error code, and exit with 1 */ +healthCheck.on('error', (err) => { + console.error(`\x1b[31mHealthceck Failed, Error: ${'\x1b[33m'}${err.code}\x1b[0m`); + process.exit(1); +}); + +healthCheck.end(); diff --git a/services/ping.js b/services/ping.js new file mode 100644 index 00000000..35e273e2 --- /dev/null +++ b/services/ping.js @@ -0,0 +1,66 @@ +/** + * This file contains the Node.js code, used for the optional status check feature + * It accepts a single url parameter, and will make an empty GET request to that + * endpoint, and then resolve the response status code, time taken, and short message + */ +const axios = require('axios').default; + +/* Determines if successful from the HTTP response code */ +const getResponseType = (code) => { + if (Number.isNaN(code)) return false; + const numericCode = parseInt(code, 10); + return (numericCode >= 200 && numericCode <= 302); +}; + +/* Makes human-readable response text for successful check */ +const makeMessageText = (data) => `${data.successStatus ? '✅' : '⚠️'} ` + + `${data.serverName || 'Server'} responded with ` + + `${data.statusCode} - ${data.statusText}. ` + + `\n⏱️Took ${data.timeTaken} ms`; + +/* Makes human-readable response text for failed check */ +const makeErrorMessage = (data) => `❌ Service Unavailable: ${data.hostname || 'Server'} ` + + `resulted in ${data.code || 'a fatal error'} ${data.errno ? `(${data.errno})` : ''}`; + +const makeErrorMessage2 = (data) => '❌ Service Error - ' + + `${data.status} - ${data.statusText}`; + +/* Kicks of a HTTP request, then formats and renders results */ +const makeRequest = (url, render) => { + const startTime = new Date(); + axios.get(url) + .then((response) => { + const statusCode = response.status; + const { statusText } = response; + const successStatus = getResponseType(statusCode); + const serverName = response.request.socket.servername; + const timeTaken = (new Date() - startTime); + const results = { + statusCode, statusText, serverName, successStatus, timeTaken, + }; + const messageText = makeMessageText(results); + results.message = messageText; + return results; + }) + .catch((error) => { + render(JSON.stringify({ + successStatus: false, + message: error.response ? makeErrorMessage2(error.response) : makeErrorMessage(error), + })); + }).then((results) => { + render(JSON.stringify(results)); + }); +}; + +/* Main function, will check if a URL present, and call function */ +module.exports = (params, render) => { + if (!params || !params.includes('=')) { + render(JSON.stringify({ + success: false, + message: '❌ Malformed URL', + })); + } else { + const url = params.split('=')[1]; + makeRequest(url, render); + } +}; diff --git a/services/print-message.js b/services/print-message.js new file mode 100644 index 00000000..d7d19ed0 --- /dev/null +++ b/services/print-message.js @@ -0,0 +1,55 @@ +/** + * Returns a welcome message, to be printed to the user when they start the app + * Contains essential info about restarting and managing the container or service + * @param String ip: The users local IP address or hostname + * @param Integer port: the port number that the app is running at + * @param Boolean isDocker: whether or not the app is being run within a container + * @returns A string formatted for the terminal + */ +module.exports = (ip, port, isDocker) => { + let msg = ''; // To return + const chars = { // Color codes used in the message + RESET: '\x1b[0m', + CYAN: '\x1b[36m', + GREEN: '\x1b[32m', + BLUE: '\x1b[34m', + BRIGHT: '\x1b[1m', + BR: '\n', + }; + // Functions to insert string of set length of characters + const printChars = (count, char) => new Array(count).fill(char).join(''); + const stars = (count) => printChars(count, '*'); + const line = (count) => printChars(count, '━'); + const blanks = (count) => printChars(count, ' '); + if (isDocker) { + // Prepare message for Docker users + const containerId = process.env.HOSTNAME || undefined; + msg = `${chars.BLUE}${stars(91)}${chars.BR}${chars.RESET}` + + `${chars.CYAN}Welcome to Dashy! 🚀${chars.RESET}${chars.BR}` + + `${chars.GREEN}Your new dashboard is now up and running ` + + `${containerId ? `in container ID ${containerId}` : 'with Docker'}${chars.BR}` + + `${chars.GREEN}After updating your config file, run ` + + `'${chars.BRIGHT}docker exec -it ${containerId || '[container-id]'} yarn build` + + `${chars.RESET}${chars.GREEN}' to rebuild${chars.BR}` + + `${chars.BLUE}${stars(91)}${chars.BR}${chars.RESET}`; + } else { + // Prepare message for users running app on bare metal + msg = `${chars.GREEN}┏${line(75)}┓${chars.BR}` + + `┃ ${chars.CYAN}Welcome to Dashy! 🚀${blanks(55)}${chars.GREEN}┃${chars.BR}` + + `┃ ${chars.CYAN}Your new dashboard is now up and running at ${chars.BRIGHT}` + + `http://${ip}:${port}${chars.RESET}${blanks(18 - ip.length)}${chars.GREEN}┃${chars.BR}` + + `┃ ${chars.CYAN}After updating your config file, run '${chars.BRIGHT}yarn build` + + `${chars.RESET}${chars.CYAN}' to rebuild the app${blanks(6)}${chars.GREEN}┃${chars.BR}` + + `┗${line(75)}┛${chars.BR}${chars.BR}${chars.RESET}`; + } + // Make some sexy ascii art ;) + const ascii = `\x1b[40m${chars.CYAN}\n\n` + + ' ██████╗ █████╗ ███████╗██╗ ██╗██╗ ██╗\n' + + ' ██╔══██╗██╔══██╗██╔════╝██║ ██║╚██╗ ██╔╝\n' + + ' ██║ ██║███████║███████╗███████║ ╚████╔╝\n' + + ' ██║ ██║██╔══██║╚════██║██╔══██║ ╚██╔╝\n' + + ' ██████╔╝██║ ██║███████║██║ ██║ ██║\n' + + ` ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝\n${chars.RESET}\n`; + + return ascii + msg; +}; diff --git a/services/rebuild-app.js b/services/rebuild-app.js new file mode 100644 index 00000000..b3ce046c --- /dev/null +++ b/services/rebuild-app.js @@ -0,0 +1,34 @@ +/** + * This script programmatically triggers a production build + * and responds with the status, message and full output + */ +const { exec } = require('child_process'); + +module.exports = () => new Promise((resolve, reject) => { + const buildProcess = exec('npm run build'); // Trigger the build command + + let output = ''; // Will store console output + + // Write output to console, and append to var for returning + buildProcess.stdout.on('data', (data) => { + process.stdout.write(data); + output += data; + }); + + // Handle errors, by sending the reject + buildProcess.on('error', (error) => { + reject(Error({ + success: false, + error, + output, + })); + }); + + // When finished, check success, make message and resolve response + buildProcess.on('exit', (response) => { + const success = response === 0; + const message = `Build process exited with ${response}: ` + + `${success ? 'Success' : 'Possible Error'}`; + resolve({ success, message, output }); + }); +}); diff --git a/services/save-config.js b/services/save-config.js new file mode 100644 index 00000000..bc74c201 --- /dev/null +++ b/services/save-config.js @@ -0,0 +1,52 @@ +/** + * This file exports a function, used by the write config endpoint. + * It will make a backup of the users conf.yml file + * and then write their new config into the main conf.yml file. + * Finally, it will call a function with the status message + */ +const fsPromises = require('fs').promises; + +module.exports = async (newConfig, render) => { + // Define constants for the config file + const settings = { + defaultLocation: './public/', + defaultFile: 'conf.yml', + filename: 'conf', + backupDenominator: '.backup.yml', + }; + + // Make the full file name and path to save the backup config file + const backupFilePath = `${settings.defaultLocation}${settings.filename}-` + + `${Math.round(new Date() / 1000)}${settings.backupDenominator}`; + + // The path where the main conf.yml should be read and saved to + const defaultFilePath = settings.defaultLocation + settings.defaultFile; + + // Returns a string confirming successful job + const getSuccessMessage = () => `Successfully backed up ${settings.defaultFile} to` + + ` ${backupFilePath}, and updated the contents of ${defaultFilePath}`; + + // Encoding options for writing to conf file + const writeFileOptions = { encoding: 'utf8' }; + + // Prepare the response returned by the API + const getRenderMessage = (success, errorMsg) => JSON.stringify({ + success, + message: !success ? errorMsg : getSuccessMessage(), + }); + + // Makes a backup of the existing config file + await fsPromises.copyFile(defaultFilePath, backupFilePath) + .catch((error) => { + render(getRenderMessage(false, `Unable to backup conf.yml: ${error}`)); + }); + + // Writes the new content to the conf.yml file + await fsPromises.writeFile(defaultFilePath, newConfig.config.toString(), writeFileOptions) + .catch((error) => { + render(getRenderMessage(false, `Unable to write changes to conf.yml: ${error}`)); + }); + + // If successful, then render hasn't yet been called- call it + await render(getRenderMessage(true)); +}; diff --git a/src/App.vue b/src/App.vue index 2598f68a..806c33e4 100644 --- a/src/App.vue +++ b/src/App.vue @@ -3,7 +3,7 @@
-