├── .github └── workflows │ └── docker-publish.yml ├── Dockerfile ├── LICENSE ├── README.md ├── docker-compose.yml ├── entrypoint.sh ├── headscale.py ├── helper.py ├── poetry.lock ├── pyproject.toml ├── renderer.py ├── requirements.txt ├── screenshots ├── key_test.png ├── machine_add.png ├── machines-page.JPG ├── machines.png └── users.png ├── server.py ├── static ├── LICENSE ├── README.md ├── css │ ├── materialize.css │ ├── materialize.min.css │ └── overrides.css ├── img │ ├── favicon │ │ ├── android-icon-144x144.png │ │ ├── android-icon-192x192.png │ │ ├── android-icon-36x36.png │ │ ├── android-icon-48x48.png │ │ ├── android-icon-72x72.png │ │ ├── android-icon-96x96.png │ │ ├── apple-icon-114x114.png │ │ ├── apple-icon-120x120.png │ │ ├── apple-icon-144x144.png │ │ ├── apple-icon-152x152.png │ │ ├── apple-icon-180x180.png │ │ ├── apple-icon-57x57.png │ │ ├── apple-icon-60x60.png │ │ ├── apple-icon-72x72.png │ │ ├── apple-icon-76x76.png │ │ ├── apple-icon-precomposed.png │ │ ├── apple-icon.png │ │ ├── browserconfig.xml │ │ ├── favicon-16x16.png │ │ ├── favicon-32x32.png │ │ ├── favicon-96x96.png │ │ ├── favicon.ico │ │ ├── manifest.json │ │ ├── ms-icon-144x144.png │ │ ├── ms-icon-150x150.png │ │ ├── ms-icon-310x310.png │ │ └── ms-icon-70x70.png │ └── headscale3-dots.png ├── js │ ├── custom.js │ ├── jquery-2.2.4.min.js │ ├── materialize.js │ └── materialize.min.js └── old │ ├── css │ └── cirrus.min.css │ └── js │ └── iconify-icon.min.js └── templates ├── machines.html ├── machines_card.html ├── overview.html ├── settings.html ├── template.html ├── users.html └── users_card.html /.github/workflows/docker-publish.yml: -------------------------------------------------------------------------------- 1 | name: Docker 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | # Publish semver tags as releases. 7 | tags: [ 'v*.*.*' ] 8 | # Run on manual trigger 9 | workflow_dispatch: 10 | env: 11 | # Use docker.io for Docker Hub if empty 12 | REGISTRY: ghcr.io 13 | # github.repository as / 14 | IMAGE_NAME: ${{ github.repository }} 15 | 16 | 17 | jobs: 18 | build: 19 | 20 | runs-on: ubuntu-latest 21 | permissions: 22 | contents: read 23 | packages: write 24 | # This is used to complete the identity challenge 25 | # with sigstore/fulcio when running outside of PRs. 26 | id-token: write 27 | 28 | steps: 29 | - name: Checkout repository 30 | uses: actions/checkout@v3 31 | 32 | # Workaround: https://github.com/docker/build-push-action/issues/461 33 | - name: Setup Docker buildx 34 | uses: docker/setup-buildx-action@79abd3f86f79a9d68a23c75a09a9a85889262adf 35 | 36 | # Login against a Docker registry except on PR 37 | # https://github.com/docker/login-action 38 | - name: Log into registry ${{ env.REGISTRY }} 39 | if: github.event_name != 'pull_request' 40 | uses: docker/login-action@28218f9b04b4f3f62068d7b6ce6ca5b26e35336c 41 | with: 42 | registry: ${{ env.REGISTRY }} 43 | username: ${{ github.actor }} 44 | password: ${{ secrets.GITHUB_TOKEN }} 45 | 46 | # Extract metadata (tags, labels) for Docker 47 | # https://github.com/docker/metadata-action 48 | - name: Extract Docker metadata 49 | id: meta 50 | uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38 51 | with: 52 | images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} 53 | 54 | # Build and push Docker image with Buildx (don't push on PR) 55 | # https://github.com/docker/build-push-action 56 | - name: Build and push Docker image 57 | id: build-and-push 58 | uses: docker/build-push-action@ac9327eae2b366085ac7f6a2d02df8aa8ead720a 59 | with: 60 | context: . 61 | push: ${{ github.event_name != 'pull_request' }} 62 | tags: ${{ steps.meta.outputs.tags }} 63 | labels: ${{ steps.meta.outputs.labels }} 64 | cache-from: type=gha 65 | cache-to: type=gha,mode=max 66 | 67 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Global ARG, available to all stages (if renewed) 2 | ARG WORKDIR="/app" 3 | FROM python:3.11-alpine AS builder 4 | 5 | # Renew (https://stackoverflow.com/a/53682110): 6 | ARG WORKDIR 7 | 8 | # Don't buffer `stdout`: 9 | ENV PYTHONUNBUFFERED=1 10 | # Don't create `.pyc` files: 11 | ENV PYTHONDONTWRITEBYTECODE=1 12 | 13 | 14 | 15 | RUN pip install poetry && poetry config virtualenvs.in-project true 16 | 17 | 18 | 19 | WORKDIR ${WORKDIR} 20 | 21 | COPY --chown=1000:1000 . . 22 | 23 | # Install dependencies globally with poetry 24 | RUN poetry install --only main 25 | 26 | FROM python:3.11-alpine 27 | 28 | ARG WORKDIR 29 | 30 | WORKDIR ${WORKDIR} 31 | 32 | RUN adduser app -DHh ${WORKDIR} -u 1000 33 | USER 1000 34 | 35 | COPY --chown=app:app --from=builder ${WORKDIR} . 36 | 37 | 38 | ENV TZ="UTC" 39 | ENV HS_SERVER="http://localhost/" 40 | ENV KEY="" 41 | ENV BASE_PATH="http://127.0.0.1/" 42 | 43 | 44 | 45 | VOLUME /headscale 46 | VOLUME /data 47 | 48 | EXPOSE 5000/tcp 49 | 50 | ENTRYPOINT ["/app/entrypoint.sh"] 51 | 52 | CMD gunicorn -w 4 -b 0.0.0.0:5000 server:app -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | AFFERO GENERAL PUBLIC LICENSE 2 | Version 1, March 2002 Copyright © 2002 Affero Inc. 3 | 510 Third Street - Suite 225, San Francisco, CA 94107, USA 4 | This license is a modified version of the GNU General Public License copyright (C) 1989, 1991 Free Software Foundation, Inc. made with their permission. Section 2(d) has been added to cover use of software over a computer network. 5 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 6 | Preamble 7 | The licenses for most software are designed to take away your freedom to share and change it. By contrast, the Affero General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This Public License applies to most of Affero's software and to any other program whose authors commit to using it. (Some other Affero software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. 8 | When we speak of free software, we are referring to freedom, not price. This General Public License is designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. 9 | To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. 10 | For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. 11 | We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. 12 | Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. 13 | Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. 14 | The precise terms and conditions for copying, distribution and modification follow. 15 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 16 | 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this Affero General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". 17 | Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 18 | 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. 19 | You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 20 | 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: 21 | a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. 22 | b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. 23 | c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) 24 | d) If the Program as you received it is intended to interact with users through a computer network and if, in the version you received, any user interacting with the Program was given the opportunity to request transmission to that user of the Program's complete source code, you must not remove that facility from your modified version of the Program or work based on the Program, and must offer an equivalent opportunity for all users interacting with your Program through a computer network to request immediate transmission by HTTP of the complete source code of your modified version or other derivative work. 25 | These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. 26 | Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. 27 | In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 28 | 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: 29 | a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, 30 | b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, 31 | c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) 32 | The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. 33 | If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 34 | 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 35 | 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 36 | 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 37 | 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. 38 | If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. 39 | It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. 40 | This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 41 | 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 42 | 9. Affero Inc. may publish revised and/or new versions of the Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 43 | Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by Affero, Inc. If the Program does not specify a version number of this License, you may choose any version ever published by Affero, Inc. 44 | You may also choose to redistribute modified versions of this program under any version of the Free Software Foundation's GNU General Public License version 3 or higher, so long as that version of the GNU GPL includes terms and conditions substantially equivalent to those of this license. 45 | 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by Affero, Inc., write to us; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. 46 | NO WARRANTY 47 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 48 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # headscale-webui 2 | * This is just a simple front-end for a Headscale server. Allows you to do the following: 3 | 1. Enable/Disable routes and exit nodes 4 | 2. Add, move, rename, and remove machines 5 | 3. Add and remove users/namespaces 6 | 4. Add and expire PreAuth keys 7 | 5. Add and remove machine tags 8 | 6. View machine details (last online, IP addresses, hsotname, PreAuth key in use, enabled/disabled routes, and tags) 9 | 10 | Screenshots: 11 | 12 | ![Machines](screenshots/machines.png) 13 | ![Users](screenshots/users.png) 14 | ![Add a new machine](screenshots/machine_add.png) 15 | ![Machine Details](screenshots/machines-page.JPG) 16 | ![API Key Test](screenshots/key_test.png) 17 | 18 | 19 | ## Installation: 20 | 1. This assumes you have traefik as your reverse proxy. I'm sure it will work with others, but I don't have experience with any. 21 | 2. Change the following variables in docker-compose.yml: 22 | 1. TZ - Change to your timezone. Example: Asia/Tokyo 23 | 2. HS_SERVER - Change to your headscale's URL 24 | 3. BASE_PATH - This will be the path your server is served on. Because the GUI expects , I usually put this as "/admin" 25 | 4. KEY - Your encryption key to store your headscale API key on disk. Generate a new one with "openssl rand -base64 32". Do not forget the quotations around the key when entering. 26 | 3. You will also need to change the volumes: 27 | 1. /data - Where your encryption key will reside. Can be anywhere 28 | 2. /etc/headscale/ - This is your Headscale configuration file. 29 | 4. Update the build context location to the directory with the Dockerfile. 30 | 1. Example: If Dockerfile is in /home/username/headscale-webui, your context will be: 31 | * `context: /home/username/headscale-webui/` 32 | 33 | ## Traefik 34 | * This was built assuming the use of the Traefik reverse proxy. 35 | * Exmaple config: 36 | ``` 37 | labels: 38 | # Traefik Configs 39 | - "traefik.enable=true" 40 | - "traefik.http.routers.headscale-webui.entrypoints=web-secure" 41 | - "traefik.http.routers.headscale-webui.rule=Host(`headscale.$DOMAIN`) && (PathPrefix(`/admin/`) || PathPrefix(`/admin`))" 42 | - "traefik.http.services.headscale-webui.loadbalancer.server.port=5000" 43 | - "traefik.http.routers.headscale-webui.tls.certresolver=letsencrypt" 44 | # redirect /admin to / 45 | - "traefik.http.middlewares.headscale-webui-stripprefix.stripprefix.forceslash=true" 46 | - "traefik.http.middlewares.headscale-webui-stripprefix.stripprefix.prefixes=/admin/" 47 | ``` 48 | * Replace $DOMAIN with your domain. -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | services: 3 | headscale-webui: 4 | image: ghcr.io/anjomro/headscale-webui:v0.1.0 5 | container_name: headscale-webui 6 | environment: 7 | - TZ=UTC # Timezone 8 | - HS_SERVER=localhost # Set this to your Headscale server's URL. It will need to access /api/ on Headscale. 9 | - BASE_PATH="/admin" # Default, can be anything you want. Tailscale's Windows app expects "HS_SERVER/admin" 10 | - KEY="YourKeyBetweenQuotes" # Generate with "openssl rand -base64 32" 11 | volumes: 12 | - ./volume:/data # Headscale-WebUI's storage 13 | - ./headscale/config/:/etc/headscale/:ro # Headscale's config storage location. Used to read your Headscale config. 14 | labels: 15 | # Traefik Configs 16 | - "traefik.enable=true" 17 | - "traefik.http.routers.headscale-webui.entrypoints=web-secure" 18 | - "traefik.http.routers.headscale-webui.rule=Host(`headscale.$DOMAIN`) && (PathPrefix(`/admin/`) || PathPrefix(`/admin`))" 19 | - "traefik.http.services.headscale-webui.loadbalancer.server.port=5000" 20 | - "traefik.http.routers.headscale-webui.tls.certresolver=letsencrypt" 21 | # redirect /admin to / 22 | - "traefik.http.middlewares.headscale-webui-stripprefix.stripprefix.forceslash=true" 23 | - "traefik.http.middlewares.headscale-webui-stripprefix.stripprefix.prefixes=/admin/" -------------------------------------------------------------------------------- /entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . /app/.venv/bin/activate 3 | exec "$@" -------------------------------------------------------------------------------- /headscale.py: -------------------------------------------------------------------------------- 1 | import requests, json, os, logging, sys 2 | from os.path import exists 3 | from cryptography.fernet import Fernet 4 | from datetime import datetime, timedelta, date 5 | from dateutil import parser 6 | 7 | log = logging.getLogger('server.headscale') 8 | handler = logging.StreamHandler(sys.stderr) 9 | handler.setFormatter(logging.Formatter('%(name)s - %(levelname)s - %(message)s')) 10 | log.addHandler(handler) 11 | log.setLevel(logging.INFO) 12 | 13 | ################################################################## 14 | # Functions related to HEADSCALE and API KEYS 15 | ################################################################## 16 | 17 | def get_url(): return os.environ['HS_SERVER'] 18 | 19 | def set_api_key(api_key): 20 | encryption_key = os.environ['KEY'] # User-set encryption key 21 | key_file = open("/data/key.txt", "wb+") # Key file on the filesystem for persistent storage 22 | fernet = Fernet(encryption_key) # Preparing the Fernet class with the key 23 | encrypted_key = fernet.encrypt(api_key.encode()) # Encrypting the key 24 | return True if key_file.write(encrypted_key) else False # Return true if the file wrote correctly 25 | 26 | def get_api_key(): 27 | if not exists("/data/key.txt"): return False 28 | encryption_key = os.environ['KEY'] # User-set encryption key 29 | key_file = open("/data/key.txt", "rb+") # Key file on the filesystem for persistent storage 30 | enc_api_key = key_file.read() # The encrypted key read from the file 31 | if enc_api_key == b'': return "NULL" 32 | 33 | fernet = Fernet(encryption_key) # Preparing the Fernet class with the key 34 | decrypted_key = fernet.decrypt(enc_api_key).decode() # Decrypting the key 35 | 36 | return decrypted_key 37 | 38 | def test_api_key(url, api_key): 39 | response = requests.get( 40 | str(url)+"/api/v1/apikey", 41 | headers={ 42 | 'Accept': 'application/json', 43 | 'Authorization': 'Bearer '+str(api_key) 44 | } 45 | ) 46 | return response.status_code 47 | 48 | # Expires an API key 49 | def expire_key(url, api_key): 50 | payload = {'prefix':str(api_key[0:10])} 51 | json_payload=json.dumps(payload) 52 | # log.warning("Sending the payload '"+str(json_payload)+"' to the headscale server") 53 | 54 | response = requests.post( 55 | str(url)+"/api/v1/apikey/expire", 56 | data=json_payload, 57 | headers={ 58 | 'Accept': 'application/json', 59 | 'Content-Type': 'application/json', 60 | 'Authorization': 'Bearer '+str(api_key) 61 | } 62 | ) 63 | return 0 64 | 65 | # Checks if the key needs to be renewed 66 | # If it does, renews the key, then expires the old key 67 | def renew_api_key(url, api_key): 68 | # 0 = Key has been updated or key is not in need of an update 69 | # 1 = Key has failed validity check or has failed to write the API key 70 | # Check when the key expires and compare it to todays date: 71 | key_info = get_api_key_info(url, api_key) 72 | 73 | expiration_time = key_info["expiration"] 74 | today_date = date.today() 75 | expire = parser.parse(expiration_time) 76 | expire_fmt = str(expire.year) + "-" + str(expire.month).zfill(2) + "-" + str(expire.day).zfill(2) # 2023-01-04 77 | expire_date = date.fromisoformat(expire_fmt) 78 | delta = expire_date - today_date 79 | tmp = today_date + timedelta(days=90) 80 | new_expiration_date = str(tmp)+"T00:00:00.000000Z" 81 | 82 | # If the delta is less than 5 days, renew the key: 83 | if delta < timedelta(days=5): 84 | # log.warning("Key is about to expire. Delta is "+str(delta)) 85 | payload = {'expiration':str(new_expiration_date)} 86 | json_payload=json.dumps(payload) 87 | # log.warning("Sending the payload '"+str(json_payload)+"' to the headscale server") 88 | 89 | response = requests.post( 90 | str(url)+"/api/v1/apikey", 91 | data=json_payload, 92 | headers={ 93 | 'Accept': 'application/json', 94 | 'Content-Type': 'application/json', 95 | 'Authorization': 'Bearer '+str(api_key) 96 | } 97 | ) 98 | new_key = response.json() 99 | # log.warning("JSON: "+json.dumps(new_key)) 100 | # log.warning("New Key is: "+new_key["apiKey"]) 101 | api_key_test = test_api_key(url, new_key["apiKey"]) 102 | # log.warning("Testing the key: "+str(api_key_test)) 103 | # Test if the new key works: 104 | if api_key_test == 200: 105 | # log.warning("The new key is valid and we are writing it to the file") 106 | if not set_api_key(new_key["apiKey"]): 107 | # log.warning("We failed writing the new key!") 108 | return False # Key write failed 109 | # log.warning("Key validated and written. Moving to expire the key.") 110 | expire_key(url, api_key) 111 | return True # Key updated and validated 112 | else: return False # The API Key test failed 113 | else: return True #No work is required 114 | 115 | # Gets information about the current API key 116 | def get_api_key_info(url, api_key): 117 | response = requests.get( 118 | str(url)+"/api/v1/apikey", 119 | headers={ 120 | 'Accept': 'application/json', 121 | 'Authorization': 'Bearer '+str(api_key) 122 | } 123 | ) 124 | json_response = response.json() 125 | # Find the current key in the array: 126 | key_prefix = str(api_key[0:10]) 127 | for key in json_response["apiKeys"]: 128 | if key_prefix == key["prefix"]: 129 | return key 130 | return "Key not found" 131 | 132 | ################################################################## 133 | # Functions related to MACHINES 134 | ################################################################## 135 | 136 | # register a new machine 137 | def register_machine(url, api_key, machine_key, user): 138 | response = requests.post( 139 | str(url)+"/api/v1/machine/register?user="+str(user)+"&key="+str(machine_key), 140 | headers={ 141 | 'Accept': 'application/json', 142 | 'Authorization': 'Bearer '+str(api_key) 143 | } 144 | ) 145 | return response.json() 146 | 147 | 148 | # Sets the machines tags 149 | def set_machine_tags(url, api_key, machine_id, tags_list): 150 | json_payload=json.dumps(tags_list) 151 | 152 | response = requests.post( 153 | str(url)+"/api/v1/machine/"+str(machine_id)+"/tags", 154 | data=tags_list, 155 | headers={ 156 | 'Accept': 'application/json', 157 | 'Content-Type': 'application/json', 158 | 'Authorization': 'Bearer '+str(api_key) 159 | } 160 | ) 161 | return response.json() 162 | 163 | # Moves machine_id to user "new_user" 164 | def move_user(url, api_key, machine_id, new_user): 165 | response = requests.post( 166 | str(url)+"/api/v1/machine/"+str(machine_id)+"/user?user="+str(new_user), 167 | headers={ 168 | 'Accept': 'application/json', 169 | 'Authorization': 'Bearer '+str(api_key) 170 | } 171 | ) 172 | return response.json() 173 | 174 | # updates routes for the given machine_id. enable / disable 175 | # The Headscale API expects a list of routes to enable. if we want to toggle 1 out of 3 routes 176 | # we need to pass all currently enabled routes and mask it 177 | # For example, if we have routes: 178 | # 0.0.0.0/0 179 | # ::/0 180 | # 192.168.1.0/24 181 | # available, but only routes 182 | # 0.0.0.0/24 183 | # 192.168.1.0/24 184 | # ENABLED, and we want to disable route 192.168.1.0/24, we need to pass ONLY the routes to KEEP enabled. 185 | # In this case, 0.0.0/24 186 | def update_route(url, api_key, route_id, current_state): 187 | action = "" 188 | if current_state == "True": action = "disable" 189 | if current_state == "False": action = "enable" 190 | 191 | # Debug 192 | #log.info("URL: "+str(url)) 193 | #log.info("Route ID: "+str(route_id)) 194 | #log.info("Current State: "+str(current_state)) 195 | #log.info("Action to take: "+str(action)) 196 | 197 | response = requests.post( 198 | str(url)+"/api/v1/routes/"+str(route_id)+"/"+str(action), 199 | headers={ 200 | 'Accept': 'application/json', 201 | 'Authorization': 'Bearer '+str(api_key) 202 | } 203 | ) 204 | return response.json() 205 | # First, get all route info: 206 | # routes = get_machine_routes(url, api_key, machine_id) 207 | # to_enable = [] 208 | # is_enabled = False 209 | # "route" is what we are toggling. On or off. 210 | # Get a list of all currently enabled routes. 211 | # If route IS currently in enabled routes, remove it 212 | # # TODO: REDO THIS FOR THE NEW API 213 | # for enabled_route in routes["routes"]["enabledRoutes"]: 214 | # if enabled_route == route: is_enabled=True 215 | # else: to_enable.append(enabled_route) 216 | # if not is_enabled: to_enable.append(route) 217 | # 218 | # query = "" 219 | # count = 0 220 | # for route in to_enable: 221 | # count = count+1 222 | # if count == 1: query = query+"routes="+route 223 | # else: query = query+"&routes="+route 224 | # 225 | # response = requests.post( 226 | # str(url)+"/api/v1/machine/"+str(machine_id)+"/routes?"+query, 227 | # headers={ 228 | # 'Accept': 'application/json', 229 | # 'Authorization': 'Bearer '+str(api_key) 230 | # } 231 | # ) 232 | # return response.json() 233 | 234 | # Get all machines on the Headscale network 235 | def get_machines(url, api_key): 236 | response = requests.get( 237 | str(url)+"/api/v1/machine", 238 | headers={ 239 | 'Accept': 'application/json', 240 | 'Authorization': 'Bearer '+str(api_key) 241 | } 242 | ) 243 | return response.json() 244 | 245 | # Get machine with "machine_id" on the Headscale network 246 | def get_machine_info(url, api_key, machine_id): 247 | response = requests.get( 248 | str(url)+"/api/v1/machine/"+str(machine_id), 249 | headers={ 250 | 'Accept': 'application/json', 251 | 'Authorization': 'Bearer '+str(api_key) 252 | } 253 | ) 254 | return response.json() 255 | 256 | # Delete a machine from Headscale 257 | def delete_machine(url, api_key, machine_id): 258 | response = requests.delete( 259 | str(url)+"/api/v1/machine/"+str(machine_id), 260 | headers={ 261 | 'Accept': 'application/json', 262 | 'Authorization': 'Bearer '+str(api_key) 263 | } 264 | ) 265 | status = "True" if response.status_code == 200 else "False" 266 | return {"status": status, "body": response.json()} 267 | 268 | # Rename "machine_id" with name "new_name" 269 | def rename_machine(url, api_key, machine_id, new_name): 270 | response = requests.post( 271 | str(url)+"/api/v1/machine/"+str(machine_id)+"/rename/"+str(new_name), 272 | headers={ 273 | 'Accept': 'application/json', 274 | 'Authorization': 'Bearer '+str(api_key) 275 | } 276 | ) 277 | status = "True" if response.status_code == 200 else "False" 278 | return {"status": status, "body": response.json()} 279 | 280 | # Gets routes for the passed machine_id 281 | def get_machine_routes(url, api_key, machine_id): 282 | response = requests.get( 283 | str(url)+"/api/v1/machine/"+str(machine_id)+"/routes", 284 | headers={ 285 | 'Accept': 'application/json', 286 | 'Authorization': 'Bearer '+str(api_key) 287 | } 288 | ) 289 | return response.json() 290 | # Gets routes for the entire tailnet 291 | def get_routes(url, api_key): 292 | response = requests.get( 293 | str(url)+"/api/v1/routes", 294 | headers={ 295 | 'Accept': 'application/json', 296 | 'Authorization': 'Bearer '+str(api_key) 297 | } 298 | ) 299 | return response.json() 300 | 301 | ################################################################## 302 | # Functions related to NAMESPACES 303 | ################################################################## 304 | 305 | # Get all users in use 306 | def get_users(url, api_key): 307 | response = requests.get( 308 | str(url)+"/api/v1/user", 309 | headers={ 310 | 'Accept': 'application/json', 311 | 'Authorization': 'Bearer '+str(api_key) 312 | } 313 | ) 314 | return response.json() 315 | 316 | # Rename "old_name" with name "new_name" 317 | def rename_user(url, api_key, old_name, new_name): 318 | response = requests.post( 319 | str(url)+"/api/v1/user/"+str(old_name)+"/rename/"+str(new_name), 320 | headers={ 321 | 'Accept': 'application/json', 322 | 'Authorization': 'Bearer '+str(api_key) 323 | } 324 | ) 325 | status = "True" if response.status_code == 200 else "False" 326 | return {"status": status, "body": response.json()} 327 | 328 | # Delete a user from Headscale 329 | def delete_user(url, api_key, user_name): 330 | response = requests.delete( 331 | str(url)+"/api/v1/user/"+str(user_name), 332 | headers={ 333 | 'Accept': 'application/json', 334 | 'Authorization': 'Bearer '+str(api_key) 335 | } 336 | ) 337 | status = "True" if response.status_code == 200 else "False" 338 | return {"status": status, "body": response.json()} 339 | 340 | # Add a user from Headscale 341 | def add_user(url, api_key, data): 342 | response = requests.post( 343 | str(url)+"/api/v1/user", 344 | data=data, 345 | headers={ 346 | 'Accept': 'application/json', 347 | 'Content-Type': 'application/json', 348 | 'Authorization': 'Bearer '+str(api_key) 349 | } 350 | ) 351 | status = "True" if response.status_code == 200 else "False" 352 | return {"status": status, "body": response.json()} 353 | 354 | ################################################################## 355 | # Functions related to PREAUTH KEYS in NAMESPACES 356 | ################################################################## 357 | 358 | # Get all PreAuth keys associated with a user "user_name" 359 | def get_preauth_keys(url, api_key, user_name): 360 | response = requests.get( 361 | str(url)+"/api/v1/preauthkey?user="+str(user_name), 362 | headers={ 363 | 'Accept': 'application/json', 364 | 'Authorization': 'Bearer '+str(api_key) 365 | } 366 | ) 367 | return response.json() 368 | 369 | # Add a preauth key to the user "user_name" given the booleans "ephemeral" and "reusable" with the expiration date "date" contained in the JSON payload "data" 370 | def add_preauth_key(url, api_key, data): 371 | response = requests.post( 372 | str(url)+"/api/v1/preauthkey", 373 | data=data, 374 | headers={ 375 | 'Accept': 'application/json', 376 | 'Content-Type': 'application/json', 377 | 'Authorization': 'Bearer '+str(api_key) 378 | } 379 | ) 380 | status = "True" if response.status_code == 200 else "False" 381 | return {"status": status, "body": response.json()} 382 | 383 | # Expire a pre-auth key. data is {"user": "string", "key": "string"} 384 | def expire_preauth_key(url, api_key, data): 385 | response = requests.post( 386 | str(url)+"/api/v1/preauthkey/expire", 387 | data=data, 388 | headers={ 389 | 'Accept': 'application/json', 390 | 'Content-Type': 'application/json', 391 | 'Authorization': 'Bearer '+str(api_key) 392 | } 393 | ) 394 | status = "True" if response.status_code == 200 else "False" 395 | log.warning("Return: "+str(response.json())) 396 | log.warning("Status: "+str(status)) 397 | return {"status": status, "body": response.json()} 398 | -------------------------------------------------------------------------------- /helper.py: -------------------------------------------------------------------------------- 1 | 2 | import logging, sys, pytz, os, headscale 3 | from datetime import datetime, timedelta, date 4 | from dateutil import parser 5 | 6 | log = logging.getLogger('server.helper') 7 | handler = logging.StreamHandler(sys.stderr) 8 | handler.setFormatter(logging.Formatter('%(name)s - %(levelname)s - %(message)s')) 9 | log.addHandler(handler) 10 | log.setLevel(logging.INFO) 11 | 12 | def pretty_print_duration(duration): 13 | days, seconds = duration.days, duration.seconds 14 | hours = (days * 24 + seconds // 3600) 15 | mins = ((seconds % 3600) // 60) 16 | secs = (seconds % 60) 17 | if days > 0: return str(days ) + " days ago" if days > 1 else str(days ) + " day ago" 18 | elif hours > 0: return str(hours) + " hours ago" if hours > 1 else str(hours) + " hour ago" 19 | elif mins > 0: return str(mins ) + " minutes ago" if mins > 1 else str(mins ) + " minute ago" 20 | else: return str(secs ) + " seconds ago" if secs >= 1 or secs == 0 else str(secs ) + " second ago" 21 | 22 | def text_color_duration(duration): 23 | days, seconds = duration.days, duration.seconds 24 | hours = (days * 24 + seconds // 3600) 25 | mins = ((seconds % 3600) // 60) 26 | secs = (seconds % 60) 27 | if days > 30: return "grey-text " 28 | elif days > 14: return "red-text text-darken-2 " 29 | elif days > 5: return "deep-orange-text text-lighten-1" 30 | elif days > 1: return "deep-orange-text text-lighten-1" 31 | elif hours > 12: return "orange-text " 32 | elif hours > 1: return "orange-text text-lighten-2" 33 | elif hours == 1: return "yellow-text " 34 | elif mins > 15: return "yellow-text text-lighten-2" 35 | elif mins > 5: return "green-text text-lighten-3" 36 | elif secs > 30: return "green-text text-lighten-2" 37 | else: return "green-text " 38 | 39 | def key_test(): 40 | api_key = headscale.get_api_key() 41 | url = headscale.get_url() 42 | 43 | # Test the API key. If the test fails, return a failure. 44 | # AKA, if headscale returns Unauthorized, fail: 45 | status = headscale.test_api_key(url, api_key) 46 | if status != 200: return False 47 | else: 48 | # Check if the key needs to be renewed 49 | headscale.renew_api_key(url, api_key) 50 | return True 51 | 52 | def get_color(id, type = ""): 53 | # Define the colors... Seems like a good number to start with 54 | if type == "text": 55 | colors = [ 56 | "red-text text-lighten-1", 57 | "teal-text text-lighten-1", 58 | "blue-text text-lighten-1", 59 | "blue-grey-text text-lighten-1", 60 | "indigo-text text-lighten-2", 61 | "green-text text-lighten-1", 62 | "deep-orange-text text-lighten-1", 63 | "yellow-text text-lighten-2", 64 | "purple-text text-lighten-2", 65 | "indigo-text text-lighten-2", 66 | "brown-text text-lighten-1", 67 | "grey-text text-lighten-1", 68 | ] 69 | index = id % len(colors) 70 | return colors[index] 71 | else: 72 | colors = [ 73 | "red lighten-1", 74 | "teal lighten-1", 75 | "blue lighten-1", 76 | "blue-grey lighten-1", 77 | "indigo lighten-2", 78 | "green lighten-1", 79 | "deep-orange lighten-1", 80 | "yellow lighten-2", 81 | "purple lighten-2", 82 | "indigo lighten-2", 83 | "brown lighten-1", 84 | "grey lighten-1", 85 | ] 86 | index = id % len(colors) 87 | return colors[index] -------------------------------------------------------------------------------- /poetry.lock: -------------------------------------------------------------------------------- 1 | [[package]] 2 | name = "certifi" 3 | version = "2022.12.7" 4 | description = "Python package for providing Mozilla's CA Bundle." 5 | category = "main" 6 | optional = false 7 | python-versions = ">=3.6" 8 | 9 | [[package]] 10 | name = "cffi" 11 | version = "1.15.1" 12 | description = "Foreign Function Interface for Python calling C code." 13 | category = "main" 14 | optional = false 15 | python-versions = "*" 16 | 17 | [package.dependencies] 18 | pycparser = "*" 19 | 20 | [[package]] 21 | name = "charset-normalizer" 22 | version = "3.0.1" 23 | description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet." 24 | category = "main" 25 | optional = false 26 | python-versions = "*" 27 | 28 | [[package]] 29 | name = "click" 30 | version = "8.1.3" 31 | description = "Composable command line interface toolkit" 32 | category = "main" 33 | optional = false 34 | python-versions = ">=3.7" 35 | 36 | [package.dependencies] 37 | colorama = {version = "*", markers = "platform_system == \"Windows\""} 38 | 39 | [[package]] 40 | name = "colorama" 41 | version = "0.4.6" 42 | description = "Cross-platform colored terminal text." 43 | category = "main" 44 | optional = false 45 | python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7" 46 | 47 | [[package]] 48 | name = "cryptography" 49 | version = "39.0.0" 50 | description = "cryptography is a package which provides cryptographic recipes and primitives to Python developers." 51 | category = "main" 52 | optional = false 53 | python-versions = ">=3.6" 54 | 55 | [package.dependencies] 56 | cffi = ">=1.12" 57 | 58 | [package.extras] 59 | docs = ["sphinx (>=1.6.5,!=1.8.0,!=3.1.0,!=3.1.1,!=5.2.0,!=5.2.0.post0)", "sphinx-rtd-theme"] 60 | docstest = ["pyenchant (>=1.6.11)", "twine (>=1.12.0)", "sphinxcontrib-spelling (>=4.0.1)"] 61 | pep8test = ["black", "ruff"] 62 | sdist = ["setuptools-rust (>=0.11.4)"] 63 | ssh = ["bcrypt (>=3.1.5)"] 64 | test = ["pytest (>=6.2.0)", "pytest-benchmark", "pytest-cov", "pytest-subtests", "pytest-xdist", "pretend", "iso8601", "pytz", "hypothesis (>=1.11.4,!=3.79.2)"] 65 | 66 | [[package]] 67 | name = "flask" 68 | version = "2.2.2" 69 | description = "A simple framework for building complex web applications." 70 | category = "main" 71 | optional = false 72 | python-versions = ">=3.7" 73 | 74 | [package.dependencies] 75 | click = ">=8.0" 76 | itsdangerous = ">=2.0" 77 | Jinja2 = ">=3.0" 78 | Werkzeug = ">=2.2.2" 79 | 80 | [package.extras] 81 | async = ["asgiref (>=3.2)"] 82 | dotenv = ["python-dotenv"] 83 | 84 | [[package]] 85 | name = "flask-executor" 86 | version = "1.0.0" 87 | description = "An easy to use Flask wrapper for concurrent.futures" 88 | category = "main" 89 | optional = false 90 | python-versions = "*" 91 | 92 | [package.dependencies] 93 | Flask = "*" 94 | 95 | [package.extras] 96 | test = ["pytest", "flask-sqlalchemy"] 97 | 98 | [[package]] 99 | name = "gunicorn" 100 | version = "20.1.0" 101 | description = "WSGI HTTP Server for UNIX" 102 | category = "main" 103 | optional = false 104 | python-versions = ">=3.5" 105 | 106 | [package.extras] 107 | eventlet = ["eventlet (>=0.24.1)"] 108 | gevent = ["gevent (>=1.4.0)"] 109 | setproctitle = ["setproctitle"] 110 | tornado = ["tornado (>=0.2)"] 111 | 112 | [[package]] 113 | name = "idna" 114 | version = "3.4" 115 | description = "Internationalized Domain Names in Applications (IDNA)" 116 | category = "main" 117 | optional = false 118 | python-versions = ">=3.5" 119 | 120 | [[package]] 121 | name = "itsdangerous" 122 | version = "2.1.2" 123 | description = "Safely pass data to untrusted environments and back." 124 | category = "main" 125 | optional = false 126 | python-versions = ">=3.7" 127 | 128 | [[package]] 129 | name = "jinja2" 130 | version = "3.1.2" 131 | description = "A very fast and expressive template engine." 132 | category = "main" 133 | optional = false 134 | python-versions = ">=3.7" 135 | 136 | [package.dependencies] 137 | MarkupSafe = ">=2.0" 138 | 139 | [package.extras] 140 | i18n = ["Babel (>=2.7)"] 141 | 142 | [[package]] 143 | name = "markupsafe" 144 | version = "2.1.2" 145 | description = "Safely add untrusted strings to HTML/XML markup." 146 | category = "main" 147 | optional = false 148 | python-versions = ">=3.7" 149 | 150 | [[package]] 151 | name = "pycparser" 152 | version = "2.21" 153 | description = "C parser in Python" 154 | category = "main" 155 | optional = false 156 | python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" 157 | 158 | [[package]] 159 | name = "python-dateutil" 160 | version = "2.8.2" 161 | description = "Extensions to the standard Python datetime module" 162 | category = "main" 163 | optional = false 164 | python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" 165 | 166 | [package.dependencies] 167 | six = ">=1.5" 168 | 169 | [[package]] 170 | name = "pytz" 171 | version = "2022.7.1" 172 | description = "World timezone definitions, modern and historical" 173 | category = "main" 174 | optional = false 175 | python-versions = "*" 176 | 177 | [[package]] 178 | name = "pyuwsgi" 179 | version = "2.0.21" 180 | description = "The uWSGI server" 181 | category = "main" 182 | optional = false 183 | python-versions = "*" 184 | 185 | [[package]] 186 | name = "pyyaml" 187 | version = "6.0" 188 | description = "YAML parser and emitter for Python" 189 | category = "main" 190 | optional = false 191 | python-versions = ">=3.6" 192 | 193 | [[package]] 194 | name = "requests" 195 | version = "2.28.2" 196 | description = "Python HTTP for Humans." 197 | category = "main" 198 | optional = false 199 | python-versions = ">=3.7, <4" 200 | 201 | [package.dependencies] 202 | certifi = ">=2017.4.17" 203 | charset-normalizer = ">=2,<4" 204 | idna = ">=2.5,<4" 205 | urllib3 = ">=1.21.1,<1.27" 206 | 207 | [package.extras] 208 | socks = ["PySocks (>=1.5.6,!=1.5.7)"] 209 | use_chardet_on_py3 = ["chardet (>=3.0.2,<6)"] 210 | 211 | [[package]] 212 | name = "six" 213 | version = "1.16.0" 214 | description = "Python 2 and 3 compatibility utilities" 215 | category = "main" 216 | optional = false 217 | python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*" 218 | 219 | [[package]] 220 | name = "urllib3" 221 | version = "1.26.14" 222 | description = "HTTP library with thread-safe connection pooling, file post, and more." 223 | category = "main" 224 | optional = false 225 | python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*" 226 | 227 | [package.extras] 228 | brotli = ["brotlicffi (>=0.8.0)", "brotli (>=1.0.9)", "brotlipy (>=0.6.0)"] 229 | secure = ["pyOpenSSL (>=0.14)", "cryptography (>=1.3.4)", "idna (>=2.0.0)", "certifi", "urllib3-secure-extra", "ipaddress"] 230 | socks = ["PySocks (>=1.5.6,!=1.5.7,<2.0)"] 231 | 232 | [[package]] 233 | name = "werkzeug" 234 | version = "2.2.2" 235 | description = "The comprehensive WSGI web application library." 236 | category = "main" 237 | optional = false 238 | python-versions = ">=3.7" 239 | 240 | [package.dependencies] 241 | MarkupSafe = ">=2.1.1" 242 | 243 | [package.extras] 244 | watchdog = ["watchdog"] 245 | 246 | [metadata] 247 | lock-version = "1.1" 248 | python-versions = "^3.10" 249 | content-hash = "5bff557bbff9c05298dd65dd067534d4b03d6e8716382013147a387013699715" 250 | 251 | [metadata.files] 252 | certifi = [] 253 | cffi = [] 254 | charset-normalizer = [] 255 | click = [] 256 | colorama = [] 257 | cryptography = [] 258 | flask = [] 259 | flask-executor = [] 260 | gunicorn = [] 261 | idna = [] 262 | itsdangerous = [] 263 | jinja2 = [] 264 | markupsafe = [] 265 | pycparser = [] 266 | python-dateutil = [] 267 | pytz = [] 268 | pyuwsgi = [] 269 | pyyaml = [] 270 | requests = [] 271 | six = [] 272 | urllib3 = [] 273 | werkzeug = [] 274 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "headscale-webui" 3 | version = "0.1.0" 4 | description = "" 5 | authors = ["Your Name "] 6 | license = "AGPL" 7 | 8 | [tool.poetry.dependencies] 9 | python = "^3.10" 10 | requests = "^2.28.2" 11 | Flask = "^2.2.2" 12 | cryptography = "^39.0.0" 13 | python-dateutil = "^2.8.2" 14 | pytz = "^2022.7.1" 15 | Flask-Executor = "^1.0.0" 16 | PyYAML = "^6.0" 17 | pyuwsgi = "^2.0.21" 18 | gunicorn = "^20.1.0" 19 | 20 | [tool.poetry.dev-dependencies] 21 | 22 | [build-system] 23 | requires = ["poetry-core>=1.0.0"] 24 | build-backend = "poetry.core.masonry.api" 25 | -------------------------------------------------------------------------------- /renderer.py: -------------------------------------------------------------------------------- 1 | import headscale, helper, json, logging, sys, pytz, os, time, yaml 2 | from flask import Markup, render_template, Flask 3 | from datetime import datetime, timedelta, date 4 | from dateutil import parser 5 | 6 | # Threading to speed things up 7 | from concurrent.futures import wait, ALL_COMPLETED 8 | from flask_executor import Executor 9 | 10 | app = Flask(__name__) 11 | executor = Executor(app) 12 | 13 | log = logging.getLogger('server.renderer') 14 | 15 | def render_overview(): 16 | url = headscale.get_url() 17 | api_key = headscale.get_api_key() 18 | 19 | timezone = pytz.timezone(os.environ["TZ"] if os.environ["TZ"] else "UTC") 20 | local_time = timezone.localize(datetime.now()) 21 | 22 | # Overview page will just read static information from the config file and display it 23 | # Open the config.yaml and parse it. 24 | config_file = open("/etc/headscale/config.yaml", "r") 25 | config_yaml = yaml.safe_load(config_file) 26 | 27 | # Get and display the following information: 28 | # Overview of the server's machines, users, preauth keys, API key expiration, server version 29 | 30 | # Get all machines: 31 | machines_count = 0 32 | machines = headscale.get_machines(url, api_key) 33 | for machine in machines["machines"]: 34 | machines_count += 1 35 | 36 | # Get all routes: 37 | routes = headscale.get_routes(url,api_key) 38 | total_routes = len(routes["routes"]) 39 | enabled_routes = 0 40 | for route in routes["routes"]: 41 | if route["enabled"] and route['advertised']: 42 | enabled_routes += 1 43 | 44 | # Get a count of all enabled exit routes 45 | exits_count = 0 46 | exits_enabled_count = 0 47 | for route in routes["routes"]: 48 | if route['advertised']: 49 | if route["prefix"] == "0.0.0.0/0" or route["prefix"] == "::/0": 50 | exits_count +=1 51 | if route["enabled"]: 52 | exits_enabled_count += 1 53 | 54 | # Get User and PreAuth Key counts 55 | user_count = 0 56 | usable_keys_count = 0 57 | users = headscale.get_users(url, api_key) 58 | for user in users["users"]: 59 | user_count +=1 60 | preauth_keys = headscale.get_preauth_keys(url, api_key, user["name"]) 61 | for key in preauth_keys["preAuthKeys"]: 62 | expiration_parse = parser.parse(key["expiration"]) 63 | key_expired = True if expiration_parse < local_time else False 64 | if key["reusable"] and not key_expired: usable_keys_count += 1 65 | if not key["reusable"] and not key["used"] and not key_expired: usable_keys_count += 1 66 | 67 | overview_content = """ 68 |
69 |
70 |
71 | Stats 72 |

