Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE/bug_report.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ body:
attributes:
label: ALPR Community version
description: Find this under Settings → Release. Include the source revision there when reporting an installation or update problem.
placeholder: v0.1.59
placeholder: v0.1.60
validations:
required: true

Expand Down
13 changes: 12 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,13 @@ jobs:
ALPR_AXIS_TEST_SERVER_URL: postgresql://postgres:fixture-test-password@127.0.0.1:5432/postgres
run: yarn test:camera-inputs:postgres

- name: Verify tracked upgrades, Blue Iris bindings and read-only display access
env:
ALPR_COMMUNITY_TEST_SERVER_URL: postgresql://postgres:fixture-test-password@127.0.0.1:5432/postgres
run: |
git fetch --no-tags origin tag v0.1.42 tag v0.1.55 tag v0.1.58 tag v0.1.59
yarn test:community-bugfixes:postgres

- name: Exercise load, no-op, guarded clear, and refusal paths
shell: bash
run: |
Expand Down Expand Up @@ -187,6 +194,7 @@ jobs:
VALUES
('vehicle-image-asset-cleanup:v1', 'ci-disposable-pg17'),
('vehicle-image-asset-campaign:v1', 'ci-disposable-pg17'),
('overview-export:v1', 'ci-disposable-pg17'),
('vehicle-event-shadow:v1', 'ci-disposable-pg17');
INSERT INTO public.codex_integration_test_guard (scope, guard_token)
VALUES ('vehicle-image-crop:v1', 'ci-disposable-pg17');
Expand All @@ -198,7 +206,10 @@ jobs:
DATABASE_URL='postgresql://postgres:fixture-test-password@127.0.0.1:5432/fixture_test' \
yarn test:vehicle-image-asset-cleanup:postgres || pg_test_failed=1

DATABASE_URL='postgresql://postgres:fixture-test-password@127.0.0.1:5432/fixture_test' \
OVERVIEW_EXPORT_POSTGRES_TEST_OPT_IN='true' \
OVERVIEW_EXPORT_POSTGRES_TEST_DATABASE='fixture_test' \
OVERVIEW_EXPORT_POSTGRES_TEST_GUARD_TOKEN='ci-disposable-pg17' \
DATABASE_URL='postgresql://postgres:fixture-test-password@127.0.0.1:5432/fixture_test' \
yarn test:overview-export:postgres || pg_test_failed=1

VEHICLE_IMAGE_ASSET_POSTGRES_TEST_OPT_IN='true' \
Expand Down
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# Changelog

## 0.1.60 — 2026-11-02

- Track ordered SQL migrations with verified checksums and legacy completion markers. Preserve the single-file updater entry point, atomic application, count validation and rollback. Completed cleanups no longer replay; Blue Iris v2 events remain visible and preserved.
- Resolve Blue Iris display names and short IDs through persisted camera inventory and explicit LPR recording bindings. Refresh camera discovery in settings, expose separate alert/read tolerances and require an explicit owner when several ALPR reads match.
- Replace the inactive Home Assistant IP-bypass setting with revocable, expiring read-only displays, optional camera scope and exact parent-origin restrictions. Administrative access continues to require its existing login.
- Update User Guide 3.28, current installation/update examples and Home Assistant access guidance. Existing installations use the normal updater; no manual database edits or intermediate release are required.
- Add disposable PostgreSQL upgrade fixtures for v0.1.42, v0.1.55, v0.1.58, v0.1.59 and fresh installs, plus production browser checks for Home Assistant and Blue Iris setup.

## 0.1.59 — 2026-11-01

