Compare commits

..

1 Commits

Author SHA1 Message Date
Maxi Quoß f21161dc7d add debug logging for wake cron #669 2024-07-31 18:16:38 +02:00
206 changed files with 11653 additions and 15207 deletions
+24
View File
@@ -0,0 +1,24 @@
version: 2
updates:
- package-ecosystem: gomod
directory: "/backend"
schedule:
interval: daily
open-pull-requests-limit: 10
commit-message:
prefix: go-dep
- package-ecosystem: npm
directory: "/frontend"
schedule:
interval: daily
open-pull-requests-limit: 10
commit-message:
prefix: npm-dep
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 10
commit-message:
prefix: gh-action
+1 -1
View File
@@ -10,7 +10,7 @@ jobs:
codeberg:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: pixta-dev/repository-mirroring-action@v1
@@ -0,0 +1,25 @@
name: dependabot automerge
on:
pull_request:
workflow_dispatch:
permissions:
contents: write
pull-requests: write
jobs:
dependabot:
runs-on: ubuntu-latest
if: ${{ github.actor == 'dependabot[bot]' }}
steps:
- name: Dependabot metadata
id: metadata
uses: dependabot/fetch-metadata@v2
with:
github-token: "${{ secrets.GITHUB_TOKEN }}"
- name: Enable auto-merge for Dependabot PRs
if: ${{steps.metadata.outputs.update-type == 'version-update:semver-patch'}} || ${{steps.metadata.outputs.update-type == 'version-update:semver-minor'}}
run: gh pr merge --auto --rebase "$PR_URL"
env:
PR_URL: ${{github.event.pull_request.html_url}}
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
+2 -2
View File
@@ -25,9 +25,9 @@ jobs:
needs: check-runner
runs-on: ${{ needs.check-runner.outputs.runner-label }}
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v6
uses: actions/setup-go@v5
with:
go-version-file: "./backend/go.mod"
cache-dependency-path: "./backend/go.sum"
+39 -104
View File
@@ -15,9 +15,7 @@ jobs:
- name: Set runner
id: set-runner
run: |
runners=$(curl -s -H "Accept: application/vnd.github+json" \
-H "Authorization: token ${{ secrets.REPO_ACCESS_TOKEN }}" \
"https://api.github.com/repos/${{ github.repository }}/actions/runners")
runners=$(curl -s -H "Accept: application/vnd.github+json" -H "Authorization: token ${{ secrets.REPO_ACCESS_TOKEN }}" "https://api.github.com/repos/${{ github.repository }}/actions/runners")
available=$(echo "$runners" | jq '.runners[] | select(.status == "online" and .busy == false and .labels[] .name == "self-hosted")')
if [ -n "$available" ]; then
echo "runner-label=self-hosted" >> "$GITHUB_OUTPUT"
@@ -25,161 +23,98 @@ jobs:
echo "runner-label=ubuntu-latest" >> "$GITHUB_OUTPUT"
fi
frontend:
goreleaser:
needs: check-runner
runs-on: ${{ needs.check-runner.outputs.runner-label }}
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 1
- uses: pnpm/action-setup@v6
with:
version: latest
- name: Set up Node.js
uses: actions/setup-node@v6
with:
node-version: latest
cache: pnpm
cache-dependency-path: frontend/pnpm-lock.yaml
- name: Cache frontend build
uses: actions/cache@v5
with:
path: |
frontend/node_modules
frontend/.svelte-kit
key: ${{ runner.os }}-pnpm-${{ hashFiles('frontend/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-
- name: Build frontend
run: |
pnpm --prefix=./frontend install --frozen-lockfile --prefer-offline
PUBLIC_VERSION=${GITHUB_REF##*/} pnpm --prefix=./frontend run build
tar -czf frontend-dist.tar.gz -C frontend/build .
- name: Upload frontend artifact
uses: actions/upload-artifact@v7
with:
name: frontend-dist
path: frontend-dist.tar.gz
goreleaser:
needs:
- check-runner
- frontend
runs-on: ${{ needs.check-runner.outputs.runner-label }}
steps:
- uses: actions/checkout@v6
# pull code
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Download frontend artifact
uses: actions/download-artifact@v8
# install latest node
- name: Set up Node.js
uses: actions/setup-node@v4
with:
name: frontend-dist
node-version: latest
- name: Extract frontend into backend
# build sveltekit frontend
- name: Build frontend
run: |
mkdir -p backend/pb_public
tar -xzf frontend-dist.tar.gz -C backend/pb_public
git reset --hard
git clean -fd
npm i -g pnpm
pnpm --prefix=./frontend i
PUBLIC_VERSION=${GITHUB_REF##*/} pnpm --prefix=./frontend run build
cp -r ./frontend/build/* ./backend/pb_public/
# setup go
- name: Set up Go
uses: actions/setup-go@v6
uses: actions/setup-go@v5
with:
go-version-file: backend/go.mod
cache-dependency-path: backend/go.sum
- name: Cache Go build
uses: actions/cache@v5
with:
path: |
~/.cache/go-build
~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('backend/go.sum') }}
restore-keys: |
${{ runner.os }}-go-
go-version-file: "./backend/go.mod"
cache-dependency-path: "./backend/go.sum"
# build
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v7
uses: goreleaser/goreleaser-action@v6
with:
distribution: goreleaser
version: "~> v2"
version: latest
args: release --clean
workdir: backend
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
AUR_KEY: ${{ secrets.AUR_KEY }}
- name: Upload backend artifact
uses: actions/upload-artifact@v7
with:
name: backend-dist
path: backend/dist
docker:
needs:
- check-runner
- frontend
- goreleaser
- check-runner
runs-on: ${{ needs.check-runner.outputs.runner-label }}
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Download backend artifact
uses: actions/download-artifact@v8
with:
name: backend-dist
path: backend/dist
# pull code
- name: Check Out Repo
uses: actions/checkout@v4
# image tags
- name: Docker meta
id: meta
uses: docker/metadata-action@v6
uses: docker/metadata-action@v5
with:
images: |
ghcr.io/seriousm4x/UpSnap
seriousm4x/UpSnap
tags: |
type=ref,event=tag
type=semver,pattern={{version}}
type=semver,pattern={{major}}
type=semver,pattern={{major}}.{{minor}}
# qemu
- name: Set up QEMU
uses: docker/setup-qemu-action@v4
uses: docker/setup-qemu-action@v3
# docker buildx
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v4
uses: docker/setup-buildx-action@v3
- name: Log in to GHCR
uses: docker/login-action@v4
# ghcr.io login
- name: Log in to the Container registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Log in to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ vars.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
# build and push
- name: Build and push
uses: docker/build-push-action@v7
id: docker_build
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64,linux/arm/v6,linux/arm/v7
builder: ${{ steps.buildx.outputs.name }}
push: true
tags: ${{ steps.meta.outputs.tags }}
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
VERSION=${{ github.ref_name }}
VERSION=${{github.ref_name}}
+4 -40
View File
@@ -1,5 +1,5 @@
# Created by https://www.toptal.com/developers/gitignore/api/go,node,svelte,visualstudiocode,macos
# Edit at https://www.toptal.com/developers/gitignore?templates=go,node,svelte,visualstudiocode,macos
# Created by https://www.toptal.com/developers/gitignore/api/go,visualstudiocode,svelte,node
# Edit at https://www.toptal.com/developers/gitignore?templates=go,visualstudiocode,svelte,node
### Go ###
# If you prefer the allow list template instead of the deny list, see community template:
@@ -24,43 +24,9 @@
# Go workspace file
go.work
### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### macOS Patch ###
# iCloud generated files
*.icloud
### Node ###
# Logs
logs
!frontend/src/routes/logs/
*.log
npm-debug.log*
yarn-debug.log*
@@ -134,7 +100,7 @@ web_modules/
.yarn-integrity
# dotenv environment variable files
.env
#.env
.env.development.local
.env.test.local
.env.production.local
@@ -224,7 +190,7 @@ package
.history
.ionide
# End of https://www.toptal.com/developers/gitignore/api/go,node,svelte,visualstudiocode,macos
# End of https://www.toptal.com/developers/gitignore/api/go,visualstudiocode,svelte,node
build
data
@@ -235,5 +201,3 @@ backend/pb_public/*
dist/
vite.config.js.timestamp*
frontend/src/lib/paraglide
+4 -12
View File
@@ -1,4 +1,4 @@
FROM alpine:3 AS downloader
FROM alpine:3 as downloader
ARG TARGETOS
ARG TARGETARCH
ARG TARGETVARIANT
@@ -11,22 +11,14 @@ RUN wget https://github.com/seriousm4x/UpSnap/releases/download/${VERSION}/UpSna
chmod +x upsnap &&\
apk update &&\
apk add --no-cache libcap &&\
setcap 'cap_net_raw=+p' ./upsnap
setcap 'cap_net_raw=+ep' ./upsnap
FROM alpine:3
ARG UPSNAP_HTTP_LISTEN=0.0.0.0:8090
ENV UPSNAP_HTTP_LISTEN=${UPSNAP_HTTP_LISTEN}
RUN apk update &&\
apk add --no-cache tzdata ca-certificates nmap samba samba-common-tools openssh sshpass curl &&\
rm -rf /var/cache/apk/*
RUN addgroup -g 1000 upsnap &&\
adduser -G upsnap -D -H -u 1000 upsnap -s /sbin/nologin
WORKDIR /app
COPY --from=downloader /app/upsnap upsnap
LABEL org.opencontainers.image.source="https://github.com/seriousm4x/UpSnap" \
org.opencontainers.image.url="https://github.com/seriousm4x/UpSnap" \
org.opencontainers.image.licenses="MIT"
HEALTHCHECK --interval=10s \
CMD curl -fs "http://${UPSNAP_HTTP_LISTEN}/api/health" || exit 1
CMD ["serve","--http","${UPSNAP_HTTP_LISTEN}"]
ENTRYPOINT ["/app/upsnap"]
CMD curl -fs "http://localhost:8090/api/health" || exit 1
ENTRYPOINT ["./upsnap", "serve", "--http=0.0.0.0:8090"]
+4 -6
View File
@@ -1,11 +1,11 @@
FROM node:bookworm AS node
FROM node:alpine as node
WORKDIR /app
COPY frontend/ .
RUN npm i -g pnpm &&\
pnpm i &&\
pnpm run build
FROM golang:alpine AS go
FROM golang:alpine as go
WORKDIR /app
COPY backend/ .
COPY --from=node /app/build ./pb_public
@@ -17,13 +17,11 @@ RUN go build -o upsnap main.go &&\
setcap 'cap_net_raw=+ep' ./upsnap
FROM alpine:3
ARG UPSNAP_HTTP_LISTEN=0.0.0.0:8090
ENV UPSNAP_HTTP_LISTEN=${UPSNAP_HTTP_LISTEN}
RUN apk update &&\
apk add --no-cache tzdata ca-certificates nmap samba samba-common-tools openssh sshpass curl &&\
rm -rf /var/cache/apk/*
WORKDIR /app
COPY --from=go /app/upsnap upsnap
HEALTHCHECK --interval=10s \
CMD curl -fs "http://${UPSNAP_HTTP_LISTEN}/api/health" || exit 1
ENTRYPOINT ["sh", "-c", "./upsnap serve --http ${UPSNAP_HTTP_LISTEN}"]
CMD curl -fs "http://localhost:8090/api/health" || exit 1
ENTRYPOINT ["./upsnap", "serve", "--http=0.0.0.0:8090"]
+68 -102
View File
@@ -5,17 +5,12 @@
<div align="center" width="100%">
<h2>UpSnap</h2>
<p>A simple wake on lan web app written with SvelteKit, Go and PocketBase.</p>
<div>
<a target="_blank" href="https://github.com/seriousm4x/upsnap"><img src="https://img.shields.io/github/stars/seriousm4x/UpSnap?style=flat&label=Stars" /></a>
<a target="_blank" href="https://hub.docker.com/r/seriousm4x/upsnap"><img src="https://img.shields.io/docker/pulls/seriousm4x/upsnap?label=docker%20hub%20pulls" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/downloads/seriousm4x/upsnap/total?label=binary%20downloads" /></a>
</div>
<div>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/go-mod/go-version/seriousm4x/UpSnap?filename=backend/go.mod" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/v/release/seriousm4x/upsnap?display_name=tag&label=Latest%20release" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/actions"><img src="https://github.com/seriousm4x/upsnap/actions/workflows/release.yml/badge.svg?event=push" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/commits/master"><img src="https://img.shields.io/github/last-commit/seriousm4x/upsnap" /></a>
</div>
<a target="_blank" href="https://github.com/seriousm4x/upsnap"><img src="https://img.shields.io/github/stars/seriousm4x/upsnap" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/downloads/seriousm4x/upsnap/total" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/go-mod/go-version/seriousm4x/UpSnap?filename=backend/go.mod" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/v/release/seriousm4x/upsnap?display_name=tag" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/actions"><img src="https://github.com/seriousm4x/upsnap/actions/workflows/release.yml/badge.svg?event=push" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/commits/master"><img src="https://img.shields.io/github/last-commit/seriousm4x/upsnap" /></a>
</div>
## ✨ Features
@@ -24,61 +19,83 @@
- ⏰ Timed Events via Cron for Automation
- 🔌 Ping Any Port You Choose
- 🔍 Discover Devices with Network Scanning (nmap required)
- 📌 Optional IP Address Tracking per Device via periodic ARP scan (nmap required, no extra privileges beyond network scanning)
- 📡 Support using a Fully Qualified Domain Name for a device (refer to the Wiki: [Use FQDN](https://github.com/seriousm4x/UpSnap/wiki/Use-FQDN))
- ❎️ Shutdown Devices with a Custom Command
- 👤 Secured User Management
- 📋 Superuser Logs Page
- 🌐 i18n support for [these](/frontend/translations) languages
- 🎨 35 Themes
- 🌐 i18n support for [these](https://github.com/seriousm4x/UpSnap/tree/master/frontend/src/lib/i18n) languages
- 🎨 29 Themes
- 🐳 [Docker images](https://github.com/seriousm4x/UpSnap/pkgs/container/upsnap) for amd64, arm64, arm/v7, arm/v6
- 🏠 Self-Hostable
## 📸 Screenshots
| Silk | Dim |
| ---------------------------------- | --------------------------------- |
| ![](/assets/home-light.webp) | ![](/assets/home-dark.webp) |
| ![](/assets/account-light.webp) | ![](/assets/account-dark.webp) |
| ![](/assets/new-manual-light.webp) | ![](/assets/new-manual-dark.webp) |
| ![](/assets/new-scan-light.webp) | ![](/assets/new-scan-dark.webp) |
| ![](/assets/settings-light.webp) | ![](/assets/settings-dark.webp) |
| ![](/assets/users-light.webp) | ![](/assets/users-dark.webp) |
| Dark | Light |
| --------------------------------- | ---------------------------------- |
| ![](/assets/home-dark.webp) | ![](/assets/home-light.webp) |
| ![](/assets/account-dark.webp) | ![](/assets/account-light.webp) |
| ![](/assets/new-manual-dark.webp) | ![](/assets/new-manual-light.webp) |
| ![](/assets/new-scan-dark.webp) | ![](/assets/new-scan-light.webp) |
| ![](/assets/settings-dark.webp) | ![](/assets/settings-light.webp) |
| ![](/assets/users-dark.webp) | ![](/assets/users-light.webp) |
## 🐧 Install from the [AUR](https://aur.archlinux.org/packages/upsnap-bin)
```bash
yay -Sy upsnap-bin
```
## 🚀 Run the binary
Just download the latest binary from the [release page](https://github.com/seriousm4x/UpSnap/releases) and run it.
### Root:
```bash
sudo ./upsnap serve --http=0.0.0.0:8090
```
To run as non-root (Linux only), refer to the Wiki: [Use non-root user](https://github.com/seriousm4x/UpSnap/wiki/Use-non%E2%80%90root-user)
### Non-root:
```bash
sudo setcap cap_net_raw=+ep ./upsnap # only once after downloading
./upsnap serve --http=0.0.0.0:8090
```
For more options check `./upsnap --help` or visit [PocketBase documentation](https://pocketbase.io/docs).
## 🐳 Run in Docker
If you want to use network discovery, make sure to have `nmap` installed and run UpSnap as root/admin.
Just pull and run the image: `docker run --network=host seriousm4x/upsnap:latest` or you can use the [docker-compose](docker-compose.yml) example. See the comments in the file for customization.
## 🐳 Run in docker
To run as non-root, refer to the Wiki: [Use non-root user](https://github.com/seriousm4x/UpSnap/wiki/Use-non%E2%80%90root-user)
You can use the [docker-compose](docker-compose.yml) example. See the comments in the file for customization.
Set `UPSNAP_LOG_LEVEL` to `DEBUG`, `INFO`, `WARN`, `ERROR`, or `OFF` to control UpSnap console logs. Default is `INFO`. PocketBase log persistence and retention remain configurable in PocketBase settings. PocketBase's `--dev` mode prints all logs regardless of this setting.
### Non-root docker user:
### Change port (Docker)
Create the mount point first:
```bash
mkdir data
```
Then add `user: 1000:1000` to the docker-compose file (or whatever your $UID:$GID is).
### Change port
If you want to change the port from 8090 to something else, change the following (5000 in this case):
```yml
environment:
- UPSNAP_HTTP_LISTEN=0.0.0.0:5000
entrypoint: /bin/sh -c "./upsnap serve --http 0.0.0.0:5000"
healthcheck:
test: curl -fs "http://localhost:5000/api/health" || exit 1
```
## ❎️ Shutting Down Devices
### Install additional packages for shutdown cmd
To shutdown devices, refer to the Wiki: [How to use shutdowns](https://github.com/seriousm4x/UpSnap/wiki/How-to-use-shutdowns)
```yml
entrypoint: /bin/sh -c "apk update && apk add --no-cache <YOUR_PACKAGE> && rm -rf /var/cache/apk/* && ./upsnap serve --http 0.0.0.0:8090"
```
## Reverse Proxy
You can search for your needed package [here](https://pkgs.alpinelinux.org/packages).
### Reverse Proxy
**Caddy example**
@@ -88,46 +105,6 @@ upsnap.example.com {
}
```
## Run in sub path
You can run UpSnap on a different path than `/`, e.g. `/upsnap-sub-path/`. To do this in caddy, set the following:
```
http://localhost:8091 {
handle /upsnap-sub-path/* {
uri strip_prefix /upsnap-sub-path
reverse_proxy localhost:8090
}
}
```
Or nginx:
```
http {
server {
listen 8091;
server_name localhost;
location /upsnap-sub-path/ {
proxy_pass http://localhost:8090/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
```
Paths must end with a trailing `/`.
## 🐧 Install from the [AUR](https://aur.archlinux.org/packages/upsnap-bin)
```bash
yay -Sy upsnap-bin
```
## 🔒 User permissions
UpSnap offers unique access for each user, per device. While admins have all permissions, they can assign specific rights to users such as displaying/hiding a device, accessing device editing, deleting and powering devices on/off. See the last screenshot in the [📸 Screenshots section](#-screenshots).
@@ -136,36 +113,21 @@ UpSnap offers unique access for each user, per device. While admins have all per
Although UpSnap has user authorisation, it is **not recommended to expose it to the open web** and make it accessible by everyone!
**Reason**: The shutdown device command is basically a command piped to #sh (possibly as root user). If anyone gains unauthorized access and can abuse this API route in any way, the attacker has access to a (root) shell on your local network.
**Reason**: The shutdown device command is basically a command piped to #sh (root if you run docker). If anyone gains unauthorized access and can abuse this api route in any way, the attacker has access to a (root) shell on your local network.
**Recommended**: If you need access from outside your network, please use a VPN. Wireguard or OpenVPN is your way to go.
**Recommended**: If you need access from outside your network, please use a vpn. Wireguard or OpenVPN is your way to go.
## 🌐 Help translating
UpSnap is available in the following languages so far:
- 🇸🇦 **Arabic (Saudi Arabia)** (ar-SA)
- 🇧🇬 **Bulgarian (Bulgaria)** (bg-BG)
- 🇨🇿 **Czech (Czech republic)** (cs-CZ)
- 🇩🇪 **German (Germany)** (de-DE)
- 🇬🇷 **Greek (Greece)** (el-GR)
- 🇺🇸 **English (United States)** (en-US)
- 🇪🇸 **Spanish (Spain)** (es-ES)
- 🇫🇷 **French (France)** (fr-FR)
- 🇮🇳 **Hindi (India)** (hi-IN)
- 🇮🇩 **Bahasa (Indonesia)** (id-ID)
- 🇮🇹 **Italian (Italy)** (it-IT)
- 🇯🇵 **Japanese (Japan)** (ja-JP)
- 🇰🇷 **Korean (Republic of Korea)** (ko-KR)
- 🇳🇴 **Norwegian (Norway)** (nb-NO)
- 🇳🇱 **Dutch (Netherlands)** (nl-NL)
- 🇵🇱 **Polish (Poland)** (pl-PL)
- 🇧🇷 **Portuguese (Brazil)** (pt-BR)
- 🇵🇹 **Portuguese (Portugal)** (pt-PT)
- 🇷🇺 **Russian (Russia)** (ru-RU)
- 🇺🇦 **Ukrainian (Ukrain)** (uk-UA)
- 🇻🇳 **Vietnamese (Vietnam)** (vi-VN)
- 🇨🇳 **Chinese (China)** (zh-CN)
- 🇺🇸 **English** (en-US)
- 🇩🇪 **German** (de-DE)
- 🇮🇹 **Italian** (it-IT)
- 🇪🇸 **Spanish** (es-ES)
- 🇫🇷 **French** (fr-FR)
- 🇵🇹 **Portuguese** (pt-PT)
- 🇨🇳 **Chinese** (zh-CN)
- 🇹🇼 **Chinese (Taiwan)** (zh-TW)
**If you want to contribute and help translating, check the wiki: [How to add languages](https://github.com/seriousm4x/UpSnap/wiki/How-to-add-languages)**
@@ -176,7 +138,7 @@ Fork this branch and clone it.
1. Start backend
```bash
```sh
cd backend
go mod tidy
go run main.go serve
@@ -184,10 +146,14 @@ go run main.go serve
2. Start frontend
```bash
```sh
cd frontend
pnpm i
pnpm run dev
```
Open up [http://localhost:5173/](http://localhost:5173/), create an admin user and add some devices.
## 🌟 Star History
[![Star History Chart](https://api.star-history.com/svg?repos=seriousm4x/UpSnap&type=Date&theme=dark)](https://star-history.com/#seriousm4x/UpSnap&Date)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 124 KiB

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 212 KiB

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 206 KiB

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 212 KiB

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 101 KiB

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 93 KiB

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

After

Width:  |  Height:  |  Size: 32 KiB

+23 -28
View File
@@ -1,6 +1,5 @@
version: 2
release:
draft: false
draft: true
prerelease: auto
before:
hooks:
@@ -15,28 +14,24 @@ builds:
- linux
- windows
- darwin
- freebsd
goarch:
- amd64
- arm64
- arm
- riscv64
goarm:
- "6"
- "7"
- 6
- 7
ignore:
- goos: windows
goarch: arm
- goos: darwin
goarch: arm
- goos: freebsd
goarch: arm
archives:
- formats: ["zip"]
- format: zip
checksum:
name_template: "checksums.txt"
snapshot:
version_template: "{{ .Version }}"
name_template: "{{ .Version }}"
changelog:
use: github
sort: asc
@@ -60,21 +55,21 @@ changelog:
order: 2
git:
ignore_tags:
- "{{ if not .Prerelease}}*beta*{{ end }}"
# aurs:
# - name: upsnap-bin
# homepage: https://github.com/seriousm4x/UpSnap
# description: "A simple wake on lan web app written with SvelteKit, Go and PocketBase."
# maintainers:
# - "SeriousM4x <maxi at quoss dot org>"
# license: "MIT"
# private_key: "{{ .Env.AUR_KEY }}"
# git_url: "ssh://aur@aur.archlinux.org/upsnap-bin.git"
# package: |-
# install -Dm755 "./upsnap" "${pkgdir}/usr/bin/upsnap"
# skip_upload: auto
# optdepends:
# - "nmap: to scan for network devices"
# commit_author:
# name: goreleaserbot
# email: bot@goreleaser.com
- "{{ if not .Prerelease}}beta{{ end }}"
aurs:
- name: upsnap-bin
homepage: https://github.com/seriousm4x/UpSnap
description: "A simple wake on lan web app written with SvelteKit, Go and PocketBase."
maintainers:
- "SeriousM4x <maxi at quoss dot org>"
license: "MIT"
private_key: "{{ .Env.AUR_KEY }}"
git_url: "ssh://aur@aur.archlinux.org/upsnap-bin.git"
package: |-
install -Dm755 "./upsnap" "${pkgdir}/usr/bin/upsnap"
skip_upload: auto
optdepends:
- "nmap: to scan for network devices"
commit_author:
name: goreleaserbot
email: bot@goreleaser.com
+76 -124
View File
@@ -1,35 +1,29 @@
package cronjobs
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/models"
"github.com/robfig/cron/v3"
"github.com/seriousm4x/upsnap/iptracking"
"github.com/seriousm4x/upsnap/logging"
"github.com/seriousm4x/upsnap/logger"
"github.com/seriousm4x/upsnap/networking"
)
var (
PingRunning = false
WakeShutdownRunning = false
CronPing = cron.New(cron.WithParser(cron.NewParser(
cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow,
)))
CronWakeShutdown = cron.New(cron.WithParser(cron.NewParser(
cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow,
)))
CronPing = cron.New()
CronWakeShutdown = cron.New()
)
func SetPingJobs(app core.App) {
log := logging.Logger(app)
func SetPingJobs(app *pocketbase.PocketBase) {
// remove existing jobs
for _, job := range CronPing.Entries() {
CronPing.Remove(job.ID)
}
settingsPrivateRecords, err := app.FindAllRecords("settings_private")
settingsPrivateRecords, err := app.Dao().FindRecordsByExpr("settings_private")
if err != nil {
log.Error("Failed to load private settings", "error", err)
return
logger.Error.Println(err)
}
CronPing.AddFunc(settingsPrivateRecords[0].GetString("interval"), func() {
@@ -39,112 +33,76 @@ func SetPingJobs(app core.App) {
return
}
devices, err := app.FindAllRecords("devices")
devices, err := app.Dao().FindRecordsByExpr("devices")
if err != nil {
log.Error("Failed to load devices for ping job", "error", err)
logger.Error.Println(err)
return
}
// expand ports field
expandFetchFunc := func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
expandFetchFunc := func(c *models.Collection, ids []string) ([]*models.Record, error) {
return app.Dao().FindRecordsByIds(c.Id, ids, nil)
}
merr := app.ExpandRecords(devices, []string{"ports"}, expandFetchFunc)
merr := app.Dao().ExpandRecords(devices, []string{"ports"}, expandFetchFunc)
if len(merr) > 0 {
log.Error("Failed to expand device ports", "errors", merr)
return
}
for _, device := range devices {
// ping device
go func(d *core.Record) {
go func(d *models.Record) {
status := d.GetString("status")
if status == "pending" {
return
}
isUp, err := networking.PingDevice(d)
if err != nil {
log.Error("Failed to ping device", "device", d.GetString("name"), "error", err)
}
if isUp {
if networking.PingDevice(d) {
if status == "online" {
return
}
d.Set("status", "online")
if err := app.Save(d); err != nil {
log.Error("Failed to save device status", "device", d.GetString("name"), "error", err)
} else {
log.Info("Device turned on", "device", d.GetString("name"))
if err := app.Dao().SaveRecord(d); err != nil {
logger.Error.Println("Failed to save record:", err)
}
} else {
if status == "offline" {
return
}
d.Set("status", "offline")
if err := app.Save(d); err != nil {
log.Error("Failed to save device status", "device", d.GetString("name"), "error", err)
} else {
log.Info("Device turned off", "device", d.GetString("name"))
if err := app.Dao().SaveRecord(d); err != nil {
logger.Error.Println("Failed to save record:", err)
}
}
}(device)
// ping ports
go func(d *core.Record) {
ports, err := app.FindRecordsByIds("ports", d.GetStringSlice("ports"))
go func(d *models.Record) {
ports, err := app.Dao().FindRecordsByIds("ports", d.GetStringSlice("ports"))
if err != nil {
log.Error("Failed to load device ports", "device", d.GetString("name"), "error", err)
return
}
deviceIP, resolveErr := networking.ResolveToIPAddr(d.GetString("ip"))
if resolveErr != nil {
log.Error("Failed to resolve device IP", "device", d.GetString("name"), "error", resolveErr)
logger.Error.Println(err)
}
for _, port := range ports {
isUp := false
// No IP found means the device is down.
if resolveErr == nil && deviceIP != "" {
var checkErr error
isUp, checkErr = networking.CheckPort(deviceIP, port.GetString("number"))
if checkErr != nil {
log.Error("Failed to check port", "device", d.GetString("name"), "port", port.GetString("number"), "error", checkErr)
}
}
isUp := networking.CheckPort(d.GetString("ip"), port.GetString("number"))
if isUp != port.GetBool("status") {
port.Set("status", isUp)
if err := app.Save(port); err != nil {
log.Error("Failed to save port status", "device", d.GetString("name"), "port", port.GetString("number"), "error", err)
if err := app.Dao().SaveRecord(port); err != nil {
logger.Error.Println("Failed to save record:", err)
}
}
}
}(device)
}
})
// update ip addresses of opted-in devices from a periodic arp scan
trackIpInterval := settingsPrivateRecords[0].GetString("track_ip_interval")
if trackIpInterval != "" {
if _, err := CronPing.AddFunc(trackIpInterval, func() {
// pause scans if no realtime clients connected and lazy_ping is
// turned on; a catch-up sweep runs when the next client connects
realtimeClients := len(app.SubscriptionsBroker().Clients())
iptracking.PeriodicSweep(app, realtimeClients == 0 && settingsPrivateRecords[0].GetBool("lazy_ping"))
}); err != nil {
log.Error("Failed to add IP tracking cron job", "error", err)
}
}
}
func SetWakeShutdownJobs(app core.App) {
log := logging.Logger(app)
func SetWakeShutdownJobs(app *pocketbase.PocketBase) {
// remove existing jobs
for _, job := range CronWakeShutdown.Entries() {
CronWakeShutdown.Remove(job.ID)
}
devices, err := app.FindAllRecords("devices")
devices, err := app.Dao().FindRecordsByExpr("devices")
if err != nil {
log.Error("Failed to load devices for wake and shutdown jobs", "error", err)
logger.Error.Println(err)
return
}
for _, dev := range devices {
@@ -155,79 +113,71 @@ func SetWakeShutdownJobs(app core.App) {
if wake_cron_enabled && wake_cron != "" {
_, err := CronWakeShutdown.AddFunc(wake_cron, func() {
d, err := app.FindRecordById("devices", dev.Id)
logger.Debug.Printf("[CRON1 \"%s\"]: cron func started", dev.GetString("name"))
dev, err = app.Dao().FindRecordById("devices", dev.Id)
if err != nil {
log.Error("Failed to load device for wake job", "device", dev.GetString("name"), "error", err)
logger.Error.Println(err)
return
}
if d.GetString("status") == "pending" {
logger.Debug.Printf("[CRON2 \"%s\"]: got record from db", dev.GetString("name"))
status := dev.GetString("status")
logger.Debug.Printf("[CRON3 \"%s\"]: status is %s", dev.GetString("name"), status)
if status == "pending" || status == "online" {
logger.Debug.Printf("[CRON3.5 \"%s\"]: skipping run because already pending", dev.GetString("name"))
return
}
isOnline, err := networking.PingDevice(d)
if err != nil {
log.Error("Failed to ping device before wake", "device", d.GetString("name"), "error", err)
dev.Set("status", "pending")
if err := app.Dao().SaveRecord(dev); err != nil {
logger.Error.Println("Failed to save record:", err)
return
}
if isOnline {
return
}
d.Set("status", "pending")
if err := app.Save(d); err != nil {
log.Error("Failed to save pending device status", "device", d.GetString("name"), "error", err)
return
}
if err := networking.WakeDevice(app, d, "cron"); err != nil {
log.Error("Wake job failed", "device", d.GetString("name"), "error", err)
d.Set("status", "offline")
logger.Debug.Printf("[CRON4 \"%s\"]: saved status pending", dev.GetString("name"))
if err := networking.WakeDevice(dev); err != nil {
logger.Error.Println(err)
dev.Set("status", "offline")
} else {
d.Set("status", "online")
dev.Set("status", "online")
}
if err := app.Save(d); err != nil {
log.Error("Failed to save device status after wake", "device", d.GetString("name"), "error", err)
logger.Debug.Printf("[CRON5 \"%s\"]: wake device done", dev.GetString("name"))
if err := app.Dao().SaveRecord(dev); err != nil {
logger.Error.Println("Failed to save record:", err)
}
logger.Debug.Printf("[CRON6 \"%s\"]: saved device", dev.GetString("name"))
})
if err != nil {
log.Error("Failed to add wake cron job", "device", dev.GetString("name"), "error", err)
logger.Error.Println(err)
}
}
if shutdown_cron_enabled && shutdown_cron != "" {
_, err := CronWakeShutdown.AddFunc(shutdown_cron, func() {
d, err := app.FindRecordById("devices", dev.Id)
dev, err = app.Dao().FindRecordById("devices", dev.Id)
if err != nil {
log.Error("Failed to load device for shutdown job", "device", dev.GetString("name"), "error", err)
logger.Error.Println(err)
return
}
if d.GetString("status") == "pending" {
status := dev.GetString("status")
if status == "pending" || status == "offline" {
return
}
isOnline, err := networking.PingDevice(d)
if err != nil {
log.Error("Failed to ping device before shutdown", "device", d.GetString("name"), "error", err)
return
dev.Set("status", "pending")
if err := app.Dao().SaveRecord(dev); err != nil {
logger.Error.Println("Failed to save record:", err)
}
if !isOnline {
return
}
// The status can be stale when lazy ping marks devices offline after
// the last client disconnects. The reachability check above is the
// authoritative signal for whether a shutdown command may run.
d.Set("status", "pending")
if err := app.Save(d); err != nil {
log.Error("Failed to save pending device status", "device", d.GetString("name"), "error", err)
}
if err := networking.ShutdownDevice(app, d, "cron"); err != nil {
log.Error("Shutdown job failed", "device", d.GetString("name"), "error", err)
d.Set("status", "online")
if err := networking.ShutdownDevice(dev); err != nil {
logger.Error.Println(err)
dev.Set("status", "online")
} else {
d.Set("status", "offline")
dev.Set("status", "offline")
}
if err := app.Save(d); err != nil {
log.Error("Failed to save device status after shutdown", "device", d.GetString("name"), "error", err)
if err := app.Dao().SaveRecord(dev); err != nil {
logger.Error.Println("Failed to save record:", err)
}
})
if err != nil {
log.Error("Failed to add shutdown cron job", "device", dev.GetString("name"), "error", err)
logger.Error.Println(err)
}
}
}
@@ -239,10 +189,11 @@ func StartWakeShutdown() {
}
func StopWakeShutdown(app core.App) {
func StopWakeShutdown() {
if WakeShutdownRunning {
logging.Logger(app).Info("Stopping wake and shutdown cron jobs")
CronWakeShutdown.Stop()
logger.Info.Println("Stopping wake/shutdown cronjob")
ctx := CronWakeShutdown.Stop()
<-ctx.Done()
}
WakeShutdownRunning = false
}
@@ -252,15 +203,16 @@ func StartPing() {
go CronPing.Run()
}
func StopPing(app core.App) {
func StopPing() {
if PingRunning {
logging.Logger(app).Info("Stopping ping cron jobs")
CronPing.Stop()
logger.Info.Println("Stopping wake/shutdown cronjob")
ctx := CronPing.Stop()
<-ctx.Done()
}
PingRunning = false
}
func StopAll(app core.App) {
StopPing(app)
StopWakeShutdown(app)
func StopAll() {
StopPing()
StopWakeShutdown()
}
+72 -36
View File
@@ -1,53 +1,89 @@
module github.com/seriousm4x/upsnap
go 1.27
go 1.22.5
require (
ganigeorgiev.com/pocketbase/dbx v1.13.0
ganigeorgiev.com/pocketbase/pocketbase v0.41.1
github.com/godbus/dbus/v5 v5.2.2
github.com/holoplot/go-avahi v1.0.1
github.com/labstack/echo/v5 v5.0.0-20230722203903-ec5b858dab61
github.com/mdlayher/wol v0.0.0-20220221231636-b763a792253a
github.com/prometheus-community/pro-bing v0.9.1
github.com/pocketbase/dbx v1.10.1
github.com/pocketbase/pocketbase v0.22.18
github.com/prometheus-community/pro-bing v0.4.1
github.com/robfig/cron/v3 v3.0.1
golang.org/x/net v0.62.0
golang.org/x/sys v0.49.0
kernel.org/pub/linux/libs/security/libcap/cap v1.2.78
golang.org/x/sys v0.22.0
)
require (
ganigeorgiev.com/fexpr v0.7.0 // indirect
ganigeorgiev.com/pocketbase/ozzo-validation/v4 v4.4.1 // indirect
github.com/AlecAivazis/survey/v2 v2.3.7 // indirect
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
github.com/aws/aws-sdk-go-v2 v1.30.3 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3 // indirect
github.com/aws/aws-sdk-go-v2/config v1.27.27 // indirect
github.com/aws/aws-sdk-go-v2/credentials v1.17.27 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.11 // indirect
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.8 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15 // indirect
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.15 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.3.17 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.15 // indirect
github.com/aws/aws-sdk-go-v2/service/s3 v1.58.2 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.22.4 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.30.3 // indirect
github.com/aws/smithy-go v1.20.3 // indirect
github.com/disintegration/imaging v1.6.2 // indirect
github.com/domodwyer/mailyak/v3 v3.6.2 // indirect
github.com/dustin/go-humanize v1.1.0 // indirect
github.com/fatih/color v1.19.0 // indirect
github.com/fsnotify/fsnotify v1.10.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
github.com/go-sql-driver/mysql v1.9.3 // indirect
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/fatih/color v1.17.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.4 // indirect
github.com/ganigeorgiev/fexpr v0.4.1 // indirect
github.com/go-ozzo/ozzo-validation/v4 v4.3.0 // indirect
github.com/goccy/go-json v0.10.3 // indirect
github.com/golang-jwt/jwt/v4 v4.5.0 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/googleapis/gax-go/v2 v2.13.0 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/mattn/go-colorable v0.1.16 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/josharian/native v1.1.0 // indirect
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-sqlite3 v1.14.22 // indirect
github.com/mdlayher/ethernet v0.0.0-20220221185849-529eae5b6118 // indirect
github.com/mdlayher/packet v1.2.0 // indirect
github.com/mdlayher/socket v0.7.0 // indirect
github.com/ncruces/go-strftime v1.1.0 // indirect
github.com/mdlayher/packet v1.1.2 // indirect
github.com/mdlayher/socket v0.5.1 // indirect
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/spf13/cast v1.10.0 // indirect
github.com/spf13/cobra v1.10.2 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/stretchr/testify v1.11.1 // indirect
golang.org/x/crypto v0.58.0 // indirect
golang.org/x/image v0.47.0 // indirect
golang.org/x/oauth2 v0.37.0 // indirect
golang.org/x/sync v0.24.0 // indirect
golang.org/x/text v0.43.0 // indirect
kernel.org/pub/linux/libs/security/libcap/psx v1.2.78 // indirect
modernc.org/libc v1.77.1 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.12.1 // indirect
modernc.org/sqlite v1.60.1 // indirect
github.com/spf13/cast v1.6.0 // indirect
github.com/spf13/cobra v1.8.1 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
go.opencensus.io v0.24.0 // indirect
gocloud.dev v0.37.0 // indirect
golang.org/x/crypto v0.25.0 // indirect
golang.org/x/image v0.18.0 // indirect
golang.org/x/net v0.27.0 // indirect
golang.org/x/oauth2 v0.21.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/term v0.22.0 // indirect
golang.org/x/text v0.16.0 // indirect
golang.org/x/time v0.5.0 // indirect
golang.org/x/xerrors v0.0.0-20240716161551-93cc26a95ae9 // indirect
google.golang.org/api v0.189.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240723171418-e6d459c13d2a // indirect
google.golang.org/grpc v1.65.0 // indirect
google.golang.org/protobuf v1.34.2 // indirect
modernc.org/gc/v3 v3.0.0-20240722195230-4a140ff9c08e // indirect
modernc.org/libc v1.55.3 // indirect
modernc.org/mathutil v1.6.0 // indirect
modernc.org/memory v1.8.0 // indirect
modernc.org/sqlite v1.31.1 // indirect
modernc.org/strutil v1.2.0 // indirect
modernc.org/token v1.1.0 // indirect
)
+318 -100
View File
@@ -1,17 +1,73 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.115.0 h1:CnFSK6Xo3lDYRoBKEcAtia6VSC837/ZkJuRduSFnr14=
cloud.google.com/go v0.115.0/go.mod h1:8jIM5vVgoAEoiVxQ/O4BFTfHqulPZgs/ufEzMcFMdWU=
cloud.google.com/go/auth v0.7.2 h1:uiha352VrCDMXg+yoBtaD0tUF4Kv9vrtrWPYXwutnDE=
cloud.google.com/go/auth v0.7.2/go.mod h1:VEc4p5NNxycWQTMQEDQF0bd6aTMb6VgYDXEwiJJQAbs=
cloud.google.com/go/auth/oauth2adapt v0.2.3 h1:MlxF+Pd3OmSudg/b1yZ5lJwoXCEaeedAguodky1PcKI=
cloud.google.com/go/auth/oauth2adapt v0.2.3/go.mod h1:tMQXOfZzFuNuUxOypHlQEXgdfX5cuhwU+ffUuXRJE8I=
cloud.google.com/go/compute v1.25.0 h1:H1/4SqSUhjPFE7L5ddzHOfY2bCAvjwNRZPNl6Ni5oYU=
cloud.google.com/go/compute/metadata v0.5.0 h1:Zr0eK8JbFv6+Wi4ilXAR8FJ3wyNdpxHKJNPos6LTZOY=
cloud.google.com/go/compute/metadata v0.5.0/go.mod h1:aHnloV2TPI38yx4s9+wAZhHykWvVCfu7hQbF+9CWoiY=
cloud.google.com/go/iam v1.1.6 h1:bEa06k05IO4f4uJonbB5iAgKTPpABy1ayxaIZV/GHVc=
cloud.google.com/go/iam v1.1.6/go.mod h1:O0zxdPeGBoFdWW3HWmBxJsk0pfvNM/p/qa82rWOGTwI=
cloud.google.com/go/storage v1.39.1 h1:MvraqHKhogCOTXTlct/9C3K3+Uy2jBmFYb3/Sp6dVtY=
cloud.google.com/go/storage v1.39.1/go.mod h1:xK6xZmxZmo+fyP7+DEF6FhNc24/JAe95OLyOHCXFH1o=
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
ganigeorgiev.com/fexpr v0.7.0 h1:Os5bP9dU13UNo5qDTsTPTTkodLM96kO52WIEmMmCt30=
ganigeorgiev.com/fexpr v0.7.0/go.mod h1:XrG5iYw+AGq55zq2+QY1zQvO+ovbEca08u7q0hucPdY=
ganigeorgiev.com/pocketbase/dbx v1.13.0 h1:t8S5CaMv93tEOqaOToFaVQ994zldshdhIrVHKmxRjwc=
ganigeorgiev.com/pocketbase/dbx v1.13.0/go.mod h1:QefEiWbbE/YoSipLGg33FbNc/GAX/2f3ymz02j2MGKo=
ganigeorgiev.com/pocketbase/ozzo-validation/v4 v4.4.1 h1:teL3Lw7HCGZRdIQdqE/gV5DueFaN5Wj+/r4Ewg3M2WA=
ganigeorgiev.com/pocketbase/ozzo-validation/v4 v4.4.1/go.mod h1:oV1SPPkS3PlKYYj+r9YDs48ooAWgC736cuFanXDXxbM=
ganigeorgiev.com/pocketbase/pocketbase v0.41.1 h1:qIDj5ZE8ysev7LJNcLR4eeYICme5hDF/Ry3bQ9nOcTA=
ganigeorgiev.com/pocketbase/pocketbase v0.41.1/go.mod h1:PBkQKVnCfL7Hi9MnXY9bJDME/sfEEbZ6VwAb+8xXQXE=
github.com/AlecAivazis/survey/v2 v2.3.7 h1:6I/u8FvytdGsgonrYsVn2t8t4QiRnh6QSTqkkhIiSjQ=
github.com/AlecAivazis/survey/v2 v2.3.7/go.mod h1:xUTIdE4KCOIjsBAE1JYsUPoCqYdZ1reCfTwbto0Fduo=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Netflix/go-expect v0.0.0-20220104043353-73e0943537d2 h1:+vx7roKuyA63nhn5WAunQHLTznkw5W8b1Xc0dNjp83s=
github.com/Netflix/go-expect v0.0.0-20220104043353-73e0943537d2/go.mod h1:HBCaDeC1lPdgDeDbhX8XFpy1jqjK0IBG8W5K+xYqA0w=
github.com/asaskevich/govalidator v0.0.0-20200108200545-475eaeb16496/go.mod h1:oGkLhpf+kjZl6xBf758TQhh5XrAeiJv/7FRz/2spLIg=
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/aws/aws-sdk-go v1.51.11 h1:El5VypsMIz7sFwAAj/j06JX9UGs4KAbAIEaZ57bNY4s=
github.com/aws/aws-sdk-go v1.51.11/go.mod h1:LF8svs817+Nz+DmiMQKTO3ubZ/6IaTpq3TjupRn3Eqk=
github.com/aws/aws-sdk-go-v2 v1.30.3 h1:jUeBtG0Ih+ZIFH0F4UkmL9w3cSpaMv9tYYDbzILP8dY=
github.com/aws/aws-sdk-go-v2 v1.30.3/go.mod h1:nIQjQVp5sfpQcTc9mPSr1B0PaWK5ByX9MOoDadSN4lc=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3 h1:tW1/Rkad38LA15X4UQtjXZXNKsCgkshC3EbmcUmghTg=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3/go.mod h1:UbnqO+zjqk3uIt9yCACHJ9IVNhyhOCnYk8yA19SAWrM=
github.com/aws/aws-sdk-go-v2/config v1.27.27 h1:HdqgGt1OAP0HkEDDShEl0oSYa9ZZBSOmKpdpsDMdO90=
github.com/aws/aws-sdk-go-v2/config v1.27.27/go.mod h1:MVYamCg76dFNINkZFu4n4RjDixhVr51HLj4ErWzrVwg=
github.com/aws/aws-sdk-go-v2/credentials v1.17.27 h1:2raNba6gr2IfA0eqqiP2XiQ0UVOpGPgDSi0I9iAP+UI=
github.com/aws/aws-sdk-go-v2/credentials v1.17.27/go.mod h1:gniiwbGahQByxan6YjQUMcW4Aov6bLC3m+evgcoN4r4=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.11 h1:KreluoV8FZDEtI6Co2xuNk/UqI9iwMrOx/87PBNIKqw=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.11/go.mod h1:SeSUYBLsMYFoRvHE0Tjvn7kbxaUhl75CJi1sbfhMxkU=
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.8 h1:u1KOU1S15ufyZqmH/rA3POkiRH6EcDANHj2xHRzq+zc=
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.8/go.mod h1:WPv2FRnkIOoDv/8j2gSUsI4qDc7392w5anFB/I89GZ8=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15 h1:SoNJ4RlFEQEbtDcCEt+QG56MY4fm4W8rYirAmq+/DdU=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15/go.mod h1:U9ke74k1n2bf+RIgoX1SXFed1HLs51OgUSs+Ph0KJP8=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15 h1:C6WHdGnTDIYETAm5iErQUiVNsclNx9qbJVPIt03B6bI=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15/go.mod h1:ZQLZqhcu+JhSrA9/NXRm8SkDvsycE+JkV3WGY41e+IM=
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0 h1:hT8rVHwugYE2lEfdFE0QWVo81lF7jMrYJVDWI+f+VxU=
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0/go.mod h1:8tu/lYfQfFe6IGnaOdrpVgEL2IrrDOf6/m9RQum4NkY=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.15 h1:Z5r7SycxmSllHYmaAZPpmN8GviDrSGhMS6bldqtXZPw=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.15/go.mod h1:CetW7bDE00QoGEmPUoZuRog07SGVAUVW6LFpNP0YfIg=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3 h1:dT3MqvGhSoaIhRseqw2I0yH81l7wiR2vjs57O51EAm8=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3/go.mod h1:GlAeCkHwugxdHaueRr4nhPuY+WW+gR8UjlcqzPr1SPI=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.3.17 h1:YPYe6ZmvUfDDDELqEKtAd6bo8zxhkm+XEFEzQisqUIE=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.3.17/go.mod h1:oBtcnYua/CgzCWYN7NZ5j7PotFDaFSUjCYVTtfyn7vw=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17 h1:HGErhhrxZlQ044RiM+WdoZxp0p+EGM62y3L6pwA4olE=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17/go.mod h1:RkZEx4l0EHYDJpWppMJ3nD9wZJAa8/0lq9aVC+r2UII=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.15 h1:246A4lSTXWJw/rmlQI+TT2OcqeDMKBdyjEQrafMaQdA=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.15/go.mod h1:haVfg3761/WF7YPuJOER2MP0k4UAXyHaLclKXB6usDg=
github.com/aws/aws-sdk-go-v2/service/s3 v1.58.2 h1:sZXIzO38GZOU+O0C+INqbH7C2yALwfMWpd64tONS/NE=
github.com/aws/aws-sdk-go-v2/service/s3 v1.58.2/go.mod h1:Lcxzg5rojyVPU/0eFwLtcyTaek/6Mtic5B1gJo7e/zE=
github.com/aws/aws-sdk-go-v2/service/sso v1.22.4 h1:BXx0ZIxvrJdSgSvKTZ+yRBeSqqgPM89VPlulEcl37tM=
github.com/aws/aws-sdk-go-v2/service/sso v1.22.4/go.mod h1:ooyCOXjvJEsUw7x+ZDHeISPMhtwI3ZCB7ggFMcFfWLU=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4 h1:yiwVzJW2ZxZTurVbYWA7QOrAaCYQR72t0wrSBfoesUE=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4/go.mod h1:0oxfLkpz3rQ/CHlx5hB7H69YUpFiI1tql6Q6Ne+1bCw=
github.com/aws/aws-sdk-go-v2/service/sts v1.30.3 h1:ZsDKRLXGWHk8WdtyYMoGNO7bTudrvuKpDKgMVRlepGE=
github.com/aws/aws-sdk-go-v2/service/sts v1.30.3/go.mod h1:zwySh8fpFyXp9yOr/KVzxOl8SRqgf/IDw5aUt9UKFcQ=
github.com/aws/smithy-go v1.20.3 h1:ryHwveWzPV5BIof6fyDvor6V3iUL7nTfiTKXHiW05nE=
github.com/aws/smithy-go v1.20.3/go.mod h1:krry+ya/rV9RDcV/Q16kpu6ypI4K2czasz0NC3qS14E=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/creack/pty v1.1.17 h1:QeVUsEDNrLBW4tMgZHvxy18sKtr6VI492kBhUfhDJNI=
github.com/creack/pty v1.1.17/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -19,67 +75,129 @@ github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
github.com/domodwyer/mailyak/v3 v3.6.2 h1:x3tGMsyFhTCaxp6ycgR0FE/bu5QiNp+hetUuCOBXMn8=
github.com/domodwyer/mailyak/v3 v3.6.2/go.mod h1:lOm/u9CyCVWHeaAmHIdF4RiKVxKUT/H5XX10lIKAL6c=
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/fatih/color v1.17.0 h1:GlRw1BRJxkpqUCBKzKOw098ed57fEsKeNjpTe3cSjK4=
github.com/fatih/color v1.17.0/go.mod h1:YZ7TlrGPkiz6ku9fK3TLD/pl3CpsiFyu8N92HLgmosI=
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
github.com/gabriel-vasile/mimetype v1.4.4 h1:QjV6pZ7/XZ7ryI2KuyeEDE8wnh7fHP9YnQy+R0LnH8I=
github.com/gabriel-vasile/mimetype v1.4.4/go.mod h1:JwLei5XPtWdGiMFB5Pjle1oEeoSeEuJfJE+TtfvdB/s=
github.com/ganigeorgiev/fexpr v0.4.1 h1:hpUgbUEEWIZhSDBtf4M9aUNfQQ0BZkGRaMePy7Gcx5k=
github.com/ganigeorgiev/fexpr v0.4.1/go.mod h1:RyGiGqmeXhEQ6+mlGdnUleLHgtzzu/VGO2WtJkF5drE=
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-ozzo/ozzo-validation/v4 v4.3.0 h1:byhDUpfEwjsVQb1vBunvIjh2BHQ9ead57VkAEY4V+Es=
github.com/go-ozzo/ozzo-validation/v4 v4.3.0/go.mod h1:2NKgrcHl3z6cJs+3Oo940FPRiTzuqKbvfrL2RxCj6Ew=
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/go-sql-driver/mysql v1.8.0 h1:UtktXaU2Nb64z/pLiGIxY4431SJ4/dR5cjMmlVHgnT4=
github.com/go-sql-driver/mysql v1.8.0/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg=
github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs=
github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/pprof v0.0.0-20240625030939-27f56978b8b0 h1:e+8XbKB6IMn8A4OAyZccO4pYfB3s7bt6azNIPE7AnPg=
github.com/google/pprof v0.0.0-20240625030939-27f56978b8b0/go.mod h1:K1liHPHnj73Fdn/EKuT8nrFqBihUSKXoLYU0BuatOYo=
github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o=
github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/wire v0.6.0 h1:HBkoIh4BdSxoyo9PveV8giw7ZsaBOvzWKfcg/6MrVwI=
github.com/google/wire v0.6.0/go.mod h1:F4QhpQ9EDIdJ1Mbop/NZBRB+5yrR6qg3BnctaoUk6NA=
github.com/googleapis/enterprise-certificate-proxy v0.3.2 h1:Vie5ybvEvT75RniqhfFxPRy3Bf7vr3h0cechB90XaQs=
github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0=
github.com/googleapis/gax-go/v2 v2.13.0 h1:yitjD5f7jQHhyDsnhKEBU52NdvvdSeGzlAnDPT0hH1s=
github.com/googleapis/gax-go/v2 v2.13.0/go.mod h1:Z/fvTZXF8/uw7Xu5GuslPw+bplx6SS338j1Is2S+B7A=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/holoplot/go-avahi v1.0.1 h1:XcqR2keL4qWRnlxHD5CAOdWpLFZJ+EOUK0vEuylfvvk=
github.com/holoplot/go-avahi v1.0.1/go.mod h1:qH5psEKb0DK+BRplMfc+RY4VMOlbf6mqfxgpMy6aP0M=
github.com/hinshun/vt10x v0.0.0-20220119200601-820417d04eec h1:qv2VnGeEQHchGaZ/u7lxST/RaJw+cv273q79D81Xbog=
github.com/hinshun/vt10x v0.0.0-20220119200601-820417d04eec/go.mod h1:Q48J4R4DvxnHolD5P8pOtXigYlRuPLGl6moFx3ulM68=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg=
github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=
github.com/josharian/native v1.0.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w=
github.com/josharian/native v1.1.0 h1:uuaP0hAbW7Y4l0ZRQ6C9zfb7Mg1mbFKry/xzDAfmtLA=
github.com/josharian/native v1.1.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiAt84A=
github.com/mattn/go-colorable v0.1.16/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/labstack/echo/v5 v5.0.0-20230722203903-ec5b858dab61 h1:FwuzbVh87iLiUQj1+uQUsuw9x5t9m5n5g7rG7o4svW4=
github.com/labstack/echo/v5 v5.0.0-20230722203903-ec5b858dab61/go.mod h1:paQfF1YtHe+GrGg5fOgjsjoCX/UKDr9bc1DoWpZfns8=
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mdlayher/ethernet v0.0.0-20190313224307-5b5fc417d966/go.mod h1:5s5p/sMJ6sNsFl6uCh85lkFGV8kLuIYJCRJLavVJwvg=
github.com/mdlayher/ethernet v0.0.0-20220221185849-529eae5b6118 h1:2oDp6OOhLxQ9JBoUuysVz9UZ9uI6oLUbvAZu0x8o+vE=
github.com/mdlayher/ethernet v0.0.0-20220221185849-529eae5b6118/go.mod h1:ZFUnHIVchZ9lJoWoEGUg8Q3M4U8aNNWA3CVSUTkW4og=
github.com/mdlayher/packet v1.0.0/go.mod h1:eE7/ctqDhoiRhQ44ko5JZU2zxB88g+JH/6jmnjzPjOU=
github.com/mdlayher/packet v1.2.0 h1:SX7/oY0+nkKo7p4Sv30+TIc3YuWgvDEf0eucTXRyPqk=
github.com/mdlayher/packet v1.2.0/go.mod h1:UtYVnQt+Zj6UD0F89HfzkqGXaYqys1NwkrS86wlLCv4=
github.com/mdlayher/packet v1.1.2 h1:3Up1NG6LZrsgDVn6X4L9Ge/iyRyxFEFD9o6Pr3Q1nQY=
github.com/mdlayher/packet v1.1.2/go.mod h1:GEu1+n9sG5VtiRE4SydOmX5GTwyyYlteZiFU+x0kew4=
github.com/mdlayher/raw v0.0.0-20190313224157-43dbcdd7739d/go.mod h1:r1fbeITl2xL/zLbVnNHFyOzQJTgr/3fpf1lJX/cjzR8=
github.com/mdlayher/socket v0.2.1/go.mod h1:QLlNPkFR88mRUNQIzRBMfXxwKal8H7u1h3bL1CV+f0E=
github.com/mdlayher/socket v0.7.0 h1:qVREPVwtUMg17pwvveQxpurq0PVisMxi3FGgpsorMYQ=
github.com/mdlayher/socket v0.7.0/go.mod h1:f7iKql2EK/rfsWYDKofKjk2Ig7I+6HQWdMIdn1tO4A4=
github.com/mdlayher/socket v0.5.1 h1:VZaqt6RkGkt2OE9l3GcC6nZkqD3xKeQLyfleW/uBcos=
github.com/mdlayher/socket v0.5.1/go.mod h1:TjPLHI1UgwEv5J1B5q0zTZq12A/6H7nKmtTanQE37IQ=
github.com/mdlayher/wol v0.0.0-20220221231636-b763a792253a h1:fpQi42PM6HzbHwNg6a7OvLbh5l49Rgr7GCARozjHwio=
github.com/mdlayher/wol v0.0.0-20220221231636-b763a792253a/go.mod h1:XX6nvyQpGc8E4KaQm62FyexOYd36ilpyfYf8wjgMDV8=
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI=
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus-community/pro-bing v0.9.1 h1:kpuAr6AU2oRtzGihJSUcetHtjc7ku7h6PxeuW9RVrQw=
github.com/prometheus-community/pro-bing v0.9.1/go.mod h1:z79wYTxAOf6FpTng0QdIhZ3j/Nd5l3+gnFSCIT+SiSQ=
github.com/pocketbase/dbx v1.10.1 h1:cw+vsyfCJD8YObOVeqb93YErnlxwYMkNZ4rwN0G0AaA=
github.com/pocketbase/dbx v1.10.1/go.mod h1:xXRCIAKTHMgUCyCKZm55pUOdvFziJjQfXaWKhu2vhMs=
github.com/pocketbase/pocketbase v0.22.18 h1:yVckUhi5GDORqCb0BbtlvRB1CVxHY9HO9btEaeZHVJU=
github.com/pocketbase/pocketbase v0.22.18/go.mod h1:0QFvDOOW7ANId78ChZSagyHbmP6CgMxDQrQFXzeaDpA=
github.com/prometheus-community/pro-bing v0.4.1 h1:aMaJwyifHZO0y+h8+icUz0xbToHbia0wdmzdVZ+Kl3w=
github.com/prometheus-community/pro-bing v0.4.1/go.mod h1:aLsw+zqCaDoa2RLVVSX3+UiCkBBXTMtZC3c7EkfWnAE=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
@@ -87,84 +205,184 @@ github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzG
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0 h1:4Pp6oUg3+e/6M4C0A/3kJ2VYa++dsWVTtGgLVj5xtHg=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0/go.mod h1:Mjt1i1INqiaoZOMGR1RIUJN+i3ChKoFRqzrRQhlkbs0=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 h1:jq9TW8u3so/bN+JPT166wjOI6/vQPF6Xe7nMNIltagk=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0/go.mod h1:p8pYQP+m5XfbZm9fxtSKAbM6oIllS7s2AfxrChvc7iw=
go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo=
go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo=
go.opentelemetry.io/otel/metric v1.24.0 h1:6EhoGWWK28x1fbpA4tYTOWBkPefTDQnb8WSGXlc88kI=
go.opentelemetry.io/otel/metric v1.24.0/go.mod h1:VYhLe1rFfxuTXLgj4CBiyz+9WYBA8pNGJgDcSFRKBco=
go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI=
go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU=
gocloud.dev v0.37.0 h1:XF1rN6R0qZI/9DYjN16Uy0durAmSlf58DHOcb28GPro=
gocloud.dev v0.37.0/go.mod h1:7/O4kqdInCNsc6LqgmuFnS0GRew4XNNYWpA44yQnwco=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.25.0 h1:ypSNr+bnYL2YhwoMt2zPxHFmbAN1KZs/njMG3hxUp30=
golang.org/x/crypto v0.25.0/go.mod h1:T+wALwcMOSE0kXgUAnPAHqTLW+XHgcELELW8VaDgm/M=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.47.0 h1:za/8gVz++PPZqmZJBNSISICN5Rrj5zixP/8K++fgmqo=
golang.org/x/image v0.47.0/go.mod h1:IkN5o4A7vq55vXN8FWjjnhg9Rs2GOtffqsSi9mWAKYE=
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
golang.org/x/image v0.18.0 h1:jGzIakQa/ZXI1I0Fxvaa9W7yP25TqT6cHIHn+6CqvSQ=
golang.org/x/image v0.18.0/go.mod h1:4yyo5vMFQjVjUcVk4jEQcU9MGy/rulF5WvUILseCM2E=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190313220215-9f648a60d977/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98=
golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys=
golang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.21.0 h1:tsimM75w1tF/uws5rbeHzIWxEqElMehnc+iW793zsZs=
golang.org/x/oauth2 v0.21.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.22.0 h1:BbsgPEJULsl2fV/AT3v15Mjva5yXKQDyKf+TbDz7QJk=
golang.org/x/term v0.22.0/go.mod h1:F3qCibpT5AMpCRfhfT53vVJwhLtIVHhB9XDjfFvnMI4=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20240716161551-93cc26a95ae9 h1:LLhsEBxRTBLuKlQxFBYUOU8xyFgXv6cOTp2HASDlsDk=
golang.org/x/xerrors v0.0.0-20240716161551-93cc26a95ae9/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90=
google.golang.org/api v0.189.0 h1:equMo30LypAkdkLMBqfeIqtyAnlyig1JSZArl4XPwdI=
google.golang.org/api v0.189.0/go.mod h1:FLWGJKb0hb+pU2j+rJqwbnsF+ym+fQs73rbJ+KAUgy8=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
google.golang.org/genproto v0.0.0-20240722135656-d784300faade h1:lKFsS7wpngDgSCeFn7MoLy+wBDQZ1UQIJD4UNM1Qvkg=
google.golang.org/genproto v0.0.0-20240722135656-d784300faade/go.mod h1:FfBgJBJg9GcpPvKIuHSZ/aE1g2ecGL74upMzGZjiGEY=
google.golang.org/genproto/googleapis/api v0.0.0-20240711142825-46eb208f015d h1:kHjw/5UfflP/L5EbledDrcG4C2597RtymmGRZvHiCuY=
google.golang.org/genproto/googleapis/api v0.0.0-20240711142825-46eb208f015d/go.mod h1:mw8MG/Qz5wfgYr6VqVCiZcHe/GJEfI+oGGDCohaVgB0=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240723171418-e6d459c13d2a h1:hqK4+jJZXCU4pW7jsAdGOVFIfLHQeV7LaizZKnZ84HI=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240723171418-e6d459c13d2a/go.mod h1:Ue6ibwXGpU+dqIcODieyLOcgj7z8+IcskoNIgZxtrFY=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc=
google.golang.org/grpc v1.65.0 h1:bs/cUb4lp1G5iImFFd3u5ixQzweKizoZJAwBNLR42lc=
google.golang.org/grpc v1.65.0/go.mod h1:WgYC2ypjlB0EiQi6wdKixMqukr6lBc0Vo+oOgjrM5ZQ=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
kernel.org/pub/linux/libs/security/libcap/cap v1.2.78 h1:jgqg4gyu2BaYW9L6uzEtGLf8GNREwk/z4UFdwt5F3pE=
kernel.org/pub/linux/libs/security/libcap/cap v1.2.78/go.mod h1:VjuVda6m2qGkpCVfrFkpTGyvkdlZ2N5/yfo89tujlg8=
kernel.org/pub/linux/libs/security/libcap/psx v1.2.78 h1:PC3yNs51cX5LZ7U57a7xielBcoXB3xnV+rXD8V0H0DQ=
kernel.org/pub/linux/libs/security/libcap/psx v1.2.78/go.mod h1:+l6Ee2F59XiJ2I6WR5ObpC1utCQJZ/VLsEbQCD8RG24=
modernc.org/cc/v4 v4.29.7 h1:q+NXGJ0bK3b4TXFYQQVr9pYETGnmwFWkrUzJnMya/Tg=
modernc.org/cc/v4 v4.29.7/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.36.1 h1:ZNIUZAryN0UgnJwtyxrdEzcFc3yD4Cu4AzjfPXsLsIE=
modernc.org/ccgo/v4 v4.36.1/go.mod h1:rrtGc2QkS239nYb/mQNuBMyjq3/y3ZXWbBjPoV3wqzA=
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.5 h1:21ldfPfRYE31Tb7B3mwAK8gy1AxP4+dKjrOQPfqakoc=
modernc.org/gc/v3 v3.1.5/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.77.1 h1:Ct8j47QtiZ1Enj2DtFXQtUqrPCAjdCmPjtCuvrYQ0Hs=
modernc.org/libc v1.77.1/go.mod h1:87/pZ4L6nD1zqW4nItuS12YO7hN1igAah34xjnQo/W0=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.60.1 h1:/blz53O951KWFOso4QQvEs/Fq6cDBKLtMVrYNSeJVKw=
modernc.org/sqlite v1.60.1/go.mod h1:1dIoEagfDE72QytD5scH1lxARtaUgKgHC/NuApA27r0=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ=
modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ=
modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y=
modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s=
modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=
modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw=
modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU=
modernc.org/gc/v3 v3.0.0-20240722195230-4a140ff9c08e h1:WPC4v0rNIFb2PY+nBBEEKyugPPRHPzUgyN3xZPpGK58=
modernc.org/gc/v3 v3.0.0-20240722195230-4a140ff9c08e/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4=
modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U=
modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w=
modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E=
modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU=
modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc=
modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss=
modernc.org/sqlite v1.31.1 h1:XVU0VyzxrYHlBhIs1DiEgSl0ZtdnPtbLVy8hSkzxGrs=
modernc.org/sqlite v1.31.1/go.mod h1:UqoylwmTb9F+IqXERT8bW9zzOWN8qwAIcLdzeBZs4hA=
modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=
modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
-136
View File
@@ -1,136 +0,0 @@
// Package iptracking updates the stored ip addresses of opted-in devices by
// scanning their local subnets for their mac addresses.
package iptracking
import (
"net"
"sync/atomic"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"github.com/seriousm4x/upsnap/logging"
"github.com/seriousm4x/upsnap/networking"
)
var sweepRunning atomic.Bool
// sweepOwed marks that a periodic sweep was skipped while no realtime
// clients were connected, so the next client to connect gets a catch-up
// sweep. Starts true so the first client after boot gets fresh ips.
var sweepOwed atomic.Bool
func init() {
sweepOwed.Store(true)
}
// nmapScan is a seam for tests to stub out the privileged nmap invocation
var nmapScan = networking.NmapScan
// TrackAllSubnets scans the local subnets of devices with ip tracking enabled
// and updates their ip address if their mac address is found at a different
// one. Non-scannable subnets are silently skipped, but their devices can
// still be updated by another subnet's scan that finds their mac address,
// as long as the new ip stays within the device's own subnet.
func TrackAllSubnets(app core.App) {
log := logging.Logger(app)
// skip if the previous sweep is still running
if !sweepRunning.CompareAndSwap(false, true) {
return
}
defer sweepRunning.Store(false)
devices, err := app.FindRecordsByFilter("devices", "track_ip = true", "", 0, 0)
if err != nil {
log.Error("Failed to load devices for IP tracking", "error", err)
return
}
// collect the unique scannable subnets of the tracked devices
subnets := make(map[string]*net.IPNet)
for _, device := range devices {
subnet, err := networking.DeviceSubnet(device.GetString("ip"), device.GetString("netmask"))
if err != nil {
log.Error("Failed to determine device subnet for IP tracking", "device", device.GetString("name"), "error", err)
continue
}
if networking.ValidateScannableSubnet(subnet) != nil {
continue
}
subnets[subnet.String()] = subnet
}
for cidr, subnet := range subnets {
if err := TrackOneSubnet(app, subnet); err != nil {
log.Error("IP tracking scan failed", "subnet", cidr, "error", err)
}
}
}
// PeriodicSweep runs the scheduled sweep, or skips it when paused — no
// realtime clients connected while lazy_ping is on — owing a catch-up
// sweep to the next client that connects.
func PeriodicSweep(app core.App, pause bool) {
if pause {
sweepOwed.Store(true)
return
}
TrackAllSubnets(app)
}
// CatchUpSweep runs a sweep if one is owed, i.e. the periodic sweep was
// skipped while nobody was connected or hasn't run since boot. Clients
// connecting while sweeps run on schedule trigger nothing.
func CatchUpSweep(app core.App) {
if !sweepOwed.CompareAndSwap(true, false) {
return
}
TrackAllSubnets(app)
}
// TrackOneSubnet runs an nmap scan of the given subnet and updates the ip
// address of any ip-tracked device whose mac address is found at a new
// address within its own subnet. Returns an error for a non-scannable subnet.
func TrackOneSubnet(app core.App, subnet *net.IPNet) error {
log := logging.Logger(app)
if err := networking.ValidateScannableSubnet(subnet); err != nil {
return err
}
scan, err := nmapScan(subnet.String())
if err != nil {
return err
}
macToIp := scan.MacToIP()
devices, err := app.FindRecordsByFilter("devices", "track_ip = true", "", 0, 0)
if err != nil {
return err
}
for _, device := range devices {
parsedMac, err := net.ParseMAC(device.GetString("mac"))
if err != nil {
continue
}
newIp, ok := macToIp[parsedMac.String()]
if !ok || newIp == device.GetString("ip") {
continue
}
// only move a device within its own subnet, so that a scan can't
// relocate devices tracked on other subnets that see the same mac
deviceSubnet, err := networking.DeviceSubnet(device.GetString("ip"), device.GetString("netmask"))
if err != nil || !deviceSubnet.Contains(net.ParseIP(newIp)) {
continue
}
oldIP := device.GetString("ip")
device.Set("ip", newIp)
// only write the changed ip field to avoid clobbering concurrent
// status updates from the ping and wake/shutdown cronjobs
device.IgnoreUnchangedFields(true)
if err := app.Save(device); err != nil {
log.Error("Failed to save tracked device IP", "device", device.GetString("name"), "error", err)
} else {
log.Info("Device IP changed", "device", device.GetString("name"), "from", oldIP, "to", newIp)
}
}
return nil
}
-347
View File
@@ -1,347 +0,0 @@
package iptracking
import (
"encoding/xml"
"fmt"
"net"
"strings"
"testing"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"ganigeorgiev.com/pocketbase/pocketbase/tests"
"github.com/seriousm4x/upsnap/networking"
// register the app migrations so test apps get the real schema
_ "github.com/seriousm4x/upsnap/migrations"
)
// newTestApp returns a throwaway app with all migrations applied.
func newTestApp(t *testing.T) *tests.TestApp {
t.Helper()
app, err := tests.NewTestApp(t.TempDir())
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
t.Cleanup(app.Cleanup)
return app
}
func buildDevice(t *testing.T, app core.App, name, ip, netmask, mac string, trackIp bool) *core.Record {
t.Helper()
collection, err := app.FindCollectionByNameOrId("devices")
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
device := core.NewRecord(collection)
device.Set("name", name)
device.Set("ip", ip)
device.Set("netmask", netmask)
device.Set("mac", mac)
device.Set("track_ip", trackIp)
return device
}
func newDevice(t *testing.T, app core.App, name, ip, netmask, mac string, trackIp bool) *core.Record {
t.Helper()
device := buildDevice(t, app, name, ip, netmask, mac, trackIp)
if err := app.Save(device); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
return device
}
// newLegacyDevice saves a device bypassing field validation, like rows
// created before the ip and mac format rules existed.
func newLegacyDevice(t *testing.T, app core.App, name, ip, netmask, mac string, trackIp bool) *core.Record {
t.Helper()
device := buildDevice(t, app, name, ip, netmask, mac, trackIp)
if err := app.SaveNoValidate(device); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
return device
}
// stubScan replaces the nmap seam with a canned scan reporting the given
// mac addresses at the given ips, and returns the list of scanned ranges.
func stubScan(t *testing.T, macToHostIp map[string]string) *[]string {
t.Helper()
var sample strings.Builder
sample.WriteString("<nmaprun>")
for mac, ip := range macToHostIp {
fmt.Fprintf(&sample, `<host><address addr=%q addrtype="ipv4"/><address addr=%q addrtype="mac"/></host>`, ip, mac)
}
sample.WriteString("</nmaprun>")
scan := networking.Nmaprun{}
if err := xml.Unmarshal([]byte(sample.String()), &scan); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
var scanned []string
orig := nmapScan
nmapScan = func(scanRange string) (networking.Nmaprun, error) {
scanned = append(scanned, scanRange)
return scan, nil
}
t.Cleanup(func() { nmapScan = orig })
return &scanned
}
func mustSubnet(t *testing.T, cidr string) *net.IPNet {
t.Helper()
_, subnet, err := net.ParseCIDR(cidr)
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
return subnet
}
// The loopback /16 passes the scannable checks on any host, making it the
// only subnet a test can scan without depending on the environment.
const (
testSubnet = "127.0.0.0/16"
testNetmask = "255.255.0.0"
)
func TestTrackOneSubnetSkipsUntrackedDevices(t *testing.T) {
app := newTestApp(t)
device := newDevice(t, app, "untracked", "127.0.0.50", testNetmask, "AA:BB:CC:DD:EE:01", false)
stubScan(t, map[string]string{"AA:BB:CC:DD:EE:01": "127.0.0.99"})
if err := TrackOneSubnet(app, mustSubnet(t, testSubnet)); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
fresh, err := app.FindRecordById("devices", device.Id)
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
if ip := fresh.GetString("ip"); ip != "127.0.0.50" {
t.Errorf("Ip of device without track_ip changed to %s", ip)
}
}
func TestTrackOneSubnetSkipPaths(t *testing.T) {
app := newTestApp(t)
saves := 0
app.OnRecordUpdate("devices").BindFunc(func(e *core.RecordEvent) error {
saves++
return e.Next()
})
testCases := []struct {
name string
ip string
mac string
legacy bool
}{
// A device mac that can't be parsed never matches
{
name: "Invalid Mac",
ip: "127.0.0.50",
mac: "not-a-mac",
legacy: true,
},
// A device mac missing from the scan results is left alone
{
name: "Mac Not In Scan",
ip: "127.0.0.50",
mac: "AA:BB:CC:DD:EE:02",
},
// A device ip without a computable subnet is never moved
{
name: "Invalid Device Ip",
ip: "999.999.999.999",
mac: "AA:BB:CC:DD:EE:01",
legacy: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
create := newDevice
if tc.legacy {
create = newLegacyDevice
}
device := create(t, app, tc.name, tc.ip, testNetmask, tc.mac, true)
stubScan(t, map[string]string{"AA:BB:CC:DD:EE:01": "127.0.0.99"})
if err := TrackOneSubnet(app, mustSubnet(t, testSubnet)); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
fresh, err := app.FindRecordById("devices", device.Id)
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
if ip := fresh.GetString("ip"); ip != tc.ip {
t.Errorf("Ip mismatch: expected %s, got %s", tc.ip, ip)
}
if saves != 0 {
t.Errorf("Expected no record updates, got %d", saves)
}
})
}
}
func TestTrackOneSubnetUnscannable(t *testing.T) {
app := newTestApp(t)
// TEST-NET-1 (RFC 5737) is never assigned to an interface
scanned := stubScan(t, nil)
if err := TrackOneSubnet(app, mustSubnet(t, "192.0.2.0/24")); err == nil {
t.Error("Expected error but got none")
}
if len(*scanned) != 0 {
t.Errorf("Expected no scans of an unscannable subnet, got %v", *scanned)
}
}
func TestTrackOneSubnetSameSubnetGuard(t *testing.T) {
app := newTestApp(t)
testCases := []struct {
name string
ip string
netmask string
mac string
scanMac string
foundIp string
wantIp string
}{
// A move within the device's own subnet is applied, with the
// stored dashed lower case mac matching the scanned
// colon-separated upper case one
{
name: "Within Own Subnet",
ip: "127.0.0.50",
netmask: testNetmask,
mac: "aa-bb-cc-dd-01-01",
scanMac: "AA:BB:CC:DD:01:01",
foundIp: "127.0.0.99",
wantIp: "127.0.0.99",
},
// The device's own subnet bounds the move, not the scanned one
{
name: "Narrower Subnet Within Scan",
ip: "127.0.5.5",
netmask: "255.255.255.0",
mac: "AA:BB:CC:DD:01:02",
foundIp: "127.0.5.9",
wantIp: "127.0.5.9",
},
// A found ip outside the device's narrower subnet is not applied,
// even though it is inside the scanned subnet
{
name: "Outside Own Subnet",
ip: "127.0.5.5",
netmask: "255.255.255.0",
mac: "AA:BB:CC:DD:01:03",
foundIp: "127.0.6.9",
wantIp: "127.0.5.5",
},
// A device from a disjoint subnet is never moved into the scanned one
{
name: "Disjoint Subnet",
ip: "10.9.9.9",
netmask: "255.255.255.0",
mac: "AA:BB:CC:DD:01:04",
foundIp: "127.0.0.99",
wantIp: "10.9.9.9",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
device := newDevice(t, app, tc.name, tc.ip, tc.netmask, tc.mac, true)
scanMac := tc.scanMac
if scanMac == "" {
scanMac = tc.mac
}
stubScan(t, map[string]string{scanMac: tc.foundIp})
if err := TrackOneSubnet(app, mustSubnet(t, testSubnet)); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
fresh, err := app.FindRecordById("devices", device.Id)
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
if ip := fresh.GetString("ip"); ip != tc.wantIp {
t.Errorf("Ip mismatch: expected %s, got %s", tc.wantIp, ip)
}
})
}
}
// A paused periodic sweep scans nothing and owes a catch-up sweep, which
// runs at most once until the next pause; an unpaused sweep scans directly.
func TestPeriodicSweepAndCatchUp(t *testing.T) {
app := newTestApp(t)
newDevice(t, app, "tracked", "127.0.0.50", testNetmask, "AA:BB:CC:DD:09:01", true)
scanned := stubScan(t, map[string]string{"AA:BB:CC:DD:09:01": "127.0.0.99"})
PeriodicSweep(app, true)
if len(*scanned) != 0 {
t.Fatalf("Expected no scans while paused, got %v", *scanned)
}
CatchUpSweep(app)
if len(*scanned) != 1 {
t.Fatalf("Expected one scan after a paused sweep, got %v", *scanned)
}
CatchUpSweep(app)
if len(*scanned) != 1 {
t.Errorf("Expected no scan when none is owed, got %v", *scanned)
}
PeriodicSweep(app, false)
if len(*scanned) != 2 {
t.Errorf("Expected an unpaused sweep to scan, got %v", *scanned)
}
CatchUpSweep(app)
if len(*scanned) != 2 {
t.Errorf("Expected an unpaused sweep to owe nothing, got %v", *scanned)
}
}
// TrackAllSubnets scans each unique scannable subnet once, silently skips the
// rest, and updates any tracked device found at a new ip within its own
// subnet — even one whose own subnet couldn't be scanned.
func TestTrackAllSubnets(t *testing.T) {
app := newTestApp(t)
first := newDevice(t, app, "first", "127.0.0.10", testNetmask, "AA:BB:CC:DD:02:01", true)
second := newDevice(t, app, "second", "127.0.0.20", testNetmask, "AA:BB:CC:DD:02:02", true)
// TEST-NET-1 (RFC 5737) is never assigned to an interface
unscannable := newDevice(t, app, "unscannable", "192.0.2.5", "255.255.255.0", "AA:BB:CC:DD:02:03", true)
// a /8 subnet is too large to scan but contains the found ip
wide := newDevice(t, app, "wide", "127.0.0.60", "255.0.0.0", "AA:BB:CC:DD:02:04", true)
scanned := stubScan(t, map[string]string{
"AA:BB:CC:DD:02:01": "127.0.0.11",
"AA:BB:CC:DD:02:02": "127.0.0.21",
"AA:BB:CC:DD:02:04": "127.0.0.61",
})
TrackAllSubnets(app)
if len(*scanned) != 1 || (*scanned)[0] != testSubnet {
t.Errorf("Expected a single scan of %s, got %v", testSubnet, *scanned)
}
wantIps := map[string]string{
first.Id: "127.0.0.11",
second.Id: "127.0.0.21",
unscannable.Id: "192.0.2.5",
wide.Id: "127.0.0.61",
}
for id, wantIp := range wantIps {
fresh, err := app.FindRecordById("devices", id)
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
if ip := fresh.GetString("ip"); ip != wantIp {
t.Errorf("Ip mismatch for %s: expected %s, got %s", fresh.GetString("name"), wantIp, ip)
}
}
}
+30
View File
@@ -0,0 +1,30 @@
package logger
import (
"log"
"os"
)
const (
flags = log.Ldate | log.Ltime | log.Lshortfile
)
var (
Info = log.New(os.Stdout, "[INFO] ", flags)
Debug = log.New(os.Stdout, "[DEBUG] ", flags)
Warning = log.New(os.Stdout, "[WARNING] ", flags)
Error = log.New(os.Stderr, "[ERROR] ", flags)
)
func init() {
// TODO: decide if you want to log to a file to max
// output := io.MultiWriter(os.Stdout, logFile)
output := os.Stdout
Info.SetOutput(output)
Error.SetOutput(output)
Debug.SetOutput(output)
log.SetOutput(Debug.Writer())
log.SetPrefix("[DEBUG]")
log.SetFlags(flags)
}
-102
View File
@@ -1,102 +0,0 @@
package logging
import (
"context"
"errors"
"fmt"
"log/slog"
"os"
"runtime"
"strconv"
"strings"
"ganigeorgiev.com/pocketbase/pocketbase/core"
)
var consoleHandler slog.Handler
// ConfigureConsole sets console output for UpSnap logs. PocketBase persistence
// remains controlled by PocketBase's built-in log settings.
func ConfigureConsole(level string) error {
level = strings.TrimSpace(level)
if level == "" {
level = "INFO"
}
if strings.EqualFold(level, "OFF") {
consoleHandler = nil
return nil
}
var parsed slog.Level
if err := parsed.UnmarshalText([]byte(strings.ToUpper(level))); err != nil {
return fmt.Errorf("invalid UPSNAP_LOG_LEVEL %q (expected DEBUG, INFO, WARN, ERROR, or OFF)", level)
}
consoleHandler = slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: parsed,
})
return nil
}
func relativeSource(file string) string {
file = strings.ReplaceAll(file, "\\", "/")
if index := strings.LastIndex(file, "/backend/"); index >= 0 {
return file[index+1:]
}
return file
}
// Logger writes through PocketBase's logger and mirrors UpSnap logs to stdout.
func Logger(app core.App) *slog.Logger {
handlers := []slog.Handler{app.Logger().Handler()}
if consoleHandler != nil && !app.IsDev() {
handlers = append(handlers, consoleHandler)
}
return slog.New(multiHandler(handlers)).With("upsnap", true)
}
type multiHandler []slog.Handler
func (h multiHandler) Enabled(ctx context.Context, level slog.Level) bool {
for _, handler := range h {
if handler.Enabled(ctx, level) {
return true
}
}
return false
}
func (h multiHandler) Handle(ctx context.Context, record slog.Record) error {
if record.PC != 0 {
frames := runtime.CallersFrames([]uintptr{record.PC})
frame, _ := frames.Next()
record.AddAttrs(slog.String(slog.SourceKey, relativeSource(frame.File)+":"+strconv.Itoa(frame.Line)))
}
var errs []error
for _, handler := range h {
if handler.Enabled(ctx, record.Level) {
if err := handler.Handle(ctx, record.Clone()); err != nil {
errs = append(errs, err)
}
}
}
return errors.Join(errs...)
}
func (h multiHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
handlers := make(multiHandler, len(h))
for i, handler := range h {
handlers[i] = handler.WithAttrs(attrs)
}
return handlers
}
func (h multiHandler) WithGroup(name string) slog.Handler {
handlers := make(multiHandler, len(h))
for i, handler := range h {
handlers[i] = handler.WithGroup(name)
}
return handlers
}
+3 -6
View File
@@ -2,18 +2,15 @@ package main
import (
"embed"
"log"
"ganigeorgiev.com/pocketbase/pocketbase/apis"
"github.com/labstack/echo/v5"
"github.com/seriousm4x/upsnap/pb"
)
//go:embed all:pb_public
var distDir embed.FS
var distDirFS = apis.MustSubFS(distDir, "pb_public")
var distDirFS = echo.MustSubFS(distDir, "pb_public")
func main() {
if err := pb.StartPocketBase(distDirFS); err != nil {
log.Fatal(err)
}
pb.StartPocketBase(distDirFS)
}
@@ -0,0 +1,207 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models"
)
func init() {
m.Register(func(db dbx.Builder) error {
jsonData := `{
"id": "z5lghx2r3tm45n1",
"created": "2023-01-28 19:10:29.223Z",
"updated": "2023-01-28 19:10:29.223Z",
"name": "devices",
"type": "base",
"system": false,
"schema": [
{
"system": false,
"id": "tiqcmnjo",
"name": "name",
"type": "text",
"required": true,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "1si6ajha",
"name": "ip",
"type": "text",
"required": true,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "fyqmpon6",
"name": "mac",
"type": "text",
"required": true,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "s8c5z7n0",
"name": "netmask",
"type": "text",
"required": true,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "qqvyfrex",
"name": "status",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "ilrwvlev",
"name": "ports",
"type": "relation",
"required": false,
"unique": false,
"options": {
"maxSelect": null,
"collectionId": "cti4l8f4mz8df3r",
"cascadeDelete": false
}
},
{
"system": false,
"id": "gdctb8hj",
"name": "link",
"type": "url",
"required": false,
"unique": false,
"options": {
"exceptDomains": null,
"onlyDomains": null
}
},
{
"system": false,
"id": "kzvdbbws",
"name": "wake_cron",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "dcd3vuc3",
"name": "wake_cron_enabled",
"type": "bool",
"required": false,
"unique": false,
"options": {}
},
{
"system": false,
"id": "91bs6clw",
"name": "shutdown_cron",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "vnlymcuw",
"name": "shutdown_cron_enabled",
"type": "bool",
"required": false,
"unique": false,
"options": {}
},
{
"system": false,
"id": "1a7yrwo9",
"name": "shutdown_cmd",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "iarksm3l",
"name": "password",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
}
],
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"options": {}
}`
collection := &models.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return daos.New(db).SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
return dao.DeleteCollection(collection)
})
}
@@ -0,0 +1,81 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models"
)
func init() {
m.Register(func(db dbx.Builder) error {
jsonData := `{
"id": "cti4l8f4mz8df3r",
"created": "2023-01-28 19:10:29.223Z",
"updated": "2023-01-28 19:10:29.223Z",
"name": "ports",
"type": "base",
"system": false,
"schema": [
{
"system": false,
"id": "8nwuncgg",
"name": "number",
"type": "number",
"required": true,
"unique": false,
"options": {
"min": null,
"max": 65535
}
},
{
"system": false,
"id": "o0he3pu6",
"name": "name",
"type": "text",
"required": true,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "w0bh39gv",
"name": "status",
"type": "bool",
"required": false,
"unique": false,
"options": {}
}
],
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"options": {}
}`
collection := &models.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return daos.New(db).SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("cti4l8f4mz8df3r")
if err != nil {
return err
}
return dao.DeleteCollection(collection)
})
}
@@ -0,0 +1,86 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models"
)
func init() {
m.Register(func(db dbx.Builder) error {
jsonData := `{
"id": "nmj3ko20gzkg8n3",
"created": "2023-01-28 19:10:29.223Z",
"updated": "2023-01-28 19:10:29.223Z",
"name": "settings",
"type": "base",
"system": false,
"schema": [
{
"system": false,
"id": "ph88gaa5",
"name": "interval",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "agw2fyd1",
"name": "scan_range",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "slrjkipw",
"name": "website_title",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
}
],
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"options": {}
}`
collection := &models.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return daos.New(db).SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
if err != nil {
return err
}
return dao.DeleteCollection(collection)
})
}
@@ -0,0 +1,90 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("_pb_users_auth_")
if err != nil {
return err
}
return dao.DeleteCollection(collection)
}, func(db dbx.Builder) error {
jsonData := `{
"id": "_pb_users_auth_",
"created": "2023-01-28 19:10:12.835Z",
"updated": "2023-01-28 19:10:12.835Z",
"name": "users",
"type": "auth",
"system": false,
"schema": [
{
"system": false,
"id": "users_name",
"name": "name",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "users_avatar",
"name": "avatar",
"type": "file",
"required": false,
"unique": false,
"options": {
"maxSelect": 1,
"maxSize": 5242880,
"mimeTypes": [
"image/jpg",
"image/jpeg",
"image/png",
"image/svg+xml",
"image/gif",
"image/webp"
],
"thumbs": null
}
}
],
"listRule": "id = @request.auth.id",
"viewRule": "id = @request.auth.id",
"createRule": "",
"updateRule": "id = @request.auth.id",
"deleteRule": "id = @request.auth.id",
"options": {
"allowEmailAuth": true,
"allowOAuth2Auth": true,
"allowUsernameAuth": true,
"exceptEmailDomains": null,
"manageRule": null,
"minPasswordLength": 8,
"onlyEmailDomains": null,
"requireEmail": false
}
}`
collection := &models.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return daos.New(db).SaveCollection(collection)
})
}
@@ -0,0 +1,55 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models"
)
func init() {
m.Register(func(db dbx.Builder) error {
jsonData := `{
"id": "27do0wbcuyfmbmx",
"created": "2023-03-04 20:33:00.558Z",
"updated": "2023-03-04 20:33:00.558Z",
"name": "users",
"type": "auth",
"system": false,
"schema": [],
"listRule": null,
"viewRule": null,
"createRule": null,
"updateRule": null,
"deleteRule": null,
"options": {
"allowEmailAuth": true,
"allowOAuth2Auth": false,
"allowUsernameAuth": true,
"exceptEmailDomains": [],
"manageRule": null,
"minPasswordLength": 8,
"onlyEmailDomains": [],
"requireEmail": false
}
}`
collection := &models.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return daos.New(db).SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
if err != nil {
return err
}
return dao.DeleteCollection(collection)
})
}
@@ -0,0 +1,50 @@
package migrations
import (
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
collection.ListRule = types.Pointer("@request.auth.id != \"\"")
collection.ViewRule = types.Pointer("@request.auth.id != \"\"")
collection.CreateRule = nil
collection.UpdateRule = nil
collection.DeleteRule = nil
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
collection.ListRule = nil
collection.ViewRule = nil
collection.CreateRule = types.Pointer("")
collection.UpdateRule = types.Pointer("")
collection.DeleteRule = types.Pointer("")
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,50 @@
package migrations
import (
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("cti4l8f4mz8df3r")
if err != nil {
return err
}
collection.ListRule = types.Pointer("@request.auth.id != \"\"")
collection.ViewRule = types.Pointer("@request.auth.id != \"\"")
collection.CreateRule = nil
collection.UpdateRule = nil
collection.DeleteRule = nil
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("cti4l8f4mz8df3r")
if err != nil {
return err
}
collection.ListRule = nil
collection.ViewRule = nil
collection.CreateRule = types.Pointer("")
collection.UpdateRule = types.Pointer("")
collection.DeleteRule = types.Pointer("")
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,50 @@
package migrations
import (
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
if err != nil {
return err
}
collection.ListRule = types.Pointer("@request.auth.id != \"\"")
collection.ViewRule = types.Pointer("@request.auth.id != \"\"")
collection.CreateRule = nil
collection.UpdateRule = nil
collection.DeleteRule = nil
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
if err != nil {
return err
}
collection.ListRule = nil
collection.ViewRule = nil
collection.CreateRule = types.Pointer("")
collection.UpdateRule = types.Pointer("")
collection.DeleteRule = types.Pointer("")
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,80 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models"
)
func init() {
m.Register(func(db dbx.Builder) error {
jsonData := `{
"id": "t1rajoyzl6691g3",
"created": "2023-03-09 22:17:29.463Z",
"updated": "2023-03-09 22:17:29.463Z",
"name": "settings_public",
"type": "base",
"system": false,
"schema": [
{
"system": false,
"id": "s1grje98",
"name": "website_title",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "tlzz87pj",
"name": "favicon",
"type": "file",
"required": false,
"unique": false,
"options": {
"maxSelect": 1,
"maxSize": 5242880,
"mimeTypes": [
"image/x-icon",
"image/png",
"image/svg+xml",
"image/gif",
"image/jpeg"
],
"thumbs": []
}
}
],
"listRule": "",
"viewRule": "",
"createRule": null,
"updateRule": null,
"deleteRule": null,
"options": {}
}`
collection := &models.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return daos.New(db).SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("t1rajoyzl6691g3")
if err != nil {
return err
}
return dao.DeleteCollection(collection)
})
}
@@ -0,0 +1,65 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
if err != nil {
return err
}
collection.Name = "settings_private"
collection.ListRule = nil
collection.ViewRule = nil
// remove
collection.Schema.RemoveField("slrjkipw")
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
if err != nil {
return err
}
collection.Name = "settings"
collection.ListRule = types.Pointer("@request.auth.id != \"\"")
collection.ViewRule = types.Pointer("@request.auth.id != \"\"")
// add
del_website_title := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "slrjkipw",
"name": "website_title",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
}`), del_website_title)
collection.Schema.AddField(del_website_title)
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,48 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("t1rajoyzl6691g3")
if err != nil {
return err
}
// add
new_setup_completed := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "vrxqcsnv",
"name": "setup_completed",
"type": "bool",
"required": false,
"unique": false,
"options": {}
}`), new_setup_completed)
collection.Schema.AddField(new_setup_completed)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("t1rajoyzl6691g3")
if err != nil {
return err
}
// remove
collection.Schema.RemoveField("vrxqcsnv")
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,61 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models"
)
func init() {
m.Register(func(db dbx.Builder) error {
jsonData := `{
"id": "djqp3uxrac2ores",
"created": "2023-06-29 10:39:59.291Z",
"updated": "2023-06-29 10:39:59.291Z",
"name": "groups",
"type": "base",
"system": false,
"schema": [
{
"system": false,
"id": "b3oaemnp",
"name": "name",
"type": "text",
"required": true,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
}
],
"indexes": [],
"listRule": "@request.auth.id != \"\"",
"viewRule": "@request.auth.id != \"\"",
"createRule": null,
"updateRule": null,
"deleteRule": null,
"options": {}
}`
collection := &models.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return daos.New(db).SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
if err != nil {
return err
}
return dao.DeleteCollection(collection)
})
}
@@ -0,0 +1,54 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// add
new_groups := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "rk2vrn57",
"name": "groups",
"type": "relation",
"required": false,
"unique": false,
"options": {
"collectionId": "djqp3uxrac2ores",
"cascadeDelete": false,
"minSelect": null,
"maxSelect": null,
"displayFields": []
}
}`), new_groups)
collection.Schema.AddField(new_groups)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// remove
collection.Schema.RemoveField("rk2vrn57")
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,57 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
if err != nil {
return err
}
options := map[string]any{}
json.Unmarshal([]byte(`{
"allowEmailAuth": true,
"allowOAuth2Auth": true,
"allowUsernameAuth": true,
"exceptEmailDomains": [],
"manageRule": null,
"minPasswordLength": 8,
"onlyEmailDomains": [],
"requireEmail": false
}`), &options)
collection.SetOptions(options)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
if err != nil {
return err
}
options := map[string]any{}
json.Unmarshal([]byte(`{
"allowEmailAuth": true,
"allowOAuth2Auth": false,
"allowUsernameAuth": true,
"exceptEmailDomains": [],
"manageRule": null,
"minPasswordLength": 8,
"onlyEmailDomains": [],
"requireEmail": false
}`), &options)
collection.SetOptions(options)
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,34 @@
package migrations
import (
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
if err != nil {
return err
}
collection.CreateRule = types.Pointer("@request.data.password:isset = false")
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
if err != nil {
return err
}
collection.CreateRule = nil
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,57 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
if err != nil {
return err
}
options := map[string]any{}
json.Unmarshal([]byte(`{
"allowEmailAuth": true,
"allowOAuth2Auth": true,
"allowUsernameAuth": true,
"exceptEmailDomains": [],
"manageRule": null,
"minPasswordLength": 5,
"onlyEmailDomains": [],
"requireEmail": false
}`), &options)
collection.SetOptions(options)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
if err != nil {
return err
}
options := map[string]any{}
json.Unmarshal([]byte(`{
"allowEmailAuth": true,
"allowOAuth2Auth": true,
"allowUsernameAuth": true,
"exceptEmailDomains": [],
"manageRule": null,
"minPasswordLength": 8,
"onlyEmailDomains": [],
"requireEmail": false
}`), &options)
collection.SetOptions(options)
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,33 @@
package migrations
import (
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
if err != nil {
return err
}
collection.Name = "device_groups"
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
if err != nil {
return err
}
collection.Name = "groups"
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,140 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models"
)
func init() {
m.Register(func(db dbx.Builder) error {
jsonData := `{
"id": "7emu7fnnwuim2ua",
"created": "2023-08-10 21:19:39.520Z",
"updated": "2023-08-10 21:19:39.520Z",
"name": "permissions",
"type": "base",
"system": false,
"schema": [
{
"system": false,
"id": "tzxtuykz",
"name": "user",
"type": "relation",
"required": false,
"unique": false,
"options": {
"collectionId": "27do0wbcuyfmbmx",
"cascadeDelete": false,
"minSelect": null,
"maxSelect": 1,
"displayFields": []
}
},
{
"system": false,
"id": "nd1ekexz",
"name": "create",
"type": "bool",
"required": false,
"unique": false,
"options": {}
},
{
"system": false,
"id": "z79gcpy3",
"name": "read",
"type": "relation",
"required": false,
"unique": false,
"options": {
"collectionId": "z5lghx2r3tm45n1",
"cascadeDelete": false,
"minSelect": null,
"maxSelect": null,
"displayFields": [
"name"
]
}
},
{
"system": false,
"id": "t7wwbk2c",
"name": "update",
"type": "relation",
"required": false,
"unique": false,
"options": {
"collectionId": "z5lghx2r3tm45n1",
"cascadeDelete": false,
"minSelect": null,
"maxSelect": null,
"displayFields": [
"name"
]
}
},
{
"system": false,
"id": "b4u0gqa7",
"name": "delete",
"type": "relation",
"required": false,
"unique": false,
"options": {
"collectionId": "z5lghx2r3tm45n1",
"cascadeDelete": false,
"minSelect": null,
"maxSelect": null,
"displayFields": [
"name"
]
}
},
{
"system": false,
"id": "nyeqt3fn",
"name": "power",
"type": "relation",
"required": false,
"unique": false,
"options": {
"collectionId": "z5lghx2r3tm45n1",
"cascadeDelete": false,
"minSelect": null,
"maxSelect": null,
"displayFields": []
}
}
],
"indexes": [
"CREATE UNIQUE INDEX ` + "`" + `idx_2GIk1Fo` + "`" + ` ON ` + "`" + `permissions` + "`" + ` (` + "`" + `user` + "`" + `)"
],
"listRule": "@request.auth.id = user.id",
"viewRule": "@request.auth.id = user.id",
"createRule": null,
"updateRule": null,
"deleteRule": "@request.auth.id = user.id",
"options": {}
}`
collection := &models.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return daos.New(db).SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("7emu7fnnwuim2ua")
if err != nil {
return err
}
return dao.DeleteCollection(collection)
})
}
@@ -0,0 +1,77 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
collection.ListRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && id ?= @collection.permissions.read.id")
collection.ViewRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && id ?= @collection.permissions.read.id")
collection.CreateRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && @collection.permissions.create = true")
collection.UpdateRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && id ?= @collection.permissions.update.id")
collection.DeleteRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && id ?= @collection.permissions.delete.id")
// add
new_created_by := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "naciykac",
"name": "created_by",
"type": "relation",
"required": false,
"unique": false,
"options": {
"collectionId": "27do0wbcuyfmbmx",
"cascadeDelete": false,
"minSelect": null,
"maxSelect": 1,
"displayFields": [
"username"
]
}
}`), new_created_by)
collection.Schema.AddField(new_created_by)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
collection.ListRule = nil
collection.ViewRule = nil
collection.CreateRule = nil
collection.UpdateRule = nil
collection.DeleteRule = nil
// remove
collection.Schema.RemoveField("naciykac")
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,42 @@
package migrations
import (
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
if err != nil {
return err
}
collection.CreateRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && @collection.permissions.create = true")
collection.UpdateRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && @collection.permissions.create = true")
collection.DeleteRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && @collection.permissions.create = true")
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
if err != nil {
return err
}
collection.CreateRule = nil
collection.UpdateRule = nil
collection.DeleteRule = nil
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,75 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// remove
collection.Schema.RemoveField("qqvyfrex")
// add
new_status := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "qmiatdwa",
"name": "status",
"type": "select",
"required": false,
"unique": false,
"options": {
"maxSelect": 1,
"values": [
"pending",
"online",
"offline"
]
}
}`), new_status)
collection.Schema.AddField(new_status)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// add
del_status := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "qqvyfrex",
"name": "status",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
}`), del_status)
collection.Schema.AddField(del_status)
// remove
collection.Schema.RemoveField("qmiatdwa")
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,68 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
if err != nil {
return err
}
collection.ListRule = types.Pointer("@request.auth.id = id")
collection.ViewRule = types.Pointer("@request.auth.id = id")
collection.UpdateRule = types.Pointer("@request.auth.id = id")
collection.DeleteRule = types.Pointer("@request.auth.id = id")
// add
new_avatar := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "i1qnezoa",
"name": "avatar",
"type": "number",
"required": false,
"unique": false,
"options": {
"min": 0,
"max": 9
}
}`), new_avatar)
collection.Schema.AddField(new_avatar)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
if err != nil {
return err
}
collection.ListRule = nil
collection.ViewRule = nil
collection.UpdateRule = nil
collection.DeleteRule = nil
// remove
collection.Schema.RemoveField("i1qnezoa")
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,48 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
if err != nil {
return err
}
// add
new_lazy_ping := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "yjyq5pvg",
"name": "lazy_ping",
"type": "bool",
"required": false,
"unique": false,
"options": {}
}`), new_lazy_ping)
collection.Schema.AddField(new_lazy_ping)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
if err != nil {
return err
}
// remove
collection.Schema.RemoveField("yjyq5pvg")
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,42 @@
package migrations
import (
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
if err != nil {
return err
}
collection.CreateRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && @collection.permissions.create = true")
collection.UpdateRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && @collection.permissions.create = true")
collection.DeleteRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && @collection.permissions.create = true")
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
if err != nil {
return err
}
collection.CreateRule = nil
collection.UpdateRule = nil
collection.DeleteRule = nil
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,50 @@
package migrations
import (
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
collection.ListRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && id ?= @collection.permissions.read.id")
collection.ViewRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && id ?= @collection.permissions.read.id")
collection.CreateRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && @collection.permissions.create = true")
collection.UpdateRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && id ?= @collection.permissions.update.id")
collection.DeleteRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && id ?= @collection.permissions.delete.id")
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
collection.ListRule = nil
collection.ViewRule = nil
collection.CreateRule = nil
collection.UpdateRule = nil
collection.DeleteRule = nil
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,123 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// add
new_sol_enabled := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "ueieydw5",
"name": "sol_enabled",
"type": "bool",
"required": false,
"unique": false,
"options": {}
}`), new_sol_enabled)
collection.Schema.AddField(new_sol_enabled)
// add
new_sol_auth := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "yfszwhpw",
"name": "sol_auth",
"type": "bool",
"required": false,
"unique": false,
"options": {}
}`), new_sol_auth)
collection.Schema.AddField(new_sol_auth)
// add
new_sol_user := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "dbcmnrmp",
"name": "sol_user",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
}`), new_sol_user)
collection.Schema.AddField(new_sol_user)
// add
new_sol_password := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "hvz8stfy",
"name": "sol_password",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
}`), new_sol_password)
collection.Schema.AddField(new_sol_password)
// add
new_sol_port := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "6kfqheid",
"name": "sol_port",
"type": "number",
"required": true,
"unique": false,
"options": {
"min": 1,
"max": 65535
}
}`), new_sol_port)
collection.Schema.AddField(new_sol_port)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// remove
collection.Schema.RemoveField("ueieydw5")
// remove
collection.Schema.RemoveField("yfszwhpw")
// remove
collection.Schema.RemoveField("dbcmnrmp")
// remove
collection.Schema.RemoveField("hvz8stfy")
// remove
collection.Schema.RemoveField("6kfqheid")
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,64 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("cti4l8f4mz8df3r")
if err != nil {
return err
}
// update
edit_number := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "8nwuncgg",
"name": "number",
"type": "number",
"required": true,
"unique": false,
"options": {
"min": 1,
"max": 65535
}
}`), edit_number)
collection.Schema.AddField(edit_number)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("cti4l8f4mz8df3r")
if err != nil {
return err
}
// update
edit_number := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "8nwuncgg",
"name": "number",
"type": "number",
"required": true,
"unique": false,
"options": {
"min": null,
"max": 65535
}
}`), edit_number)
collection.Schema.AddField(edit_number)
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,64 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update
edit_sol_port := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "6kfqheid",
"name": "sol_port",
"type": "number",
"required": false,
"unique": false,
"options": {
"min": 1,
"max": 65535
}
}`), edit_sol_port)
collection.Schema.AddField(edit_sol_port)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update
edit_sol_port := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "6kfqheid",
"name": "sol_port",
"type": "number",
"required": true,
"unique": false,
"options": {
"min": 1,
"max": 65535
}
}`), edit_sol_port)
collection.Schema.AddField(edit_sol_port)
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,66 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// add
new_wake_confirm := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "chtoblvl",
"name": "wake_confirm",
"type": "bool",
"required": false,
"presentable": false,
"unique": false,
"options": {}
}`), new_wake_confirm)
collection.Schema.AddField(new_wake_confirm)
// add
new_shutdown_confirm := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "muqy3axq",
"name": "shutdown_confirm",
"type": "bool",
"required": false,
"presentable": false,
"unique": false,
"options": {}
}`), new_shutdown_confirm)
collection.Schema.AddField(new_shutdown_confirm)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// remove
collection.Schema.RemoveField("chtoblvl")
// remove
collection.Schema.RemoveField("muqy3axq")
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,74 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// add
new_wake_cmd := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "murx1eum",
"name": "wake_cmd",
"type": "text",
"required": false,
"presentable": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
}`), new_wake_cmd)
collection.Schema.AddField(new_wake_cmd)
// add
new_ping_cmd := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "kefxqjbj",
"name": "ping_cmd",
"type": "text",
"required": false,
"presentable": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
}`), new_ping_cmd)
collection.Schema.AddField(new_ping_cmd)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// remove
collection.Schema.RemoveField("murx1eum")
// remove
collection.Schema.RemoveField("kefxqjbj")
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,52 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("cti4l8f4mz8df3r")
if err != nil {
return err
}
// add
new_link := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "i3uvw7ij",
"name": "link",
"type": "url",
"required": false,
"presentable": false,
"unique": false,
"options": {
"exceptDomains": null,
"onlyDomains": null
}
}`), new_link)
collection.Schema.AddField(new_link)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("cti4l8f4mz8df3r")
if err != nil {
return err
}
// remove
collection.Schema.RemoveField("i3uvw7ij")
return dao.SaveCollection(collection)
})
}
File diff suppressed because it is too large Load Diff
@@ -1,43 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_3142635823")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(6, []byte(`{
"hidden": false,
"id": "number376926767",
"max": 9,
"min": 0,
"name": "avatar",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_3142635823")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("number376926767")
return app.Save(collection)
})
}
@@ -1,56 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_3142635823")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(6, []byte(`{
"hidden": false,
"id": "number376926767",
"max": 9,
"min": 0,
"name": "avatar",
"onlyInt": true,
"presentable": false,
"required": false,
"system": false,
"type": "number"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_3142635823")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(6, []byte(`{
"hidden": false,
"id": "number376926767",
"max": 9,
"min": 0,
"name": "avatar",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
}`)); err != nil {
return err
}
return app.Save(collection)
})
}
@@ -1,40 +0,0 @@
package migrations
import (
"encoding/json"
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("27do0wbcuyfmbmx")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(`{
"createRule": ""
}`), &collection); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("27do0wbcuyfmbmx")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(`{
"createRule": "@request.body.password:isset = false"
}`), &collection); err != nil {
return err
}
return app.Save(collection)
})
}
@@ -1,106 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
// Up migration: Change `url` field type from URL to string
collectionName := "devices"
return app.RunInTransaction(func(txApp core.App) error {
// Step 1: Fetch the collection
collection, err := txApp.FindCollectionByNameOrId(collectionName)
if err != nil {
return err
}
// Step 2: Add a new text field
newField := &core.TextField{
Name: "new_field",
Required: false,
}
collection.Fields.AddAt(6, newField)
if err := txApp.Save(collection); err != nil {
return err
}
// Step 3: Migrate data from `url` to `new_field`
records, err := txApp.FindAllRecords(collectionName)
if err != nil {
return err
}
for _, record := range records {
url := record.GetString("link")
record.Set("new_field", url)
if err := txApp.Save(record); err != nil {
return err
}
}
// Step 4: Remove the old `url` field
collection.Fields.RemoveByName("link")
if err := txApp.Save(collection); err != nil {
return err
}
// Step 5: Rename `new_field` to `url`
renamedField := collection.Fields.GetByName("new_field")
renamedField.SetName("link")
return txApp.Save(collection)
})
}, func(app core.App) error {
// Down migration: Restore the `url` field
collectionName := "devices"
return app.RunInTransaction(func(txApp core.App) error {
// Step 1: Fetch the collection
collection, err := txApp.FindCollectionByNameOrId(collectionName)
if err != nil {
return err
}
// Step 2: Add a new `url` field
newField := &core.URLField{
Name: "new_field",
Required: false,
}
collection.Fields.AddAt(6, newField)
if err := txApp.Save(collection); err != nil {
return err
}
// Step 3: Migrate data from `url` to `new_field`
records, err := txApp.FindAllRecords(collectionName)
if err != nil {
return err
}
for _, record := range records {
text := record.GetString("link")
record.Set("new_field", text)
if err := txApp.Save(record); err != nil {
return err
}
}
// Step 4: Remove the old `url` field
collection.Fields.RemoveByName("link")
if err := txApp.Save(collection); err != nil {
return err
}
// Step 5: Rename `new_field` to `url`
renamedField := collection.Fields.GetByName("new_field")
renamedField.SetName("link")
return txApp.Save(collection)
})
})
}
@@ -1,106 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
// Up migration: Change `url` field type from URL to string
collectionName := "ports"
return app.RunInTransaction(func(txApp core.App) error {
// Step 1: Fetch the collection
collection, err := txApp.FindCollectionByNameOrId(collectionName)
if err != nil {
return err
}
// Step 2: Add a new text field
newField := &core.TextField{
Name: "new_field",
Required: false,
}
collection.Fields.AddAt(5, newField)
if err := txApp.Save(collection); err != nil {
return err
}
// Step 3: Migrate data from `url` to `new_field`
records, err := txApp.FindAllRecords(collectionName)
if err != nil {
return err
}
for _, record := range records {
url := record.GetString("link")
record.Set("new_field", url)
if err := txApp.Save(record); err != nil {
return err
}
}
// Step 4: Remove the old `url` field
collection.Fields.RemoveByName("link")
if err := txApp.Save(collection); err != nil {
return err
}
// Step 5: Rename `new_field` to `url`
renamedField := collection.Fields.GetByName("new_field")
renamedField.SetName("link")
return txApp.Save(collection)
})
}, func(app core.App) error {
// Down migration: Restore the `url` field
collectionName := "ports"
return app.RunInTransaction(func(txApp core.App) error {
// Step 1: Fetch the collection
collection, err := txApp.FindCollectionByNameOrId(collectionName)
if err != nil {
return err
}
// Step 2: Add a new `url` field
newField := &core.URLField{
Name: "new_field",
Required: false,
}
collection.Fields.AddAt(5, newField)
if err := txApp.Save(collection); err != nil {
return err
}
// Step 3: Migrate data from `url` to `new_field`
records, err := txApp.FindAllRecords(collectionName)
if err != nil {
return err
}
for _, record := range records {
text := record.GetString("link")
record.Set("new_field", text)
if err := txApp.Save(record); err != nil {
return err
}
}
// Step 4: Remove the old `url` field
collection.Fields.RemoveByName("link")
if err := txApp.Save(collection); err != nil {
return err
}
// Step 5: Rename `new_field` to `url`
renamedField := collection.Fields.GetByName("new_field")
renamedField.SetName("link")
return txApp.Save(collection)
})
})
}
@@ -1,45 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(5, []byte(`{
"autogeneratePattern": "",
"hidden": false,
"id": "text1843675174",
"max": 0,
"min": 0,
"name": "description",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("text1843675174")
return app.Save(collection)
})
}
@@ -1,45 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(8, []byte(`{
"hidden": false,
"id": "select355930381",
"maxSelect": 1,
"name": "link_open",
"presentable": false,
"required": false,
"system": false,
"type": "select",
"values": [
"same_tab",
"new_tab"
]
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("select355930381")
return app.Save(collection)
})
}
@@ -1,43 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(11, []byte(`{
"hidden": false,
"id": "number361076486",
"max": null,
"min": 1,
"name": "wake_timeout",
"onlyInt": true,
"presentable": false,
"required": false,
"system": false,
"type": "number"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("number361076486")
return app.Save(collection)
})
}
@@ -1,43 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(15, []byte(`{
"hidden": false,
"id": "number2068100152",
"max": null,
"min": 1,
"name": "shutdown_timeout",
"onlyInt": true,
"presentable": false,
"required": false,
"system": false,
"type": "number"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("number2068100152")
return app.Save(collection)
})
}
@@ -1,100 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(2, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "1si6ajha",
"max": 0,
"min": 0,
"name": "ip",
"pattern": "^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}$",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(3, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "fyqmpon6",
"max": 0,
"min": 0,
"name": "mac",
"pattern": "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(2, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "1si6ajha",
"max": 0,
"min": 0,
"name": "ip",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(3, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "fyqmpon6",
"max": 0,
"min": 0,
"name": "mac",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
})
}
@@ -1,62 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(2, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "1si6ajha",
"max": 0,
"min": 0,
"name": "ip",
"pattern": "^(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}$",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(2, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "1si6ajha",
"max": 0,
"min": 0,
"name": "ip",
"pattern": "^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}$",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
})
}
@@ -1,62 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(4, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "s8c5z7n0",
"max": 0,
"min": 0,
"name": "netmask",
"pattern": "^(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}$",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(4, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "s8c5z7n0",
"max": 0,
"min": 0,
"name": "netmask",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
})
}
@@ -1,40 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(6, []byte(`{
"hidden": false,
"id": "bool2618032555",
"name": "track_ip",
"presentable": false,
"required": false,
"system": false,
"type": "bool"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("bool2618032555")
return app.Save(collection)
})
}
@@ -1,45 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(4, []byte(`{
"autogeneratePattern": "",
"hidden": false,
"id": "text3846109882",
"max": 0,
"min": 0,
"name": "track_ip_interval",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("text3846109882")
return app.Save(collection)
})
}
@@ -1,100 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(2, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "1si6ajha",
"max": 0,
"min": 0,
"name": "ip",
"pattern": "^(?:(?:[\\p{L}\\p{N}](?:[\\p{L}\\p{N}-]{0,61}[\\p{L}\\p{N}])?\\.)+[\\p{L}\\p{N}](?:[\\p{L}\\p{N}-]{0,61}[\\p{L}\\p{N}])?|(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})$",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(4, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "s8c5z7n0",
"max": 0,
"min": 0,
"name": "netmask",
"pattern": "^(?:255\\.255\\.255\\.(?:255|254|252|248|240|224|192|128|0)|255\\.255\\.(?:255|254|252|248|240|224|192|128|0)\\.0|255\\.(?:255|254|252|248|240|224|192|128|0)\\.0\\.0|(?:255|254|252|248|240|224|192|128|0)\\.0\\.0\\.0)$",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(2, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "1si6ajha",
"max": 0,
"min": 0,
"name": "ip",
"pattern": "^(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}$",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(4, []byte(`{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "s8c5z7n0",
"max": 0,
"min": 0,
"name": "netmask",
"pattern": "^(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}$",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
})
}
+27 -113
View File
@@ -5,15 +5,12 @@ import (
"fmt"
"net"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"github.com/mdlayher/wol"
"github.com/pocketbase/pocketbase/models"
)
func SendMagicPacket(device *core.Record) error {
ip, err := ResolveToIPAddr(device.GetString("ip"))
if err != nil {
return err
}
func SendMagicPacket(device *models.Record) error {
ip := device.GetString("ip")
mac := device.GetString("mac")
netmask := device.GetString("netmask")
password := device.GetString("password")
@@ -23,100 +20,56 @@ func SendMagicPacket(device *core.Record) error {
if err != nil {
return err
}
if !ValidateSubnetMask(netmask) {
return fmt.Errorf("%q is not a valid subnet mask", netmask)
}
// calculate broadcast IP, if possible
var broadcastIp string
// an IP was provided or FQDN resolved to an IP so calculate broadcast destination based on that
if ip != "" {
broadcastIp, err = getBroadcastIp(ip, netmask)
if err != nil {
return err
}
} else {
// No IP available, so no broadcast IP can be calculated. This occurs if FQDN is .local and the device is powered off
broadcastIp = ""
}
var bytePassword []byte
if len(password) == 0 || len(password) == 4 || len(password) == 6 {
bytePassword = []byte(password)
} else {
return errors.New("error: password must be 0, 4 or 6 characters long")
return fmt.Errorf("error: password must be 0, 4 or 6 characters long")
}
// an IP was provided or FQDN resolved to an IP so calculate broadcast destination based on that
if ip != "" {
broadcastIp, err = getBroadcastIp(ip, netmask)
if err != nil {
return err
}
} else {
// No IP available, so no broadcast IP can be calculated. This occurs if FQDN is .local and the device is powered off
broadcastIp = ""
}
// send wake
if err := wakeUDP(broadcastIp, ip, parsedMac, bytePassword); err != nil {
// get target addr
broadcastIp, err := getBroadcastIp(ip, netmask)
if err != nil {
return err
}
targetAddr := fmt.Sprintf("%s:%d", broadcastIp, 9)
// send wake via udp port 9
if err := wakeUDP(targetAddr, parsedMac, bytePassword); err != nil {
return err
}
return nil
}
func wakeUDP(broadcastIp string, deviceIp string, target net.HardwareAddr, password []byte) error {
func wakeUDP(addr string, target net.HardwareAddr, password []byte) error {
c, err := wol.NewClient()
if err != nil {
return err
}
defer c.Close()
var destinations []string
// Broadcast IP available, add to destinations
if broadcastIp != "" {
// user-calculated broadcast packet to port 9 and alternative port 7
destinations = append(destinations,
fmt.Sprintf("%s:9", broadcastIp),
fmt.Sprintf("%s:7", broadcastIp),
)
}
if deviceIp != "" {
// For routed network WOL, send a unicast packet to device IP on port 9 and alternative port 7
destinations = append(destinations,
fmt.Sprintf("%s:9", deviceIp),
fmt.Sprintf("%s:7", deviceIp),
)
}
// No IP for the device is available, broadcast WOL packet to all interfaces
if deviceIp == "" {
allBroadcastDests, err := getAllBroadcastDests()
if err != nil {
return err
}
destinations = append(destinations, allBroadcastDests...)
}
for _, dest := range destinations {
if err := c.WakePassword(dest, target, password); err != nil {
return err
}
}
return nil
return c.WakePassword(addr, target, password)
}
func getBroadcastIp(ipStr, maskStr string) (string, error) {
ip := net.ParseIP(ipStr).To4()
ip := net.ParseIP(ipStr)
if ip == nil {
return "", errors.New("ip not a valid ipv4 address")
}
ip = ip.To4()
if ip == nil {
return "", errors.New("ip not a valid ipv4 address")
}
mask := net.ParseIP(maskStr).To4()
mask := net.ParseIP(maskStr)
if mask == nil {
return "", errors.New("subnet mask not a valid ipv4 address")
}
mask = mask.To4()
ip = ip.To4()
if ip == nil {
return "", errors.New("subnet mask not a valid ipv4 address")
}
broadcast := make(net.IP, 4)
for i := range ip {
@@ -125,42 +78,3 @@ func getBroadcastIp(ipStr, maskStr string) (string, error) {
return broadcast.String(), nil
}
// Returns a slice of all broadcast addresses for ports 9 and 7 using local interfaces
func getAllBroadcastDests() ([]string, error) {
var allIps []string
interfaces, err := net.Interfaces()
if err != nil {
return nil, err
}
// Iterate through all the interfaces
for _, iface := range interfaces {
isRunning := iface.Flags&net.FlagRunning != 0
isLoopback := iface.Flags&net.FlagLoopback != 0
isNotBroadcast := iface.Flags&net.FlagBroadcast == 0
// exclude interfaces that are not running, are loopback, or can't broadcast
if !isRunning || isLoopback || isNotBroadcast {
continue
}
addrs, err := iface.Addrs()
if err != nil {
return nil, err
}
// Iterate through each interface's address
for _, addr := range addrs {
if ipNet, ok := addr.(*net.IPNet); ok {
ip := ipNet.IP
// Only use IPv4
if ip.To4() != nil {
bcastip, err := getBroadcastIp(ip.String(), net.IP(ipNet.Mask).String())
if err != nil {
return nil, err
}
allIps = append(allIps, fmt.Sprintf("%s:9", bcastip), fmt.Sprintf("%s:7", bcastip))
}
}
}
}
return allIps, nil
}
+114 -186
View File
@@ -1,10 +1,11 @@
package networking
import (
"fmt"
"net"
"testing"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/models"
)
type Device struct {
@@ -16,221 +17,148 @@ type Device struct {
}
func TestSendMagicPacket(t *testing.T) {
testCases := []struct {
name string
ip string
mac string
netmask string
password string
wantError bool
}{
// Valid case: all inputs correct
collection := &models.Collection{}
devices_success := []Device{
{
name: "Valid Case",
ip: "192.168.1.100",
mac: "00:11:22:33:44:55",
netmask: "255.255.255.0",
password: "secret",
wantError: false,
IP: "8.8.8.8",
MAC: "aa:aa:aa:aa:aa:aa",
Netmask: "255.0.0.0",
Password: "",
},
// Invalid MAC address
{
name: "Invalid MAC",
ip: "192.168.1.100",
mac: "invalid",
netmask: "255.255.255.0",
password: "secret",
wantError: true,
},
// Password too short
{
name: "Password Too Short",
ip: "192.168.1.100",
mac: "00:11:22:33:44:55",
netmask: "255.255.255.0",
password: "s", // length 1
wantError: true,
},
// Password too long
{
name: "Password Too Long",
ip: "192.168.1.100",
mac: "00:11:22:33:44:55",
netmask: "255.255.255.0",
password: "password", // length 9
wantError: true,
},
// Invalid IP address
{
name: "Invalid IP",
ip: "256.1.1.1", // invalid
mac: "00:11:22:33:44:55",
netmask: "255.255.255.0",
password: "secret",
wantError: true,
},
// Invalid netmask
{
name: "Invalid Netmask",
ip: "192.168.1.100",
mac: "00:11:22:33:44:55",
netmask: "300.255.255.0", // invalid
password: "secret",
wantError: true,
IP: "1.1.1.1",
MAC: "bb:bb:bb:bb:bb:bb",
Netmask: "255.255.0.0",
Password: "abcd",
},
}
collection := &core.Collection{}
devices_fail := []Device{
{
IP: "1.1.1.1",
MAC: "aa",
Netmask: "255.255.0.0",
Password: "abcd",
},
{
IP: "1.1.1.1",
MAC: "cc:cc:cc:cc:cc:cc",
Netmask: "255.255.0.0",
Password: "abcdefg",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
device := core.NewRecord(collection)
device.Set("ip", tc.ip)
device.Set("mac", tc.mac)
device.Set("netmask", tc.netmask)
device.Set("password", tc.password)
for _, v := range devices_success {
device := models.NewRecord(collection)
device.Set("ip", v.IP)
device.Set("mac", v.MAC)
device.Set("netmask", v.Netmask)
device.Set("password", v.Password)
err := SendMagicPacket(device)
if tc.wantError {
if err == nil {
t.Errorf("Expected error but got none")
}
} else {
if err != nil {
t.Errorf("Got unexpected error: %v", err)
}
}
})
if err := SendMagicPacket(device); err != nil {
t.Fatal(err)
}
}
for _, v := range devices_fail {
device := models.NewRecord(collection)
device.Set("ip", v.IP)
device.Set("mac", v.MAC)
device.Set("netmask", v.Netmask)
device.Set("password", v.Password)
if err := SendMagicPacket(device); err == nil {
t.Fatal("should have cause an error")
}
}
}
func TestWakeUDP(t *testing.T) {
testCases := []struct {
name string
ip string
broadcastIp string
targetMac string
password string
wantError bool
}{
// Valid case: all inputs correct
devices := []Device{
{
name: "Valid Case",
ip: "192.168.1.10",
broadcastIp: "192.168.1.255",
targetMac: "00:11:22:33:44:55",
password: "secret",
wantError: false,
IP: "8.8.8.8",
MAC: "aa:aa:aa:aa:aa:aa",
Netmask: "255.0.0.0",
Password: "",
ExpectFailPassword: false,
},
// Invalid MAC address
{
name: "Invalid MAC",
ip: "192.168.1.10",
broadcastIp: "192.168.1.255",
targetMac: "invalid",
password: "secret",
wantError: true,
IP: "1.1.1.1",
MAC: "bb:bb:bb:bb:bb:bb",
Netmask: "255.255.0.0",
Password: "abcd",
ExpectFailPassword: false,
},
// Password too short
{
name: "Password Too Short",
ip: "192.168.1.10",
broadcastIp: "192.168.1.255",
targetMac: "00:11:22:33:44:55",
password: "s", // length 1
wantError: true,
IP: "10.10.10.1",
MAC: "cc:cc:cc:cc:cc:cc",
Netmask: "255.255.0.0",
Password: "abcd",
ExpectFailPassword: false,
},
// Password too long
{
name: "Password Too Long",
ip: "192.168.1.10",
broadcastIp: "192.168.1.255",
targetMac: "00:11:22:33:44:55",
password: "password", // length 9
wantError: true,
IP: "1.1.1.1",
MAC: "dd:dd:dd:dd:dd:dd",
Netmask: "255.255.0.0",
Password: "abcdefg",
ExpectFailPassword: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
mac, err := net.ParseMAC(tc.targetMac)
if err != nil && !tc.wantError {
t.Errorf("Unexpected error parsing MAC: %v", err)
} else if err != nil {
return
}
for _, v := range devices {
parsedMac, err := net.ParseMAC(v.MAC)
if err != nil {
t.Fatalf(`%v (parsedMac "%v")`, err, parsedMac)
}
// Now test the wakeUDP function
err = wakeUDP(tc.broadcastIp, tc.ip, mac, []byte(tc.password))
if tc.wantError {
if err == nil {
t.Errorf("Expected error but got none")
}
}
})
var bytePassword []byte
if len(v.Password) == 0 || len(v.Password) == 4 || len(v.Password) == 6 {
bytePassword = []byte(v.Password)
} else if !v.ExpectFailPassword {
t.Fatal("password must be 0, 4 or 6 characters long")
}
broadcastIp, err := getBroadcastIp(v.IP, v.Netmask)
if err != nil {
t.Fatal(err)
}
targetAddr := fmt.Sprintf("%s:%d", broadcastIp, 9)
if err := wakeUDP(targetAddr, parsedMac, bytePassword); err != nil {
t.Fatalf(`%v (targetAddr "%v", parsedMac "%v", bytePassword "%v")`, err, targetAddr, parsedMac, bytePassword)
}
}
}
func TestGetBroadcastIp(t *testing.T) {
testCases := []struct {
name string
ip string
netmask string
wantIp string
wantError bool
}{
// Valid case: all inputs correct
type address struct {
IP string
Netmask string
BroadcastResult string
}
addresses := []address{
{
name: "Valid Case",
ip: "192.168.1.100",
netmask: "255.255.255.0",
wantIp: "192.168.1.255",
wantError: false,
},
// Invalid IP address
{
name: "Invalid IP",
ip: "256.1.1.1", // invalid
netmask: "255.255.255.0",
wantIp: "",
wantError: true,
},
// Invalid netmask
{
name: "Invalid Netmask",
ip: "192.168.1.100",
netmask: "300.255.255.0", // invalid
wantIp: "",
wantError: true,
IP: "192.168.0.1",
Netmask: "255.255.255.0",
BroadcastResult: "192.168.0.255",
}, {
IP: "10.1.1.1",
Netmask: "255.255.0.0",
BroadcastResult: "10.1.255.255",
}, {
IP: "10.2.3.4",
Netmask: "255.0.0.0",
BroadcastResult: "10.255.255.255",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
ip := net.ParseIP(tc.ip)
if ip == nil && !tc.wantError {
t.Errorf("Unexpected error parsing IP: %v", ip)
} else if ip == nil {
return
}
mask := net.ParseIP(tc.netmask)
if mask == nil && !tc.wantError {
t.Errorf("Unexpected error parsing netmask: %v", mask)
} else if mask == nil {
return
}
broadcast, err := getBroadcastIp(tc.ip, tc.netmask)
if tc.wantError {
if err == nil {
t.Errorf("Expected error but got none")
}
} else {
if broadcast != tc.wantIp {
t.Errorf("Broadcast IP mismatch: expected %s, got %s", tc.wantIp, broadcast)
}
}
})
for _, v := range addresses {
broadcast, err := getBroadcastIp(v.IP, v.Netmask)
if err != nil {
t.Fatal(err)
}
if broadcast != v.BroadcastResult {
t.Fatalf(`getBroadcastIp("%v, %v"), want %v, got %v`, v.IP, v.Netmask, v.BroadcastResult, broadcast)
}
}
}
+51 -22
View File
@@ -1,39 +1,68 @@
package networking
import (
"errors"
"net"
"os"
"syscall"
"os/exec"
"runtime"
"strconv"
"time"
"github.com/pocketbase/pocketbase/models"
probing "github.com/prometheus-community/pro-bing"
"github.com/seriousm4x/upsnap/logger"
)
func isNoRouteOrDownError(err error) bool {
opErr, ok := err.(*net.OpError)
if !ok {
return false
func PingDevice(device *models.Record) bool {
ping_cmd := device.GetString("ping_cmd")
if ping_cmd == "" {
pinger, err := probing.NewPinger(device.GetString("ip"))
if err != nil {
logger.Error.Println(err)
return false
}
pinger.Count = 1
pinger.Timeout = 500 * time.Millisecond
privileged, err := strconv.ParseBool(os.Getenv("UPSNAP_PING_PRIVILEGED"))
if err != nil {
privileged = true
}
pinger.SetPrivileged(privileged)
err = pinger.Run()
if err != nil {
logger.Error.Println(err)
return false
}
stats := pinger.Statistics()
if stats.PacketLoss > 0 {
return false
} else {
return true
}
} else {
var shell string
var shell_arg string
if runtime.GOOS == "windows" {
shell = "cmd"
shell_arg = "/C"
} else {
shell = "/bin/sh"
shell_arg = "-c"
}
cmd := exec.Command(shell, shell_arg, ping_cmd)
err := cmd.Run()
return err == nil
}
syscallErr, ok := opErr.Err.(*os.SyscallError)
if !ok {
return false
}
return syscallErr.Err == syscall.EHOSTUNREACH || syscallErr.Err == syscall.EHOSTDOWN
}
func CheckPort(host string, port string) (bool, error) {
func CheckPort(host string, port string) bool {
timeout := 500 * time.Millisecond
conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, port), timeout)
if err != nil {
// treat "host unreachable", "connection refused" and "timeout" as no error
if netErr, ok := errors.AsType[*net.OpError](err); ok {
if errors.Is(netErr.Err, syscall.EHOSTUNREACH) ||
errors.Is(netErr.Err, syscall.ECONNREFUSED) ||
netErr.Timeout() {
return false, nil
}
}
return false, err
return false
}
defer conn.Close()
return conn != nil, nil
return conn != nil
}
-90
View File
@@ -1,90 +0,0 @@
package networking
import (
"testing"
"ganigeorgiev.com/pocketbase/pocketbase/core"
)
func TestPingDevice(t *testing.T) {
testCases := []struct {
name string
ip string
ping_cmd string
wantError bool
}{
// Valid case: all inputs correct
{
name: "Valid Case",
ip: "8.8.8.8",
ping_cmd: "exit 0",
wantError: false,
},
// Invalid ping command
{
name: "Invalid Ping Command",
ip: "8.8.8.8",
ping_cmd: "exit 1",
wantError: false,
},
}
collection := &core.Collection{}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
device := core.NewRecord(collection)
device.Set("ip", tc.ip)
device.Set("ping_cmd", tc.ping_cmd)
_, err := PingDevice(device)
if err == nil && tc.wantError {
t.Errorf("Expected error but got none")
} else if err != nil && !tc.wantError {
t.Errorf("Got unexpected error: %v", err)
}
})
}
}
func TestCheckPort(t *testing.T) {
testCases := []struct {
name string
host string
port string
wantError bool
}{
// Valid case: all inputs correct
{
name: "Valid Case",
host: "0.0.0.0",
port: "443",
wantError: false,
},
// Invalid IP address
{
name: "Invalid IP",
host: "256.1.1.1", // invalid
port: "443",
wantError: true,
},
// Invalid port number
{
name: "Invalid Port",
host: "0.0.0.0",
port: "70000", // invalid
wantError: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
_, err := CheckPort(tc.host, tc.port)
if err == nil && tc.wantError {
t.Errorf("Expected error but got none")
} else if err != nil && !tc.wantError {
t.Errorf("Got unexpected error: %v", err)
}
})
}
}
-92
View File
@@ -1,92 +0,0 @@
//go:build linux
package networking
import (
"fmt"
"os"
"os/exec"
"strconv"
"time"
"ganigeorgiev.com/pocketbase/pocketbase/core"
probing "github.com/prometheus-community/pro-bing"
"kernel.org/pub/linux/libs/security/libcap/cap"
)
func PingDevice(device *core.Record) (bool, error) {
ping_cmd := device.GetString("ping_cmd")
if ping_cmd == "" {
ip, err := ResolveToIPAddr(device.GetString("ip"))
if err != nil {
return false, err
}
if ip == "" {
return false, nil
}
pinger, err := probing.NewPinger(ip)
if err != nil {
return false, err
}
pinger.Count = 1
pinger.Timeout = 500 * time.Millisecond
privileged := true
privilegedEnv := os.Getenv("UPSNAP_PING_PRIVILEGED")
if privilegedEnv != "" {
privileged, err = strconv.ParseBool(privilegedEnv)
if err != nil {
privileged = false
}
}
if privileged {
orig := cap.GetProc()
defer orig.SetProc() // restore original caps on exit.
c, err := orig.Dup()
if err != nil {
return false, fmt.Errorf("Failed to dup existing capabilities: %v", err)
}
if on, _ := c.GetFlag(cap.Permitted, cap.NET_RAW); !on {
return false, fmt.Errorf("Privileged ping selected but NET_RAW capability not permitted")
}
if err := c.SetFlag(cap.Effective, true, cap.NET_RAW); err != nil {
return false, fmt.Errorf("unable to set NET_RAW capability")
}
if err := c.SetProc(); err != nil {
return false, fmt.Errorf("unable to raise NET_RAW capability")
}
}
pinger.SetPrivileged(privileged)
err = pinger.Run()
if err != nil {
if isNoRouteOrDownError(err) {
return false, nil
}
return false, err
}
stats := pinger.Statistics()
return stats.PacketLoss == 0, nil
} else {
var shell string
var shell_arg string
shell = "/bin/sh"
shell_arg = "-c"
cmd := exec.Command(shell, shell_arg, ping_cmd)
err := cmd.Run()
if err != nil {
if _, ok := err.(*exec.ExitError); ok {
return false, nil
}
return false, err
}
return true, nil
}
}
-75
View File
@@ -1,75 +0,0 @@
//go:build !linux
package networking
import (
"os"
"os/exec"
"runtime"
"strconv"
"time"
"ganigeorgiev.com/pocketbase/pocketbase/core"
probing "github.com/prometheus-community/pro-bing"
)
func PingDevice(device *core.Record) (bool, error) {
ping_cmd := device.GetString("ping_cmd")
if ping_cmd == "" {
ip, err := ResolveToIPAddr(device.GetString("ip"))
if err != nil || ip == "" {
return false, err
}
pinger, err := probing.NewPinger(ip)
if err != nil {
return false, err
}
pinger.Count = 1
pinger.Timeout = 500 * time.Millisecond
privileged := true // default to privileged ping, required by Windows
if runtime.GOOS == "darwin" {
// macOS pings will fail when using privileged ping as non root, but works with non-privileged.
privileged = false
}
privilegedEnv := os.Getenv("UPSNAP_PING_PRIVILEGED")
if privilegedEnv != "" {
privileged, err = strconv.ParseBool(privilegedEnv)
if err != nil {
privileged = false
}
}
pinger.SetPrivileged(privileged)
err = pinger.Run()
if err != nil {
if isNoRouteOrDownError(err) {
return false, nil
}
return false, err
}
stats := pinger.Statistics()
return stats.PacketLoss == 0, nil
} else {
var shell string
var shell_arg string
if runtime.GOOS == "windows" {
shell = "cmd"
shell_arg = "/C"
} else {
shell = "/bin/sh"
shell_arg = "-c"
}
cmd := exec.Command(shell, shell_arg, ping_cmd)
err := cmd.Run()
if err != nil {
if _, ok := err.(*exec.ExitError); ok {
return false, nil
}
return false, err
}
return true, nil
}
}
-57
View File
@@ -1,57 +0,0 @@
//go:build windows || darwin
package networking
import (
"context"
"errors"
"fmt"
"net"
"net/netip"
"strings"
"time"
)
/*
Takes one parameter 'host' and returns its IP. If 'host' is already formatted
as an IP, simply return it. If 'host' is formatted as an FQDN, attempt to
resolve it with mDNS (if .local suffix) or else use a DNS lookup with
net.DefaultResolver
Windows and MacOS can resolve mDNS/DNS with one call to net.DefaultResolver
*/
func ResolveToIPAddr(host string) (string, error) {
// If host is already an IP, simply return it
addr, err := netip.ParseAddr(host)
if err == nil && addr.Is4() {
return host, nil
}
if err := ValidateFQDN(host); err != nil {
return "", fmt.Errorf("%q is the host", host)
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
ips, err := net.DefaultResolver.LookupNetIP(ctx, "ip4", host)
if err != nil {
if strings.HasSuffix(strings.ToLower(host), ".local") {
var dnsErr *net.DNSError
isNotFound := errors.As(err, &dnsErr) && dnsErr.IsNotFound
isTimeout := errors.Is(err, context.DeadlineExceeded) || ctx.Err() == context.DeadlineExceeded
if isTimeout || isNotFound {
return "", nil
}
}
return "", err
}
if len(ips) > 0 {
// only return one result
return ips[0].String(), nil
}
// No results, but it's expected for a .local FQDN device that is offline. Don't return an error.
if strings.HasSuffix(strings.ToLower(host), ".local") {
return "", nil
} else {
// No results, but FQDN should have resolved since it's not .local. Return an error.
return "", fmt.Errorf("No IP address found for %s", host)
}
}
-133
View File
@@ -1,133 +0,0 @@
//go:build linux || freebsd
package networking
import (
"context"
"errors"
"fmt"
"net"
"net/netip"
"strings"
"sync"
"time"
"github.com/godbus/dbus/v5"
"github.com/holoplot/go-avahi"
)
var (
avahiServer *avahi.Server
avahiErr error
avahiOnce sync.Once
)
// getAvahiServer initializes and returns a shared, long-lived Avahi client.
// It handles high throughput gracefully by using a single D-Bus socket connection.
func getAvahiServer() (*avahi.Server, error) {
avahiOnce.Do(func() {
// Using the cached system bus here is safe because we never call server.Close() on it.
conn, err := dbus.SystemBus()
if err != nil {
avahiErr = fmt.Errorf("failed to connect to dbus: %w", err)
return
}
server, err := avahi.ServerNew(conn)
if err != nil {
avahiErr = fmt.Errorf("failed to create avahi server: %w", err)
return
}
avahiServer = server
})
return avahiServer, avahiErr
}
/*
Takes one parameter 'host' and returns its IP. If 'host' is already formatted
as an IP, simply return it. If 'host' is formatted as an FQDN, attempt to
resolve it with mDNS (if .local suffix) or else use a DNS lookup with
net.DefaultResolver
Linux and FreeBSD require dbus and avahi for mDNS lookups
*/
func ResolveToIPAddr(host string) (string, error) {
// If host is already an IP, simply return it
addr, err := netip.ParseAddr(host)
if err == nil && addr.Is4() {
return host, nil
}
if err := ValidateFQDN(host); err != nil {
return "", err
}
// attempt mDNS query first
if strings.HasSuffix(strings.ToLower(host), ".local") {
// conn, err := dbus.Dial("unix:path=/var/run/dbus/system_bus_socket")
server, err := getAvahiServer()
if err != nil {
return "", fmt.Errorf("Failed to create connection: %w", err)
}
// defer conn.Close()
// server, err := avahi.ServerNew(conn)
// if err != nil {
// return "", fmt.Errorf("Failed to create avahi server: %w", err)
// }
// defer server.Close()
// set a context with 2 secs and only wait that long for an mDNS response. otherwise, avahi takes 5 secs
ctx1, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
type result struct {
address string
err error
}
ch := make(chan result, 1)
go func() {
resolved, err := server.ResolveHostName(
avahi.InterfaceUnspec,
avahi.ProtoInet,
host,
avahi.ProtoInet,
0,
)
if err != nil {
ch <- result{"", err}
return
}
// mDNS result received
ch <- result{resolved.Address, nil}
}()
select {
case <-ctx1.Done():
// 2 second timeout reached,
return "", nil
case res := <-ch:
if res.err != nil {
var dbusErr *dbus.Error
// in theory we shouldn't encounter this error since the 2 second context always beats the race
if errors.As(res.err, &dbusErr) && dbusErr.Name == "org.freedesktop.Avahi.TimeoutError" {
return "", nil
}
return "", fmt.Errorf("%s: %w", host, res.err)
}
return res.address, nil
}
}
// Not .local, attempt unicast (regular) DNS lookup
ctx2, cancel2 := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel2()
ips, err := net.DefaultResolver.LookupNetIP(ctx2, "ip4", host)
if err != nil {
return "", err
}
if len(ips) > 0 {
// only return one result
return ips[0].String(), nil
}
// No results, but FQDN should have resolved since it's not .local. Return an error.
return "", err
}
-65
View File
@@ -1,65 +0,0 @@
package networking
import (
"encoding/xml"
"net"
"os"
"os/exec"
)
type Nmaprun struct {
Host []struct {
Address []struct {
Addr string `xml:"addr,attr" binding:"required"`
Addrtype string `xml:"addrtype,attr" binding:"required"`
Vendor string `xml:"vendor,attr"`
} `xml:"address"`
} `xml:"host"`
}
// MacToIP maps each scanned host's normalized mac address to its ipv4
// address, skipping hosts that lack either.
func (n Nmaprun) MacToIP() map[string]string {
macToIp := make(map[string]string)
for _, host := range n.Host {
var hostIp, hostMac string
for _, addr := range host.Address {
switch addr.Addrtype {
case "ipv4":
hostIp = addr.Addr
case "mac":
hostMac = addr.Addr
}
}
if parsedMac, err := net.ParseMAC(hostMac); hostIp != "" && err == nil {
macToIp[parsedMac.String()] = hostIp
}
}
return macToIp
}
func runNmap(scanRange string) (Nmaprun, error) {
nmapOutput := Nmaprun{}
nmap, err := exec.LookPath("nmap")
if err != nil {
return nmapOutput, err
}
timeout := os.Getenv("UPSNAP_SCAN_TIMEOUT")
if timeout == "" {
timeout = "500ms"
}
cmd := exec.Command(nmap, "-sn", "-oX", "-", scanRange, "--host-timeout", timeout, "--privileged")
cmdOutput, err := cmd.Output()
if err != nil {
return nmapOutput, err
}
if err := xml.Unmarshal(cmdOutput, &nmapOutput); err != nil {
return nmapOutput, err
}
return nmapOutput, nil
}
-41
View File
@@ -1,41 +0,0 @@
//go:build linux
package networking
import (
"fmt"
"kernel.org/pub/linux/libs/security/libcap/cap"
)
func NmapScan(scanRange string) (Nmaprun, error) {
orig := cap.GetProc()
defer orig.SetProc() // restore original caps on exit.
c, err := orig.Dup()
if err != nil {
return Nmaprun{}, fmt.Errorf("Failed to dup existing capabilities: %v", err)
}
if on, _ := c.GetFlag(cap.Permitted, cap.NET_RAW); !on {
return Nmaprun{}, fmt.Errorf("unable to get NET_RAW permissions")
}
if err := c.SetFlag(cap.Effective, true, cap.NET_RAW); err != nil {
return Nmaprun{}, fmt.Errorf("unable to set NET_RAW capability effective")
}
if err := c.SetFlag(cap.Inheritable, true, cap.NET_RAW); err != nil {
return Nmaprun{}, fmt.Errorf("unable to set NET_RAW capability inheritable")
}
if err := c.SetProc(); err != nil {
return Nmaprun{}, fmt.Errorf("unable to raise NET_RAW capability")
}
if err := cap.SetAmbient(true, cap.NET_RAW); err != nil {
return Nmaprun{}, fmt.Errorf("unable to set NET_RAW capability ambient")
}
return runNmap(scanRange)
}
-7
View File
@@ -1,7 +0,0 @@
//go:build !linux
package networking
func NmapScan(scanRange string) (Nmaprun, error) {
return runNmap(scanRange)
}
-65
View File
@@ -1,65 +0,0 @@
package networking
import (
"encoding/xml"
"testing"
)
// Trimmed from real `nmap -sn -oX -` output: one host with a mac (scanned
// with raw socket privileges), one without (the scanning host itself).
const nmapSample = `<?xml version="1.0" encoding="UTF-8"?>
<nmaprun scanner="nmap" args="nmap -sn -oX - 10.1.10.0/24" version="7.94">
<host><status state="up" reason="arp-response"/>
<address addr="10.1.10.1" addrtype="ipv4"/>
<address addr="AA:BB:CC:DD:EE:FF" addrtype="mac" vendor="Ubiquiti Networks"/>
<hostnames></hostnames>
</host>
<host><status state="up" reason="localhost-response"/>
<address addr="10.1.10.9" addrtype="ipv4"/>
<hostnames></hostnames>
</host>
<runstats><finished time="1754000000" exit="success"/></runstats>
</nmaprun>`
func TestNmaprunUnmarshal(t *testing.T) {
nmapOutput := Nmaprun{}
if err := xml.Unmarshal([]byte(nmapSample), &nmapOutput); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
if len(nmapOutput.Host) != 2 {
t.Fatalf("Host count mismatch: expected 2, got %d", len(nmapOutput.Host))
}
first := nmapOutput.Host[0].Address
if len(first) != 2 {
t.Fatalf("Address count mismatch: expected 2, got %d", len(first))
}
if first[0].Addrtype != "ipv4" || first[0].Addr != "10.1.10.1" {
t.Errorf("Unexpected ipv4 address: %+v", first[0])
}
if first[1].Addrtype != "mac" || first[1].Addr != "AA:BB:CC:DD:EE:FF" || first[1].Vendor != "Ubiquiti Networks" {
t.Errorf("Unexpected mac address: %+v", first[1])
}
second := nmapOutput.Host[1].Address
if len(second) != 1 || second[0].Addrtype != "ipv4" {
t.Errorf("Unexpected addresses for mac-less host: %+v", second)
}
}
func TestNmaprunMacToIP(t *testing.T) {
nmapOutput := Nmaprun{}
if err := xml.Unmarshal([]byte(nmapSample), &nmapOutput); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
macToIp := nmapOutput.MacToIP()
if len(macToIp) != 1 {
t.Fatalf("Entry count mismatch: expected 1, got %d", len(macToIp))
}
// the mac address is normalized to lower case, the mac-less host is skipped
if ip := macToIp["aa:bb:cc:dd:ee:ff"]; ip != "10.1.10.1" {
t.Errorf("Unexpected ip for aa:bb:cc:dd:ee:ff: %q", ip)
}
}
+22 -63
View File
@@ -4,22 +4,19 @@ import (
"bytes"
"context"
"fmt"
"net"
"os/exec"
"runtime"
"strings"
"time"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"github.com/seriousm4x/upsnap/logging"
"github.com/pocketbase/pocketbase/models"
"github.com/seriousm4x/upsnap/logger"
)
func ShutdownDevice(app core.App, device *core.Record, trigger string) error {
log := logging.Logger(app)
log.Info("Shutdown triggered", "device", device.GetString("name"), "trigger", trigger)
func ShutdownDevice(device *models.Record) error {
logger.Info.Println("Shutdown triggered for", device.GetString("name"))
shutdown_cmd := device.GetString("shutdown_cmd")
if shutdown_cmd == "" {
return fmt.Errorf("%s: no shutdown_cmd defined", device.GetString("name"))
return fmt.Errorf("%s: no shutdown_cmd definded", device.GetString("name"))
}
var shell string
@@ -32,20 +29,6 @@ func ShutdownDevice(app core.App, device *core.Record, trigger string) error {
shell_arg = "-c"
}
// Validate IP or resolve FQDN to IP
deviceIP, err := ResolveToIPAddr(device.GetString("ip"))
if err != nil || deviceIP == "" {
return fmt.Errorf("Unable to resolve %s to an IP address", device.GetString("ip"))
}
// Validate MAC address before replacing placeholder to prevent command injection
deviceMAC := device.GetString("mac")
if _, err := net.ParseMAC(deviceMAC); err != nil {
return fmt.Errorf("invalid device MAC address: %q", deviceMAC)
}
shutdown_cmd = strings.ReplaceAll(shutdown_cmd, "{{ DEVICE_IP }}", deviceIP)
shutdown_cmd = strings.ReplaceAll(shutdown_cmd, "{{ DEVICE_MAC }}", deviceMAC)
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
@@ -57,7 +40,7 @@ func ShutdownDevice(app core.App, device *core.Record, trigger string) error {
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
return err
logger.Error.Println(err)
}
done := make(chan error, 1)
@@ -65,55 +48,31 @@ func ShutdownDevice(app core.App, device *core.Record, trigger string) error {
done <- cmd.Wait()
}()
shutdownTimeout := device.GetInt("shutdown_timeout")
if shutdownTimeout <= 0 {
shutdownTimeout = 120
}
// check state every seconds for 2 min
start := time.Now()
for {
select {
case err := <-done:
if err != nil {
return fmt.Errorf("%s", stderr.String())
} else {
for {
isOnline, err := PingDevice(device)
if err != nil {
log.Error("Failed to ping device during shutdown", "error", err)
return err
}
if isOnline {
if time.Since(start) >= time.Duration(shutdownTimeout)*time.Second {
return fmt.Errorf("%s not offline after %d seconds", device.GetString("name"), shutdownTimeout)
}
}
if !isOnline {
return nil
}
time.Sleep(1 * time.Second)
case <-time.After(1 * time.Second):
if time.Since(start) >= 2*time.Minute {
if err := KillProcess(cmd.Process); err != nil {
logger.Error.Println(err)
}
return fmt.Errorf("%s not offline after 2 minutes", device.GetString("name"))
}
default:
isOnline, err := PingDevice(device)
if err != nil {
log.Error("Failed to ping device during shutdown", "error", err)
return err
}
if time.Since(start) >= time.Duration(shutdownTimeout)*time.Second {
if err := KillProcess(app, cmd.Process); err != nil {
log.Error("Failed to kill shutdown command", "error", err)
}
return fmt.Errorf("%s not offline after %d seconds", device.GetString("name"), shutdownTimeout)
}
isOnline := PingDevice(device)
if !isOnline {
if err := KillProcess(app, cmd.Process); err != nil {
log.Error("Failed to kill shutdown command", "error", err)
if err := KillProcess(cmd.Process); err != nil {
logger.Error.Println(err)
}
return nil
}
time.Sleep(1 * time.Second)
case err := <-done:
if err != nil {
if err := KillProcess(cmd.Process); err != nil {
logger.Error.Println(err)
}
return fmt.Errorf("%s", stderr.String())
}
}
}
}
+6 -4
View File
@@ -1,4 +1,5 @@
//go:build !windows
// +build !windows
package networking
@@ -6,8 +7,7 @@ import (
"os"
"os/exec"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"github.com/seriousm4x/upsnap/logging"
"github.com/seriousm4x/upsnap/logger"
"golang.org/x/sys/unix"
)
@@ -17,8 +17,8 @@ func SetProcessAttributes(cmd *exec.Cmd) {
}
// Kills child processes on Linux. Windows doesn't provide a direct way to kill child processes, so we kill just the main process.
func KillProcess(app core.App, process *os.Process) error {
logging.Logger(app).Warn("Command did not finish in time and will be killed")
func KillProcess(process *os.Process) error {
logger.Warning.Println("Your shutdown cmd didn't finish in 2 minutes. It will be killed.")
pgid, err := unix.Getpgid(process.Pid)
if err != nil {
return err
@@ -29,5 +29,7 @@ func KillProcess(app core.App, process *os.Process) error {
return unix.Kill(-pgid, unix.SIGKILL)
}
_, err = process.Wait()
return err
}
+2 -3
View File
@@ -1,4 +1,5 @@
//go:build windows
// +build windows
package networking
@@ -6,8 +7,6 @@ import (
"os"
"os/exec"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"golang.org/x/sys/windows"
)
@@ -15,6 +14,6 @@ import (
func SetProcessAttributes(cmd *exec.Cmd) {}
// Kills child processes on Linux. Windows doesn't provide a direct way to kill child processes, so we kill just the main process.
func KillProcess(_ core.App, process *os.Process) error {
func KillProcess(process *os.Process) error {
return windows.GenerateConsoleCtrlEvent(windows.CTRL_BREAK_EVENT, uint32(process.Pid))
}
+6 -10
View File
@@ -7,29 +7,25 @@ import (
"io"
"net/http"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"github.com/seriousm4x/upsnap/logging"
"github.com/pocketbase/pocketbase/models"
"github.com/seriousm4x/upsnap/logger"
)
type SolResponse struct {
Message string `json:"message"`
}
func SleepDevice(app core.App, device *core.Record) (SolResponse, error) {
logging.Logger(app).Info("Sleep triggered", "device", device.GetString("name"))
func SleepDevice(device *models.Record) (SolResponse, error) {
logger.Info.Println("Sleep triggered for", device.GetString("name"))
var solResp SolResponse
var url string
deviceIP, err := ResolveToIPAddr(device.GetString("ip"))
if err != nil || deviceIP == "" {
return solResp, fmt.Errorf("Unable to resolve %s to an IP address: %w", device.GetString("ip"), err)
}
if device.GetBool("sol_auth") {
url = fmt.Sprintf("http://%s:%s@%s:%d/sleep?format=JSON",
device.GetString("sol_user"), device.GetString("sol_password"), deviceIP, device.GetInt("sol_port"))
device.GetString("sol_user"), device.GetString("sol_password"), device.GetString("ip"), device.GetInt("sol_port"))
} else {
url = fmt.Sprintf("http://%s:%d/sleep?format=JSON", deviceIP, device.GetInt("sol_port"))
url = fmt.Sprintf("http://%s:%d/sleep?format=JSON", device.GetString("ip"), device.GetInt("sol_port"))
}
resp, err := http.Get(url)
-59
View File
@@ -1,59 +0,0 @@
package networking
import (
"errors"
"net"
)
// DeviceSubnet returns the device's IPv4 subnet computed from its ip and netmask.
func DeviceSubnet(ipStr, maskStr string) (*net.IPNet, error) {
ip := net.ParseIP(ipStr)
if ip == nil || ip.To4() == nil {
return nil, errors.New("ip not a valid ipv4 address")
}
ip = ip.To4()
mask := net.ParseIP(maskStr)
if mask == nil || mask.To4() == nil {
return nil, errors.New("subnet mask not a valid ipv4 address")
}
ipMask := net.IPMask(mask.To4())
return &net.IPNet{IP: ip.Mask(ipMask), Mask: ipMask}, nil
}
// ValidateScannableSubnet returns nil if the subnet is suitable for an nmap
// scan, or an error explaining why it isn't.
func ValidateScannableSubnet(subnet *net.IPNet) error {
ones, bits := subnet.Mask.Size()
if ones == 0 && bits == 0 {
// Size() returns 0,0 for a non-contiguous mask, which has no cidr
// notation to hand to nmap
return errors.New("netmask is not contiguous")
}
if ones == bits {
return errors.New("a single address has nothing to scan")
}
if ones < 16 {
return errors.New("subnets larger than a /16 take too long to scan")
}
// arp only answers on-link, so the subnet must overlap one of the
// host's attached ipv4 networks for a scan to find mac addresses
addrs, err := net.InterfaceAddrs()
if err != nil {
return err
}
for _, addr := range addrs {
attached, ok := addr.(*net.IPNet)
if !ok || attached.IP.To4() == nil {
continue
}
// subnets are either disjoint or nested, so checking containment
// in both directions covers overlap
if attached.Contains(subnet.IP) || subnet.Contains(attached.IP) {
return nil
}
}
return errors.New("subnet does not overlap a directly attached network")
}
-146
View File
@@ -1,146 +0,0 @@
package networking
import (
"testing"
)
func TestDeviceSubnet(t *testing.T) {
testCases := []struct {
name string
ip string
netmask string
wantCidr string
wantError bool
}{
// Valid case: address is masked down to the network
{
name: "Valid Case",
ip: "192.168.1.100",
netmask: "255.255.255.0",
wantCidr: "192.168.1.0/24",
wantError: false,
},
// Valid case: wider mask
{
name: "Valid /16",
ip: "10.1.10.142",
netmask: "255.255.0.0",
wantCidr: "10.1.0.0/16",
wantError: false,
},
// Valid case: host mask
{
name: "Valid /32",
ip: "192.168.1.5",
netmask: "255.255.255.255",
wantCidr: "192.168.1.5/32",
wantError: false,
},
// Invalid IP address
{
name: "Invalid IP",
ip: "256.1.1.1", // invalid
netmask: "255.255.255.0",
wantCidr: "",
wantError: true,
},
// Invalid netmask
{
name: "Invalid Netmask",
ip: "192.168.1.100",
netmask: "300.255.255.0", // invalid
wantCidr: "",
wantError: true,
},
// IPv6 address is not a valid device ip
{
name: "IPv6 IP",
ip: "fe80::1",
netmask: "255.255.255.0",
wantCidr: "",
wantError: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
subnet, err := DeviceSubnet(tc.ip, tc.netmask)
if tc.wantError {
if err == nil {
t.Errorf("Expected error but got none")
}
} else {
if err != nil {
t.Errorf("Got unexpected error: %v", err)
} else if subnet.String() != tc.wantCidr {
t.Errorf("Subnet mismatch: expected %s, got %s", tc.wantCidr, subnet.String())
}
}
})
}
}
func TestValidateScannableSubnet(t *testing.T) {
testCases := []struct {
name string
ip string
netmask string
wantError bool
}{
// A /32 has nothing to scan
{
name: "Host Mask",
ip: "192.168.1.5",
netmask: "255.255.255.255",
wantError: true,
},
// A non-contiguous mask has no cidr notation to scan
{
name: "Non-contiguous Mask",
ip: "10.0.1.5",
netmask: "255.0.255.0",
wantError: true,
},
// Anything larger than a /16 takes too long to scan
{
name: "Too Large",
ip: "10.0.0.1",
netmask: "255.0.0.0",
wantError: true,
},
// The loopback address as a /16 is within limits and always attached
{
name: "Local /16",
ip: "127.0.0.1",
netmask: "255.255.0.0",
wantError: false,
},
// A sub-block of the attached loopback /8 is on-link even though
// it doesn't contain the host's own 127.0.0.1
{
name: "Nested In Attached",
ip: "127.0.1.5",
netmask: "255.255.255.0",
wantError: false,
},
// TEST-NET-1 (RFC 5737) is never assigned to an interface
{
name: "No Overlap",
ip: "192.0.2.1",
netmask: "255.255.255.0",
wantError: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
subnet, err := DeviceSubnet(tc.ip, tc.netmask)
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
if err := ValidateScannableSubnet(subnet); (err != nil) != tc.wantError {
t.Errorf("ValidateScannableSubnet(%s): expected error=%v, got %v", subnet.String(), tc.wantError, err)
}
})
}
}
-50
View File
@@ -1,50 +0,0 @@
package networking
import (
"fmt"
"net/netip"
"regexp"
"strings"
"golang.org/x/net/idna"
)
var fqdnRegex = regexp.MustCompile(`^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z0-9-]{2,63}$`)
/*
Validate's FQDN by converting it to Punycode and checking it against several criteria
*/
func ValidateFQDN(host string) error {
// Remove trailing . just in case, but DB and form validation should already prevent that
trimmedHost := strings.TrimSuffix(host, ".")
if len(trimmedHost) == 0 {
return fmt.Errorf("%q: invalid length of 0. original %q", trimmedHost, host)
}
// convert to punycode
punycodeHost, err := idna.Lookup.ToASCII(trimmedHost)
if err != nil {
return fmt.Errorf("%q: failed to convert to punycode - %w", trimmedHost, err)
}
if len(punycodeHost) < 1 || len(punycodeHost) > 253 {
return fmt.Errorf("%q -> %q: invalid length %d bytes. Must be 1-253 bytes (chars) after conversion.", trimmedHost, punycodeHost, len(punycodeHost))
}
if !fqdnRegex.MatchString(punycodeHost) {
return fmt.Errorf("%q -> %q: Failed validation.", trimmedHost, punycodeHost)
}
return nil
}
func ValidateSubnetMask(mask string) bool {
addr, err := netip.ParseAddr(mask)
if err != nil || !addr.Is4() {
return false
}
byteArray := addr.As4()
maskInt := uint32(byteArray[0])<<24 | uint32(byteArray[1])<<16 | uint32(byteArray[2])<<8 | uint32(byteArray[3])
inverted := ^maskInt
return (inverted & (inverted + 1)) == 0
}
+20 -61
View File
@@ -4,24 +4,16 @@ import (
"bytes"
"context"
"fmt"
"net"
"os/exec"
"runtime"
"strings"
"time"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"github.com/seriousm4x/upsnap/logging"
"github.com/pocketbase/pocketbase/models"
"github.com/seriousm4x/upsnap/logger"
)
func WakeDevice(app core.App, device *core.Record, trigger string) error {
log := logging.Logger(app)
log.Info("Wake triggered", "device", device.GetString("name"), "trigger", trigger)
wakeTimeout := device.GetInt("wake_timeout")
if wakeTimeout <= 0 {
wakeTimeout = 120
}
func WakeDevice(device *models.Record) error {
logger.Info.Println("Wake triggered for", device.GetString("name"))
wake_cmd := device.GetString("wake_cmd")
if wake_cmd != "" {
@@ -35,21 +27,6 @@ func WakeDevice(app core.App, device *core.Record, trigger string) error {
shell_arg = "-c"
}
deviceIP, err := ResolveToIPAddr(device.GetString("ip"))
if err != nil {
return err
}
if deviceIP == "" {
deviceIP = device.GetString("ip")
}
// Validate MAC address before replacing placeholders to prevent command injection
deviceMAC := device.GetString("mac")
if _, err := net.ParseMAC(deviceMAC); err != nil {
return fmt.Errorf("invalid device MAC address: %q", deviceMAC)
}
wake_cmd = strings.ReplaceAll(wake_cmd, "{{ DEVICE_IP }}", deviceIP)
wake_cmd = strings.ReplaceAll(wake_cmd, "{{ DEVICE_MAC }}", deviceMAC)
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
@@ -61,8 +38,7 @@ func WakeDevice(app core.App, device *core.Record, trigger string) error {
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
log.Error("Failed to start wake command", "error", err)
return err
logger.Error.Println(err)
}
done := make(chan error, 1)
@@ -70,45 +46,31 @@ func WakeDevice(app core.App, device *core.Record, trigger string) error {
done <- cmd.Wait()
}()
// check state every seconds for 2 min
start := time.Now()
commandFinished := false
for {
select {
case <-time.After(1 * time.Second):
if time.Since(start) >= time.Duration(wakeTimeout)*time.Second {
if !commandFinished && cmd.Process != nil {
if err := KillProcess(app, cmd.Process); err != nil {
log.Error("Failed to kill wake command", "error", err)
}
if time.Since(start) >= 2*time.Minute {
if err := KillProcess(cmd.Process); err != nil {
logger.Error.Println(err)
}
return fmt.Errorf("%s not online after %d seconds", device.GetString("name"), wakeTimeout)
}
// Reachability alone does not mean a custom wake command has finished.
// For example, a Mac can respond to ping while it is still in DarkWake.
if !commandFinished {
continue
}
isOnline, err := PingDevice(device)
if err != nil {
log.Error("Failed to ping device after wake", "error", err)
return err
return fmt.Errorf("%s not online after 2 minutes", device.GetString("name"))
}
isOnline := PingDevice(device)
if isOnline {
if err := KillProcess(cmd.Process); err != nil {
logger.Error.Println(err)
}
return nil
}
case err := <-done:
if err != nil {
if cmd.Process != nil {
if err := KillProcess(app, cmd.Process); err != nil {
log.Error("Failed to kill wake command", "error", err)
}
if err := KillProcess(cmd.Process); err != nil {
logger.Error.Println(err)
}
return fmt.Errorf("%s", stderr.String())
}
commandFinished = true
done = nil
// Command finished successfully, but we continue the loop until device is online or timeout
}
}
} else {
@@ -117,21 +79,18 @@ func WakeDevice(app core.App, device *core.Record, trigger string) error {
return err
}
// check state every seconds for 2 min
start := time.Now()
for {
time.Sleep(1 * time.Second)
isOnline, err := PingDevice(device)
if err != nil {
log.Error("Failed to ping device after wake", "error", err)
return err
}
isOnline := PingDevice(device)
if isOnline {
return nil
}
if time.Since(start) >= time.Duration(wakeTimeout)*time.Second {
if time.Since(start) >= 2*time.Minute {
break
}
}
return fmt.Errorf("%s not online after %d seconds", device.GetString("name"), wakeTimeout)
return fmt.Errorf(device.GetString("name"), "not online after 2 min")
}
}
-92
View File
@@ -1,92 +0,0 @@
//go:build !windows
package networking
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"ganigeorgiev.com/pocketbase/pocketbase/tests"
)
func newWakeTestDevice(t *testing.T, command, pingCommand string, timeout int) (core.App, *core.Record) {
t.Helper()
app, err := tests.NewTestApp(t.TempDir())
if err != nil {
t.Fatal(err)
}
t.Cleanup(app.Cleanup)
device := core.NewRecord(&core.Collection{})
device.Set("name", "test-device")
device.Set("ip", "127.0.0.1")
device.Set("mac", "02:00:00:00:00:01")
device.Set("wake_cmd", command)
device.Set("ping_cmd", pingCommand)
device.Set("wake_timeout", timeout)
return app, device
}
func TestCustomWakeWaitsForCommandWhenDeviceIsAlreadyOnline(t *testing.T) {
dir := t.TempDir()
t.Setenv("UPSNAP_WAKE_TEST_DIR", dir)
app, device := newWakeTestDevice(t,
`sleep 2; printf done > "$UPSNAP_WAKE_TEST_DIR/completed"`, "exit 0", 10)
if err := WakeDevice(app, device, "test"); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(filepath.Join(dir, "completed"))
if err != nil || string(data) != "done" {
t.Fatalf("wake command was interrupted despite successful ping: data=%q err=%v", data, err)
}
}
func TestCustomWakeReturnsFailureWhenDeviceIsAlreadyOnline(t *testing.T) {
app, device := newWakeTestDevice(t, "sleep 2; echo wake-failed >&2; exit 7", "exit 0", 10)
err := WakeDevice(app, device, "test")
if err == nil || !strings.Contains(err.Error(), "wake-failed") {
t.Fatalf("expected wake command failure despite successful ping, got %v", err)
}
}
func TestCustomWakeStillWaitsForReachabilityAfterCommandFinishes(t *testing.T) {
dir := t.TempDir()
t.Setenv("UPSNAP_WAKE_TEST_DIR", dir)
app, device := newWakeTestDevice(t, "exit 0",
`if [ -f "$UPSNAP_WAKE_TEST_DIR/pinged" ]; then exit 0; fi; touch "$UPSNAP_WAKE_TEST_DIR/pinged"; exit 1`, 10)
if err := WakeDevice(app, device, "test"); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(dir, "pinged")); err != nil {
t.Fatalf("wake returned without checking reachability: %v", err)
}
}
func TestCustomWakeTimesOutWhenCommandSucceedsButDeviceStaysOffline(t *testing.T) {
app, device := newWakeTestDevice(t, "exit 0", "exit 1", 2)
err := WakeDevice(app, device, "test")
if err == nil || !strings.Contains(err.Error(), "not online after 2 seconds") {
t.Fatalf("expected reachability timeout, got %v", err)
}
}
func TestCustomWakeTimeoutStillStopsRunningCommand(t *testing.T) {
dir := t.TempDir()
t.Setenv("UPSNAP_WAKE_TEST_DIR", dir)
app, device := newWakeTestDevice(t,
`sleep 3; touch "$UPSNAP_WAKE_TEST_DIR/completed"`, "exit 0", 1)
err := WakeDevice(app, device, "test")
if err == nil || !strings.Contains(err.Error(), "not online after 1 seconds") {
t.Fatalf("expected command timeout even though ping succeeds, got %v", err)
}
// A surviving shell/child would write this file after its sleep finishes.
time.Sleep(3 * time.Second)
if _, err := os.Stat(filepath.Join(dir, "completed")); !os.IsNotExist(err) {
t.Fatalf("timed-out wake command continued running: %v", err)
}
}
+144 -331
View File
@@ -1,239 +1,120 @@
package pb
import (
"encoding/json"
"fmt"
"encoding/xml"
"net"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"time"
"ganigeorgiev.com/pocketbase/dbx"
"ganigeorgiev.com/pocketbase/pocketbase/apis"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"ganigeorgiev.com/pocketbase/pocketbase/tools/router"
"github.com/robfig/cron/v3"
"github.com/seriousm4x/upsnap/logging"
"github.com/labstack/echo/v5"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/models"
"github.com/seriousm4x/upsnap/logger"
"github.com/seriousm4x/upsnap/networking"
)
func HandlerWake(e *core.RequestEvent) error {
record, err := e.App.FindFirstRecordByData("devices", "id", e.Request.PathValue("id"))
func HandlerWake(c echo.Context) error {
record, err := App.Dao().FindFirstRecordByData("devices", "id", c.PathParam("id"))
if err != nil {
return apis.NewNotFoundError("The device does not exist.", err)
}
record.Set("status", "pending")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save pending device status", "device", record.GetString("name"), "error", err)
if err := App.Dao().SaveRecord(record); err != nil {
logger.Error.Println("Failed to save record:", err)
}
if err := asyncCall(e, func() *router.ApiError {
if err := networking.WakeDevice(e.App, record, "manual"); err != nil {
logging.Logger(e.App).Error("Failed to wake device", "device", record.GetString("name"), "error", err)
record.Set("status", "offline")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return apis.NewBadRequestError(err.Error(), nil)
go func(r *models.Record) {
if err := networking.WakeDevice(r); err != nil {
logger.Error.Println(err)
r.Set("status", "offline")
} else {
r.Set("status", "online")
}
if err := App.Dao().SaveRecord(r); err != nil {
logger.Error.Println("Failed to save record:", err)
}
}(record)
return c.JSON(http.StatusOK, record)
}
func HandlerSleep(c echo.Context) error {
record, err := App.Dao().FindFirstRecordByData("devices", "id", c.PathParam("id"))
if err != nil {
return apis.NewNotFoundError("The device does not exist.", err)
}
record.Set("status", "pending")
if err := App.Dao().SaveRecord(record); err != nil {
logger.Error.Println("Failed to save record:", err)
}
resp, err := networking.SleepDevice(record)
if err != nil {
logger.Error.Println(err)
record.Set("status", "online")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
if err := App.Dao().SaveRecord(record); err != nil {
logger.Error.Println("Failed to save record:", err)
}
return nil
}); err != nil {
return err
return apis.NewBadRequestError(resp.Message, nil)
}
return e.JSON(http.StatusOK, record)
record.Set("status", "offline")
if err := App.Dao().SaveRecord(record); err != nil {
logger.Error.Println("Failed to save record:", err)
}
return c.JSON(http.StatusOK, nil)
}
func HandlerSleep(e *core.RequestEvent) error {
record, err := e.App.FindFirstRecordByData("devices", "id", e.Request.PathValue("id"))
func HandlerReboot(c echo.Context) error {
record, err := App.Dao().FindFirstRecordByData("devices", "id", c.PathParam("id"))
if err != nil {
return apis.NewNotFoundError("The device does not exist.", err)
}
record.Set("status", "pending")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save pending device status", "device", record.GetString("name"), "error", err)
if err := App.Dao().SaveRecord(record); err != nil {
logger.Error.Println("Failed to save record:", err)
}
if err := asyncCall(e, func() *router.ApiError {
resp, err := networking.SleepDevice(e.App, record)
if err != nil {
logging.Logger(e.App).Error("Failed to sleep device", "device", record.GetString("name"), "error", err)
record.Set("status", "online")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
go func(r *models.Record) {
if err := networking.ShutdownDevice(r); err != nil {
logger.Error.Println(err)
r.Set("status", "online")
} else {
time.Sleep(15 * time.Second) // some devices might not respond to ping but are still shutting down
if err := networking.WakeDevice(r); err != nil {
logger.Error.Println(err)
r.Set("status", "offline")
} else {
r.Set("status", "online")
}
return apis.NewBadRequestError(resp.Message, nil)
}
record.Set("status", "offline")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
if err := App.Dao().SaveRecord(r); err != nil {
logger.Error.Println("Failed to save record:", err)
}
return nil
}); err != nil {
return err
}
return e.JSON(http.StatusOK, nil)
}(record)
return c.JSON(http.StatusOK, record)
}
func HandlerReboot(e *core.RequestEvent) error {
record, err := e.App.FindFirstRecordByData("devices", "id", e.Request.PathValue("id"))
func HandlerShutdown(c echo.Context) error {
record, err := App.Dao().FindFirstRecordByData("devices", "id", c.PathParam("id"))
if err != nil {
return apis.NewNotFoundError("The device does not exist.", err)
}
record.Set("status", "pending")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save pending device status", "device", record.GetString("name"), "error", err)
if err := App.Dao().SaveRecord(record); err != nil {
logger.Error.Println("Failed to save record:", err)
}
if err := asyncCall(e, func() *router.ApiError {
if err := networking.ShutdownDevice(e.App, record, "manual"); err != nil {
logging.Logger(e.App).Error("Failed to shut down device for reboot", "device", record.GetString("name"), "error", err)
record.Set("status", "online")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return apis.NewBadRequestError(err.Error(), nil)
go func(r *models.Record) {
if err := networking.ShutdownDevice(r); err != nil {
logger.Error.Println(err)
r.Set("status", "online")
} else {
r.Set("status", "offline")
}
// if this code is reached, the device is shutting down and not responding to pings anymore.
// this does not mean it is ready to boot again, it might still be in the process of shutting down.
// so we wait a little to make sure the device has shut down completely and is ready to receive wake requests.
time.Sleep(15 * time.Second)
if err := networking.WakeDevice(e.App, record, "manual"); err != nil {
logging.Logger(e.App).Error("Failed to wake device after reboot", "device", record.GetString("name"), "error", err)
record.Set("status", "offline")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return apis.NewBadRequestError(err.Error(), nil)
if err := App.Dao().SaveRecord(r); err != nil {
logger.Error.Println("Failed to save record:", err)
}
record.Set("status", "online")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return nil
}); err != nil {
return err
}
return e.JSON(http.StatusOK, record)
}
func HandlerShutdown(e *core.RequestEvent) error {
record, err := e.App.FindFirstRecordByData("devices", "id", e.Request.PathValue("id"))
if err != nil {
return apis.NewNotFoundError("The device does not exist.", err)
}
record.Set("status", "pending")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save pending device status", "device", record.GetString("name"), "error", err)
}
if err := asyncCall(e, func() *router.ApiError {
if err := networking.ShutdownDevice(e.App, record, "manual"); err != nil {
logging.Logger(e.App).Error("Failed to shut down device", "device", record.GetString("name"), "error", strings.ReplaceAll(err.Error(), "\n", ""))
record.Set("status", "online")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return apis.NewBadRequestError(err.Error(), nil)
}
record.Set("status", "offline")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return nil
}); err != nil {
return err
}
return e.JSON(http.StatusOK, record)
}
func HandlerWakeGroup(e *core.RequestEvent) error {
records, err := e.App.FindRecordsByFilter("devices", "groups.id ?= {:grpId} && status = 'offline'", "", 0, 0,
dbx.Params{"grpId": e.Request.PathValue("id")},
)
if err != nil {
return apis.NewNotFoundError("No devices in group", err)
}
for _, record := range records {
go func() {
record.Set("status", "pending")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save pending device status", "device", record.GetString("name"), "error", err)
}
if err := networking.WakeDevice(e.App, record, "manual"); err != nil {
logging.Logger(e.App).Error("Failed to wake device", "device", record.GetString("name"), "error", err)
record.Set("status", "offline")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return
}
record.Set("status", "online")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
}()
}
return e.JSON(http.StatusOK, records)
}
func HandlerShutdownGroup(e *core.RequestEvent) error {
records, err := e.App.FindRecordsByFilter("devices", "groups.id ?= {:grpId} && status = 'online'", "", 0, 0,
dbx.Params{"grpId": e.Request.PathValue("id")},
)
if err != nil {
return apis.NewNotFoundError("No devices in group", err)
}
for _, record := range records {
go func() {
record.Set("status", "pending")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save pending device status", "device", record.GetString("name"), "error", err)
}
if err := networking.ShutdownDevice(e.App, record, "manual"); err != nil {
logging.Logger(e.App).Error("Failed to shut down device", "device", record.GetString("name"), "error", err)
record.Set("status", "online")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
return
}
record.Set("status", "offline")
if err := e.App.Save(record); err != nil {
logging.Logger(e.App).Error("Failed to save device status", "device", record.GetString("name"), "error", err)
}
}()
}
return e.JSON(http.StatusOK, records)
}(record)
return c.JSON(http.StatusOK, record)
}
type Nmaprun struct {
@@ -246,161 +127,93 @@ type Nmaprun struct {
} `xml:"host"`
}
func HandlerInitSuperuser(e *core.RequestEvent) error {
superusersCollection, err := e.App.FindCollectionByNameOrId(core.CollectionNameSuperusers)
func HandlerScan(c echo.Context) error {
// check if nmap installed
nmap, err := exec.LookPath("nmap")
if err != nil {
return e.NotFoundError("Failed to retrieve superusers collection", err)
return apis.NewBadRequestError(err.Error(), nil)
}
totalSuperusers, err := e.App.CountRecords(superusersCollection)
// check if scan range is valid
allPrivateSettings, err := App.Dao().FindRecordsByExpr("settings_private")
if err != nil {
return e.InternalServerError("Failed to retrieve superusers count", err)
return err
}
if totalSuperusers > 0 {
return e.BadRequestError("An initial superuser already exists", nil)
}
data := struct {
Email string `json:"email" form:"email"`
Password string `json:"password" form:"password"`
PasswordConfirm string `json:"password_confirm" form:"password-confirm"`
}{}
err = e.BindBody(&data)
settingsPrivate := allPrivateSettings[0]
scanRange := settingsPrivate.GetString("scan_range")
_, ipNet, err := net.ParseCIDR(scanRange)
if err != nil {
return e.BadRequestError("Failed to read request data", err)
return apis.NewBadRequestError(err.Error(), nil)
}
if data.Password != data.PasswordConfirm {
return e.BadRequestError("Password don't match", err)
// run nmap
timeout := os.Getenv("UPSNAP_SCAN_TIMEOUT")
if timeout == "" {
timeout = "500ms"
}
record := core.NewRecord(superusersCollection)
record.SetEmail(data.Email)
record.SetPassword(data.Password)
err = e.App.Save(record)
cmd := exec.Command(nmap, "-sn", "-oX", "-", scanRange, "--host-timeout", timeout)
cmdOutput, err := cmd.Output()
if err != nil {
return e.BadRequestError("Failed to create initial superuser", err)
return err
}
return apis.RecordAuthResponse(e, record, "", nil)
}
type ValidateCronRequest struct {
Cron string `json:"cron"`
}
func HandlerValidateCron(e *core.RequestEvent) error {
var body ValidateCronRequest
if err := e.BindBody(&body); err != nil {
logging.Logger(e.App).Error("Failed to bind cron validation request", "error", err)
return e.BadRequestError("invalid request", err)
// unmarshal xml
nmapOutput := Nmaprun{}
if err := xml.Unmarshal(cmdOutput, &nmapOutput); err != nil {
return err
}
p := cron.NewParser(cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow)
if _, err := p.Parse(body.Cron); err != nil {
return e.BadRequestError("failed to parse cron expression", err)
type Device struct {
Name string `json:"name"`
IP string `json:"ip"`
MAC string `json:"mac"`
MACVendor string `json:"mac_vendor"`
}
return e.JSON(200, "valid")
}
func asyncCall(e *core.RequestEvent, fn func() *router.ApiError) *router.ApiError {
isAsync, err := strconv.ParseBool(e.Request.URL.Query().Get("async"))
if err != nil {
isAsync = false
// extract info from struct into data
type Response struct {
Netmask string `json:"netmask"`
Devices []Device `json:"devices"`
}
if !isAsync {
return fn()
res := Response{}
var nm []string
for _, octet := range ipNet.Mask {
nm = append(nm, strconv.Itoa(int(octet)))
}
res.Netmask = strings.Join(nm, ".")
go func() {
_ = fn()
}()
return nil
}
func HandlerWebsiteManifest(e *core.RequestEvent) error {
scheme := "http"
if e.Request.TLS != nil || e.Request.Header.Get("X-Forwarded-Proto") == "https" {
scheme = "https"
}
baseUrl := fmt.Sprintf("%s://%s", scheme, e.Request.Host)
manifest := map[string]any{
"name": "UpSnap",
"short_name": "UpSnap",
"description": "A simple wake on lan web app written with SvelteKit, Go and PocketBase.",
"theme_color": "#55BCD9",
"background_color": "#55BCD9",
"display": "standalone",
"scope": baseUrl,
"start_url": baseUrl,
"icons": []map[string]string{
{
"src": "/icon_192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any",
},
{
"src": "/icon_512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any",
},
{
"src": "/maskable_192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable",
},
{
"src": "/maskable_512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable",
},
{
"src": "/gopher.svg",
"sizes": "any",
"type": "image/svg+xml",
},
},
}
publicSettings, err := e.App.FindFirstRecordByFilter("settings_public", "")
if err != nil {
return writeManifest(e, manifest)
}
// override title if set
if title := publicSettings.GetString("website_title"); title != "" {
manifest["name"] = title
manifest["short_name"] = title
}
// override icons if set
if favicon := publicSettings.GetString("favicon"); favicon != "" {
manifest["icons"] = []map[string]string{
{
"src": fmt.Sprintf("%s/api/files/settings_public/%s/%s", baseUrl, publicSettings.Id, favicon),
"sizes": "any",
"purpose": "any",
},
for _, host := range nmapOutput.Host {
dev := Device{}
for _, addr := range host.Address {
if addr.Addrtype == "ipv4" {
dev.IP = addr.Addr
} else if addr.Addrtype == "mac" {
dev.MAC = addr.Addr
}
if addr.Vendor != "" {
dev.MACVendor = addr.Vendor
} else {
dev.MACVendor = "Unknown"
}
}
if dev.IP == "" || dev.MAC == "" {
continue
}
names, err := net.LookupAddr(dev.IP)
if err != nil || len(names) == 0 {
dev.Name = dev.MACVendor
} else {
dev.Name = strings.TrimSuffix(names[0], ".")
}
if dev.Name == "" && dev.MACVendor == "" {
continue
}
res.Devices = append(res.Devices, dev)
}
return writeManifest(e, manifest)
}
func writeManifest(e *core.RequestEvent, manifest map[string]any) error {
e.Response.Header().Set("Content-Type", "application/manifest+json")
e.Response.Header().Set("Cache-Control", "no-cache, no-store")
enc := json.NewEncoder(e.Response)
return enc.Encode(manifest)
return c.JSON(http.StatusOK, res)
}
-137
View File
@@ -1,137 +0,0 @@
//go:build linux
package pb
import (
"encoding/xml"
"fmt"
"net"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"ganigeorgiev.com/pocketbase/pocketbase/apis"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"kernel.org/pub/linux/libs/security/libcap/cap"
)
func HandlerScan(e *core.RequestEvent) error {
// check if nmap installed
nmap, err := exec.LookPath("nmap")
if err != nil {
return apis.NewBadRequestError(err.Error(), nil)
}
// check if scan range is valid
allPrivateSettings, err := e.App.FindAllRecords("settings_private")
if err != nil {
return err
}
settingsPrivate := allPrivateSettings[0]
scanRange := settingsPrivate.GetString("scan_range")
_, ipNet, err := net.ParseCIDR(scanRange)
if err != nil {
return apis.NewBadRequestError(err.Error(), nil)
}
// run nmap
timeout := os.Getenv("UPSNAP_SCAN_TIMEOUT")
if timeout == "" {
timeout = "500ms"
}
orig := cap.GetProc()
defer orig.SetProc() // restore original caps on exit.
c, err := orig.Dup()
if err != nil {
return fmt.Errorf("Failed to dup existing capabilities: %v", err)
}
if on, _ := c.GetFlag(cap.Permitted, cap.NET_RAW); !on {
return fmt.Errorf("unable to get NET_RAW permissions")
}
if err := c.SetFlag(cap.Effective, true, cap.NET_RAW); err != nil {
return fmt.Errorf("unable to set NET_RAW capability effective")
}
if err := c.SetFlag(cap.Inheritable, true, cap.NET_RAW); err != nil {
return fmt.Errorf("unable to set NET_RAW capability inheritable")
}
if err := c.SetProc(); err != nil {
return fmt.Errorf("unable to raise NET_RAW capability")
}
if err := cap.SetAmbient(true, cap.NET_RAW); err != nil {
return fmt.Errorf("unable to set NET_RAW capability ambient")
}
cmd := exec.Command(nmap, "-sn", "-oX", "-", scanRange, "--host-timeout", timeout, "--privileged")
cmdOutput, err := cmd.Output()
if err != nil {
return err
}
// unmarshal xml
nmapOutput := Nmaprun{}
if err := xml.Unmarshal(cmdOutput, &nmapOutput); err != nil {
return err
}
type Device struct {
Name string `json:"name"`
IP string `json:"ip"`
MAC string `json:"mac"`
MACVendor string `json:"mac_vendor"`
}
// extract info from struct into data
type Response struct {
Netmask string `json:"netmask"`
Devices []Device `json:"devices"`
}
res := Response{}
var nm []string
for _, octet := range ipNet.Mask {
nm = append(nm, strconv.Itoa(int(octet)))
}
res.Netmask = strings.Join(nm, ".")
for _, host := range nmapOutput.Host {
dev := Device{}
for _, addr := range host.Address {
if addr.Addrtype == "ipv4" {
dev.IP = addr.Addr
} else if addr.Addrtype == "mac" {
dev.MAC = addr.Addr
}
if addr.Vendor != "" {
dev.MACVendor = addr.Vendor
} else {
dev.MACVendor = "Unknown"
}
}
if dev.IP == "" || dev.MAC == "" {
continue
}
names, err := net.LookupAddr(dev.IP)
if err != nil || len(names) == 0 {
dev.Name = dev.MACVendor
} else {
dev.Name = strings.TrimSuffix(names[0], ".")
}
if dev.Name == "" && dev.MACVendor == "" {
continue
}
res.Devices = append(res.Devices, dev)
}
return e.JSON(http.StatusOK, res)
}

Some files were not shown because too many files have changed in this diff Show More