73 | 74 | 75 | 76 | 77 | 78 | 79 |
Machines Added """+ str(machines_count) +"""
Users """+ str(user_count) +"""
Usable PreAuth Keys """+ str(usable_keys_count) +"""
Enabled/Total Routes """+ str(enabled_routes) +"""/"""+str(total_routes)+"""
Enabled/Total Exits """+ str(exits_enabled_count) +"""/"""+str(exits_count)+"""
80 |

81 |
82 |
83 |
84 | """ 85 | # Overview of general configs from the YAML 86 | general_content = """ 87 |
88 |
89 |
90 | General 91 |

92 | 93 | 94 | 95 | 96 | 97 | 98 |
IP Prefixes """+str(config_yaml["ip_prefixes"]) +"""
Server URL """+str(config_yaml["server_url"]) +"""
Updates Disabled? """+str(config_yaml["disable_check_updates"]) +"""
Ephemeral Node Timeout """+str(config_yaml["ephemeral_node_inactivity_timeout"]) +"""
Node Update Check Interval """+str(config_yaml["node_update_check_interval"]) +"""
99 |

100 |
101 |
102 |
103 | """ 104 | 105 | # Whether OIDC is configured 106 | if config_yaml["oidc"]: 107 | oidc_content = """ 108 |
109 |
110 |
111 | OIDC 112 |

