Alert on genuinely new (never-seen-before) devices
New seen_macs table: permanent, insert-only, MAC-keyed record of the first time each device was ever seen -- deliberately decoupled from devices.first_seen (IP-keyed, would false-positive on every DHCP lease change). Bootstrap-safe: first call seeds the baseline from whatever's currently on the network without alerting on all 71+ existing devices at once. Verified locally: bootstrap call reports nothing new, repeat calls with the same MACs report nothing new, one genuinely new MAC gets reported exactly once. Pushes a Home Assistant persistent_notification when a new MAC appears (gated behind HOME_ASSISTANT_TOKEN + homeAssistant.url in hosts.yaml -- missing config just means no push, detection still runs). Also surfaced directly in the dashboard as a blue "new" badge for anything first seen in the last 24h, independent of HA config. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,11 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import type Database from "better-sqlite3";
|
||||
import { upsertDevices, type DiscoveredDevice } from "../db/index.js";
|
||||
import { upsertDevices, recordSeenMacs, type DiscoveredDevice } from "../db/index.js";
|
||||
import { notifyNewDevices, type HomeAssistantConfig, type NewDeviceInfo } from "./homeAssistant.js";
|
||||
// mac-oui-lookup is CommonJS; see routes/devices.ts for why this needs the
|
||||
// default-import-and-destructure form instead of a named import.
|
||||
import macOuiLookup from "mac-oui-lookup";
|
||||
const { getVendor } = macOuiLookup;
|
||||
|
||||
interface RawEntry {
|
||||
ip: string;
|
||||
@@ -15,7 +20,9 @@ interface RawEntry {
|
||||
export async function refreshDevices(
|
||||
db: Database.Database,
|
||||
filePath: string,
|
||||
knownDevices: Map<string, string>
|
||||
knownDevices: Map<string, string>,
|
||||
homeAssistant: HomeAssistantConfig | undefined,
|
||||
onNotifyError: (err: unknown) => void
|
||||
): Promise<void> {
|
||||
let raw: RawEntry[];
|
||||
try {
|
||||
@@ -35,4 +42,21 @@ export async function refreshDevices(
|
||||
}));
|
||||
|
||||
upsertDevices(db, devices);
|
||||
|
||||
const newMacs = new Set(recordSeenMacs(db, raw.map((r) => r.mac)));
|
||||
if (newMacs.size > 0 && homeAssistant) {
|
||||
const newDevices: NewDeviceInfo[] = raw
|
||||
.filter((r) => newMacs.has(r.mac))
|
||||
.map((r) => ({
|
||||
ip: r.ip,
|
||||
mac: r.mac,
|
||||
vendor: getVendor(r.mac),
|
||||
name: knownDevices.get(r.ip) ?? r.mdnsHostname ?? null,
|
||||
}));
|
||||
try {
|
||||
await notifyNewDevices(homeAssistant, newDevices);
|
||||
} catch (err) {
|
||||
onNotifyError(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user