- Add configurable AXIS License Plate Verifier inputs through HTTP push, MQTT, or both under Settings > Integrations > Camera Inputs. Existing Blue Iris cameras continue automatically.
Expand Down
60 changes: 47 additions & 13 deletions app/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ import { revalidatePath, revalidateTag, unstable_noStore } from "next/cache";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import crypto from "crypto";
import { HomeAssistantDisplayService } from "@/lib/home-assistant-display.mjs";
import { readMatchTolerance } from "@/lib/blue-iris-camera-binding.mjs";
import { getConfig, saveConfig } from "@/lib/settings";
import {
environmentManagedSettings,
Expand Down Expand Up @@ -1756,6 +1758,7 @@ export async function testBlueIrisConnection() {
try {
const config = await getConfig();
const result = await new BlueIrisClient(config.blueiris).testConnection();
await new BlueIrisVehicleFrameRepository(await getPool()).syncBlueIrisCameraInventory(result.cameras);
return { success: true, ...result };
} catch (error) {
return {
Expand All @@ -1774,7 +1777,13 @@ export async function previewBlueIrisAlertMatch(input = {}) {
timestamp: input.timestamp,
toleranceSeconds: input.toleranceSeconds,
});
return { success: true, ...result };
const readToleranceSeconds = readMatchTolerance(input.readToleranceSeconds);
const reads = await new BlueIrisVehicleFrameRepository(await getPool()).findReadCandidates({
camera: input.camera, timestamp: input.timestamp, toleranceSeconds: readToleranceSeconds,
});
return { success: true, ...result, readToleranceSeconds, reads: reads.map(read => ({
id: read.id, cameraName: read.camera_name, plateNumber: read.plate_number, timestamp: new Date(read.timestamp).toISOString(),
})) };
} catch (error) {
return {
success: false,
Expand All @@ -1785,6 +1794,9 @@ export async function previewBlueIrisAlertMatch(input = {}) {

export async function selectBlueIrisVehicleFrame(input = {}) {
await requirePermission("system.manage_settings");
if (input.readId != null && (!Number.isSafeInteger(Number(input.readId)) || Number(input.readId) < 1)) {
return { success: false, message: "Choose a valid ALPR read to own the image." };
}
try {
const config = await getConfig();
const pool = await getPool();
Expand All @@ -1796,10 +1808,8 @@ export async function selectBlueIrisVehicleFrame(input = {}) {
camera: input.camera,
cameraName: input.cameraName,
timestamp: input.timestamp,
toleranceSeconds: Math.min(
30,
Math.max(1, Number.parseInt(String(input.readToleranceSeconds ?? 3), 10) || 3)
),
toleranceSeconds: readMatchTolerance(input.readToleranceSeconds),
readId: input.readId == null ? null : Number(input.readId),
});
revalidatePath("/live_feed");
return { success: result.status === "ready", ...result };
Expand Down Expand Up @@ -1977,10 +1987,39 @@ export async function getBlueIrisVehicleFrameQueueStatus(input = {}) {
}
}

export async function getHomeAssistantDisplays() {
await requirePermission("system.manage_settings");
try {
const pool = await getPool();
const [grants, cameras] = await Promise.all([
new HomeAssistantDisplayService(pool).list(),
pool.query("SELECT DISTINCT camera_name FROM public.plate_reads WHERE NULLIF(BTRIM(camera_name),'') IS NOT NULL ORDER BY camera_name"),
]);
return { success: true, grants, cameras: cameras.rows.map(row => row.camera_name) };
} catch { return { success: false, error: "Unable to load display access." }; }
}

export async function createHomeAssistantDisplay(input = {}) {
const principal = await requirePermission("system.manage_settings");
try {
const data = await new HomeAssistantDisplayService(await getPool()).create(input, principal);
return { success: true, data };
} catch { return { success: false, error: "Unable to create display access. Check the name, exact Home Assistant origin, camera and expiration (1–90 days)." }; }
}

export async function revokeHomeAssistantDisplay(id) {
await requirePermission("system.manage_settings");
try {
await new HomeAssistantDisplayService(await getPool()).revoke(id);
return { success: true };
} catch { return { success: false, error: "Unable to revoke display access." }; }
}

export async function getVehicleImageSourceSetup() {
await requirePermission("system.manage_settings");
try {
const runtime = await getBlueIrisVehicleFrameRuntime();
await runtime.queue.refreshCameraInventory({ force: true });
const [profiles, inventory] = await Promise.all([
runtime.repository.listOverviewPairProfiles(),
(await getPool()).query(`SELECT short_name, display_name FROM public.blue_iris_camera_inventory
Expand All @@ -2007,9 +2046,10 @@ export async function saveVehicleImageSource(input = {}) {
const inventory = await (await getPool()).query(`SELECT display_name FROM public.blue_iris_camera_inventory
WHERE present = TRUE AND enabled = TRUE AND LOWER(BTRIM(short_name)) = LOWER(BTRIM($1))`,
[normalized.sourceCameraShortName]);
if (inventory.rows.length !== 1 || inventory.rows[0].display_name.trim().toLowerCase() !== normalized.sourceCameraName.toLowerCase()) {
if (inventory.rows.length !== 1) {
return { success: false, error: "The selected camera does not match the Blue Iris camera list. Test the Blue Iris connection and try again." };
}
normalized.sourceCameraName = inventory.rows[0].display_name.trim();
const runtime = await getBlueIrisVehicleFrameRuntime();
const saved = await runtime.repository.saveOverviewPairProfile({ ...normalized, replacePrimary: true }, principal);
runtime.worker.wake();
Expand Down Expand Up @@ -2898,13 +2938,7 @@ export async function updateSettings(formData) {
}

if (updateIfExists("haEnabled") || updateIfExists("haWhitelist")) {
newConfig.homeassistant = {
...currentConfig.homeassistant,
enabled: formData.get("haEnabled") === "true",
whitelist: formData.get("haWhitelist")
? JSON.parse(formData.get("haWhitelist"))
: currentConfig.homeassistant?.whitelist || [],
};
throw new Error("The IP whitelist is retired. Create read-only display access in Home Assistant settings.");
}
if (
updateIfExists("bihost") ||
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { getPool } from "@/lib/db";
import fileStorage from "@/lib/fileStorage";
import { HomeAssistantDisplayService, createDisplayReadHandler } from "@/lib/home-assistant-display.mjs";

export const dynamic = "force-dynamic";
export async function GET(request, context) {
return createDisplayReadHandler({ service: new HomeAssistantDisplayService(await getPool()), readImage: path => fileStorage.getImage(path) })(request, context);
}
7 changes: 7 additions & 0 deletions app/api/home-assistant/display/[grantId]/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { getPool } from "@/lib/db";
import { HomeAssistantDisplayService, createDisplayReadHandler } from "@/lib/home-assistant-display.mjs";

export const dynamic = "force-dynamic";
export async function GET(request, context) {
return createDisplayReadHandler({ service: new HomeAssistantDisplayService(await getPool()) })(request, context);
}
93 changes: 2 additions & 91 deletions app/api/verify-whitelist/route.js
Original file line number Diff line number Diff line change
@@ -1,94 +1,5 @@
import { getConfig } from "@/lib/settings";
import { NextResponse } from "next/server";

// Validates IPv4 address format
const isValidIPv4 = (ip) => {
const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
if (!ipv4Regex.test(ip)) return false;

const parts = ip.split(".");
return parts.every((part) => {
const num = parseInt(part, 10);
return num >= 0 && num <= 255;
});
};

// Validates IPv6 address format
const isValidIPv6 = (ip) => {
// Remove any leading/trailing brackets
ip = ip.replace(/^\[|\]$/g, "");

// Handle compressed IPv6 format
const ipv6Regex =
/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^(([0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4}$/;
return ipv6Regex.test(ip);
};

// Normalizes an IP address
const normalizeIP = (ip) => {
ip = ip.trim();

// Handle IPv4-mapped IPv6 addresses
if (ip.startsWith("::ffff:")) {
ip = ip.substring(7);
}

// Remove any square brackets from IPv6
ip = ip.replace(/^\[|\]$/g, "");

return ip;
};

// Gets client IP from X-Forwarded-For header
const getClientIP = (forwardedFor) => {
if (!forwardedFor) return null;

// Split the header into individual IPs
const ips = forwardedFor.split(",").map((ip) => normalizeIP(ip));

// Get the leftmost valid IP (original client)
for (const ip of ips) {
if (isValidIPv4(ip) || isValidIPv6(ip)) {
return ip;
}
}

return null;
};

export async function POST(request) {
try {
const { headers } = await request.json();
const forwardedFor = headers["x-forwarded-for"];
if (!forwardedFor) {
console.warn("No X-Forwarded-For header present");
return NextResponse.json({ allowed: false });
}

// Get the client IP from X-Forwarded-For header
const clientIP = getClientIP(forwardedFor);
if (!clientIP) {
console.warn("No valid IP found in X-Forwarded-For header");
return NextResponse.json({ allowed: false });
}

// Load the configuration data
const config = await getConfig();
const whitelist = config.homeassistant?.whitelist || [];

if (whitelist.length === 0) {
console.warn("No whitelisted IPs configured");
return NextResponse.json({ allowed: false });
}

// Normalize all whitelist IPs and compare
const normalizedWhitelist = whitelist.map(normalizeIP);
const isAllowedIp = normalizedWhitelist.includes(normalizeIP(clientIP));

return NextResponse.json({ allowed: isAllowedIp });
} catch {
console.error("IP whitelist check failed");
return NextResponse.json({ allowed: false }, { status: 500 });
}
export async function POST() {
return NextResponse.json({ error: "IP login bypass is retired. Create read-only display access in Home Assistant settings." }, { status: 410 });
}

18 changes: 18 additions & 0 deletions app/embed/home-assistant/[grantId]/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { randomBytes } from "node:crypto";
import { getPool } from "@/lib/db";
import { HomeAssistantDisplayService, displayHeaders } from "@/lib/home-assistant-display.mjs";
import { displayDocument } from "@/lib/home-assistant-display-document.mjs";

export const dynamic = "force-dynamic";
export async function GET(_request, { params }) {
try {
const { grantId } = await params;
const grant = await new HomeAssistantDisplayService(await getPool()).publicGrant(grantId);
if (!grant) return new Response("Display expired, revoked or unavailable.", { status: 404, headers: displayHeaders });
const nonce = randomBytes(18).toString("base64");
return new Response(displayDocument(nonce), { headers: {
...displayHeaders, "Content-Type": "text/html; charset=utf-8",
"Content-Security-Policy": `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; img-src 'self' blob:; frame-ancestors ${grant.allowed_origin}; base-uri 'none'; form-action 'none'`,
} });
} catch { return new Response("Display temporarily unavailable.", { status: 503, headers: displayHeaders }); }
}
Loading
Loading