113 | 114 | 115 | 116 | 117 | 118 | 119 |
Issuer """+str(config_yaml["oidc"]["issuer"]) +"""
Client ID """+str(config_yaml["oidc"]["client_id"]) +"""
Scope """+str(config_yaml["oidc"]["scope"]) +"""
Allowed Domains """+str(config_yaml["oidc"]["allowed_domains"]) +"""
Strip Email Domain """+str(config_yaml["oidc"]["strip_email_domain"])+"""
120 |

121 |
122 |
123 |
124 | """ 125 | 126 | if config_yaml["derp"]["server"]: 127 | derp_content = """ 128 |
129 |
130 |
131 | Built-in DERP 132 |

133 | 134 | 135 | 136 | 137 | 138 | 139 |
Enabled """+str(config_yaml["derp"]["server"]["enabled"]) +"""
Region ID """+str(config_yaml["derp"]["server"]["region_id"]) +"""
Region Code """+str(config_yaml["derp"]["server"]["region_code"]) +"""
Region Name """+str(config_yaml["derp"]["server"]["region_name"]) +"""
STUN Address """+str(config_yaml["derp"]["server"]["stun_listen_addr"]) +"""
140 |

141 |
142 |
143 |
144 | """ 145 | 146 | # Whether there are custom DERP servers 147 | # If there are custom DERP servers, get the file location from the config file. Assume mapping is the same. 148 | # Whether the built-in DERP server is enabled 149 | # The IP prefixes 150 | # The DNS config 151 | if config_yaml["dns_config"]: 152 | dns_content = """ 153 |
154 |
155 |
156 | DNS 157 |

158 | 159 | 160 | 161 | 162 | 163 | 164 |
Nameservers """+str(config_yaml["dns_config"]["nameservers"])+"""
MagicDNS """+str(config_yaml["dns_config"]["magic_dns"]) +"""
Domains """+str(config_yaml["dns_config"]["domains"]) +"""
Base Domain """+str(config_yaml["dns_config"]["base_domain"])+"""

165 |

