LAN-Orangutan is a self-hosted network discovery tool. Find every device on your LAN, label and group them, snapshot your network and compare it later, and get flagged when something unexpected shows up. Single binary, no setup, Tailscale built in. Built by 291 Group.
Go clidevice-discoverygolanghomelabinternet-of-thingslannetwork-discoverynetwork-monitoringnetwork-monitoring-toolnetwork-scannernetworkingnmapsecurityself-hostedselfhostedtailscaletailscale-networkweb-dashboard
feat(device): support editing and manually assigning device types
Adam Maguedfa3dc9314c65
diff --git a/internal/api/api.go b/internal/api/api.goindex 0a469f0..4e4f02f 100644--- a/internal/api/api.go+++ b/internal/api/api.go@@ -213,11 +213,13 @@ func (h *Handler) handleDevice(w http.ResponseWriter, r *http.Request) {case http.MethodPost:var req struct {- IP string `json:"ip"`- Label *string `json:"label"`- Notes *string `json:"notes"`- Group *string `json:"group"`- Expected *bool `json:"expected"`+ IP string `json:"ip"`+ Label *string `json:"label"`+ Notes *string `json:"notes"`+ Group *string `json:"group"`+ Expected *bool `json:"expected"`+ Type *string `json:"type"`+ CustomType *bool `json:"custom_type"`}if err := json.NewDecoder(r.Body).Decode(&req); err != nil {h.error(w, http.StatusBadRequest, "invalid JSON")@@ -234,8 +236,21 @@ func (h *Handler) handleDevice(w http.ResponseWriter, r *http.Request) {return}- if err := h.store.UpdateDeviceFields(ip, req.Label, req.Notes, req.Group, req.Expected); err != nil {- h.error(w, http.StatusNotFound, err.Error())+ if req.Type != nil {+ cleanType, err := scanner.ValidateType(*req.Type)+ if err != nil {+ h.error(w, http.StatusBadRequest, err.Error())+ return+ }+ req.Type = &cleanType+ }++ if err := h.store.UpdateDeviceFields(ip, req.Label, req.Notes, req.Group, req.Expected, req.Type, req.CustomType); err != nil {+ if strings.Contains(err.Error(), "device not found") {+ h.error(w, http.StatusNotFound, err.Error())+ } else {+ h.error(w, http.StatusBadRequest, err.Error())+ }return}h.success(w, map[string]string{"message": "device updated"})diff --git a/internal/api/api_test.go b/internal/api/api_test.gonew file mode 100644index 0000000..ae01a92--- /dev/null+++ b/internal/api/api_test.go@@ -0,0 +1,177 @@+package api++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "path/filepath"+ "testing"++ "github.com/291-Group/LAN-Orangutan/internal/config"+ "github.com/291-Group/LAN-Orangutan/internal/storage"+ "github.com/291-Group/LAN-Orangutan/internal/types"+)++func newTestAPI(t *testing.T) (*Handler, *storage.Storage) {+ t.Helper()+ dir := t.TempDir()+ store, err := storage.New(filepath.Join(dir, "devices.json"), filepath.Join(dir, "state.json"))+ if err != nil {+ t.Fatalf("storage.New: %v", err)+ }+ cfg := config.Default()+ h := NewHandler(store, cfg)+ return h, store+}++func TestAPIGetDevice(t *testing.T) {+ h, store := newTestAPI(t)++ if err := store.MergeDevices([]types.Device{+ {IP: "192.168.1.100", Hostname: "test-dev", Type: "Computer"},+ }); err != nil {+ t.Fatal(err)+ }++ req := httptest.NewRequest(http.MethodGet, "/api/device?ip=192.168.1.100", nil)+ rec := httptest.NewRecorder()+ h.ServeHTTP(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d", rec.Code)+ }++ var resp types.APIResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {+ t.Fatal(err)+ }+ if !resp.Success {+ t.Fatalf("expected success, got %v", resp.Error)+ }+}++func TestAPIPostDevice_CustomType(t *testing.T) {+ h, store := newTestAPI(t)++ if err := store.MergeDevices([]types.Device{+ {IP: "192.168.1.101", Hostname: "plug", Type: "Router"},+ }); err != nil {+ t.Fatal(err)+ }++ // Update device with custom type from supported taxonomy+ body := []byte(`{"ip":"192.168.1.101","label":"Smart Plug 1","type":"IoT","custom_type":true}`)+ req := httptest.NewRequest(http.MethodPost, "/api/device", bytes.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ rec := httptest.NewRecorder()+ h.ServeHTTP(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())+ }++ dev := store.GetDevice("192.168.1.101")+ if dev == nil {+ t.Fatal("device missing")+ }+ if dev.Label != "Smart Plug 1" {+ t.Errorf("expected label 'Smart Plug 1', got %q", dev.Label)+ }+ if dev.Type != "IoT" {+ t.Errorf("expected Type 'IoT', got %q", dev.Type)+ }+ if !dev.CustomType {+ t.Errorf("expected CustomType true, got %v", dev.CustomType)+ }++ // Rescan should not overwrite custom type+ if err := store.MergeDevices([]types.Device{+ {IP: "192.168.1.101", Hostname: "plug", Type: "Router"},+ }); err != nil {+ t.Fatal(err)+ }+ dev = store.GetDevice("192.168.1.101")+ if dev.Type != "IoT" {+ t.Errorf("rescan overwrote custom type; got %q", dev.Type)+ }+}++func TestAPIPostDevice_InvalidType_Rejected(t *testing.T) {+ h, store := newTestAPI(t)++ if err := store.MergeDevices([]types.Device{+ {IP: "192.168.1.102", Hostname: "outlet"},+ }); err != nil {+ t.Fatal(err)+ }++ // Unsupported arbitrary type should be rejected with HTTP 400+ body := []byte(`{"ip":"192.168.1.102","type":"Smart Outlet","custom_type":true}`)+ req := httptest.NewRequest(http.MethodPost, "/api/device", bytes.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ rec := httptest.NewRecorder()+ h.ServeHTTP(rec, req)++ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 Bad Request, got %d: %s", rec.Code, rec.Body.String())+ }++ dev := store.GetDevice("192.168.1.102")+ if dev.Type != "" || dev.CustomType {+ t.Errorf("expected type to remain untouched, got type=%q custom=%v", dev.Type, dev.CustomType)+ }+}++func TestAPIPostDevice_TypeTooLong_Rejected(t *testing.T) {+ h, store := newTestAPI(t)++ if err := store.MergeDevices([]types.Device{+ {IP: "192.168.1.104", Hostname: "device"},+ }); err != nil {+ t.Fatal(err)+ }++ tooLong := "ThisDeviceTypeStringIsWayTooLongToBeValid"+ body := []byte(`{"ip":"192.168.1.104","type":"` + tooLong + `"}`)+ req := httptest.NewRequest(http.MethodPost, "/api/device", bytes.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ rec := httptest.NewRecorder()+ h.ServeHTTP(rec, req)++ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 Bad Request, got %d: %s", rec.Code, rec.Body.String())+ }+}++func TestAPIPostDevice_ResetType(t *testing.T) {+ h, store := newTestAPI(t)++ if err := store.MergeDevices([]types.Device{+ {IP: "192.168.1.103", Hostname: "mybox", Type: "Computer"},+ }); err != nil {+ t.Fatal(err)+ }++ // Mark as custom first+ customType := "Server"+ if err := store.UpdateDeviceFields("192.168.1.103", nil, nil, nil, nil, &customType, nil); err != nil {+ t.Fatal(err)+ }++ // Reset via API+ body := []byte(`{"ip":"192.168.1.103","type":"","custom_type":false}`)+ req := httptest.NewRequest(http.MethodPost, "/api/device", bytes.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ rec := httptest.NewRecorder()+ h.ServeHTTP(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())+ }++ dev := store.GetDevice("192.168.1.103")+ if dev.Type != "" || dev.CustomType {+ t.Errorf("expected cleared type and custom_type false, got type=%q custom=%v", dev.Type, dev.CustomType)+ }+}diff --git a/internal/cli/list.go b/internal/cli/list.goindex 40fe127..b29cf2a 100644--- a/internal/cli/list.go+++ b/internal/cli/list.go@@ -20,13 +20,14 @@ var (listOnline boollistOffline boollistGroup string+ listType stringlistFormat string)var listCmd = &cobra.Command{Use: "list",Short: "List discovered devices",- Long: `List all discovered devices with optional filtering by status or group.`,+ Long: `List all discovered devices with optional filtering by status, group, or type.`,RunE: runList,}@@ -34,6 +35,7 @@ func init() {listCmd.Flags().BoolVar(&listOnline, "online", false, "Show only online devices")listCmd.Flags().BoolVar(&listOffline, "offline", false, "Show only offline devices")listCmd.Flags().StringVar(&listGroup, "group", "", "Filter by group")+ listCmd.Flags().StringVar(&listType, "type", "", "Filter by device type")listCmd.Flags().StringVar(&listFormat, "format", "table", "Output format (table, csv, json)")}@@ -59,6 +61,9 @@ func runList(cmd *cobra.Command, args []string) error {if listGroup != "" && !strings.EqualFold(d.Group, listGroup) {continue}+ if listType != "" && !strings.EqualFold(d.Type, listType) {+ continue+ }filtered = append(filtered, d)}diff --git a/internal/scanner/classify.go b/internal/scanner/classify.goindex 69bc1c5..6f23cba 100644--- a/internal/scanner/classify.go+++ b/internal/scanner/classify.go@@ -1,6 +1,10 @@package scanner-import "strings"+import (+ "fmt"+ "strings"+ "unicode"+)// Device type labels produced by Classify. They are stable strings so stored// records, the API and the UI can all rely on them. TypeUnknown is the empty@@ -18,6 +22,57 @@ const (TypeUnknown = "")+// KnownTypes lists the standard built-in device types.+var KnownTypes = []string{+ TypePhone,+ TypeComputer,+ TypePrinter,+ TypeTV,+ TypeMediaPlayer,+ TypeRouter,+ TypeServer,+ TypeIoT,+ TypeConsole,+}++// MaxTypeLen bounds the length of a device type string.+const MaxTypeLen = 32++// IsKnownType reports whether t is one of the built-in classification types.+func IsKnownType(t string) bool {+ for _, k := range KnownTypes {+ if k == t {+ return true+ }+ }+ return false+}++// ValidateType checks whether t is a valid device type string.+// An empty string is valid and represents an unclassified / auto-detected device.+// Non-empty strings must match one of the 9 built-in taxonomy types (case-insensitively).+// Returns the canonical casing of the matched type, or an error if invalid or too long.+func ValidateType(t string) (string, error) {+ for _, r := range t {+ if unicode.IsControl(r) {+ return "", fmt.Errorf("device type cannot contain control characters")+ }+ }+ t = strings.TrimSpace(t)+ if t == "" {+ return "", nil+ }+ if len([]rune(t)) > MaxTypeLen {+ return "", fmt.Errorf("device type cannot be longer than %d characters", MaxTypeLen)+ }+ for _, k := range KnownTypes {+ if strings.EqualFold(t, k) {+ return k, nil+ }+ }+ return "", fmt.Errorf("invalid device type %q: must be one of %s", t, strings.Join(KnownTypes, ", "))+}+// Classify infers a device's type from the signals a scan gathers: its vendor// (from the MAC OUI), its hostname, and, when service detection is enabled, the// open ports found. It returns one of the Type* labels, or TypeUnknown whendiff --git a/internal/scanner/classify_test.go b/internal/scanner/classify_test.goindex 1f49d99..044ca6c 100644--- a/internal/scanner/classify_test.go+++ b/internal/scanner/classify_test.go@@ -64,3 +64,100 @@ func TestClassify(t *testing.T) {})}}++func TestKnownTypes(t *testing.T) {+ if len(KnownTypes) != 9 {+ t.Fatalf("expected 9 standard types, got %d: %v", len(KnownTypes), KnownTypes)+ }+ expected := []string{+ TypePhone, TypeComputer, TypePrinter, TypeTV,+ TypeMediaPlayer, TypeRouter, TypeServer, TypeIoT, TypeConsole,+ }+ for i, exp := range expected {+ if KnownTypes[i] != exp {+ t.Errorf("expected KnownTypes[%d] == %q, got %q", i, exp, KnownTypes[i])+ }+ }+}++func TestIsKnownType(t *testing.T) {+ for _, kt := range KnownTypes {+ if !IsKnownType(kt) {+ t.Errorf("expected IsKnownType(%q) to be true", kt)+ }+ }+ for _, unknown := range []string{"Smart Plug", "Thermostat", "Unknown", "", "Custom"} {+ if IsKnownType(unknown) {+ t.Errorf("expected IsKnownType(%q) to be false", unknown)+ }+ }+}++func TestValidateType(t *testing.T) {+ // Empty string is valid (auto / reset)+ got, err := ValidateType("")+ if err != nil || got != "" {+ t.Fatalf("ValidateType(\"\") = (%q, %v), want (\"\", nil)", got, err)+ }++ // Whitespace only is treated as empty+ got, err = ValidateType(" ")+ if err != nil || got != "" {+ t.Fatalf("ValidateType(\" \") = (%q, %v), want (\"\", nil)", got, err)+ }++ // Canonical types match and return normalized+ for _, kt := range KnownTypes {+ got, err := ValidateType(kt)+ if err != nil || got != kt {+ t.Errorf("ValidateType(%q) = (%q, %v), want (%q, nil)", kt, got, err, kt)+ }+ }++ // Case-insensitive and trimmed matches+ cases := []struct {+ input string+ want string+ }{+ {"phone", "Phone"},+ {"COMPUTER", "Computer"},+ {" server ", "Server"},+ {"media player", "Media Player"},+ {"game console", "Game Console"},+ {"IoT", "IoT"},+ {"iot", "IoT"},+ }+ for _, c := range cases {+ got, err := ValidateType(c.input)+ if err != nil || got != c.want {+ t.Errorf("ValidateType(%q) = (%q, %v), want (%q, nil)", c.input, got, err, c.want)+ }+ }++ // Invalid / unknown types rejected+ invalids := []string{+ "Smart Plug",+ "Outlet",+ "Thermostat",+ "Random",+ "FooBar",+ }+ for _, inv := range invalids {+ if _, err := ValidateType(inv); err == nil {+ t.Errorf("expected ValidateType(%q) to fail", inv)+ }+ }++ // Length cap exceeded (> 32 characters)+ tooLong := "ThisDeviceTypeStringIsWayTooLongToBeValid"+ if _, err := ValidateType(tooLong); err == nil {+ t.Errorf("expected error for type exceeding maxTypeLen, got nil")+ }++ // Control characters rejected+ control := "Server\x00"+ if _, err := ValidateType(control); err == nil {+ t.Errorf("expected error for control character in type, got nil")+ }+}+diff --git a/internal/storage/address_history_test.go b/internal/storage/address_history_test.goindex ac4e288..0070d90 100644--- a/internal/storage/address_history_test.go+++ b/internal/storage/address_history_test.go@@ -18,7 +18,7 @@ func TestDeviceMovingIPIsTrackedByMAC(t *testing.T) {}); err != nil {t.Fatal(err)}- if err := s.UpdateDeviceFields("192.168.1.10", strptr("File Server"), strptr("rack 1"), strptr("Infra"), nil); err != nil {+ if err := s.UpdateDeviceFields("192.168.1.10", strptr("File Server"), strptr("rack 1"), strptr("Infra"), nil, nil, nil); err != nil {t.Fatal(err)}diff --git a/internal/storage/device_type_test.go b/internal/storage/device_type_test.gonew file mode 100644index 0000000..ac9647f--- /dev/null+++ b/internal/storage/device_type_test.go@@ -0,0 +1,349 @@+package storage++import (+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/291-Group/LAN-Orangutan/internal/scanner"+ "github.com/291-Group/LAN-Orangutan/internal/types"+)++func TestUpdateDeviceFields_CustomType(t *testing.T) {+ s := newTestStorage(t)++ // Create initial device with auto-detected type+ if err := s.MergeDevices([]types.Device{+ {IP: "192.168.1.50", MAC: "50:c7:bf:11:22:33", Hostname: "switch-room", Type: "Router"},+ }); err != nil {+ t.Fatal(err)+ }++ dev := s.GetDevice("192.168.1.50")+ if dev == nil {+ t.Fatal("device not found")+ }+ if dev.Type != "Router" || dev.CustomType {+ t.Fatalf("expected initial type Router, custom_type false, got type=%q custom_type=%v", dev.Type, dev.CustomType)+ }++ // User overrides type to a supported taxonomy type "Server"+ customType := "Server"+ if err := s.UpdateDeviceFields("192.168.1.50", nil, nil, nil, nil, &customType, nil); err != nil {+ t.Fatalf("UpdateDeviceFields: %v", err)+ }++ dev = s.GetDevice("192.168.1.50")+ if dev.Type != "Server" {+ t.Errorf("expected Type 'Server', got %q", dev.Type)+ }+ if !dev.CustomType {+ t.Errorf("expected CustomType true, got %v", dev.CustomType)+ }+}++func TestUpdateDeviceFields_InvalidType_Rejected(t *testing.T) {+ s := newTestStorage(t)++ if err := s.MergeDevices([]types.Device{+ {IP: "192.168.1.51", MAC: "50:c7:bf:11:22:34", Hostname: "dev", Type: "Computer"},+ }); err != nil {+ t.Fatal(err)+ }++ // Arbitrary free-text type must be rejected+ invalidType := "Smart Plug"+ if err := s.UpdateDeviceFields("192.168.1.51", nil, nil, nil, nil, &invalidType, nil); err == nil {+ t.Fatal("expected error updating with invalid type 'Smart Plug', got nil")+ }++ // Oversized type must be rejected+ tooLong := strings.Repeat("A", scanner.MaxTypeLen+1)+ if err := s.UpdateDeviceFields("192.168.1.51", nil, nil, nil, nil, &tooLong, nil); err == nil {+ t.Fatal("expected error updating with oversized type, got nil")+ }++ // Control character must be rejected+ control := "Server\n"+ if err := s.UpdateDeviceFields("192.168.1.51", nil, nil, nil, nil, &control, nil); err == nil {+ t.Fatal("expected error updating with control character, got nil")+ }++ // Device should remain untouched+ dev := s.GetDevice("192.168.1.51")+ if dev.Type != "Computer" || dev.CustomType {+ t.Fatalf("expected original type Computer and CustomType false, got %q, %v", dev.Type, dev.CustomType)+ }+}++func TestMergeDevices_PreservesCustomType(t *testing.T) {+ s := newTestStorage(t)++ // Device originally scanned as Router+ if err := s.MergeDevices([]types.Device{+ {IP: "192.168.1.50", MAC: "50:c7:bf:11:22:33", Hostname: "switch-room", Type: "Router"},+ }); err != nil {+ t.Fatal(err)+ }++ // User overrides to standard device type "Server"+ userType := "Server"+ isCustom := true+ if err := s.UpdateDeviceFields("192.168.1.50", nil, nil, nil, nil, &userType, &isCustom); err != nil {+ t.Fatal(err)+ }++ // Subsequent scan discovers the device again and classifies it as Router+ if err := s.MergeDevices([]types.Device{+ {IP: "192.168.1.50", MAC: "50:c7:bf:11:22:33", Hostname: "switch-room", Type: "Router"},+ }); err != nil {+ t.Fatal(err)+ }++ dev := s.GetDevice("192.168.1.50")+ if dev.Type != "Server" {+ t.Errorf("scan merge should not overwrite custom type; expected 'Server', got %q", dev.Type)+ }+ if !dev.CustomType {+ t.Errorf("custom_type should remain true after scan merge; got %v", dev.CustomType)+ }+}++func TestMergeDevices_UpdatesNonCustomType(t *testing.T) {+ s := newTestStorage(t)++ // Device discovered with initial guess+ if err := s.MergeDevices([]types.Device{+ {IP: "192.168.1.60", MAC: "00:11:22:33:44:55", Hostname: "box", Type: "Computer"},+ }); err != nil {+ t.Fatal(err)+ }++ // Subsequent scan refines classification to Server+ if err := s.MergeDevices([]types.Device{+ {IP: "192.168.1.60", MAC: "00:11:22:33:44:55", Hostname: "box", Type: "Server"},+ }); err != nil {+ t.Fatal(err)+ }++ dev := s.GetDevice("192.168.1.60")+ if dev.Type != "Server" {+ t.Errorf("non-custom type should update on rescan; expected 'Server', got %q", dev.Type)+ }+}++func TestUpdateDeviceFields_ResetToAuto(t *testing.T) {+ s := newTestStorage(t)++ if err := s.MergeDevices([]types.Device{+ {IP: "192.168.1.70", MAC: "aa:bb:cc:11:22:33", Hostname: "dev", Type: "Computer"},+ }); err != nil {+ t.Fatal(err)+ }++ // User assigns custom type+ customType := "Game Console"+ if err := s.UpdateDeviceFields("192.168.1.70", nil, nil, nil, nil, &customType, nil); err != nil {+ t.Fatal(err)+ }+ if d := s.GetDevice("192.168.1.70"); !d.CustomType {+ t.Fatal("expected CustomType to be true")+ }++ // User resets back to auto (empty string)+ empty := ""+ if err := s.UpdateDeviceFields("192.168.1.70", nil, nil, nil, nil, &empty, nil); err != nil {+ t.Fatal(err)+ }++ dev := s.GetDevice("192.168.1.70")+ if dev.Type != "" {+ t.Errorf("expected empty type after reset, got %q", dev.Type)+ }+ if dev.CustomType {+ t.Errorf("expected CustomType false after reset, got %v", dev.CustomType)+ }++ // Next scan can now re-classify device+ if err := s.MergeDevices([]types.Device{+ {IP: "192.168.1.70", MAC: "aa:bb:cc:11:22:33", Hostname: "dev", Type: "Server"},+ }); err != nil {+ t.Fatal(err)+ }++ dev = s.GetDevice("192.168.1.70")+ if dev.Type != "Server" {+ t.Errorf("expected re-classified Server after reset, got %q", dev.Type)+ }+}++func TestCustomTypePersistsAcrossIPChange(t *testing.T) {+ s := newTestStorage(t)++ // First seen at .10 with custom type+ if err := s.MergeDevices([]types.Device{+ {IP: "192.168.1.10", MAC: "aa:bb:cc:dd:ee:01", Hostname: "iot-device"},+ }); err != nil {+ t.Fatal(err)+ }+ iotType := "IoT"+ if err := s.UpdateDeviceFields("192.168.1.10", nil, nil, nil, nil, &iotType, nil); err != nil {+ t.Fatal(err)+ }++ // Device moves to .20, scan reports Router guess+ if err := s.MergeDevices([]types.Device{+ {IP: "192.168.1.20", MAC: "aa:bb:cc:dd:ee:01", Hostname: "iot-device", Type: "Router"},+ }); err != nil {+ t.Fatal(err)+ }++ moved := s.GetDevice("192.168.1.20")+ if moved == nil {+ t.Fatal("device not found at new IP")+ }+ if moved.Type != "IoT" {+ t.Errorf("expected custom type to carry over to new IP, got %q", moved.Type)+ }+ if !moved.CustomType {+ t.Errorf("expected CustomType flag to carry over to new IP, got %v", moved.CustomType)+ }+}++func TestMergeSupplementalAndIPv6_PreservesCustomType(t *testing.T) {+ s := newTestStorage(t)++ // Primary device with custom type+ if err := s.MergeDevices([]types.Device{+ {IP: "192.168.1.80", MAC: "00:1a:2b:3c:4d:88", Hostname: "my-pi"},+ }); err != nil {+ t.Fatal(err)+ }+ customType := "Server"+ if err := s.UpdateDeviceFields("192.168.1.80", nil, nil, nil, nil, &customType, nil); err != nil {+ t.Fatal(err)+ }++ // Secondary supplemental source reports different type+ if err := s.MergeSupplemental([]types.Device{+ {IP: "192.168.1.80", Type: "Router"},+ }); err != nil {+ t.Fatal(err)+ }++ // IPv6 neighbor discovery reports different type+ if err := s.MergeIPv6Neighbors([]types.Device{+ {IP: "2001:db8::80", MAC: "00:1a:2b:3c:4d:88", Type: "Computer"},+ }); err != nil {+ t.Fatal(err)+ }++ dev := s.GetDevice("192.168.1.80")+ if dev.Type != "Server" {+ t.Errorf("custom type was overwritten by secondary sources, got %q", dev.Type)+ }+ if !dev.CustomType {+ t.Errorf("CustomType flag was lost; got %v", dev.CustomType)+ }+}++func TestDeviceSerializationWithCustomType(t *testing.T) {+ dir := t.TempDir()+ devicesFile := filepath.Join(dir, "devices.json")+ stateFile := filepath.Join(dir, "state.json")++ s1, err := New(devicesFile, stateFile)+ if err != nil {+ t.Fatal(err)+ }++ if err := s1.MergeDevices([]types.Device{+ {IP: "192.168.1.90", MAC: "11:22:33:44:55:66", Hostname: "nas"},+ }); err != nil {+ t.Fatal(err)+ }++ customType := "Server"+ if err := s1.UpdateDeviceFields("192.168.1.90", nil, nil, nil, nil, &customType, nil); err != nil {+ t.Fatal(err)+ }++ // Verify file on disk contains custom_type JSON field+ data, err := os.ReadFile(devicesFile)+ if err != nil {+ t.Fatal(err)+ }+ var raw map[string]interface{}+ if err := json.Unmarshal(data, &raw); err != nil {+ t.Fatal(err)+ }+ entry := raw["192.168.1.90"].(map[string]interface{})+ if entry["type"] != "Server" {+ t.Errorf("expected JSON type 'Server', got %v", entry["type"])+ }+ if entry["custom_type"] != true {+ t.Errorf("expected JSON custom_type true, got %v", entry["custom_type"])+ }++ // Reopen storage and confirm reload preserves custom type+ s2, err := New(devicesFile, stateFile)+ if err != nil {+ t.Fatal(err)+ }+ dev := s2.GetDevice("192.168.1.90")+ if dev == nil || dev.Type != "Server" || !dev.CustomType {+ t.Fatalf("reloaded device should have type 'Server' and CustomType true, got %+v", dev)+ }+}++func TestRetentionKeepsCustomTypeDevice(t *testing.T) {+ s := newTestStorage(t)+ now := time.Now()++ // Seed an offline device with CustomType true and no label/notes/group/expected+ seedDevice(s, "10.0.0.19", now.Add(-365*24*time.Hour), func(d *types.Device) {+ d.Type = "Server"+ d.CustomType = true+ })++ if !isCurated(s.GetDevice("10.0.0.19")) {+ t.Fatal("device with CustomType: true must be curated")+ }++ if err := s.SetLimits(90, 0); err != nil {+ t.Fatalf("SetLimits: %v", err)+ }++ if _, ok := s.GetDevices()["10.0.0.19"]; !ok {+ t.Error("a device with custom type must never be pruned by retention, even a year offline")+ }+}++func TestMaxDevicesCapProtectsCustomTypeDevice(t *testing.T) {+ s := newTestStorage(t)+ now := time.Now()++ // Five offline devices (> 1h old), staggered by age.+ for i := 1; i <= 4; i++ {+ seedDevice(s, fmt.Sprintf("10.0.1.%d", i), now.Add(-time.Duration(i)*24*time.Hour), nil)+ }+ // The oldest device (.5) is curated via CustomType: true+ seedDevice(s, "10.0.1.5", now.Add(-5*24*time.Hour), func(d *types.Device) {+ d.Type = "Printer"+ d.CustomType = true+ })++ // Cap at 3 devices+ if err := s.SetLimits(0, 3); err != nil {+ t.Fatalf("SetLimits: %v", err)+ }++ devs := s.GetDevices()+ if _, ok := devs["10.0.1.5"]; !ok {+ t.Errorf("custom-typed device 10.0.1.5 was evicted by max-devices cap; should be protected as curated")+ }+}diff --git a/internal/storage/groups_test.go b/internal/storage/groups_test.goindex aed318c..535d4d6 100644--- a/internal/storage/groups_test.go+++ b/internal/storage/groups_test.go@@ -18,7 +18,7 @@ func seedGrouped(t *testing.T, s *Storage, groups map[string]string) {}for ip, g := range groups {group := g- if err := s.UpdateDeviceFields(ip, nil, nil, &group, nil); err != nil {+ if err := s.UpdateDeviceFields(ip, nil, nil, &group, nil, nil, nil); err != nil {t.Fatalf("UpdateDeviceFields(%s): %v", ip, err)}}diff --git a/internal/storage/storage.go b/internal/storage/storage.goindex efcf1a8..fc214b7 100644--- a/internal/storage/storage.go+++ b/internal/storage/storage.go@@ -11,6 +11,7 @@ import ("sync""time"+ "github.com/291-Group/LAN-Orangutan/internal/scanner""github.com/291-Group/LAN-Orangutan/internal/types")@@ -215,6 +216,12 @@ func (s *Storage) UpdateDevice(device *types.Device) error {if device.Group == "" {device.Group = existing.Group}+ if device.Type == "" {+ device.Type = existing.Type+ device.CustomType = existing.CustomType+ } else if existing.CustomType && !device.CustomType && device.Type == existing.Type {+ device.CustomType = true+ }if device.FirstSeen.IsZero() {device.FirstSeen = existing.FirstSeen}@@ -225,7 +232,7 @@ func (s *Storage) UpdateDevice(device *types.Device) error {}// UpdateDeviceFields updates specific fields of a device-func (s *Storage) UpdateDeviceFields(ip string, label, notes, group *string, expected *bool) error {+func (s *Storage) UpdateDeviceFields(ip string, label, notes, group *string, expected *bool, deviceType *string, customType *bool) error {s.mu.Lock()defer s.mu.Unlock()@@ -246,6 +253,20 @@ func (s *Storage) UpdateDeviceFields(ip string, label, notes, group *string, expif expected != nil {device.Expected = *expected}+ if deviceType != nil {+ cleanType, err := scanner.ValidateType(*deviceType)+ if err != nil {+ return err+ }+ device.Type = cleanType+ if customType != nil {+ device.CustomType = *customType+ } else {+ device.CustomType = (cleanType != "")+ }+ } else if customType != nil {+ device.CustomType = *customType+ }return s.saveDevices()}@@ -297,7 +318,7 @@ func (s *Storage) MergeDevices(discovered []types.Device) error {if d.Vendor != "" {existing.Vendor = d.Vendor}- if d.Type != "" {+ if !existing.CustomType && d.Type != "" {existing.Type = d.Type}if d.ResponseTime != nil {@@ -343,7 +364,7 @@ func (s *Storage) MergeSupplemental(discovered []types.Device) error {if existing.Vendor == "" && d.Vendor != "" {existing.Vendor = d.Vendor}- if existing.Type == "" && d.Type != "" {+ if !existing.CustomType && existing.Type == "" && d.Type != "" {existing.Type = d.Type}existing.LastSeen = now@@ -388,7 +409,7 @@ func (s *Storage) MergeIPv6Neighbors(discovered []types.Device) error {if existing.Vendor == "" && d.Vendor != "" {existing.Vendor = d.Vendor}- if existing.Type == "" && d.Type != "" {+ if !existing.CustomType && existing.Type == "" && d.Type != "" {existing.Type = d.Type}// Record the routable IPv6 address on the IPv4-primary device so a@@ -430,8 +451,9 @@ func (s *Storage) addNewDeviceLocked(d *types.Device, now time.Time) {d.Group = old.Groupd.Expected = old.Expectedd.FirstSeen = old.FirstSeen- if d.Type == "" {+ if old.CustomType || d.Type == "" {d.Type = old.Type+ d.CustomType = old.CustomType}d.AddressHistory = appendAddressChange(old.AddressHistory, oldIP, now)delete(s.devices, oldIP)@@ -523,11 +545,12 @@ func (s *Storage) pruneEphemeralIPv6Locked() bool {}// isCurated reports whether the user has personalised a device with a label,-// notes, or a group. Curated devices are never removed by any automatic cleanup:-// the user told us this one matters, so retention, the device cap, and the IPv6-// phantom prune all leave it alone.+// notes, a group, expected status, or a custom device type. Curated devices+// are never removed by any automatic cleanup: the user told us this one+// matters, so retention, the device cap, and the IPv6 phantom prune all+// leave it alone.func isCurated(d *types.Device) bool {- return d.Label != "" || d.Notes != "" || d.Group != "" || d.Expected+ return d.Label != "" || d.Notes != "" || d.Group != "" || d.Expected || d.CustomType}// SetLimits records the retention window (in days) and the maximum device count,diff --git a/internal/storage/storage_test.go b/internal/storage/storage_test.goindex 85d527f..b53ac46 100644--- a/internal/storage/storage_test.go+++ b/internal/storage/storage_test.go@@ -754,7 +754,7 @@ func TestExpectedFlagAndBaseline(t *testing.T) {t.Fatal(err)}// Mark one expected via UpdateDeviceFields.- if err := s.UpdateDeviceFields("192.168.1.5", nil, nil, nil, boolptr(true)); err != nil {+ if err := s.UpdateDeviceFields("192.168.1.5", nil, nil, nil, boolptr(true), nil, nil); err != nil {t.Fatal(err)}if !s.GetDevices()["192.168.1.5"].Expected {diff --git a/internal/types/types.go b/internal/types/types.goindex fba50b8..c82d0b5 100644--- a/internal/types/types.go+++ b/internal/types/types.go@@ -15,10 +15,12 @@ type Device struct {MAC string `json:"mac"`Hostname string `json:"hostname"`Vendor string `json:"vendor"`- // Type is the inferred device kind (Phone, Printer, TV, and so on), or ""- // when it could not be determined. It is derived at scan time from the- // vendor, the hostname and, when service detection is on, the open ports.+ // Type is the inferred or user-assigned device kind (Phone, Printer, TV,+ // Router, or custom type), or "" when it could not be determined.Type string `json:"type,omitempty"`+ // CustomType reports whether Type was set or overridden by the user.+ // When true, automated network scans preserve Type rather than recalculating it.+ CustomType bool `json:"custom_type,omitempty"`// WebUI is true when the device answered on a common web port during an// opt-in service probe, meaning it likely serves a dashboard or admin page.// Always false when service detection is off.diff --git a/internal/web/handler.go b/internal/web/handler.goindex 7e37753..6aebbb0 100644--- a/internal/web/handler.go+++ b/internal/web/handler.go@@ -57,6 +57,7 @@ type PageData struct {Stats types.DeviceStatsGroups []stringCurrentGroup string+ Types []stringError string// AuthEnabled reports whether a password is configured, so pages can show@@ -391,6 +392,9 @@ func (h *Handler) handleIndex(w http.ResponseWriter, r *http.Request) {// is kept, so a user's ordering is not re-sorted out from under them.groups := h.store.GetGroups()+ // Standard taxonomy types for device type selection+ typesList := scanner.KnownTypes+// Get networksnetworks, _ := network.DetectNetworks()networks = network.WithConfigured(networks, h.networkFilter())@@ -409,6 +413,7 @@ func (h *Handler) handleIndex(w http.ResponseWriter, r *http.Request) {Tailscale: tailscale,Stats: stats,Groups: groups,+ Types: typesList,AuthEnabled: h.auth.Enabled(),Flagged: flagged,Moved: moved,diff --git a/internal/web/static/app.js b/internal/web/static/app.jsindex 5d13ba8..48b3953 100644--- a/internal/web/static/app.js+++ b/internal/web/static/app.js@@ -389,8 +389,18 @@ function editDevice(ip) {document.getElementById('edit-ip-display').value = ip;document.getElementById('edit-label').value = row.dataset.labelOriginal || '';document.getElementById('edit-group').value = row.dataset.group || '';- document.getElementById('edit-notes').value = row.dataset.notes || '';- document.getElementById('edit-expected').checked = row.dataset.expected === '1';+ const exp = document.getElementById('edit-expected');+ if (exp) exp.checked = row.dataset.expected === '1';++ const currentType = row.dataset.typeOriginal || '';+ const isCustom = row.dataset.customType === '1';+ const typeSelect = document.getElementById('edit-type-select');+ if (typeSelect) {+ const initialVal = (isCustom && currentType) ? currentType : '';+ typeSelect.value = initialVal;+ typeSelect.dataset.initial = initialVal;+ }+modal.style.display = 'flex';}@@ -537,9 +547,22 @@ async function saveDevice() {const label = document.getElementById('edit-label').value;const group = document.getElementById('edit-group').value;const notes = document.getElementById('edit-notes').value;- const expected = document.getElementById('edit-expected').checked;+ const expected = document.getElementById('edit-expected') ? document.getElementById('edit-expected').checked : false;++ const payload = { ip, label, group, notes, expected };+ const typeSelect = document.getElementById('edit-type-select');+ if (typeSelect) {+ if (typeSelect.value !== '') {+ payload.type = typeSelect.value;+ payload.custom_type = true;+ } else if (typeSelect.dataset.initial && typeSelect.dataset.initial !== '') {+ payload.type = '';+ payload.custom_type = false;+ }+ }+try {- const result = await api('device', { ip, label, group, notes, expected }, 'POST');+ const result = await api('device', payload, 'POST');if (result.success) {showToast('Device updated', 'success');closeModal();diff --git a/internal/web/templates/index.html b/internal/web/templates/index.htmlindex b82a3ec..bf7a7b1 100644--- a/internal/web/templates/index.html+++ b/internal/web/templates/index.html@@ -267,6 +267,8 @@ orangutan export out.csv</code></pre>data-mac="{{lower .MAC}}"data-vendor="{{lower .Vendor}}"data-type="{{lower .Type}}"+ data-type-original="{{.Type}}"+ data-custom-type="{{if .CustomType}}1{{else}}0{{end}}"data-label="{{lower .Label}}"data-label-original="{{.Label}}"data-notes="{{.Notes}}"@@ -358,6 +360,13 @@ orangutan export out.csv</code></pre><label>Label</label><input type="text" id="edit-label" name="label" class="input" placeholder="e.g., Living Room TV"></div>+ <div class="form-group">+ <label>Device Type</label>+ <select id="edit-type-select" name="type" class="select">+ <option value="">Auto (Detect)</option>+ {{range .Types}}<option value="{{.}}">{{.}}</option>{{end}}+ </select>+ </div><div class="form-group"><label>Group</label><select id="edit-group" name="group" class="select">