Compare commits

...

12 Commits

Author SHA1 Message Date
seriousm4x 710329e8ab remove star history 2026-08-28 00:33:51 +02:00
Maxi Quoß df7a577db2 remove info
This is just to de-clutter the readme and changelog. I still stand
behind this statement. Nothing changes.
2026-08-27 20:58:29 +02:00
Maxi Quoß d8eafbc123 fix: set device status for lazy ping devices, close #1762 2026-08-27 20:56:16 +02:00
Maxi Quoß 11bdb8ad36 use correct pocketbase app values 2026-08-27 20:28:19 +02:00
Maxi Quoß 9057fa710b update deps 2026-08-27 20:26:47 +02:00
Mike Pastore b5fd864320 feat: optional per-device IP address tracking via periodic ARP scan (#1763)
* feat: optional per-device ip address tracking via periodic arp scan

Adds a per-device "Track IP address" toggle (disabled by default) and a
global cron interval setting. When enabled, upsnap periodically arp-scans
the local subnets of opted-in devices with nmap and updates a device's ip
address whenever its mac address is found at a different one. Subnets are
skipped unless directly attached to the host, so routed devices are never
scanned. Uses the same nmap + CAP_NET_RAW requirements as the existing
network scan feature; no new privileges needed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test: cover ip tracking subnet helpers and nmap xml parsing

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: extract ip tracking into its own package and expand test coverage

Move the arp scan sweep out of cronjobs into a new iptracking package with
two entry points: TrackAllSubnets (the cron sweep) and TrackOneSubnet (a
single validated scan). Device lookup is now by mac address across all
tracked devices, with updates constrained to the device's own subnet.

The scannability check becomes networking.ValidateScannableSubnet, which
reports why a subnet can't be scanned and accepts any subnet overlapping a
directly attached network, so sub-blocks of an attached prefix are now
scannable. The mac-to-ip mapping moves to networking as Nmaprun.MacToIP.

Cover the subnet guard, mac normalization, skip paths, and sweep
orchestration with tests against a stubbed scanner and a real migrated
schema.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: pause tracking sweeps while nobody is connected

With lazy_ping turned on, the periodic tracking sweep now skips its tick
while no realtime clients are connected, just like the ping cron, and owes
a catch-up sweep to the next client that connects: the realtime connect
hook runs one sweep only when a tick was actually skipped (or none has run
since boot), so page reloads during active use trigger nothing. This
extends lazy_ping's meaning from "pause pings when idle" to "pause
periodic network activity when idle"; the setting's description is updated
accordingly.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* ui: move lazy ping section below ip tracking in settings

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* disable toggle when tracking is disabled

* fix: load private store

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Maxi Quoß <maxi@quoss.org>
2026-08-27 20:21:51 +02:00
Maxi Quoß 297518f008 fix: only allow valid ipv4 addresses as netmask, close #1761 2026-07-26 12:20:30 +02:00
Maxi Quoß e3c7342932 fix: only allow valid ipv4 addresses as netmask, close #1761 2026-07-26 12:19:58 +02:00
Maxi Quoß 89977debc5 update deps 2026-07-23 19:15:28 +02:00
invario 391b218fe5 fix: ip and mac address regex validation (#1758)
* fix: ip and mac address regex validation

* fix quoting/escaping, add migration file

Signed-off-by: invario <67800603+invario@users.noreply.github.com>

---------

Signed-off-by: invario <67800603+invario@users.noreply.github.com>
2026-07-23 19:07:39 +02:00
invario 3614f3654b Fix: subnet mask check (#1757) 2026-07-23 19:01:04 +02:00
Maxi Quoß c4cf006832 update deps
https://github.com/pocketbase/pocketbase/releases/tag/v0.39.7
2026-07-16 19:38:09 +02:00
29 changed files with 2009 additions and 702 deletions
+1 -13
View File
@@ -18,21 +18,13 @@
</div>
</div>
> [!NOTE]
>
> #### UpSnap is, and always will be, free and open source software.
>
> If someone is asking you to pay money for access to UpSnap binaries, source code, or licenses, you are being scammed.
>
> The official and only trusted source for UpSnap is this repository (and its linked releases).
> Do not pay third parties for something that is provided here for free.
## ✨ Features
- 🚀 One-Click Device Wake-Up Dashboard
- ⏰ 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)
- ❎️ Shutdown Devices with a Custom Command
- 👤 Secured User Management
- 🌐 i18n support for [these](/frontend/translations) languages
@@ -195,7 +187,3 @@ 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)
-9
View File
@@ -2,15 +2,6 @@ version: 2
release:
draft: false
prerelease: auto
header: |
> [!NOTE]
>
> #### UpSnap is, and always will be, free and open source software.
>
> If someone is asking you to pay money for access to UpSnap binaries, source code, or licenses, you are being scammed.
>
> The official and only trusted source for UpSnap is this repository (and its linked releases).
> Do not pay third parties for something that is provided here for free.
before:
hooks:
- go mod tidy
+16 -3
View File
@@ -1,9 +1,9 @@
package cronjobs
import (
"github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/core"
"github.com/robfig/cron/v3"
"github.com/seriousm4x/upsnap/iptracking"
"github.com/seriousm4x/upsnap/logger"
"github.com/seriousm4x/upsnap/networking"
)
@@ -19,7 +19,7 @@ var (
)))
)
func SetPingJobs(app *pocketbase.PocketBase) {
func SetPingJobs(app core.App) {
// remove existing jobs
for _, job := range CronPing.Entries() {
CronPing.Remove(job.ID)
@@ -103,9 +103,22 @@ func SetPingJobs(app *pocketbase.PocketBase) {
}(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 {
logger.Error.Println("Failed to add ip tracking cronjob:", err)
}
}
}
func SetWakeShutdownJobs(app *pocketbase.PocketBase) {
func SetWakeShutdownJobs(app core.App) {
// remove existing jobs
for _, job := range CronWakeShutdown.Entries() {
CronWakeShutdown.Remove(job.ID)
+15 -15
View File
@@ -1,14 +1,14 @@
module github.com/seriousm4x/upsnap
go 1.26.3
go 1.27
require (
github.com/mdlayher/wol v0.0.0-20220221231636-b763a792253a
github.com/pocketbase/dbx v1.12.0
github.com/pocketbase/pocketbase v0.39.5
github.com/pocketbase/pocketbase v0.40.1
github.com/prometheus-community/pro-bing v0.9.1
github.com/robfig/cron/v3 v3.0.1
golang.org/x/sys v0.46.0
golang.org/x/sys v0.47.0
kernel.org/pub/linux/libs/security/libcap/cap v1.2.78
)
@@ -19,34 +19,34 @@ require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/fatih/color v1.19.0 // indirect
github.com/fsnotify/fsnotify v1.10.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
github.com/ganigeorgiev/fexpr v0.5.0 // indirect
github.com/go-ozzo/ozzo-validation/v4 v4.3.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
github.com/ganigeorgiev/fexpr v0.6.0 // indirect
github.com/go-sql-driver/mysql v1.9.3 // indirect
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/josharian/native v1.1.0 // indirect
github.com/mattn/go-colorable v0.1.15 // indirect
github.com/mattn/go-isatty v0.0.22 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/mdlayher/ethernet v0.0.0-20220221185849-529eae5b6118 // indirect
github.com/mdlayher/packet v1.1.2 // indirect
github.com/mdlayher/socket v0.6.1 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/pocketbase/ozzo-validation/v4 v4.3.0 // 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.53.0 // indirect
golang.org/x/image v0.43.0 // indirect
golang.org/x/net v0.56.0 // indirect
golang.org/x/crypto v0.55.0 // indirect
golang.org/x/image v0.45.0 // indirect
golang.org/x/net v0.58.0 // indirect
golang.org/x/oauth2 v0.36.0 // indirect
golang.org/x/sync v0.21.0 // indirect
golang.org/x/text v0.38.0 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/text v0.41.0 // indirect
kernel.org/pub/linux/libs/security/libcap/psx v1.2.78 // indirect
modernc.org/libc v1.72.3 // indirect
modernc.org/libc v1.74.4 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
modernc.org/sqlite v1.52.0 // indirect
modernc.org/memory v1.12.1 // indirect
modernc.org/sqlite v1.57.0 // indirect
)
+40 -40
View File
@@ -19,12 +19,10 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk
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.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/ganigeorgiev/fexpr v0.5.0 h1:XA9JxtTE/Xm+g/JFI6RfZEHSiQlk+1glLvRK1Lpv/Tk=
github.com/ganigeorgiev/fexpr v0.5.0/go.mod h1:RyGiGqmeXhEQ6+mlGdnUleLHgtzzu/VGO2WtJkF5drE=
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/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/ganigeorgiev/fexpr v0.6.0 h1:Fza3O/QMBKEudUvxV862qe6GjxM60GJjjKytdp+VQus=
github.com/ganigeorgiev/fexpr v0.6.0/go.mod h1:RyGiGqmeXhEQ6+mlGdnUleLHgtzzu/VGO2WtJkF5drE=
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=
@@ -36,8 +34,8 @@ github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
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-20260604005048-7023385849c0 h1:h1QTMDl6q9wDvDCJVpKQSjgleGFYnd2fOxmg2K+6BGE=
github.com/google/pprof v0.0.0-20260604005048-7023385849c0/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI=
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
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/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
@@ -53,8 +51,8 @@ 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.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY=
github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
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/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=
@@ -73,8 +71,10 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pocketbase/dbx v1.12.0 h1:/oLErM+A0b4xI0PWTGPqSDVjzix48PqI/bng2l0PzoA=
github.com/pocketbase/dbx v1.12.0/go.mod h1:xXRCIAKTHMgUCyCKZm55pUOdvFziJjQfXaWKhu2vhMs=
github.com/pocketbase/pocketbase v0.39.5 h1:tAqVi6/SfSXw4DwJZ6S6zaYlfdMDZG2t3sNc3f1xR+Q=
github.com/pocketbase/pocketbase v0.39.5/go.mod h1:o/iskDiVCrYFC04uTBpMrwgZm07UCIOkuw1QP/oXOp0=
github.com/pocketbase/ozzo-validation/v4 v4.3.0 h1:uKBDVma7bZqgR2a6AwE+k9hkuDFfiZMpBHQdZ1z3iQs=
github.com/pocketbase/ozzo-validation/v4 v4.3.0/go.mod h1:6XNjSTw/Jb2F8LOkKO3oyzIWExbrGiYoS4uVxVwz90g=
github.com/pocketbase/pocketbase v0.40.1 h1:JS+Kr75bY67IPKhKgcIypn2kKc0Zd4yDGAZ4nkhuQEc=
github.com/pocketbase/pocketbase v0.40.1/go.mod h1:++Krwfbk+s2qtFerpHlWVEl8FO7J7rRQ6/MMtS9LGOo=
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/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
@@ -97,36 +97,36 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
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=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.43.0 h1:FLxcP4ec2350nTfOC8ysKtqYSIFbk/QGjw1ZHNP4tsY=
golang.org/x/image v0.43.0/go.mod h1:rrpelvGFt+kLPAjPM4HeWPgrl0FtafueU//e5N0qk/Q=
golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4=
golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ=
golang.org/x/image v0.45.0 h1:FMb1nTbH5H9vF55SriQHgFw5GnNL9Jg6L25BwXKzhB0=
golang.org/x/image v0.45.0/go.mod h1:n62x/7RqlwXDvGsSU4u6IUTUf6KghUZ9Bt7cG/T9Fx4=
golang.org/x/mod v0.40.0 h1:hUv+3cXcdRHz08UmSiOob7sadHig73uo5bkXxQ/tvUs=
golang.org/x/mod v0.40.0/go.mod h1:0/weTWkPWGBikyTWAX3dkjVztMmBA5hM0DH6BElSupE=
golang.org/x/net v0.0.0-20190313220215-9f648a60d977/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.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/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-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.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
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.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8=
golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0=
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
@@ -137,30 +137,30 @@ kernel.org/pub/linux/libs/security/libcap/cap v1.2.78 h1:jgqg4gyu2BaYW9L6uzEtGLf
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.28.2 h1:3tQ0lf2ADtoby2EtSP+J7IE2SHwEJdP8ioR59wx7XpY=
modernc.org/cc/v4 v4.28.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.34.0 h1:yRLPFZieg532OT4rp4JFNIVcquwalMX26G95WQDqwCQ=
modernc.org/ccgo/v4 v4.34.0/go.mod h1:AS5WYMyBakQ+fhsHhtP8mWB82KTGPkNNJDGfGQCe0/A=
modernc.org/cc/v4 v4.29.1 h1:MKgdCV3WykTSPqpVrnxdEDS0HEd2FHpKZDzxzU5LyeI=
modernc.org/cc/v4 v4.29.1/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU=
modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk=
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.2 h1:ZtDCnhonXSZexk/AYsegNRV1lJGgaNZJuKjJSWKyEqo=
modernc.org/gc/v3 v3.1.2/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI=
modernc.org/gc/v3 v3.1.4/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.72.3 h1:ZnDF4tXn4NBXFutMMQC4vtbTFSXhhKzR73fv0beZEAU=
modernc.org/libc v1.72.3/go.mod h1:dn0dZNnnn1clLyvRxLxYExxiKRZIRENOfqQ8XEeg4Qs=
modernc.org/libc v1.74.4 h1:fX1Omw4o2/1C2iRkkIsrQTasJQldLhRmuPreXLoWs9k=
modernc.org/libc v1.74.4/go.mod h1:eeQAS9W3sZeKYMFubydxJpII9ybHWshk+7or7bLG9co=
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.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
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.52.0 h1:p4dhYh2tXZCiyaqHwRVJDjIGKWyXayiQpThxgDzJaxo=
modernc.org/sqlite v1.52.0/go.mod h1:tcNzv5p84E0skkmJn038y+hWJbLQXQqEnQfeh5r2JLM=
modernc.org/sqlite v1.57.0 h1:qNQP6xnx5M0ISNtlnxoOX0+cD5bJ0/gr9aMmndFczzg=
modernc.org/sqlite v1.57.0/go.mod h1:yCJ2cmAaIkHQ25oXWrF8H4O1lIfPYPR26yCEDj2P3pQ=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
+132
View File
@@ -0,0 +1,132 @@
// 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"
"github.com/pocketbase/pocketbase/core"
"github.com/seriousm4x/upsnap/logger"
"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) {
// 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 {
logger.Error.Println(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 {
logger.Error.Println("Ip tracking for", device.GetString("name")+":", err)
continue
}
if networking.ValidateScannableSubnet(subnet) != nil {
continue
}
subnets[subnet.String()] = subnet
}
for cidr, subnet := range subnets {
if err := TrackOneSubnet(app, subnet); err != nil {
logger.Error.Println("Ip tracking scan for", cidr+":", 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 {
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
}
logger.Info.Println("Ip tracking: updating", device.GetString("name"), "from", device.GetString("ip"), "to", newIp)
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 {
logger.Error.Println("Failed to save record:", err)
}
}
return nil
}
+347
View File
@@ -0,0 +1,347 @@
package iptracking
import (
"encoding/xml"
"fmt"
"net"
"strings"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.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)
}
}
}
@@ -0,0 +1,62 @@
package migrations
import (
"github.com/pocketbase/pocketbase/core"
m "github.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)
})
}
@@ -0,0 +1,62 @@
package migrations
import (
"github.com/pocketbase/pocketbase/core"
m "github.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)
})
}
@@ -0,0 +1,40 @@
package migrations
import (
"github.com/pocketbase/pocketbase/core"
m "github.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)
})
}
@@ -0,0 +1,45 @@
package migrations
import (
"github.com/pocketbase/pocketbase/core"
m "github.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)
})
}
+2 -3
View File
@@ -61,7 +61,7 @@ func wakeUDP(broadcastIp string, deviceIp string, target net.HardwareAddr, passw
// send direct to device via port 9 (for routed network WOL)
fmt.Sprintf("%s:9", deviceIp),
// send direct to device via alternative port 7 (for routed network WOL)
fmt.Sprintf("%s:7", deviceIp),
fmt.Sprintf("%s:7", deviceIp),
}
for _, dest := range destinations {
@@ -88,8 +88,7 @@ func getBroadcastIp(ipStr, maskStr string) (string, error) {
return "", errors.New("subnet mask not a valid ipv4 address")
}
mask = mask.To4()
ip = ip.To4()
if ip == nil {
if mask == nil {
return "", errors.New("subnet mask not a valid ipv4 address")
}
+1 -2
View File
@@ -25,8 +25,7 @@ func CheckPort(host string, port string) (bool, error) {
conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, port), timeout)
if err != nil {
// treat "host unreachable", "connection refused" and "timeout" as no error
var netErr *net.OpError
if errors.As(err, &netErr) {
if netErr, ok := errors.AsType[*net.OpError](err); ok {
if errors.Is(netErr.Err, syscall.EHOSTUNREACH) ||
errors.Is(netErr.Err, syscall.ECONNREFUSED) ||
netErr.Timeout() {
+65
View File
@@ -0,0 +1,65 @@
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
@@ -0,0 +1,41 @@
//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
@@ -0,0 +1,7 @@
//go:build !linux
package networking
func NmapScan(scanRange string) (Nmaprun, error) {
return runNmap(scanRange)
}
+65
View File
@@ -0,0 +1,65 @@
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)
}
}
+59
View File
@@ -0,0 +1,59 @@
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
@@ -0,0 +1,146 @@
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)
}
})
}
}
+69 -8
View File
@@ -3,9 +3,12 @@ package pb
import (
"fmt"
"io/fs"
"net"
"os"
"path"
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
@@ -13,6 +16,7 @@ import (
"github.com/pocketbase/pocketbase/plugins/migratecmd"
"github.com/robfig/cron/v3"
"github.com/seriousm4x/upsnap/cronjobs"
"github.com/seriousm4x/upsnap/iptracking"
"github.com/seriousm4x/upsnap/logger"
_ "github.com/seriousm4x/upsnap/migrations"
)
@@ -138,7 +142,7 @@ func StartPocketBase(distDirFS fs.FS) {
return se.Next()
})
app.OnModelAfterCreateSuccess().BindFunc(func(e *core.ModelEvent) error {
app.OnModelAfterCreateSuccess("_superusers", "devices").BindFunc(func(e *core.ModelEvent) error {
if e.Model.TableName() == "_superusers" {
// when pocketbase creates it's default superuser, do not trigger setSetupCompleted()
if e.Model.(*core.Record).Email() == core.DefaultInstallerEmail {
@@ -174,16 +178,73 @@ func StartPocketBase(distDirFS fs.FS) {
return e.Next()
})
app.OnModelAfterDeleteSuccess().BindFunc(func(e *core.ModelEvent) error {
if e.Model.TableName() == "_superusers" {
if err := setSetupCompleted(e.App); err != nil {
logger.Error.Println(err)
return err
app.OnModelAfterDeleteSuccess("_superusers").BindFunc(func(e *core.ModelEvent) error {
if err := setSetupCompleted(e.App); err != nil {
logger.Error.Println(err)
return err
}
return e.Next()
})
app.OnRecordValidate("devices").BindFunc(func(e *core.RecordEvent) error {
ip := net.ParseIP(e.Record.GetString("netmask"))
if ip == nil {
logger.Warning.Println("device", e.Record.GetString("name"), "does not contain a valid netmask! Will be set to 255.255.255.255")
e.Record.Set("netmask", "255.255.255.255")
saveErr := e.App.Save(e.Record)
if saveErr != nil {
return saveErr
}
}
return e.Next()
})
app.OnRealtimeConnectRequest().BindFunc(func(e *core.RealtimeConnectRequestEvent) error {
// a client just became active: catch up on any tracking sweep that
// was skipped while nobody was connected
settings, err := e.App.FindFirstRecordByFilter("settings_private", "")
if err != nil {
logger.Error.Println(err)
} else if settings.GetBool("lazy_ping") && settings.GetString("track_ip_interval") != "" {
go iptracking.CatchUpSweep(e.App)
}
return e.Next()
})
app.OnRealtimeConnectRequest().BindFunc(func(e *core.RealtimeConnectRequestEvent) error {
// PocketBase has no realtime disconnect hook. When a browser refreshes,
// the old client may disappear before the new connection is registered.
// Delay the offline transition and use the connecting client's id to
// distinguish a refresh from a genuine disconnect.
clientID := e.Client.Id()
defer func() {
if len(e.App.SubscriptionsBroker().Clients()) != 0 {
return
}
time.AfterFunc(2*time.Second, func() {
if _, err := e.App.SubscriptionsBroker().ClientById(clientID); err == nil {
return
}
if len(e.App.SubscriptionsBroker().Clients()) != 0 {
return
}
allDevices, err := app.FindAllRecords("devices", dbx.NewExp("shutdown_cmd != ''"))
if err != nil {
logger.Error.Println(err)
return
}
for _, device := range allDevices {
device.Set("status", "offline")
if err := app.Save(device); err != nil {
logger.Error.Println(err)
return
}
}
})
}()
return e.Next()
})
app.OnTerminate().BindFunc(func(e *core.TerminateEvent) error {
cronjobs.StopAll()
return e.Next()
@@ -209,7 +270,7 @@ func StartPocketBase(distDirFS fs.FS) {
}
func importSettings(app *pocketbase.PocketBase) error {
func importSettings(app core.App) error {
settingsPrivateRecords, err := app.FindAllRecords("settings_private")
if err != nil {
return err
@@ -288,7 +349,7 @@ func importSettings(app *pocketbase.PocketBase) error {
return nil
}
func resetDeviceStates(app *pocketbase.PocketBase) error {
func resetDeviceStates(app core.App) error {
devices, err := app.FindAllRecords("devices")
if err != nil {
return err
+1 -1
View File
@@ -1,7 +1,7 @@
services:
upsnap:
cap_add:
- NET_RAW # NET_RAW is required for privileged ping and network device scan (nmap)
- NET_RAW # NET_RAW is required for privileged ping, network device scan and ip address tracking (nmap)
cap_drop:
- ALL
container_name: upsnap
+19 -19
View File
@@ -17,27 +17,27 @@
"devDependencies": {
"@eslint/compat": "^2.1.0",
"@eslint/js": "^10.0.1",
"@inlang/cli": "^3.1.14",
"@inlang/paraglide-js": "2.18.1",
"@inlang/cli": "^3.3.3",
"@inlang/paraglide-js": "^2.24.1",
"@sveltejs/adapter-static": "^3.0.10",
"@sveltejs/kit": "^2.69.0",
"@sveltejs/vite-plugin-svelte": "^7.1.2",
"daisyui": "^5.6.10",
"eslint": "^10.6.0",
"@sveltejs/kit": "^2.70.3",
"@sveltejs/vite-plugin-svelte": "^7.3.0",
"daisyui": "^5.7.22",
"eslint": "^10.9.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-svelte": "^3.20.0",
"globals": "^17.7.0",
"eslint-plugin-svelte": "^3.23.0",
"globals": "^17.11.0",
"husky": "^9.1.7",
"prettier": "^3.9.4",
"prettier": "^3.9.6",
"prettier-plugin-svelte": "^4.1.1",
"prettier-plugin-tailwindcss": "^0.8.0",
"svelte": "^5.56.4",
"svelte-check": "^4.7.1",
"tailwindcss": "^4.3.2",
"prettier-plugin-tailwindcss": "^0.8.1",
"svelte": "^5.56.10",
"svelte-check": "^4.7.6",
"tailwindcss": "^4.3.3",
"tslib": "^2.8.1",
"typescript": "^6.0.3",
"typescript-eslint": "^8.62.1",
"vite": "^8.1.3"
"typescript-eslint": "^8.68.0",
"vite": "^8.2.2"
},
"type": "module",
"lint-staged": {
@@ -45,11 +45,11 @@
"*.{js,css,md,svelte,scss}": "prettier --write --cache --cache-strategy content --ignore-path ../.gitignore ."
},
"dependencies": {
"@fortawesome/free-solid-svg-icons": "^7.3.0",
"@tailwindcss/vite": "^4.3.2",
"cron-parser": "^5.6.1",
"@fortawesome/free-solid-svg-icons": "^7.3.1",
"@tailwindcss/vite": "^4.3.3",
"cron-parser": "^5.10.0",
"date-fns": "^4.4.0",
"pocketbase": "^0.27.0",
"pocketbase": "^0.28.0",
"svelte-fa": "^4.0.4",
"svelte-french-toast": "github:seriousm4x/svelte-french-toast#fix-72-build",
"theme-change": "^2.5.2"
+698 -584
View File
File diff suppressed because it is too large Load Diff
+21 -2
View File
@@ -5,6 +5,7 @@
import { nextCronDate, parseCron as validateCron } from '$lib/helpers/cron';
import { m } from '$lib/paraglide/messages';
import { permission, pocketbase } from '$lib/stores/pocketbase';
import { settingsPriv } from '$lib/stores/settings';
import type { Device, Group, Port } from '$lib/types/device';
import { faSave, faTrash, faX } from '@fortawesome/free-solid-svg-icons';
import { onMount } from 'svelte';
@@ -21,6 +22,10 @@
await getGroups();
});
const ipPattern =
'^(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}$';
const macPattern = '^([0-9A-Fa-f]{2}[:\\-]){5}([0-9A-Fa-f]{2})$';
async function save() {
// validate crons
if (device.wake_cron_enabled && !(await validateCron(device.wake_cron))) {
@@ -225,7 +230,7 @@
type="text"
placeholder={m.device_general_ip()}
class="input"
pattern="^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b)\{4}$"
pattern={ipPattern}
bind:value={device.ip}
required
/>
@@ -238,7 +243,7 @@
type="text"
placeholder={m.device_general_mac()}
class="input"
pattern="^([0-9\A-Fa-f]{2}[:-]){5}([0-9\A-Fa-f]{2})$"
pattern={macPattern}
bind:value={device.mac}
required
/>
@@ -251,6 +256,7 @@
type="text"
placeholder={m.device_general_netmask()}
class="input"
pattern={ipPattern}
bind:value={device.netmask}
required
/>
@@ -269,6 +275,19 @@
</fieldset>
<span class="badge text-error self-center">* {m.device_general_required_field()}</span>
</div>
<fieldset class="fieldset bg-base-100 border-base-300 rounded-box mt-2 w-fit border p-4">
<legend class="fieldset-legend">{m.device_general_track_ip()}</legend>
<label class="fieldset-label">
<input
type="checkbox"
bind:checked={device.track_ip}
class="toggle toggle-success"
disabled={$settingsPriv?.track_ip_interval === ''}
/>
{m.device_general_track_ip()}
</label>
<p class="fieldset-label max-w-md">{m.device_general_track_ip_desc()}</p>
</fieldset>
</div>
</div>
<div class="card bg-base-200 mt-6 w-full shadow-sm">
+1
View File
@@ -5,6 +5,7 @@ export type Device = RecordModel & {
ip: string;
mac: string;
netmask: string;
track_ip: boolean;
description: string;
status: 'pending' | 'online' | 'offline' | '';
ports: string[];
+1
View File
@@ -11,4 +11,5 @@ export type SettingsPrivate = RecordModel & {
interval: string;
lazy_ping: boolean;
scan_range: string;
track_ip_interval: string;
};
+17 -2
View File
@@ -7,9 +7,9 @@
import { m } from '$lib/paraglide/messages.js';
import { localeStore } from '$lib/stores/locale';
import { backendUrl, permission, pocketbase } from '$lib/stores/pocketbase';
import { settingsPub } from '$lib/stores/settings';
import { settingsPriv, settingsPub } from '$lib/stores/settings';
import type { Permission } from '$lib/types/permission';
import type { SettingsPublic } from '$lib/types/settings';
import type { SettingsPrivate, SettingsPublic } from '$lib/types/settings';
import { onMount } from 'svelte';
import toast, { Toaster, type ToastOptions } from 'svelte-french-toast';
import '../app.css';
@@ -79,6 +79,13 @@
await $pocketbase
.collection('_superusers')
.authRefresh()
.then(async () => {
// set settingsPriv store on load
if (!$settingsPriv) {
const res = await $pocketbase.collection('settings_private').getFirstListItem('');
settingsPriv.set(res as SettingsPrivate);
}
})
.catch((err) => {
// clear the store only on invalidated/expired token
const status = err?.status << 0;
@@ -93,6 +100,14 @@
await $pocketbase
.collection('users')
.authRefresh()
.then(async () => {
// set settingsPriv store on load
if (!$settingsPriv) {
const res = await $pocketbase.collection('settings_private').getFirstListItem('');
settingsPriv.set(res as SettingsPrivate);
}
})
.catch((err) => {
// clear the store only on invalidated/expired token
const status = err?.status << 0;
+31
View File
@@ -72,6 +72,14 @@
throw new Error('ping_interval not valid');
}
if (
settingsPrivClone.track_ip_interval !== '' &&
!(await parseCron(settingsPrivClone.track_ip_interval))
) {
toast.error(m.settings_invalid_cron());
throw new Error('track_ip_interval not valid');
}
await $pocketbase
.collection('settings_public')
.update(settingsPubClone.id, settingsPubClone)
@@ -153,6 +161,29 @@
| minute (0–59)
second (0–59, optional)
</code></pre>
<h2 class="card-title mt-2">{m.settings_track_ip_title()}</h2>
<p class="mt-2">
{m.settings_track_ip_desc()}
</p>
<div class="mt-2 w-full">
<input
type="text"
placeholder="e.g. '0 */30 * * * *'"
class="input"
bind:value={settingsPrivClone.track_ip_interval}
/>
</div>
{#if settingsPrivClone.track_ip_interval}
<p class="fieldset-label">
{#await parseCron(settingsPrivClone.track_ip_interval)}
<span class="loading loading-spinner loading-xs"></span>
{:then valid}
{valid
? '✅ ' + nextCronDate(settingsPrivClone.track_ip_interval)
: m.settings_invalid_cron()}
{/await}
</p>
{/if}
<h2 class="card-title mt-2">{m.settings_lazy_ping_title()}</h2>
<p class="mt-2">
{m.settings_lazy_ping_desc()}
+5 -1
View File
@@ -40,6 +40,8 @@
"device_general_name": "Name",
"device_general_netmask": "Netmask",
"device_general_required_field": "required field",
"device_general_track_ip": "Track IP address",
"device_general_track_ip_desc": "Updates this device's IP address automatically whenever the periodic network scan finds its MAC address at a different IP. Requires the 'IP address tracking' interval to be set in the settings and only works on subnets UpSnap is directly attached to.",
"device_groups": "Groups",
"device_groups_desc": "You can add devices to a group to have them sorted by group on the dashboard.",
"device_groups_placeholder": "e.g. 'Basement' or 'Office'",
@@ -133,13 +135,15 @@
"settings_icon_desc": "Set a custom favicon. Supported file types are:",
"settings_icon_title": "Icon",
"settings_invalid_cron": "❌ Invalid cron syntax",
"settings_lazy_ping_desc": "When lazy ping is turned on, UpSnap will only ping devices if there is an active user visiting the website. If it's turned off, UpSnap will always ping devices.",
"settings_lazy_ping_desc": "When lazy ping is turned on, UpSnap will only ping devices and run IP tracking scans while a user has the website open. If it's turned off, UpSnap always pings and scans.",
"settings_lazy_ping_enable": "Enable",
"settings_lazy_ping_title": "Lazy ping",
"settings_page_title": "Settings",
"settings_ping_interval_desc1": "Sets the interval in which the devices are pinged. Leave blank to use default value of <span class=\"badge\">*/3 * * * * *</span>.",
"settings_ping_interval_desc2": "Learn more about the correct syntax for cron on <a class=\"link\" href=\"https://en.wikipedia.org/wiki/Cron\" target=\"_blank\">Wikipedia</a> or refer to the <a class=\"link\" href=\"https://github.com/harrisiirak/cron-parser\" target=\"_blank\">package documentation</a>.",
"settings_ping_interval_title": "Ping interval",
"settings_track_ip_desc": "Cron interval at which UpSnap scans the local subnets of devices with 'Track IP address' enabled and updates their IP address if their MAC address is found at a different one. Every 15-60 minutes is plenty; short intervals broadcast-scan your network aggressively, which can be especially bad on wider subnets. Leave empty to disable. Requires nmap, same as the network scan.",
"settings_track_ip_title": "IP address tracking",
"settings_upsnap_version": "UpSnap version",
"settings_website_title_desc": "Sets the title of the website and in the browser tab.",
"settings_website_title_title": "Website title",