166 |
167 |
168 |
169 | """ 170 | if config_yaml["derp"]["paths"]: pass 171 | # # open the path: 172 | # derp_file = 173 | # config_file = open("/etc/headscale/config.yaml", "r") 174 | # config_yaml = yaml.safe_load(config_file) 175 | # The ACME config, if not empty 176 | # Whether updates are running 177 | # Whether metrics are enabled (and their listen addr) 178 | # The log level 179 | # What kind of Database is being used to drive headscale 180 | 181 | content = "
" + overview_content + general_content + derp_content + oidc_content + dns_content + "
" 182 | return Markup(content) 183 | 184 | def thread_machine_content(machine, machine_content, idx): 185 | # machine = passed in machine information 186 | # content = place to write the content 187 | 188 | url = headscale.get_url() 189 | api_key = headscale.get_api_key() 190 | 191 | # Set the current timezone and local time 192 | timezone = pytz.timezone(os.environ["TZ"] if os.environ["TZ"] else "UTC") 193 | local_time = timezone.localize(datetime.now()) 194 | 195 | # Get the machines routes 196 | pulled_routes = headscale.get_machine_routes(url, api_key, machine["id"]) 197 | routes = "" 198 | 199 | # New format to parse: 200 | # New JSON endpoint requires a machine_id and a route_id to toggle. 201 | # Pass the following info: 202 | # 1. Machine ID 203 | # 2. Route ID (NEW REQ) 204 | # 3. Route State (NEW REQ) - This would be the JSON key of pulled_routes["routes"][index][enabled] 205 | # { 206 | # "routes": [ 207 | # { 208 | # "id": "1", 209 | # "prefix": "0.0.0.0/0", 210 | # "advertised": true, 211 | # "enabled": true, 212 | # }, 213 | 214 | # Test if the machine is an exit node: 215 | exit_node = False 216 | # If the LENGTH of "routes" is NULL/0, there are no routes, enabled or disabled: 217 | if len(pulled_routes["routes"]) > 0: 218 | advertised_and_enabled = False 219 | advertised_route = False 220 | # First, check if there are any routes that are both enabled and advertised 221 | for route in pulled_routes["routes"]: 222 | if route ["advertised"] and route["enabled"]: 223 | advertised_and_enabled = True 224 | if route["advertised"]: 225 | advertised_route = True 226 | if advertised_and_enabled or advertised_route: 227 | routes = """ 228 |
  • 229 | directions 230 | Routes 231 |

    232 | """ 233 | for route in pulled_routes["routes"]: 234 | # log.info("Route: ["+str(route['machine']['name'])+"] id: "+str(route['id'])+" / prefix: "+str(route['prefix'])+" enabled?: "+str(route['enabled'])) 235 | # Check if the route is enabled: 236 | route_enabled = "red" 237 | route_tooltip = 'enable' 238 | if route["enabled"]: 239 | route_enabled = "green" 240 | route_tooltip = 'disable' 241 | if route["prefix"] == "0.0.0.0/0" or route["prefix"] == "::/0" and str(route["enabled"]) == "True": 242 | exit_node = True 243 | routes = routes+""" 244 |

    249 | """+route['prefix']+""" 250 |

    251 | """ 252 | routes = routes+"

  • " 253 | # This entire thing will probably need to change after the new API endpoint change. 254 | # Old code for v1.17.0 255 | # # Test if the machine is an exit node: 256 | # exit_node = False 257 | # # If there are ANY advertised routes, print them: 258 | # if len(pulled_routes["routes"]["advertisedRoutes"]) > 0: 259 | # routes = """ 260 | #
  • 261 | # directions 262 | # Routes 263 | #

    264 | # """ 265 | # for advertised_route in pulled_routes["routes"]["advertisedRoutes"]: 266 | # # Check if the route has been enabled. Red for False, Green for True 267 | # route_enabled = "red" 268 | # route_tooltip = 'enable' 269 | # for enabled_route in pulled_routes["routes"]["enabledRoutes"]: 270 | # if advertised_route == enabled_route: 271 | # route_enabled = "green" 272 | # route_tooltip = 'disable' 273 | # if (advertised_route == "0.0.0.0/0" or advertised_route == "::/0") and route_enabled == "green": 274 | # exit_node = True 275 | # routes = routes+""" 276 | #

    281 | # """+advertised_route+""" 282 | #

    283 | # """ 284 | # routes = routes+"

  • " 285 | 286 | # Get machine tags 287 | tag_array = "" 288 | for tag in machine["forcedTags"]: tag_array = tag_array+"{tag: '"+tag[4:]+"'}, " 289 | tags = """ 290 |
  • 291 | label 292 | Tags 293 |

    294 |
  • 295 | 308 | """ 309 | 310 | # Get the machine IP's 311 | machine_ips = "
      " 312 | for ip in machine["ipAddresses"]: 313 | machine_ips = machine_ips+"
    • "+ip+"
    • " 314 | machine_ips = machine_ips+"
    " 315 | 316 | # Format the dates for easy readability 317 | last_seen_parse = parser.parse(machine["lastSeen"]) 318 | last_seen_local = last_seen_parse.astimezone(timezone) 319 | last_seen_delta = local_time - last_seen_local 320 | last_seen_print = helper.pretty_print_duration(last_seen_delta) 321 | last_seen_time = str(last_seen_local.strftime('%A %m/%d/%Y, %H:%M:%S'))+" "+str(timezone)+" ("+str(last_seen_print)+")" 322 | 323 | last_update_parse = local_time if machine["lastSuccessfulUpdate"] is None else parser.parse(machine["lastSuccessfulUpdate"]) 324 | last_update_local = last_update_parse.astimezone(timezone) 325 | last_update_delta = local_time - last_update_local 326 | last_update_print = helper.pretty_print_duration(last_update_delta) 327 | last_update_time = str(last_update_local.strftime('%A %m/%d/%Y, %H:%M:%S'))+" "+str(timezone)+" ("+str(last_update_print)+")" 328 | 329 | created_parse = parser.parse(machine["createdAt"]) 330 | created_local = created_parse.astimezone(timezone) 331 | created_delta = local_time - created_local 332 | created_print = helper.pretty_print_duration(created_delta) 333 | created_time = str(created_local.strftime('%A %m/%d/%Y, %H:%M:%S'))+" "+str(timezone)+" ("+str(created_print)+")" 334 | 335 | # Get the first 10 characters of the PreAuth Key: 336 | if machine["preAuthKey"]: 337 | preauth_key = str(machine["preAuthKey"]["key"])[0:10] 338 | else: preauth_key = "None" 339 | 340 | # Set the status badge color: 341 | text_color = helper.text_color_duration(last_seen_delta) 342 | # Set the user badge color: 343 | user_color = helper.get_color(int(machine["user"]["id"])) 344 | 345 | # Generate the various badges: 346 | status_badge = "fiber_manual_record" 347 | user_badge = ""+machine["user"]["name"]+"" 348 | exit_node_badge = "" if not exit_node else "Exit Node" 349 | 350 | 351 | machine_content[idx] = (str(render_template( 352 | 'machines_card.html', 353 | given_name = machine["givenName"], 354 | machine_id = machine["id"], 355 | hostname = machine["name"], 356 | ns_name = machine["user"]["name"], 357 | ns_id = machine["user"]["id"], 358 | ns_created = machine["user"]["createdAt"], 359 | last_seen = str(last_seen_print), 360 | last_update = str(last_update_print), 361 | machine_ips = Markup(machine_ips), 362 | advertised_routes = Markup(routes), 363 | exit_node_badge = Markup(exit_node_badge), 364 | status_badge = Markup(status_badge), 365 | user_badge = Markup(user_badge), 366 | last_update_time = str(last_update_time), 367 | last_seen_time = str(last_seen_time), 368 | created_time = str(created_time), 369 | preauth_key = str(preauth_key), 370 | machine_tags = Markup(tags), 371 | ))) 372 | log.info("Finished thread for machine "+machine["givenName"]+" index "+str(idx)) 373 | 374 | # Render the cards for the machines page: 375 | def render_machines_cards(): 376 | url = headscale.get_url() 377 | api_key = headscale.get_api_key() 378 | machines_list = headscale.get_machines(url, api_key) 379 | 380 | ######################################### 381 | # Thread this entire thing. 382 | numThreads = len(machines_list["machines"]) 383 | iterable = [] 384 | machine_content = {} 385 | for i in range (0, numThreads): 386 | log.info("Appending iterable: "+str(i)) 387 | iterable.append(i) 388 | # Flask-Executor Method: 389 | log.info("Starting futures") 390 | futures = [executor.submit(thread_machine_content, machines_list["machines"][idx], machine_content, idx) for idx in iterable] 391 | # Wait for the executor to finish all jobs: 392 | wait(futures, return_when=ALL_COMPLETED) 393 | log.info("Finished futures") 394 | 395 | # DEBUG: Do in a forloop: 396 | # for idx in iterable: thread_machine_content(machines_list["machines"][idx], machine_content, idx) 397 | 398 | # Sort the content by machine_id: 399 | sorted_machines = {key: val for key, val in sorted(machine_content.items(), key = lambda ele: ele[0])} 400 | 401 | content = "
    " 402 | # Print the content 403 | 404 | for index in range(0, numThreads): 405 | content = content+str(sorted_machines[index]) 406 | # content = content+str(sorted_machines[index]) 407 | 408 | content = content+"
    " 409 | 410 | return Markup(content) 411 | 412 | # Render the cards for the Users page: 413 | def render_users_cards(): 414 | url = headscale.get_url() 415 | api_key = headscale.get_api_key() 416 | user_list = headscale.get_users(url, api_key) 417 | 418 | # Set the current timezone and local time 419 | timezone = pytz.timezone(os.environ["TZ"] if os.environ["TZ"] else "UTC") 420 | local_time = timezone.localize(datetime.now()) 421 | 422 | content = "
    " 423 | for user in user_list["users"]: 424 | # Get all preAuth Keys in the user, only display if one exists: 425 | preauth_keys_collection = build_preauth_key_table(user["name"]) 426 | 427 | # Set the user badge color: 428 | user_color = helper.get_color(int(user["id"]), "text") 429 | 430 | # Generate the various badges: 431 | status_badge = "fiber_manual_record" 432 | 433 | content = content + render_template( 434 | 'users_card.html', 435 | status_badge = Markup(status_badge), 436 | user_name = user["name"], 437 | user_id = user["id"], 438 | preauth_keys_collection = Markup(preauth_keys_collection) 439 | ) 440 | content = content+"
    " 441 | return Markup(content) 442 | 443 | # Builds the preauth key table for the User page 444 | def build_preauth_key_table(user_name): 445 | url = headscale.get_url() 446 | api_key = headscale.get_api_key() 447 | 448 | preauth_keys = headscale.get_preauth_keys(url, api_key, user_name) 449 | preauth_keys_collection = """
  • 450 | Toggle Expired 454 | Add PreAuth Key 459 | vpn_key 460 | PreAuth Keys 461 | """ 462 | if len(preauth_keys["preAuthKeys"]) == 0: preauth_keys_collection += "

    No keys defined for this user

    " 463 | if len(preauth_keys["preAuthKeys"]) > 0: 464 | preauth_keys_collection += """ 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | """ 478 | for key in preauth_keys["preAuthKeys"]: 479 | # Get the key expiration date and compare it to now to check if it's expired: 480 | # Set the current timezone and local time 481 | timezone = pytz.timezone(os.environ["TZ"] if os.environ["TZ"] else "UTC") 482 | local_time = timezone.localize(datetime.now()) 483 | expiration_parse = parser.parse(key["expiration"]) 484 | key_expired = True if expiration_parse < local_time else False 485 | expiration_time = str(expiration_parse.strftime('%A %m/%d/%Y, %H:%M:%S'))+" "+str(timezone) 486 | 487 | # Class for the javascript function to look for to toggle the hide function 488 | hide_expired = "expired-row" if key_expired else "" 489 | 490 | key_usable = False 491 | if key["reusable"] and not key_expired: key_usable = True 492 | if not key["reusable"] and not key["used"] and not key_expired: key_usable = True 493 | 494 | tooltip_expired = "Expiration: "+expiration_time 495 | 496 | btn_reusable = "fiber_manual_record" if key["reusable"] else "" 497 | btn_ephemeral = "fiber_manual_record" if key["ephemeral"] else "" 498 | btn_used = "fiber_manual_record" if key["used"] else "" 499 | btn_usable = "fiber_manual_record" if key_usable else "" 500 | 501 | # Other buttons: 502 | btn_delete = "Expire" if not key_expired else "" 503 | tooltip_data = "Expiration: "+expiration_time 504 | 505 | # TR ID will look like "1-albert-tr" 506 | preauth_keys_collection = preauth_keys_collection+""" 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | """ 517 | 518 | preauth_keys_collection = preauth_keys_collection+"""
    IDKey
    Reusable
    Used
    Ephemeral
    Usable
    Actions
    """+str(key["id"])+""""""+str(key["key"])+"""
    """+btn_reusable+"""
    """+btn_used+"""
    """+btn_ephemeral+"""
    """+btn_usable+"""
    """+btn_delete+"""
    519 |
  • 520 | """ 521 | return preauth_keys_collection -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests # API requests to Headscale 2 | flask # Flask for web development 3 | cryptography # Used to encrypt the API key 4 | python-dateutil # Date / Time utility 5 | pytz # Date / Time utility 6 | Flask-Executor # Flask threading application 7 | pyyaml # Used to read YAML files 8 | pyuwsgi # Used to run the application -------------------------------------------------------------------------------- /screenshots/key_test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/screenshots/key_test.png -------------------------------------------------------------------------------- /screenshots/machine_add.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/screenshots/machine_add.png -------------------------------------------------------------------------------- /screenshots/machines-page.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/screenshots/machines-page.JPG -------------------------------------------------------------------------------- /screenshots/machines.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/screenshots/machines.png -------------------------------------------------------------------------------- /screenshots/users.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/screenshots/users.png -------------------------------------------------------------------------------- /server.py: -------------------------------------------------------------------------------- 1 | import requests, json, renderer, headscale, helper, logging, sys, pytz, os, time 2 | from flask import Flask, render_template, request, url_for, redirect 3 | from datetime import datetime, timedelta, date 4 | from dateutil import parser 5 | 6 | # Threading to speed things up 7 | from concurrent.futures import wait, ALL_COMPLETED 8 | from flask_executor import Executor 9 | 10 | app = Flask(__name__) 11 | executor = Executor(app) 12 | 13 | # Logging headers 14 | handler = logging.StreamHandler(sys.stdout) 15 | handler.setFormatter(logging.Formatter( 16 | '%(asctime)s - %(name)s - %(levelname)s - %(message)s')) 17 | app.logger.addHandler(handler) 18 | app.logger.setLevel(logging.DEBUG) 19 | 20 | # Global vars 21 | # Colors: https://materializecss.com/color.html 22 | COLOR_NAV = "blue-grey darken-1" 23 | COLOR_BTN = "blue-grey darken-3" 24 | BASE_PATH = os.environ["BASE_PATH"] 25 | APP_VERSION = "2023.01.1" 26 | HS_VERSION = "0.20.0" 27 | DEBUG_STATE = False 28 | 29 | @app.route('/') 30 | @app.route(BASE_PATH+'/') 31 | @app.route('/overview') 32 | def overview_page(): 33 | # If the API key fails, redirect to the settings page: 34 | if not helper.key_test(): return redirect(BASE_PATH+url_for('settings_page')) 35 | 36 | return render_template('overview.html', 37 | render_page = renderer.render_overview(), 38 | COLOR_NAV = COLOR_NAV, 39 | COLOR_BTN = COLOR_BTN 40 | ) 41 | 42 | @app.route('/machines', methods=('GET', 'POST')) 43 | def machines_page(): 44 | # If the API key fails, redirect to the settings page: 45 | if not helper.key_test(): return redirect(BASE_PATH+url_for('settings_page')) 46 | 47 | cards = renderer.render_machines_cards() 48 | return render_template('machines.html', 49 | cards = cards, 50 | headscale_server = headscale.get_url(), 51 | COLOR_NAV = COLOR_NAV, 52 | COLOR_BTN = COLOR_BTN 53 | ) 54 | 55 | @app.route('/users', methods=('GET', 'POST')) 56 | def users_page(): 57 | # If the API key fails, redirect to the settings page: 58 | if not helper.key_test(): return redirect(BASE_PATH+url_for('settings_page')) 59 | 60 | cards = renderer.render_users_cards() 61 | return render_template('users.html', 62 | cards = cards, 63 | headscale_server = headscale.get_url(), 64 | COLOR_NAV = COLOR_NAV, 65 | COLOR_BTN = COLOR_BTN 66 | ) 67 | 68 | @app.route('/settings', methods=('GET', 'POST')) 69 | def settings_page(): 70 | url = headscale.get_url() 71 | api_key = headscale.get_api_key() 72 | 73 | return render_template('settings.html', 74 | url = url, 75 | COLOR_NAV = COLOR_NAV, 76 | COLOR_BTN = COLOR_BTN, 77 | HS_VERSION = HS_VERSION, 78 | APP_VERSION = APP_VERSION 79 | ) 80 | 81 | ######################################################################################## 82 | # /api pages 83 | ######################################################################################## 84 | 85 | ######################################################################################## 86 | # Headscale API Key Endpoints 87 | ######################################################################################## 88 | 89 | @app.route('/api/test_key', methods=('GET', 'POST')) 90 | def test_key_page(): 91 | api_key = headscale.get_api_key() 92 | url = headscale.get_url() 93 | 94 | # Test the API key. If the test fails, return a failure. 95 | status = headscale.test_api_key(url, api_key) 96 | if status != 200: return "Unauthenticated" 97 | 98 | renewed = headscale.renew_api_key(url, api_key) 99 | app.logger.debug("The below statement will be TRUE if the key has been renewed or DOES NOT need renewal. False in all other cases") 100 | app.logger.debug("Renewed: "+str(renewed)) 101 | # The key works, let's renew it if it needs it. If it does, re-read the api_key from the file: 102 | if renewed: api_key = headscale.get_api_key() 103 | 104 | key_info = headscale.get_api_key_info(url, api_key) 105 | 106 | # Set the current timezone and local time 107 | timezone = pytz.timezone(os.environ["TZ"] if os.environ["TZ"] else "UTC") 108 | local_time = timezone.localize(datetime.now()) 109 | 110 | # Format the dates for easy readability 111 | expiration_parse = parser.parse(key_info['expiration']) 112 | expiration_local = expiration_parse.astimezone(timezone) 113 | expiration_delta = expiration_local - local_time 114 | expiration_print = helper.pretty_print_duration(expiration_delta) 115 | expiration_time = str(expiration_local.strftime('%A %m/%d/%Y, %H:%M:%S'))+" "+str(timezone) 116 | 117 | creation_parse = parser.parse(key_info['createdAt']) 118 | creation_local = creation_parse.astimezone(timezone) 119 | creation_delta = local_time - creation_local 120 | creation_print = helper.pretty_print_duration(creation_delta) 121 | creation_time = str(creation_local.strftime('%A %m/%d/%Y, %H:%M:%S'))+" "+str(timezone) 122 | 123 | key_info['expiration'] = expiration_time 124 | key_info['createdAt'] = creation_time 125 | 126 | message = json.dumps(key_info) 127 | return message 128 | 129 | @app.route('/api/save_key', methods=['POST']) 130 | def save_key_page(): 131 | json_response = request.get_json() 132 | api_key = json_response['api_key'] 133 | url = headscale.get_url() 134 | file_written = headscale.set_api_key(api_key) 135 | message = '' 136 | 137 | if file_written: 138 | # Re-read the file and get the new API key and test it 139 | api_key = headscale.get_api_key() 140 | test_status = headscale.test_api_key(url, api_key) 141 | if test_status == 200: 142 | key_info = headscale.get_api_key_info(url, api_key) 143 | expiration = key_info['expiration'] 144 | message = "Key: '"+api_key+"', Expiration: "+expiration 145 | # If the key was saved successfully, test it: 146 | return "Key saved and tested: "+message 147 | else: return "Key failed testing. Check your key" 148 | else: return "Key did not save properly. Check logs" 149 | 150 | 151 | ######################################################################################## 152 | # Machine API Endpoints 153 | ######################################################################################## 154 | @app.route('/api/update_route', methods=['POST']) 155 | def update_route_page(): 156 | json_response = request.get_json() 157 | route_id = json_response['route_id'] 158 | url = headscale.get_url() 159 | api_key = headscale.get_api_key() 160 | current_state = json_response['current_state'] 161 | 162 | return headscale.update_route(url, api_key, route_id, current_state) 163 | 164 | @app.route('/api/machine_information', methods=['POST']) 165 | def machine_information_page(): 166 | json_response = request.get_json() 167 | machine_id = json_response['id'] 168 | url = headscale.get_url() 169 | api_key = headscale.get_api_key() 170 | 171 | return headscale.get_machine_info(url, api_key, machine_id) 172 | 173 | @app.route('/api/delete_machine', methods=['POST']) 174 | def delete_machine_page(): 175 | json_response = request.get_json() 176 | machine_id = json_response['id'] 177 | url = headscale.get_url() 178 | api_key = headscale.get_api_key() 179 | 180 | return headscale.delete_machine(url, api_key, machine_id) 181 | 182 | @app.route('/api/rename_machine', methods=['POST']) 183 | def rename_machine_page(): 184 | json_response = request.get_json() 185 | machine_id = json_response['id'] 186 | new_name = json_response['new_name'] 187 | url = headscale.get_url() 188 | api_key = headscale.get_api_key() 189 | 190 | return headscale.rename_machine(url, api_key, machine_id, new_name) 191 | 192 | @app.route('/api/move_user', methods=['POST']) 193 | def move_user_page(): 194 | json_response = request.get_json() 195 | machine_id = json_response['id'] 196 | new_user = json_response['new_user'] 197 | url = headscale.get_url() 198 | api_key = headscale.get_api_key() 199 | 200 | return headscale.move_user(url, api_key, machine_id, new_user) 201 | 202 | @app.route('/api/set_machine_tags', methods=['POST']) 203 | def set_machine_tags(): 204 | json_response = request.get_json() 205 | machine_id = json_response['id'] 206 | machine_tags = json_response['tags_list'] 207 | url = headscale.get_url() 208 | api_key = headscale.get_api_key() 209 | 210 | return headscale.set_machine_tags(url, api_key, machine_id, machine_tags) 211 | 212 | @app.route('/api/register_machine', methods=['POST']) 213 | def register_machine(): 214 | json_response = request.get_json() 215 | machine_key = json_response['key'] 216 | user = json_response['user'] 217 | url = headscale.get_url() 218 | api_key = headscale.get_api_key() 219 | 220 | return str(headscale.register_machine(url, api_key, machine_key, user)) 221 | 222 | ######################################################################################## 223 | # User API Endpoints 224 | ######################################################################################## 225 | @app.route('/api/rename_user', methods=['POST']) 226 | def rename_user_page(): 227 | json_response = request.get_json() 228 | old_name = json_response['old_name'] 229 | new_name = json_response['new_name'] 230 | url = headscale.get_url() 231 | api_key = headscale.get_api_key() 232 | 233 | return headscale.rename_user(url, api_key, old_name, new_name) 234 | 235 | @app.route('/api/add_user', methods=['POST']) 236 | def add_user(): 237 | json_response = json.dumps(request.get_json()) 238 | url = headscale.get_url() 239 | api_key = headscale.get_api_key() 240 | 241 | return headscale.add_user(url, api_key, json_response) 242 | 243 | @app.route('/api/delete_user', methods=['POST']) 244 | def delete_user(): 245 | json_response = request.get_json() 246 | user_name = json_response['name'] 247 | url = headscale.get_url() 248 | api_key = headscale.get_api_key() 249 | 250 | return headscale.delete_user(url, api_key, user_name) 251 | 252 | @app.route('/api/get_users', methods=['POST']) 253 | def get_users_page(): 254 | url = headscale.get_url() 255 | api_key = headscale.get_api_key() 256 | 257 | return headscale.get_users(url, api_key) 258 | 259 | ######################################################################################## 260 | # Pre-Auth Key API Endpoints 261 | ######################################################################################## 262 | @app.route('/api/add_preauth_key', methods=['POST']) 263 | def add_preauth_key(): 264 | json_response = json.dumps(request.get_json()) 265 | url = headscale.get_url() 266 | api_key = headscale.get_api_key() 267 | 268 | return headscale.add_preauth_key(url, api_key, json_response) 269 | 270 | @app.route('/api/expire_preauth_key', methods=['POST']) 271 | def expire_preauth_key(): 272 | json_response = json.dumps(request.get_json()) 273 | url = headscale.get_url() 274 | api_key = headscale.get_api_key() 275 | 276 | return headscale.expire_preauth_key(url, api_key, json_response) 277 | 278 | @app.route('/api/build_preauthkey_table', methods=['POST']) 279 | def build_preauth_key_table(): 280 | json_response = request.get_json() 281 | user_name = json_response['name'] 282 | 283 | return renderer.build_preauth_key_table(user_name) 284 | 285 | ######################################################################################## 286 | # Main thread 287 | ######################################################################################## 288 | if __name__ == '__main__': 289 | app.run(host="0.0.0.0", debug=DEBUG_STATE) 290 | -------------------------------------------------------------------------------- /static/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014-2018 Materialize 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /static/README.md: -------------------------------------------------------------------------------- 1 |

    2 | 3 | 4 | 5 |

    6 | 7 |

    MaterializeCSS

    8 | 9 |

    10 | Materialize, a CSS Framework based on material design. 11 |
    12 | -- Browse the docs -- 13 |
    14 |
    15 | 16 | Travis CI badge 17 | 18 | 19 | npm version badge 20 | 21 | 22 | CDNJS version badge 23 | 24 | 25 | dependencies Status badge 26 | 27 | 28 | devDependency Status badge 29 | 30 | 31 | Gitter badge 32 | 33 |

    34 | 35 | ## Table of Contents 36 | - [Quickstart](#quickstart) 37 | - [Documentation](#documentation) 38 | - [Supported Browsers](#supported-browsers) 39 | - [Changelog](#changelog) 40 | - [Testing](#testing) 41 | - [Contributing](#contributing) 42 | - [Copyright and license](#copyright-and-license) 43 | 44 | ## Quickstart: 45 | Read the [getting started guide](http://materializecss.com/getting-started.html) for more information on how to use materialize. 46 | 47 | - [Download the latest release](https://github.com/Dogfalo/materialize/releases/latest) of materialize directly from GitHub. ([Beta](https://github.com/Dogfalo/materialize/releases/)) 48 | - Clone the repo: `git clone https://github.com/Dogfalo/materialize.git` (Beta: `git clone -b v1-dev https://github.com/Dogfalo/materialize.git`) 49 | - Include the files via [cdnjs](https://cdnjs.com/libraries/materialize). More [here](http://materializecss.com/getting-started.html). ([Beta](https://cdnjs.com/libraries/materialize/1.0.0-beta)) 50 | - Install with [npm](https://www.npmjs.com): `npm install materialize-css` (Beta: `npm install materialize-css@next`) 51 | - Install with [Bower](https://bower.io): `bower install materialize` ([DEPRECATED](https://bower.io/blog/2017/how-to-migrate-away-from-bower/)) 52 | - Install with [Atmosphere](https://atmospherejs.com): `meteor add materialize:materialize` (Beta: `meteor add materialize:materialize@=1.0.0-beta`) 53 | 54 | ## Documentation 55 | The documentation can be found at . To run the documentation locally on your machine, you need [Node.js](https://nodejs.org/en/) installed on your computer. 56 | 57 | ### Running documentation locally 58 | Run these commands to set up the documentation: 59 | 60 | ```bash 61 | git clone https://github.com/Dogfalo/materialize 62 | cd materialize 63 | npm install 64 | ``` 65 | 66 | Then run `grunt monitor` to compile the documentation. When it finishes, open a new browser window and navigate to `localhost:8000`. We use [BrowserSync](https://www.browsersync.io/) to display the documentation. 67 | 68 | ### Documentation for previous releases 69 | Previous releases and their documentation are available for [download](https://github.com/Dogfalo/materialize/releases). 70 | 71 | ## Supported Browsers: 72 | Materialize is compatible with: 73 | 74 | - Chrome 35+ 75 | - Firefox 31+ 76 | - Safari 9+ 77 | - Opera 78 | - Edge 79 | - IE 11+ 80 | 81 | ## Changelog 82 | For changelogs, check out [the Releases section of materialize](https://github.com/Dogfalo/materialize/releases) or the [CHANGELOG.md](CHANGELOG.md). 83 | 84 | ## Testing 85 | We use Jasmine as our testing framework and we're trying to write a robust test suite for our components. If you want to help, [here's a starting guide on how to write tests in Jasmine](CONTRIBUTING.md#jasmine-testing-guide). 86 | 87 | ## Contributing 88 | Check out the [CONTRIBUTING document](CONTRIBUTING.md) in the root of the repository to learn how you can contribute. You can also browse the [help-wanted](https://github.com/Dogfalo/materialize/labels/help-wanted) tag in our issue tracker to find things to do. 89 | 90 | ## Copyright and license 91 | Code Copyright 2018 Materialize. Code released under the MIT license. 92 | -------------------------------------------------------------------------------- /static/css/overrides.css: -------------------------------------------------------------------------------- 1 | .collection .collection-item.avatar { 2 | min-height: 0px; 3 | } 4 | 5 | .collapsible span.badge { 6 | margin-left: 5px; 7 | } -------------------------------------------------------------------------------- /static/img/favicon/android-icon-144x144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/android-icon-144x144.png -------------------------------------------------------------------------------- /static/img/favicon/android-icon-192x192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/android-icon-192x192.png -------------------------------------------------------------------------------- /static/img/favicon/android-icon-36x36.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/android-icon-36x36.png -------------------------------------------------------------------------------- /static/img/favicon/android-icon-48x48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/android-icon-48x48.png -------------------------------------------------------------------------------- /static/img/favicon/android-icon-72x72.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/android-icon-72x72.png -------------------------------------------------------------------------------- /static/img/favicon/android-icon-96x96.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/android-icon-96x96.png -------------------------------------------------------------------------------- /static/img/favicon/apple-icon-114x114.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/apple-icon-114x114.png -------------------------------------------------------------------------------- /static/img/favicon/apple-icon-120x120.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/apple-icon-120x120.png -------------------------------------------------------------------------------- /static/img/favicon/apple-icon-144x144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/apple-icon-144x144.png -------------------------------------------------------------------------------- /static/img/favicon/apple-icon-152x152.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/apple-icon-152x152.png -------------------------------------------------------------------------------- /static/img/favicon/apple-icon-180x180.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/apple-icon-180x180.png -------------------------------------------------------------------------------- /static/img/favicon/apple-icon-57x57.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/apple-icon-57x57.png -------------------------------------------------------------------------------- /static/img/favicon/apple-icon-60x60.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/apple-icon-60x60.png -------------------------------------------------------------------------------- /static/img/favicon/apple-icon-72x72.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/apple-icon-72x72.png -------------------------------------------------------------------------------- /static/img/favicon/apple-icon-76x76.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/apple-icon-76x76.png -------------------------------------------------------------------------------- /static/img/favicon/apple-icon-precomposed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/apple-icon-precomposed.png -------------------------------------------------------------------------------- /static/img/favicon/apple-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/apple-icon.png -------------------------------------------------------------------------------- /static/img/favicon/browserconfig.xml: -------------------------------------------------------------------------------- 1 | 2 | #ffffff -------------------------------------------------------------------------------- /static/img/favicon/favicon-16x16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/favicon-16x16.png -------------------------------------------------------------------------------- /static/img/favicon/favicon-32x32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/favicon-32x32.png -------------------------------------------------------------------------------- /static/img/favicon/favicon-96x96.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/favicon-96x96.png -------------------------------------------------------------------------------- /static/img/favicon/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/favicon.ico -------------------------------------------------------------------------------- /static/img/favicon/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "App", 3 | "icons": [ 4 | { 5 | "src": "\/android-icon-36x36.png", 6 | "sizes": "36x36", 7 | "type": "image\/png", 8 | "density": "0.75" 9 | }, 10 | { 11 | "src": "\/android-icon-48x48.png", 12 | "sizes": "48x48", 13 | "type": "image\/png", 14 | "density": "1.0" 15 | }, 16 | { 17 | "src": "\/android-icon-72x72.png", 18 | "sizes": "72x72", 19 | "type": "image\/png", 20 | "density": "1.5" 21 | }, 22 | { 23 | "src": "\/android-icon-96x96.png", 24 | "sizes": "96x96", 25 | "type": "image\/png", 26 | "density": "2.0" 27 | }, 28 | { 29 | "src": "\/android-icon-144x144.png", 30 | "sizes": "144x144", 31 | "type": "image\/png", 32 | "density": "3.0" 33 | }, 34 | { 35 | "src": "\/android-icon-192x192.png", 36 | "sizes": "192x192", 37 | "type": "image\/png", 38 | "density": "4.0" 39 | } 40 | ] 41 | } -------------------------------------------------------------------------------- /static/img/favicon/ms-icon-144x144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/ms-icon-144x144.png -------------------------------------------------------------------------------- /static/img/favicon/ms-icon-150x150.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/ms-icon-150x150.png -------------------------------------------------------------------------------- /static/img/favicon/ms-icon-310x310.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/ms-icon-310x310.png -------------------------------------------------------------------------------- /static/img/favicon/ms-icon-70x70.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/favicon/ms-icon-70x70.png -------------------------------------------------------------------------------- /static/img/headscale3-dots.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anjomro/headscale-webui/7ab508f071fe9040ea9133020601197ffb8e4d5d/static/img/headscale3-dots.png -------------------------------------------------------------------------------- /static/js/custom.js: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------- 2 | // General Helpers 3 | //----------------------------------------------------------- 4 | function loading () { 5 | return `
    6 |
    7 |
    8 |
    9 |
    10 |
    11 |
    12 |
    13 |
    14 |
    15 |
    16 |
    17 |
    18 |
    19 |
    20 |
    21 |
    ` 22 | } 23 | 24 | function get_color(id) { 25 | // Define the colors... Seems like a good number to start with 26 | var colors = [ 27 | "red lighten-1", 28 | "teal lighten-1", 29 | "blue lighten-1", 30 | "blue-grey lighten-1", 31 | "indigo lighten-2", 32 | "green lighten-1", 33 | "deep-orange lighten-1", 34 | "yellow lighten-2", 35 | "purple lighten-2", 36 | "indigo lighten-2", 37 | "brown lighten-1", 38 | "grey lighten-1" 39 | ]; 40 | index = id % colors.length 41 | return colors[index] 42 | } 43 | 44 | function get_base_path() { 45 | 46 | } 47 | 48 | // Generic modal used for alerts / problems 49 | function load_modal_generic(type, title, message) { 50 | console.log("Loading the generic modal") 51 | element = document.getElementById('generic_modal') 52 | content_element = document.getElementById('generic_modal_content') 53 | title_element = document.getElementById('generic_modal_title') 54 | 55 | 56 | content_element.innerHTML = loading() 57 | title_element.innerHTML = "Loading..." 58 | html = "" 59 | 60 | switch (type) { 61 | case "warning" || "Warning": 62 | title_html = "Warning" 63 | content_html =` 64 |
      65 |
    • 66 | priority_high 67 | ${title} 68 |

      ${message}

      69 |
    • 70 |
    ` 71 | break; 72 | case "success" || "Success": 73 | title_html = "Success" 74 | content_html =` 75 |
      76 |
    • 77 | check 78 | ${title} 79 |

      ${message}

      80 |
    • 81 |
    ` 82 | break; 83 | case "error" || "Error": 84 | title_html = "Error" 85 | content_html =` 86 |
      87 |
    • 88 | warning 89 | ${title} 90 |

      ${message}

      91 |
    • 92 |
    ` 93 | break; 94 | case "information" || "Information": 95 | title_html = "Information" 96 | content_html =` 97 |
      98 |
    • 99 | help 100 | ${title} 101 |

      ${message}

      102 |
    • 103 |
    ` 104 | break; 105 | } 106 | title_element.innerHTML = title_html 107 | content_element.innerHTML = content_html 108 | 109 | var instance = M.Modal.getInstance(element); 110 | instance.open() 111 | } 112 | 113 | // Enables the Floating Action Button (FAB) for the Machines and Users page 114 | document.addEventListener('DOMContentLoaded', function() { 115 | var elems = document.querySelectorAll('.fixed-action-btn'); 116 | var instances = M.FloatingActionButton.init(elems, {hoverEnabled:false}); 117 | }); 118 | 119 | // Init the date picker when adding PreAuth keys 120 | document.addEventListener('DOMContentLoaded', function() { 121 | var elems = document.querySelectorAll('.datepicker'); 122 | var instances = M.Datepicker.init(elems); 123 | }); 124 | 125 | //----------------------------------------------------------- 126 | // Settings Page Actions 127 | //----------------------------------------------------------- 128 | function test_key() { 129 | document.getElementById('test_modal_results').innerHTML = loading() 130 | var data = $.ajax({ 131 | type:"GET", 132 | url: "api/test_key", 133 | success: function(response) { 134 | if(response == "Unauthenticated") { 135 | html = ` 136 |
      137 |
    • 138 | warning 139 | Error 140 |

      Key authentication failed. Check your key.

      141 |
    • 142 |
    143 | ` 144 | document.getElementById('test_modal_results').innerHTML = html 145 | } else { 146 | json = JSON.parse(response) 147 | var html = ` 148 |
      149 |
    • 150 | check 151 | Success 152 |

      Key authenticated with the Headscale server.

      153 |
    • 154 |
    155 |
    Key Information
    156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 |
    Key ID${json['id']}
    Prefix${json['prefix']}
    Expiration Date${json['expiration']}
    Creation Date${json['createdAt']}
    176 | ` 177 | document.getElementById('test_modal_results').innerHTML = html 178 | } 179 | } 180 | }) 181 | 182 | } 183 | 184 | function save_key() { 185 | var api_key = document.getElementById('api_key').value; 186 | if (!api_key) { 187 | html = ` 188 |
      189 |
    • 190 | warning 191 | Error 192 |

      You must enter an API key before saving.

      193 |
    • 194 |
    195 | ` 196 | document.getElementById('test_modal_results').innerHTML = html 197 | return 198 | }; 199 | var data = {"api_key": api_key}; 200 | $.ajax({ 201 | type:"POST", 202 | url: "api/save_key", 203 | data: JSON.stringify(data), 204 | contentType: "application/json", 205 | success: function(response) { 206 | M.toast({html: 'Key saved. Testing...'}); 207 | test_key(); 208 | } 209 | }) 210 | } 211 | 212 | //----------------------------------------------------------- 213 | // Modal Loaders 214 | //----------------------------------------------------------- 215 | function load_modal_rename_user(user_id, old_name) { 216 | document.getElementById('modal_content').innerHTML = loading() 217 | document.getElementById('modal_title').innerHTML = "Loading..." 218 | document.getElementById('modal_confirm').className = "green btn-flat white-text" 219 | document.getElementById('modal_confirm').innerText = "Rename" 220 | 221 | modal = document.getElementById('card_modal'); 222 | modal_title = document.getElementById('modal_title'); 223 | modal_body = document.getElementById('modal_content'); 224 | modal_confirm = document.getElementById('modal_confirm'); 225 | 226 | modal_title.innerHTML = "Rename user '"+old_name+"'?" 227 | body_html = ` 228 |
      229 |
    • 230 | language 231 | Information 232 |

      You are about to rename the user '${old_name}'

      233 |
    • 234 |
    235 |
    New Name
    236 |
    237 | language 238 | 239 |
    240 | ` 241 | 242 | modal_body.innerHTML = body_html 243 | $(document).ready(function() { $('input#new_user_name_form').characterCounter(); }); 244 | 245 | modal_confirm.setAttribute('onclick', 'rename_user('+user_id+', "'+old_name+'")') 246 | } 247 | 248 | function load_modal_delete_user(user_id, user_name) { 249 | document.getElementById('modal_content').innerHTML = loading() 250 | document.getElementById('modal_title').innerHTML = "Loading..." 251 | document.getElementById('modal_confirm').className = "red btn-flat white-text" 252 | document.getElementById('modal_confirm').innerText = "Delete" 253 | 254 | modal = document.getElementById('card_modal'); 255 | modal_title = document.getElementById('modal_title'); 256 | modal_body = document.getElementById('modal_content'); 257 | modal_confirm = document.getElementById('modal_confirm'); 258 | 259 | modal_title.innerHTML = "Delete user '"+user_name+"'?" 260 | body_html = ` 261 |
      262 |
    • 263 | warning 264 | Warning 265 |

      Are you sure you want to delete the user '${user_name}'?

      266 |
    • 267 |
    268 | ` 269 | modal_body.innerHTML = body_html 270 | modal_confirm.setAttribute('onclick', 'delete_user("'+user_id+'", "'+user_name+'")') 271 | } 272 | 273 | function load_modal_add_preauth_key(user_name) { 274 | document.getElementById('modal_content').innerHTML = loading() 275 | document.getElementById('modal_title').innerHTML = "Loading..." 276 | document.getElementById('modal_confirm').className = "green btn-flat white-text" 277 | document.getElementById('modal_confirm').innerText = "Add" 278 | 279 | modal = document.getElementById('card_modal'); 280 | modal_title = document.getElementById('modal_title'); 281 | modal_body = document.getElementById('modal_content'); 282 | modal_confirm = document.getElementById('modal_confirm'); 283 | 284 | modal_title.innerHTML = "Adding a PreAuth key to '"+user_name+"'" 285 | body_html = ` 286 |
      287 |
    • 288 | help 289 | Information 290 |

      291 |

        292 |
      • Pre-Auth keys can be used to authenticate to Headscale without manually registering a machine. Use the flag --auth-key to do so.
      • 293 |
      • "Ephemeral" keys can be used to register devices that frequently come on and drop off the newtork (for example, docker containers)
      • 294 |
      • Keys that are "Reusable" can be used multiple times. Keys that are "One Time Use" will expire after their first use.
      • 295 |
      296 |

      297 |
    • 298 |
    299 |

    PreAuth Key Information

    300 |
    301 | 302 |

    303 | 307 |

    308 |

    309 | 313 |

    314 | 315 | ` 316 | 317 | modal_body.innerHTML = body_html 318 | 319 | // Init the date picker 320 | M.Datepicker.init(document.querySelector('.datepicker'), {format:'yyyy-mm-dd'}); 321 | 322 | modal_confirm.setAttribute('onclick', 'add_preauth_key("'+user_name+'")') 323 | } 324 | 325 | function load_modal_expire_preauth_key(user_name, key) { 326 | document.getElementById('modal_content').innerHTML = loading() 327 | document.getElementById('modal_title').innerHTML = "Loading..." 328 | document.getElementById('modal_confirm').className = "red lighten-2 btn-flat white-text" 329 | document.getElementById('modal_confirm').innerText = "Expire" 330 | 331 | modal = document.getElementById('card_modal'); 332 | modal_title = document.getElementById('modal_title'); 333 | modal_body = document.getElementById('modal_content'); 334 | modal_confirm = document.getElementById('modal_confirm'); 335 | 336 | modal_title.innerHTML = "Expire PreAuth Key?" 337 | body_html = ` 338 |
      339 |
    • 340 | warning 341 | Warning 342 |

      Are you sure you want to expire this key? It will become unusable afterwards, and any machine currently using it will disconnect.

      343 |
    • 344 |
    345 | ` 346 | modal_body.innerHTML = body_html 347 | modal_confirm.setAttribute('onclick', 'expire_preauth_key("'+user_name+'", "'+key+'")') 348 | } 349 | 350 | function load_modal_move_machine(machine_id) { 351 | document.getElementById('modal_content').innerHTML = loading() 352 | document.getElementById('modal_title').innerHTML = "Loading..." 353 | document.getElementById('modal_confirm').className = "green btn-flat white-text" 354 | document.getElementById('modal_confirm').innerText = "Move" 355 | 356 | var data = {"id": machine_id} 357 | $.ajax({ 358 | type: "POST", 359 | url: "api/machine_information", 360 | data: JSON.stringify(data), 361 | contentType: "application/json", 362 | success: function(headscale) { 363 | $.ajax({ 364 | type: "POST", 365 | url: "api/get_users", 366 | success: function(response) { 367 | modal = document.getElementById('card_modal'); 368 | modal_title = document.getElementById('modal_title'); 369 | modal_body = document.getElementById('modal_content'); 370 | modal_confirm = document.getElementById('modal_confirm'); 371 | 372 | modal_title.innerHTML = "Move machine '"+headscale.machine.givenName+"'?" 373 | 374 | select_html = `
    Select a User
    ` 380 | 381 | body_html = ` 382 |
      383 |
    • 384 | language 385 | Information 386 |

      You are about to move ${headscale.machine.givenName} to a new user.

      387 |
    • 388 |
    ` 389 | body_html = body_html+select_html 390 | body_html = body_html+`
    Machine Information
    391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 |
    Machine ID${headscale.machine.id}
    Hostname${headscale.machine.name}
    User${headscale.machine.user.name}
    407 | ` 408 | 409 | modal_body.innerHTML = body_html 410 | M.FormSelect.init(document.querySelectorAll('select')) 411 | } 412 | }) 413 | modal_confirm.setAttribute('onclick', 'move_machine('+machine_id+')') 414 | } 415 | }) 416 | } 417 | 418 | function load_modal_delete_machine(machine_id) { 419 | document.getElementById('modal_content').innerHTML = loading() 420 | document.getElementById('modal_title').innerHTML = "Loading..." 421 | document.getElementById('modal_confirm').className = "red btn-flat white-text" 422 | document.getElementById('modal_confirm').innerText = "Delete" 423 | 424 | var data = {"id": machine_id} 425 | $.ajax({ 426 | type: "POST", 427 | url: "api/machine_information", 428 | data: JSON.stringify(data), 429 | contentType: "application/json", 430 | success: function(response) { 431 | modal = document.getElementById('card_modal'); 432 | modal_title = document.getElementById('modal_title'); 433 | modal_body = document.getElementById('modal_content'); 434 | modal_confirm = document.getElementById('modal_confirm'); 435 | 436 | modal_title.innerHTML = "Delete machine '"+response.machine.givenName+"'?" 437 | body_html = ` 438 |
      439 |
    • 440 | warning 441 | Warning 442 |

      Are you sure you want to delete ${response.machine.givenName}?

      443 |
    • 444 |
    445 |
    Machine Information
    446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 |
    Machine ID${response.machine.id}
    Hostname${response.machine.name}
    User${response.machine.user.name}
    462 | ` 463 | modal_body.innerHTML = body_html 464 | modal_confirm.setAttribute('onclick', 'delete_machine('+machine_id+')') 465 | } 466 | }) 467 | } 468 | 469 | function load_modal_rename_machine(machine_id) { 470 | document.getElementById('modal_content').innerHTML = loading() 471 | document.getElementById('modal_title').innerHTML = "Loading..." 472 | document.getElementById('modal_confirm').className = "green btn-flat white-text" 473 | document.getElementById('modal_confirm').innerText = "Rename" 474 | var data = {"id": machine_id} 475 | $.ajax({ 476 | type: "POST", 477 | url: "api/machine_information", 478 | data: JSON.stringify(data), 479 | contentType: "application/json", 480 | success: function(response) { 481 | modal = document.getElementById('card_modal'); 482 | modal_title = document.getElementById('modal_title'); 483 | modal_body = document.getElementById('modal_content'); 484 | modal_confirm = document.getElementById('modal_confirm'); 485 | 486 | modal_title.innerHTML = "Rename machine '"+response.machine.givenName+"'?" 487 | body_html = ` 488 |
      489 |
    • 490 | devices 491 | Information 492 |

      You are about to rename ${response.machine.givenName}

      493 |
    • 494 |
    495 |
    New Name
    496 |
    497 | 498 | 499 |
    500 |
    Machine Information
    501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 |
    Machine ID${response.machine.id}
    Hostname${response.machine.name}
    User${response.machine.user.name}
    517 | ` 518 | modal_body.innerHTML = body_html 519 | modal_confirm.setAttribute('onclick', 'rename_machine('+machine_id+')') 520 | } 521 | }) 522 | } 523 | 524 | function load_modal_add_machine() { 525 | $.ajax({ 526 | type: "POST", 527 | url: "api/get_users", 528 | success: function(response) { 529 | modal_body = document.getElementById('default_add_new_machine_modal'); 530 | modal_confirm = document.getElementById('new_machine_modal_confirm'); 531 | 532 | select_html = ` 533 |
    534 |
    535 | language 536 | 545 |
    546 |
    ` 547 | select_html = select_html + ` 548 |
    549 |
    550 | vpn_key 551 | 552 | 553 |
    554 |
    ` 555 | for (let i=0; i < response.users.length; i++) { 556 | var name = response["users"][i]["name"] 557 | select_html = select_html+`


    ` 558 | } 559 | select_html = select_html+`


    ` 560 | select_html = select_html+`


    ` 561 | 562 | modal_body.innerHTML = select_html 563 | // Initialize the form and the machine tabs 564 | M.FormSelect.init(document.querySelectorAll('select')) 565 | M.Tabs.init(document.getElementById('new_machine_tabs')); 566 | } 567 | }) 568 | } 569 | 570 | //----------------------------------------------------------- 571 | // Machine Page Actions 572 | //----------------------------------------------------------- 573 | function delete_chip(machine_id, chipsData) { 574 | // We need to get ALL the current tags -- We don't care about what's deleted, just what's remaining 575 | // chipsData is an array generated from from the creation of the array. 576 | chips = JSON.stringify(chipsData) 577 | 578 | var formattedData = []; 579 | for (let tag in chipsData) { 580 | formattedData[tag] = '"tag:'+chipsData[tag].tag+'"' 581 | } 582 | var tags_list = '{"tags": [' + formattedData + ']}' 583 | var data = {"id": machine_id, "tags_list": tags_list} 584 | 585 | $.ajax({ 586 | type:"POST", 587 | url: "api/set_machine_tags", 588 | data: JSON.stringify(data), 589 | contentType: "application/json", 590 | success: function(response) { 591 | M.toast({html: 'Tag removed.'}); 592 | } 593 | }) 594 | } 595 | 596 | function add_chip(machine_id, chipsData) { 597 | chips = JSON.stringify(chipsData).toLowerCase() 598 | chipsData[chipsData.length - 1].tag = chipsData[chipsData.length - 1].tag.trim().replace(/\s+/g, '-') 599 | last_chip_fixed = chipsData[chipsData.length - 1].tag 600 | 601 | var formattedData = []; 602 | for (let tag in chipsData) { 603 | formattedData[tag] = '"tag:'+chipsData[tag].tag+'"' 604 | } 605 | var tags_list = '{"tags": [' + formattedData + ']}' 606 | var data = {"id": machine_id, "tags_list": tags_list} 607 | 608 | $.ajax({ 609 | type:"POST", 610 | url: "api/set_machine_tags", 611 | data: JSON.stringify(data), 612 | contentType: "application/json", 613 | success: function(response) { 614 | M.toast({html: 'Tag "' + last_chip_fixed + '" added.'}); 615 | } 616 | }) 617 | } 618 | 619 | function add_machine() { 620 | var key = document.getElementById('add_machine_key_field').value 621 | var user = document.getElementById('add_machine_user_select').value 622 | var data = {"key": key, "user": user} 623 | 624 | if (user == "") { 625 | load_modal_generic("error", "User is empty", "Select a user before submitting") 626 | return 627 | } 628 | if (key == "") { 629 | load_modal_generic("error", "Key is empty", "Input the key generated by your tailscale login command") 630 | return 631 | } 632 | 633 | $.ajax({ 634 | type: "POST", 635 | url: "api/register_machine", 636 | data: JSON.stringify(data), 637 | contentType: "application/json", 638 | success: function(response) { 639 | alert("Response: "+response) 640 | } 641 | }) 642 | } 643 | 644 | function rename_machine(machine_id) { 645 | var new_name = document.getElementById('new_name_form').value; 646 | var data = {"id": machine_id, "new_name": new_name}; 647 | 648 | // String to test against 649 | var regexIT= /[`!@#$%^&*()_+\=\[\]{};':"\\|,.<>\/?~]/; 650 | if (regexIT.test(new_name)) { load_modal_generic("error", "Invalid Name", "Name cannot contain special characters ('"+regexIT+"')") ;return } 651 | // If there are characters other than - and alphanumeric, throw an error 652 | if (new_name.includes(' ')) { load_modal_generic("error", "Name cannot have spaces", "Allowed characters are dashes (-) and alphanumeric characters"); return } 653 | // If it is longer than 32 characters, throw an error 654 | if (new_name.length > 32) { load_modal_generic("error", "Name is too long", "The name name is too long. Maximum length is 32 characters"); return } 655 | // If the new_name is empty, throw an error 656 | if (!new_name) { load_modal_generic("error", "Name can't be empty", "Please enter a machine name before submitting."); return} 657 | 658 | $.ajax({ 659 | type:"POST", 660 | url: "api/rename_machine", 661 | data: JSON.stringify(data), 662 | contentType: "application/json", 663 | success: function(response) { 664 | 665 | if (response.status == "True") { 666 | // Get the modal element and close it 667 | modal_element = document.getElementById('card_modal') 668 | M.Modal.getInstance(modal_element).close() 669 | 670 | document.getElementById(machine_id+'-name-container').innerHTML = machine_id+". "+new_name 671 | M.toast({html: 'Machine '+machine_id+' renamed to '+new_name}); 672 | } else { 673 | load_modal_generic("error", "Error setting the machine name", "Headscale response: "+JSON.stringify(response.body.message)) 674 | } 675 | } 676 | }) 677 | } 678 | 679 | function move_machine(machine_id) { 680 | new_user = document.getElementById('move-select').value 681 | var data = {"id": machine_id, "new_user": new_user}; 682 | 683 | $.ajax({ 684 | type:"POST", 685 | url: "api/move_user", 686 | data: JSON.stringify(data), 687 | contentType: "application/json", 688 | success: function(response) { 689 | // Get the modal element and close it 690 | modal_element = document.getElementById('card_modal') 691 | M.Modal.getInstance(modal_element).close() 692 | 693 | document.getElementById(machine_id+'-user-container').innerHTML = response.machine.user.name 694 | document.getElementById(machine_id+'-ns-badge').innerHTML = response.machine.user.name 695 | 696 | // Get the color and set it 697 | var user_color = get_color(response.machine.user.id) 698 | document.getElementById(machine_id+'-ns-badge').className = "badge ipinfo " + user_color + " white-text hide-on-small-only" 699 | 700 | M.toast({html: "'"+response.machine.givenName+"' moved to user "+response.machine.user.name}); 701 | } 702 | }) 703 | } 704 | 705 | function delete_machine(machine_id) { 706 | var data = {"id": machine_id}; 707 | $.ajax({ 708 | type: "POST", 709 | url: "api/delete_machine", 710 | data: JSON.stringify(data), 711 | contentType: "application/json", 712 | success: function(response) { 713 | // Get the modal element and close it 714 | modal_element = document.getElementById('card_modal') 715 | M.Modal.getInstance(modal_element).close() 716 | 717 | // When the machine is deleted, hide its collapsible: 718 | document.getElementById(machine_id+'-main-collapsible').className = "collapsible popout hide"; 719 | 720 | M.toast({html: 'Machine deleted.'}); 721 | } 722 | }) 723 | } 724 | 725 | function toggle_route(route_id, current_state) { 726 | var data = {"route_id": route_id, "current_state": current_state} 727 | $.ajax({ 728 | type:"POST", 729 | url: "api/update_route", 730 | data: JSON.stringify(data), 731 | contentType: "application/json", 732 | success: function(response) { 733 | // Response is a JSON object containing the Headscale API response of /v1/api/machines//route 734 | var element = document.getElementById(route_id); 735 | var disabledClass = "waves-effect waves-light btn-small red lighten-2 tooltipped"; 736 | var enabledClass = "waves-effect waves-light btn-small green lighten-2 tooltipped"; 737 | var disabledTooltip = "Click to enable" 738 | var enabledTooltip = "Click to disable" 739 | var disableState = "False" 740 | var enableState = "True" 741 | var action_taken = "unchanged."; 742 | 743 | if (element.className == disabledClass) { 744 | // 1. Change the class to change the color of the icon 745 | // 2. Change the "action taken" for the M.toast popup 746 | // 3. Change the tooltip to say "Click to enable/disable" 747 | element.className = enabledClass 748 | var action_taken = "enabled." 749 | element.setAttribute('data-tooltip', enabledTooltip) 750 | element.setAttribute('onclick', 'toggle_route('+route_id+', "'+enableState+'")') 751 | } else if (element.className == enabledClass) { 752 | element.className = disabledClass 753 | var action_taken = "disabled." 754 | element.setAttribute('data-tooltip', disabledTooltip) 755 | element.setAttribute('onclick', 'toggle_route('+route_id+', "'+disableState+'")') 756 | } 757 | M.toast({html: 'Route '+action_taken}); 758 | } 759 | }) 760 | } 761 | 762 | //----------------------------------------------------------- 763 | // Machine Page Helpers 764 | //----------------------------------------------------------- 765 | function btn_toggle(state) { 766 | if (state == "show" ) { document.getElementById('new_machine_modal_confirm').className = 'green btn-flat white-text' } 767 | else { document.getElementById('new_machine_modal_confirm').className = 'green btn-flat white-text hide' } 768 | } 769 | 770 | //----------------------------------------------------------- 771 | // User Page Actions 772 | //----------------------------------------------------------- 773 | function rename_user(user_id, old_name) { 774 | var new_name = document.getElementById('new_user_name_form').value; 775 | var data = {"old_name": old_name, "new_name": new_name} 776 | 777 | // String to test against 778 | var regexIT= /[`!@#$%^&*()_+\=\[\]{};':"\\|,.<>\/?~]/; 779 | if (regexIT.test(new_name)) { load_modal_generic("error", "Invalid Name", "Name cannot contain special characters ('"+regexIT+"')") ;return } 780 | // If there are characters other than - and alphanumeric, throw an error 781 | if (new_name.includes(' ')) { load_modal_generic("error", "Name cannot have spaces", "Allowed characters are dashes (-) and alphanumeric characters"); return } 782 | // If it is longer than 32 characters, throw an error 783 | if (new_name.length > 32) { load_modal_generic("error", "Name is too long", "The user name is too long. Maximum length is 32 characters"); return } 784 | // If the new_name is empty, throw an error 785 | if (!new_name) { load_modal_generic("error", "Name can't be empty", "The user name cannot be empty."); return} 786 | 787 | $.ajax({ 788 | type: "POST", 789 | url: "api/rename_user", 790 | data: JSON.stringify(data), 791 | contentType: "application/json", 792 | success: function(response) { 793 | if (response.status == "True") { 794 | // Get the modal element and close it 795 | modal_element = document.getElementById('card_modal') 796 | M.Modal.getInstance(modal_element).close() 797 | 798 | // Rename the user on the page: 799 | document.getElementById(user_id+'-name-span').innerHTML = new_name 800 | 801 | // Set the button to use the NEW name as the OLD name for both buttons 802 | var rename_button_sm = document.getElementById(user_id+'-rename-user-sm') 803 | rename_button_sm.setAttribute('onclick', 'load_modal_rename_user('+user_id+', "'+new_name+'")') 804 | var rename_button_lg = document.getElementById(user_id+'-rename-user-lg') 805 | rename_button_lg.setAttribute('onclick', 'load_modal_rename_user('+user_id+', "'+new_name+'")') 806 | 807 | // Send the completion toast 808 | M.toast({html: "User '"+old_name+"' renamed to '"+new_name+"'."}) 809 | } else { 810 | load_modal_generic("error", "Error setting user name", "Headscale response: "+JSON.stringify(response.body.message)) 811 | } 812 | } 813 | }) 814 | } 815 | 816 | function delete_user(user_id, user_name) { 817 | var data = {"name": user_name}; 818 | $.ajax({ 819 | type: "POST", 820 | url: "api/delete_user", 821 | data: JSON.stringify(data), 822 | contentType: "application/json", 823 | success: function(response) { 824 | if (response.status == "True") { 825 | // Get the modal element and close it 826 | modal_element = document.getElementById('card_modal') 827 | M.Modal.getInstance(modal_element).close() 828 | 829 | // When the machine is deleted, hide its collapsible: 830 | document.getElementById(user_id+'-main-collapsible').className = "collapsible popout hide"; 831 | 832 | M.toast({html: 'User deleted.'}); 833 | } else { 834 | // We errored. Decipher the error Headscale sent us and display it: 835 | load_modal_generic("error", "Error deleting user", "Headscale response: "+JSON.stringify(response.body.message)) 836 | } 837 | } 838 | }) 839 | } 840 | 841 | function add_user() { 842 | var user_name = document.getElementById('add_user_name_field').value 843 | var data = {"name": user_name} 844 | $.ajax({ 845 | type: "POST", 846 | url: "api/add_user", 847 | data: JSON.stringify(data), 848 | contentType: "application/json", 849 | success: function(response) { 850 | if (response.status == "True") { 851 | // Get the modal element and close it 852 | modal_element = document.getElementById('card_modal') 853 | M.Modal.getInstance(modal_element).close() 854 | 855 | // Send the completion toast 856 | M.toast({html: "User '"+user_name+"' added to Headscale. Refreshing..."}) 857 | window.location.reload() 858 | } else { 859 | // We errored. Decipher the error Headscale sent us and display it: 860 | load_modal_generic("error", "Error adding user", "Headscale response: "+JSON.stringify(response.body.message)) 861 | } 862 | } 863 | }) 864 | } 865 | 866 | function add_preauth_key(user_name) { 867 | var date = document.getElementById('preauth_key_expiration_date').value 868 | var ephemeral = document.getElementById('checkbox-ephemeral').checked 869 | var reusable = document.getElementById('checkbox-reusable').checked 870 | var expiration = date+"T00:00:00.000Z" // Headscale format. 871 | 872 | // If there is no date, error: 873 | if (!date) {load_modal_generic("error", "Invalid Date", "Please enter a valid date"); return} 874 | var data = {"user": user_name, "reusable": reusable, "ephemeral": ephemeral, "expiration": expiration} 875 | 876 | $.ajax({ 877 | type: "POST", 878 | url: "api/add_preauth_key", 879 | data: JSON.stringify(data), 880 | contentType: "application/json", 881 | success: function(response) { 882 | if (response.status == "True") { 883 | // Send the completion toast 884 | M.toast({html: 'PreAuth key created in user '+user_name}) 885 | // If this is successfull, we should reload the table and close the modal: 886 | var user_data = {"name": user_name} 887 | $.ajax({ 888 | type: "POST", 889 | url: "api/build_preauthkey_table", 890 | data: JSON.stringify(user_data), 891 | contentType: "application/json", 892 | success: function(table_data) { 893 | table = document.getElementById(user_name+'-preauth-keys-collection') 894 | table.innerHTML = table_data 895 | // The tooltips need to be re-initialized afterwards: 896 | M.Tooltip.init(document.querySelectorAll('.tooltipped')) 897 | } 898 | }) 899 | // Get the modal element and close it 900 | modal_element = document.getElementById('card_modal') 901 | M.Modal.getInstance(modal_element).close() 902 | 903 | // The tooltips need to be re-initialized afterwards: 904 | M.Tooltip.init(document.querySelectorAll('.tooltipped')) 905 | 906 | } else { 907 | load_modal_generic("error", "Error adding a pre-auth key", "Headscale response: "+JSON.stringify(response.body.message)) 908 | } 909 | } 910 | }) 911 | } 912 | 913 | function expire_preauth_key(user_name, key) { 914 | var data = {"user": user_name, "key": key} 915 | 916 | $.ajax({ 917 | type: "POST", 918 | url: "api/expire_preauth_key", 919 | data: JSON.stringify(data), 920 | contentType: "application/json", 921 | success: function(response) { 922 | if (response.status == "True") { 923 | // Send the completion toast 924 | M.toast({html: 'PreAuth key created in user '+user_name}) 925 | // If this is successfull, we should reload the table and close the modal: 926 | var user_data = {"name": user_name} 927 | $.ajax({ 928 | type: "POST", 929 | url: "api/build_preauthkey_table", 930 | data: JSON.stringify(user_data), 931 | contentType: "application/json", 932 | success: function(table_data) { 933 | table = document.getElementById(user_name+'-preauth-keys-collection') 934 | table.innerHTML = table_data 935 | // The tooltips need to be re-initialized afterwards: 936 | M.Tooltip.init(document.querySelectorAll('.tooltipped')) 937 | } 938 | }) 939 | // Get the modal element and close it 940 | modal_element = document.getElementById('card_modal') 941 | M.Modal.getInstance(modal_element).close() 942 | 943 | // The tooltips need to be re-initialized afterwards: 944 | M.Tooltip.init(document.querySelectorAll('.tooltipped')) 945 | 946 | } else { 947 | load_modal_generic("error", "Error adding a pre-auth key", "Headscale response: "+JSON.stringify(response.body.message)) 948 | } 949 | } 950 | }) 951 | } 952 | 953 | //----------------------------------------------------------- 954 | // User Page Helpers 955 | //----------------------------------------------------------- 956 | // Toggle expired items on the Users PreAuth section: 957 | function toggle_expired() { 958 | var toggle_hide = document.getElementsByClassName('expired-row'); 959 | var hidden = document.getElementsByClassName('expired-row hide'); 960 | 961 | if (hidden.length == 0) { 962 | for (var i = 0; i < toggle_hide.length; i++) { 963 | toggle_hide[i].className = "expired-row hide"; 964 | } 965 | } else if (hidden.length > 0) { 966 | for (var i = 0; i < toggle_hide.length; i++) { 967 | toggle_hide[i].className = "expired-row"; 968 | } 969 | } 970 | } 971 | -------------------------------------------------------------------------------- /static/old/js/iconify-icon.min.js: -------------------------------------------------------------------------------- 1 | /** 2 | * (c) Iconify 3 | * 4 | * For the full copyright and license information, please view the license.txt 5 | * files at https://github.com/iconify/iconify 6 | * 7 | * Licensed under MIT. 8 | * 9 | * @license MIT 10 | * @version 1.0.0 11 | */ 12 | !function(){"use strict";const t=Object.freeze({left:0,top:0,width:16,height:16}),e=Object.freeze({rotate:0,vFlip:!1,hFlip:!1}),n=Object.freeze({...t,...e}),o=Object.freeze({...n,body:"",hidden:!1}),i=Object.freeze({width:null,height:null}),r=Object.freeze({...i,...e});const s=/[\s,]+/;const c={...r,preserveAspectRatio:""};function a(t){const e={...c},n=(e,n)=>t.getAttribute(e)||n;var o;return e.width=n("width",null),e.height=n("height",null),e.rotate=function(t,e=0){const n=t.replace(/^-?[0-9.]*/,"");function o(t){for(;t<0;)t+=4;return t%4}if(""===n){const e=parseInt(t);return isNaN(e)?0:o(e)}if(n!==t){let e=0;switch(n){case"%":e=25;break;case"deg":e=90}if(e){let i=parseFloat(t.slice(0,t.length-n.length));return isNaN(i)?0:(i/=e,i%1==0?o(i):0)}}return e}(n("rotate","")),o=e,n("flip","").split(s).forEach((t=>{switch(t.trim()){case"horizontal":o.hFlip=!0;break;case"vertical":o.vFlip=!0}})),e.preserveAspectRatio=n("preserveAspectRatio",n("preserveaspectratio","")),e}const u=/^[a-z0-9]+(-[a-z0-9]+)*$/,l=(t,e,n,o="")=>{const i=t.split(":");if("@"===t.slice(0,1)){if(i.length<2||i.length>3)return null;o=i.shift().slice(1)}if(i.length>3||!i.length)return null;if(i.length>1){const t=i.pop(),n=i.pop(),r={provider:i.length>0?i[0]:o,prefix:n,name:t};return e&&!f(r)?null:r}const r=i[0],s=r.split("-");if(s.length>1){const t={provider:o,prefix:s.shift(),name:s.join("-")};return e&&!f(t)?null:t}if(n&&""===o){const t={provider:o,prefix:"",name:r};return e&&!f(t,n)?null:t}return null},f=(t,e)=>!!t&&!(""!==t.provider&&!t.provider.match(u)||!(e&&""===t.prefix||t.prefix.match(u))||!t.name.match(u));function d(t,n){const i=function(t,e){const n={};!t.hFlip!=!e.hFlip&&(n.hFlip=!0),!t.vFlip!=!e.vFlip&&(n.vFlip=!0);const o=((t.rotate||0)+(e.rotate||0))%4;return o&&(n.rotate=o),n}(t,n);for(const r in o)r in e?r in t&&!(r in i)&&(i[r]=e[r]):r in n?i[r]=n[r]:r in t&&(i[r]=t[r]);return i}function h(t,e,n){const o=t.icons,i=t.aliases||{};let r={};function s(t){r=d(o[t]||i[t],r)}return s(e),n.forEach(s),d(t,r)}function p(t,e){const n=[];if("object"!=typeof t||"object"!=typeof t.icons)return n;t.not_found instanceof Array&&t.not_found.forEach((t=>{e(t,null),n.push(t)}));const o=function(t,e){const n=t.icons,o=t.aliases||{},i=Object.create(null);return(e||Object.keys(n).concat(Object.keys(o))).forEach((function t(e){if(n[e])return i[e]=[];if(!(e in i)){i[e]=null;const n=o[e]&&o[e].parent,r=n&&t(n);r&&(i[e]=[n].concat(r))}return i[e]})),i}(t);for(const i in o){const r=o[i];r&&(e(i,h(t,i,r)),n.push(i))}return n}const g={provider:"",aliases:{},not_found:{},...t};function m(t,e){for(const n in e)if(n in t&&typeof t[n]!=typeof e[n])return!1;return!0}function b(t){if("object"!=typeof t||null===t)return null;const e=t;if("string"!=typeof e.prefix||!t.icons||"object"!=typeof t.icons)return null;if(!m(t,g))return null;const n=e.icons;for(const t in n){const e=n[t];if(!t.match(u)||"string"!=typeof e.body||!m(e,o))return null}const i=e.aliases||{};for(const t in i){const e=i[t],r=e.parent;if(!t.match(u)||"string"!=typeof r||!n[r]&&!i[r]||!m(e,o))return null}return e}const y=Object.create(null);function v(t,e){const n=y[t]||(y[t]=Object.create(null));return n[e]||(n[e]=function(t,e){return{provider:t,prefix:e,icons:Object.create(null),missing:new Set}}(t,e))}function x(t,e){return b(e)?p(e,((e,n)=>{n?t.icons[e]=n:t.missing.add(e)})):[]}function w(t,e){let n=[];return("string"==typeof t?[t]:Object.keys(y)).forEach((t=>{("string"==typeof t&&"string"==typeof e?[e]:Object.keys(y[t]||{})).forEach((e=>{const o=v(t,e);n=n.concat(Object.keys(o.icons).map((n=>(""!==t?"@"+t+":":"")+e+":"+n)))}))})),n}let k=!1;function j(t){return"boolean"==typeof t&&(k=t),k}function _(t){const e="string"==typeof t?l(t,!0,k):t;if(e){const t=v(e.provider,e.prefix),n=e.name;return t.icons[n]||(t.missing.has(n)?null:void 0)}}function C(t,e){const n=l(t,!0,k);if(!n)return!1;return function(t,e,n){try{if("string"==typeof n.body)return t.icons[e]={...n},!0}catch(t){}return!1}(v(n.provider,n.prefix),n.name,e)}function A(t,e){if("object"!=typeof t)return!1;if("string"!=typeof e&&(e=t.provider||""),k&&!e&&!t.prefix){let e=!1;return b(t)&&(t.prefix="",p(t,((t,n)=>{n&&C(t,n)&&(e=!0)}))),e}const n=t.prefix;if(!f({provider:e,prefix:n,name:"a"}))return!1;return!!x(v(e,n),t)}function O(t){return!!_(t)}function S(t){const e=_(t);return e?{...n,...e}:null}function I(t,e){t.forEach((t=>{const n=t.loaderCallbacks;n&&(t.loaderCallbacks=n.filter((t=>t.id!==e)))}))}let E=0;const M=Object.create(null);function T(t,e){M[t]=e}function F(t){return M[t]||M[""]}var P={resources:[],index:0,timeout:2e3,rotate:750,random:!1,dataAfterTimeout:!1};function R(t,e,n,o){const i=t.resources.length,r=t.random?Math.floor(Math.random()*i):t.index;let s;if(t.random){let e=t.resources.slice(0);for(s=[];e.length>1;){const t=Math.floor(Math.random()*e.length);s.push(e[t]),e=e.slice(0,t).concat(e.slice(t+1))}s=s.concat(e)}else s=t.resources.slice(r).concat(t.resources.slice(0,r));const c=Date.now();let a,u="pending",l=0,f=null,d=[],h=[];function p(){f&&(clearTimeout(f),f=null)}function g(){"pending"===u&&(u="aborted"),p(),d.forEach((t=>{"pending"===t.status&&(t.status="aborted")})),d=[]}function m(t,e){e&&(h=[]),"function"==typeof t&&h.push(t)}function b(){u="failed",h.forEach((t=>{t(void 0,a)}))}function y(){d.forEach((t=>{"pending"===t.status&&(t.status="aborted")})),d=[]}function v(){if("pending"!==u)return;p();const o=s.shift();if(void 0===o)return d.length?void(f=setTimeout((()=>{p(),"pending"===u&&(y(),b())}),t.timeout)):void b();const i={status:"pending",resource:o,callback:(e,n)=>{!function(e,n,o){const i="success"!==n;switch(d=d.filter((t=>t!==e)),u){case"pending":break;case"failed":if(i||!t.dataAfterTimeout)return;break;default:return}if("abort"===n)return a=o,void b();if(i)return a=o,void(d.length||(s.length?v():b()));if(p(),y(),!t.random){const n=t.resources.indexOf(e.resource);-1!==n&&n!==t.index&&(t.index=n)}u="completed",h.forEach((t=>{t(o)}))}(i,e,n)}};d.push(i),l++,f=setTimeout(v,t.rotate),n(o,e,i.callback)}return"function"==typeof o&&h.push(o),setTimeout(v),function(){return{startTime:c,payload:e,status:u,queriesSent:l,queriesPending:d.length,subscribe:m,abort:g}}}function L(t){const e={...P,...t};let n=[];function o(){n=n.filter((t=>"pending"===t().status))}return{query:function(t,i,r){const s=R(e,t,i,((t,e)=>{o(),r&&r(t,e)}));return n.push(s),s},find:function(t){return n.find((e=>t(e)))||null},setIndex:t=>{e.index=t},getIndex:()=>e.index,cleanup:o}}function N(t){let e;if("string"==typeof t.resources)e=[t.resources];else if(e=t.resources,!(e instanceof Array&&e.length))return null;return{resources:e,path:t.path||"/",maxURL:t.maxURL||500,rotate:t.rotate||750,timeout:t.timeout||5e3,random:!0===t.random,index:t.index||0,dataAfterTimeout:!1!==t.dataAfterTimeout}}const z=Object.create(null),Q=["https://api.simplesvg.com","https://api.unisvg.com"],q=[];for(;Q.length>0;)1===Q.length||Math.random()>.5?q.push(Q.shift()):q.push(Q.pop());function D(t,e){const n=N(e);return null!==n&&(z[t]=n,!0)}function J(t){return z[t]}function U(){return Object.keys(z)}function $(){}z[""]=N({resources:["https://api.iconify.design"].concat(q)});const H=Object.create(null);function B(t,e,n){let o,i;if("string"==typeof t){const e=F(t);if(!e)return n(void 0,424),$;i=e.send;const r=function(t){if(!H[t]){const e=J(t);if(!e)return;const n={config:e,redundancy:L(e)};H[t]=n}return H[t]}(t);r&&(o=r.redundancy)}else{const e=N(t);if(e){o=L(e);const n=F(t.resources?t.resources[0]:"");n&&(i=n.send)}}return o&&i?o.query(e,i,n)().abort:(n(void 0,424),$)}const G="iconify2",K="iconify",V="iconify-count",W="iconify-version",X=36e5;function Y(t,e){try{return t.getItem(e)}catch(t){}}function Z(t,e,n){try{return t.setItem(e,n),!0}catch(t){}}function tt(t,e){try{t.removeItem(e)}catch(t){}}function et(t,e){return Z(t,V,e.toString())}function nt(t){return parseInt(Y(t,V))||0}const ot={local:!0,session:!0},it={local:new Set,session:new Set};let rt=!1;let st="undefined"==typeof window?{}:window;function ct(t){const e=t+"Storage";try{if(st&&st[e]&&"number"==typeof st[e].length)return st[e]}catch(t){}ot[t]=!1}function at(t,e){const n=ct(t);if(!n)return;const o=Y(n,W);if(o!==G){if(o){const t=nt(n);for(let e=0;e{const o=K+t.toString(),r=Y(n,o);if("string"==typeof r){try{const n=JSON.parse(r);if("object"==typeof n&&"number"==typeof n.cached&&n.cached>i&&"string"==typeof n.provider&&"object"==typeof n.data&&"string"==typeof n.data.prefix&&e(n,t))return!0}catch(t){}tt(n,o)}};let s=nt(n);for(let e=s-1;e>=0;e--)r(e)||(e===s-1?(s--,et(n,s)):it[t].add(e))}function ut(){if(!rt){rt=!0;for(const t in ot)at(t,(t=>{const e=t.data,n=v(t.provider,e.prefix);if(!x(n,e).length)return!1;const o=e.lastModified||-1;return n.lastModifiedCached=n.lastModifiedCached?Math.min(n.lastModifiedCached,o):o,!0}))}}function lt(t,e){function n(n){let o;if(!ot[n]||!(o=ct(n)))return;const i=it[n];let r;if(i.size)i.delete(r=Array.from(i).shift());else if(r=nt(o),!et(o,r+1))return;const s={cached:Math.floor(Date.now()/X),provider:t.provider,data:e};return Z(o,K+r.toString(),JSON.stringify(s))}rt||ut(),e.lastModified&&!function(t,e){const n=t.lastModifiedCached;if(n&&n>=e)return n===e;if(t.lastModifiedCached=e,n)for(const n in ot)at(n,(n=>{const o=n.data;return n.provider!==t.provider||o.prefix!==t.prefix||o.lastModified===e}));return!0}(t,e.lastModified)||Object.keys(e.icons).length&&(e.not_found&&delete(e=Object.assign({},e)).not_found,n("local")||n("session"))}function ft(){}function dt(t){t.iconsLoaderFlag||(t.iconsLoaderFlag=!0,setTimeout((()=>{t.iconsLoaderFlag=!1,function(t){t.pendingCallbacksFlag||(t.pendingCallbacksFlag=!0,setTimeout((()=>{t.pendingCallbacksFlag=!1;const e=t.loaderCallbacks?t.loaderCallbacks.slice(0):[];if(!e.length)return;let n=!1;const o=t.provider,i=t.prefix;e.forEach((e=>{const r=e.icons,s=r.pending.length;r.pending=r.pending.filter((e=>{if(e.prefix!==i)return!0;const s=e.name;if(t.icons[s])r.loaded.push({provider:o,prefix:i,name:s});else{if(!t.missing.has(s))return n=!0,!0;r.missing.push({provider:o,prefix:i,name:s})}return!1})),r.pending.length!==s&&(n||I([t],e.id),e.callback(r.loaded.slice(0),r.missing.slice(0),r.pending.slice(0),e.abort))}))})))}(t)})))}const ht=(t,e)=>{const n=function(t,e=!0,n=!1){const o=[];return t.forEach((t=>{const i="string"==typeof t?l(t,e,n):t;i&&o.push(i)})),o}(t,!0,j()),o=function(t){const e={loaded:[],missing:[],pending:[]},n=Object.create(null);t.sort(((t,e)=>t.provider!==e.provider?t.provider.localeCompare(e.provider):t.prefix!==e.prefix?t.prefix.localeCompare(e.prefix):t.name.localeCompare(e.name)));let o={provider:"",prefix:"",name:""};return t.forEach((t=>{if(o.name===t.name&&o.prefix===t.prefix&&o.provider===t.provider)return;o=t;const i=t.provider,r=t.prefix,s=t.name,c=n[i]||(n[i]=Object.create(null)),a=c[r]||(c[r]=v(i,r));let u;u=s in a.icons?e.loaded:""===r||a.missing.has(s)?e.missing:e.pending;const l={provider:i,prefix:r,name:s};u.push(l)})),e}(n);if(!o.pending.length){let t=!0;return e&&setTimeout((()=>{t&&e(o.loaded,o.missing,o.pending,ft)})),()=>{t=!1}}const i=Object.create(null),r=[];let s,c;return o.pending.forEach((t=>{const{provider:e,prefix:n}=t;if(n===c&&e===s)return;s=e,c=n,r.push(v(e,n));const o=i[e]||(i[e]=Object.create(null));o[n]||(o[n]=[])})),o.pending.forEach((t=>{const{provider:e,prefix:n,name:o}=t,r=v(e,n),s=r.pendingIcons||(r.pendingIcons=new Set);s.has(o)||(s.add(o),i[e][n].push(o))})),r.forEach((t=>{const{provider:e,prefix:n}=t;i[e][n].length&&function(t,e){t.iconsToLoad?t.iconsToLoad=t.iconsToLoad.concat(e).sort():t.iconsToLoad=e,t.iconsQueueFlag||(t.iconsQueueFlag=!0,setTimeout((()=>{t.iconsQueueFlag=!1;const{provider:e,prefix:n}=t,o=t.iconsToLoad;let i;delete t.iconsToLoad,o&&(i=F(e))&&i.prepare(e,n,o).forEach((n=>{B(e,n,((e,o)=>{if("object"!=typeof e){if(404!==o)return;n.icons.forEach((e=>{t.missing.add(e)}))}else try{const n=x(t,e);if(!n.length)return;const o=t.pendingIcons;o&&n.forEach((t=>{o.delete(t)})),lt(t,e)}catch(t){console.error(t)}dt(t)}))}))})))}(t,i[e][n])})),e?function(t,e,n){const o=E++,i=I.bind(null,n,o);if(!e.pending.length)return i;const r={id:o,icons:e,callback:t,abort:i};return n.forEach((t=>{(t.loaderCallbacks||(t.loaderCallbacks=[])).push(r)})),i}(e,o,r):ft},pt=t=>new Promise(((e,o)=>{const i="string"==typeof t?l(t):t;ht([i||t],(r=>{if(r.length&&i){const t=_(i);if(t)return void e({...n,...t})}o(t)}))}));function gt(t,e){const n="string"==typeof t?l(t,!0,!0):null;if(!n){const e=function(t){try{const e="string"==typeof t?JSON.parse(t):t;if("string"==typeof e.body)return{...e}}catch(t){}}(t);return{value:t,data:e}}const o=_(n);if(void 0!==o||!n.prefix)return{value:t,name:n,data:o};const i=ht([n],(()=>e(t,n,_(n))));return{value:t,name:n,loading:i}}function mt(t){return t.hasAttribute("inline")}let bt=!1;try{bt=0===navigator.vendor.indexOf("Apple")}catch(t){}const yt=/(-?[0-9.]*[0-9]+[0-9.]*)/g,vt=/^-?[0-9.]*[0-9]+[0-9.]*$/g;function xt(t,e,n){if(1===e)return t;if(n=n||100,"number"==typeof t)return Math.ceil(t*e*n)/n;if("string"!=typeof t)return t;const o=t.split(yt);if(null===o||!o.length)return t;const i=[];let r=o.shift(),s=vt.test(r);for(;;){if(s){const t=parseFloat(r);isNaN(t)?i.push(r):i.push(Math.ceil(t*e*n)/n)}else i.push(r);if(r=o.shift(),void 0===r)return i.join("");s=!s}}function wt(t,e){const o={...n,...t},i={...r,...e},s={left:o.left,top:o.top,width:o.width,height:o.height};let c=o.body;[o,i].forEach((t=>{const e=[],n=t.hFlip,o=t.vFlip;let i,r=t.rotate;switch(n?o?r+=2:(e.push("translate("+(s.width+s.left).toString()+" "+(0-s.top).toString()+")"),e.push("scale(-1 1)"),s.top=s.left=0):o&&(e.push("translate("+(0-s.left).toString()+" "+(s.height+s.top).toString()+")"),e.push("scale(1 -1)"),s.top=s.left=0),r<0&&(r-=4*Math.floor(r/4)),r%=4,r){case 1:i=s.height/2+s.top,e.unshift("rotate(90 "+i.toString()+" "+i.toString()+")");break;case 2:e.unshift("rotate(180 "+(s.width/2+s.left).toString()+" "+(s.height/2+s.top).toString()+")");break;case 3:i=s.width/2+s.left,e.unshift("rotate(-90 "+i.toString()+" "+i.toString()+")")}r%2==1&&(s.left!==s.top&&(i=s.left,s.left=s.top,s.top=i),s.width!==s.height&&(i=s.width,s.width=s.height,s.height=i)),e.length&&(c=''+c+"")}));const a=i.width,u=i.height,l=s.width,f=s.height;let d,h;null===a?(h=null===u?"1em":"auto"===u?f:u,d=xt(h,l/f)):(d="auto"===a?l:a,h=null===u?xt(d,f/l):"auto"===u?f:u);return{attributes:{width:d.toString(),height:h.toString(),viewBox:s.left.toString()+" "+s.top.toString()+" "+l.toString()+" "+f.toString()},body:c}}let kt=(()=>{let t;try{if(t=fetch,"function"==typeof t)return t}catch(t){}})();function jt(t){kt=t}function _t(){return kt}const Ct={prepare:(t,e,n)=>{const o=[],i=function(t,e){const n=J(t);if(!n)return 0;let o;if(n.maxURL){let t=0;n.resources.forEach((e=>{const n=e;t=Math.max(t,n.length)}));const i=e+".json?icons=";o=n.maxURL-t-n.path.length-i.length}else o=0;return o}(t,e),r="icons";let s={type:r,provider:t,prefix:e,icons:[]},c=0;return n.forEach(((n,a)=>{c+=n.length+1,c>=i&&a>0&&(o.push(s),s={type:r,provider:t,prefix:e,icons:[]},c=n.length),s.icons.push(n)})),o.push(s),o},send:(t,e,n)=>{if(!kt)return void n("abort",424);let o=function(t){if("string"==typeof t){const e=J(t);if(e)return e.path}return"/"}(e.provider);switch(e.type){case"icons":{const t=e.prefix,n=e.icons.join(",");o+=t+".json?"+new URLSearchParams({icons:n}).toString();break}case"custom":{const t=e.uri;o+="/"===t.slice(0,1)?t.slice(1):t;break}default:return void n("abort",400)}let i=503;kt(t+o).then((t=>{const e=t.status;if(200===e)return i=501,t.json();setTimeout((()=>{n(function(t){return 404===t}(e)?"abort":"next",e)}))})).then((t=>{"object"==typeof t&&null!==t?setTimeout((()=>{n("success",t)})):setTimeout((()=>{n("next",i)}))})).catch((()=>{n("next",i)}))}};function At(t,e){switch(t){case"local":case"session":ot[t]=e;break;case"all":for(const t in ot)ot[t]=e}}function Ot(t,e){let n=-1===t.indexOf("xlink:")?"":' xmlns:xlink="http://www.w3.org/1999/xlink"';for(const t in e)n+=" "+t+'="'+e[t]+'"';return'"+t+""}const St={"background-color":"currentColor"},It={"background-color":"transparent"},Et={image:"var(--svg)",repeat:"no-repeat",size:"100% 100%"},Mt={"-webkit-mask":St,mask:St,background:It};for(const t in Mt){const e=Mt[t];for(const n in Et)e[t+"-"+n]=Et[n]}function Tt(t){return t+(t.match(/^[-0-9.]+$/)?"px":"")}function Ft(t,e){const o=e.icon.data,i=e.customisations,r=wt(o,i);i.preserveAspectRatio&&(r.attributes.preserveAspectRatio=i.preserveAspectRatio);const s=e.renderedMode;let c;if("svg"===s)c=function(t){const e=document.createElement("span");return e.innerHTML=Ot(t.body,t.attributes),e.firstChild}(r);else c=function(t,e,n){const o=document.createElement("span");let i=t.body;-1!==i.indexOf("/g,"%3E").replace(/\s+/g," ")+'")'),c=o.style,a={"--svg":s,width:Tt(r.width),height:Tt(r.height),...n?St:It};var u;for(const t in a)c.setProperty(t,a[t]);return o}(r,{...n,...o},"mask"===s);if(t.childNodes.length>1){const e=t.lastChild;"SPAN"===c.tagName&&e.tagName===c.tagName?e.setAttribute("style",c.getAttribute("style")):t.replaceChild(c,e)}else t.appendChild(c)}function Pt(t,e){let n=t.firstChild;n||(n=document.createElement("style"),t.appendChild(n)),n.textContent=":host{display:inline-block;vertical-align:"+(e?"-0.125em":"0")+"}span,svg{display:block}"}function Rt(t,e,n){return{rendered:!1,inline:e,icon:t,lastRender:n&&(n.rendered?n:n.lastRender)}}!function(t="iconify-icon"){let e,n;try{e=window.customElements,n=window.HTMLElement}catch(t){return}if(!e||!n)return;const o=e.get(t);if(o)return o;const i=["icon","mode","inline","width","height","rotate","flip"],r=class extends n{_shadowRoot;_state;_checkQueued=!1;constructor(){super();const t=this._shadowRoot=this.attachShadow({mode:"closed"}),e=mt(this);Pt(t,e),this._state=Rt({value:""},e),this._queueCheck()}static get observedAttributes(){return i.slice(0)}attributeChangedCallback(t){if("inline"===t){const t=mt(this),e=this._state;t!==e.inline&&(e.inline=t,Pt(this._shadowRoot,t))}else this._queueCheck()}get icon(){const t=this.getAttribute("icon");if(t&&"{"===t.slice(0,1))try{return JSON.parse(t)}catch(t){}return t}set icon(t){"object"==typeof t&&(t=JSON.stringify(t)),this.setAttribute("icon",t)}get inline(){return mt(this)}set inline(t){this.setAttribute("inline",t?"true":null)}restartAnimation(){const t=this._state;if(t.rendered){const e=this._shadowRoot;if("svg"===t.renderedMode)try{return void e.lastChild.setCurrentTime(0)}catch(t){}Ft(e,t)}}get status(){const t=this._state;return t.rendered?"rendered":null===t.icon.data?"failed":"loading"}_queueCheck(){this._checkQueued||(this._checkQueued=!0,setTimeout((()=>{this._check()})))}_check(){if(!this._checkQueued)return;this._checkQueued=!1;const t=this._state,e=this.getAttribute("icon");if(e!==t.icon.value)return void this._iconChanged(e);if(!t.rendered)return;const n=this.getAttribute("mode"),o=a(this);(t.attrMode!==n||function(t,e){for(const n in c)if(t[n]!==e[n])return!0;return!1}(t.customisations,o))&&this._renderIcon(t.icon,o,n)}_iconChanged(t){const e=gt(t,((t,e,n)=>{const o=this._state;if(o.rendered||this.getAttribute("icon")!==t)return;const i={value:t,name:e,data:n};i.data?this._gotIconData(i):o.icon=i}));e.data?this._gotIconData(e):this._state=Rt(e,this._state.inline,this._state)}_gotIconData(t){this._checkQueued=!1,this._renderIcon(t,a(this),this.getAttribute("mode"))}_renderIcon(t,e,n){const o=function(t,e){switch(e){case"svg":case"bg":case"mask":return e}return"style"===e||!bt&&-1!==t.indexOf("{t in r.prototype||Object.defineProperty(r.prototype,t,{get:function(){return this.getAttribute(t)},set:function(e){this.setAttribute(t,e)}})}));const s=function(){let t;T("",Ct),j(!0);try{t=window}catch(t){}if(t){if(ut(),void 0!==t.IconifyPreload){const e=t.IconifyPreload,n="Invalid IconifyPreload syntax.";"object"==typeof e&&null!==e&&(e instanceof Array?e:[e]).forEach((t=>{try{("object"!=typeof t||null===t||t instanceof Array||"object"!=typeof t.icons||"string"!=typeof t.prefix||!A(t))&&console.error(n)}catch(t){console.error(n)}}))}if(void 0!==t.IconifyProviders){const e=t.IconifyProviders;if("object"==typeof e&&null!==e)for(const t in e){const n="IconifyProviders["+t+"] is invalid.";try{const o=e[t];if("object"!=typeof o||!o||void 0===o.resources)continue;D(t,o)||console.error(n)}catch(t){console.error(n)}}}}return{enableCache:t=>At(t,!0),disableCache:t=>At(t,!1),iconExists:O,getIcon:S,listIcons:w,addIcon:C,addCollection:A,calculateSize:xt,buildIcon:wt,loadIcons:ht,loadIcon:pt,addAPIProvider:D,_api:{getAPIConfig:J,setAPIModule:T,sendAPIQuery:B,setFetch:jt,getFetch:_t,listAPIProviders:U}}}();for(const t in s)r[t]=r.prototype[t]=s[t];e.define(t,r)}()}(); 13 | -------------------------------------------------------------------------------- /templates/machines.html: -------------------------------------------------------------------------------- 1 | {% extends 'template.html' %} 2 | {% set page = "Machines" %} 3 | {% set machines_active = "active" %} 4 | 5 | {% block title %} {{ page }} {% endblock %} 6 | {% block header %} {{ page }} {% endblock %} 7 | 8 | {% block content %} 9 |

    10 | {{ cards }} 11 |
    12 | 13 | 14 | 24 | 25 | 26 | 78 | 79 |
    80 | 84 | add 85 | 86 |
    87 | 88 | {% endblock %} -------------------------------------------------------------------------------- /templates/machines_card.html: -------------------------------------------------------------------------------- 1 |
      2 |
    • 3 |
      4 |
      5 | {{ status_badge }} 6 | 7 | {{ machine_id }}. {{ given_name }} 8 | 9 |
      10 | 11 |
      12 | {{ user_badge }} 13 | {{ exit_node_badge }} 14 |
      15 |
      16 |
      17 |
        18 |
      • 19 | settings 20 | Machine Actions 21 |

        22 | Rename 23 | Move 24 | Delete 25 |

        26 |

        27 |

        32 |

        33 |
      • 34 |
      • 35 | domain 36 | Hostname 37 |

        {{ hostname }}

        38 |
      • 39 |
      • 40 | language 41 | User 42 |

        {{ ns_name }}

        43 |
      • 44 |
      • 45 | network_wifi 46 | IP Addresses 47 |

        {{ machine_ips}}

        48 |
      • 49 |
      • 50 | access_time 51 | Last Seen 52 |

        {{ last_seen_time}}

        53 |
      • 54 |
      • 55 | update 56 | Last Update 57 |

        {{ last_update_time }}

        58 |
      • 59 |
      • 60 | update 61 | Created At 62 |

        {{ created_time }}

        63 |
      • 64 |
      • 65 | key 66 | PreAuth Key Prefix 67 |

        {{ preauth_key }}

        68 |
      • 69 | {{ advertised_routes }} 70 | {{ machine_tags }} 71 |
      72 |
      73 |
    • 74 |
    -------------------------------------------------------------------------------- /templates/overview.html: -------------------------------------------------------------------------------- 1 | {% extends 'template.html' %} 2 | {% set page = "Overview" %} 3 | {% set overview_active = "active" %} 4 | 5 | {% block title %} {{ page }} {% endblock %} 6 | {% block header %} {{ page }} {% endblock %} 7 | 8 | {% block content %} 9 | {{ render_page }} 10 | {% endblock %} -------------------------------------------------------------------------------- /templates/settings.html: -------------------------------------------------------------------------------- 1 | {% extends 'template.html' %} 2 | {% set page = "Settings" %} 3 | {% set settings_active = "active" %} 4 | {% block title %} {{ page }} {% endblock %} 5 | {% block header %} {{ page }} {% endblock %} 6 | 7 | {% block content %} 8 |

    9 |
    10 |
    11 |
    12 |
    13 | Server Information 14 |
    15 | vpn_key 16 | 17 | 18 |
    19 |
    20 |
    21 | Save 22 | Test 23 | Instructions 24 |
    25 |
    26 |
    27 |
    28 |
    29 |
    30 |
    31 |
    32 |
    33 |
    34 | About 35 |

    This was developed with Flask, Python, MaterializeCSS, and jQuery.

    36 |

    Version: {{ APP_VERSION }}

    37 |

    Tested on Headscale: {{ HS_VERSION }}

    38 |
    39 |
    40 |
    41 |
    42 |
    43 | 44 | 57 | 66 | 75 | {% endblock %} -------------------------------------------------------------------------------- /templates/template.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ●::[●●] {% block title %} {% endblock %} 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 61 | 67 |
    68 | {% block content %} {% endblock %} 69 |
    70 | 71 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /templates/users.html: -------------------------------------------------------------------------------- 1 | {% extends 'template.html' %} 2 | {% set page = "Users" %} 3 | {% set users_active = "active" %} 4 | 5 | {% block title %} {{ page }} {% endblock %} 6 | {% block header %} {{ page }} {% endblock %} 7 | 8 | {% block content %} 9 |

    10 | {{ cards }} 11 |
    12 | 13 | 14 | 24 | 25 | 26 | 44 | 45 |
    46 | 49 | add 50 | 51 |
    52 | {% endblock %} -------------------------------------------------------------------------------- /templates/users_card.html: -------------------------------------------------------------------------------- 1 | --------------------------------------------------------------------------------