feat: serve the BYOS device API

The panel now pairs, fetches its image and files its logs against this
application rather than against the TRMNL cloud.

Four endpoints: /api/setup issues a token on first contact,
/api/display hands back an image and a wake interval, /api/log stores
firmware diagnostics, and /api/device/image/<hash> serves the bytes.

The wake interval is where freshness and battery are traded off. In BYOS
nothing can be pushed: the device sleeps, wakes, asks and sleeps again.
So the interval is short while the shop trades and long overnight, and
it is shortened further whenever a change of state falls inside it —
the door opening in twenty minutes means waking in twenty-one,
whatever the base interval says.

The image filename is the hash of its own bytes. The firmware skips the
redraw when the name is unchanged, which is the whole battery strategy,
and the URL is immutable, unguessable and safe to cache forever. Two
integration tests pin this: unchanged data must yield the same filename
and store one row, changed hours must yield a different one.

MAC addresses are normalised before use. They are a primary key here,
and firmwares are inconsistent about case and separators; without this a
panel could register twice by capitalising itself differently. Header
names are read in both the hyphen and underscore spellings for the same
reason — the TRMNL docs and the Seeed sources disagree, and being
liberal costs nothing while being wrong costs a blank shop window.

Pairing is deliberately made to survive a rendering failure. The token
is issued once and only its digest is kept, so a device stranded by a
failed response would be registered yet hold no credential, and unable
to register again. The welcome image is worth far less than that. This
was found by running the flow, not by reading it.

satori, yoga and harfbuzz are marked external: bundling rewrites the
relative path satori uses to load its WebAssembly, and the renderer dies
on a missing hb.wasm.

The integration tests run against a real Postgres, in CI too. Mocking
Prisma here would only prove the mock works.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012cSY9pVhZmJUKNN7wf1Myd
This commit is contained in:
2026-09-20 18:00:50 +02:00
co-authored by Claude Opus 5
parent fccccbd118
commit dd4d1b97c8
25 changed files with 1500 additions and 4 deletions
+45
View File
@@ -0,0 +1,45 @@
/**
* Environment access, in one place so nothing else has to guess.
*/
/**
* The origin the device and the browser reach us on.
*
* Prefers what the request actually arrived as, because the panel has to be
* handed a URL it can fetch — a mismatch here shows up as a blank screen in a
* shop window, which is the most expensive place to debug. Falls back to the
* configured domain for calls that have no request, such as background jobs.
*/
export function publicBaseUrl(request?: Request): string {
if (request) {
const host = request.headers.get('x-forwarded-host') ?? request.headers.get('host');
if (host) {
const proto = request.headers.get('x-forwarded-proto') ?? new URL(request.url).protocol.replace(':', '');
return `${proto}://${host}`;
}
}
const configured = process.env.NEXTAUTH_URL;
if (configured) {
return configured.replace(/\/$/, '');
}
const domain = process.env.APP_DOMAIN;
if (domain) {
return domain.startsWith('http') ? domain.replace(/\/$/, '') : `https://${domain}`;
}
return 'http://localhost:3000';
}
/**
* Whether the panel may talk to us over plain HTTP.
*
* Off by default. It exists because these ESP32 firmwares sometimes fail on a
* certificate chain, and a shop with a blank window needs a way out that does
* not involve reflashing. The device token is separate and revocable precisely
* so this switch stays survivable.
*/
export function deviceAllowsHttp(): boolean {
return process.env.DEVICE_ALLOW_HTTP === 'true';
}
+84
View File
@@ -0,0 +1,84 @@
import { describe, expect, it } from 'vitest';
import {
generateDeviceToken,
generateFriendlyId,
hashToken,
normaliseMac,
tokenMatches,
} from './auth';
describe('generateDeviceToken', () => {
it('is URL-safe and long enough to be worth nothing to a guesser', () => {
const token = generateDeviceToken();
expect(token).toMatch(/^[A-Za-z0-9_-]+$/);
expect(token.length).toBeGreaterThanOrEqual(43);
});
it('never repeats', () => {
const tokens = new Set(Array.from({ length: 50 }, generateDeviceToken));
expect(tokens.size).toBe(50);
});
});
describe('hashToken / tokenMatches', () => {
it('accepts the right token', () => {
const token = generateDeviceToken();
expect(tokenMatches(token, hashToken(token))).toBe(true);
});
it('rejects the wrong token', () => {
expect(tokenMatches('wrong', hashToken(generateDeviceToken()))).toBe(false);
});
it('rejects an empty token', () => {
expect(tokenMatches('', hashToken('something'))).toBe(false);
});
it('rejects a stored digest of the wrong length without throwing', () => {
// A truncated or corrupted column must fail closed, not crash the route.
expect(tokenMatches('token', 'abcd')).toBe(false);
});
it('rejects a stored digest that is not hex without throwing', () => {
expect(tokenMatches('token', 'not-hex-at-all')).toBe(false);
});
it('produces a 64-character hex digest', () => {
expect(hashToken('token')).toMatch(/^[0-9a-f]{64}$/);
});
});
describe('generateFriendlyId', () => {
it('uses only characters that survive being read aloud', () => {
for (let attempt = 0; attempt < 50; attempt += 1) {
expect(generateFriendlyId()).toMatch(/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/);
}
});
it('honours a requested length', () => {
expect(generateFriendlyId(10)).toHaveLength(10);
});
});
describe('normaliseMac', () => {
it('accepts the colon form', () => {
expect(normaliseMac('FE:68:44:CE:CA:C3')).toBe('FE:68:44:CE:CA:C3');
});
it('accepts lower case, dashes and bare hex', () => {
// A device must not be able to register twice by spelling itself
// differently; the address is a primary key here.
expect(normaliseMac('fe:68:44:ce:ca:c3')).toBe('FE:68:44:CE:CA:C3');
expect(normaliseMac('fe-68-44-ce-ca-c3')).toBe('FE:68:44:CE:CA:C3');
expect(normaliseMac('fe6844ceCAc3')).toBe('FE:68:44:CE:CA:C3');
});
it('rejects anything that is not twelve hex digits', () => {
expect(normaliseMac('FE:68:44:CE:CA')).toBeNull();
expect(normaliseMac('not a mac')).toBeNull();
expect(normaliseMac('')).toBeNull();
expect(normaliseMac(null)).toBeNull();
expect(normaliseMac(undefined)).toBeNull();
});
});
+66
View File
@@ -0,0 +1,66 @@
/**
* Device credentials.
*
* The panel cannot sign in through the identity provider, so it carries a
* static bearer token instead. That makes two things non-negotiable: only the
* digest is ever stored, and comparisons run in constant time — an endpoint
* that leaks timing is an endpoint that leaks the token.
*/
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
/** Unambiguous in print: no O/0, no I/1. Friendly ids get read aloud. */
const FRIENDLY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
/** 256 bits of entropy, URL-safe so it survives a captive-portal form. */
export function generateDeviceToken(): string {
return randomBytes(32).toString('base64url');
}
export function hashToken(token: string): string {
return createHash('sha256').update(token, 'utf8').digest('hex');
}
/**
* Constant-time comparison of a presented token against a stored digest.
*
* Both sides are hashed first, so the buffers always have the same length and
* `timingSafeEqual` can never throw on a length mismatch — which would itself
* be an observable signal.
*/
export function tokenMatches(presented: string, storedHash: string): boolean {
const presentedDigest = Buffer.from(hashToken(presented), 'hex');
let storedDigest: Buffer;
try {
storedDigest = Buffer.from(storedHash, 'hex');
} catch {
return false;
}
if (storedDigest.length !== presentedDigest.length) {
return false;
}
return timingSafeEqual(presentedDigest, storedDigest);
}
export function generateFriendlyId(length = 6): string {
const bytes = randomBytes(length);
return Array.from(bytes, (byte) => FRIENDLY_ALPHABET[byte % FRIENDLY_ALPHABET.length]).join('');
}
/**
* Normalises a MAC address to upper-case colon-separated form.
*
* Firmwares are not consistent about separators or case, and the address is a
* primary key here, so a device must not be able to register twice by
* capitalising itself differently.
*/
export function normaliseMac(value: string | null | undefined): string | null {
if (!value) {
return null;
}
const hex = value.replace(/[^0-9a-fA-F]/g, '').toUpperCase();
if (hex.length !== 12) {
return null;
}
return (hex.match(/.{2}/g) ?? []).join(':');
}
+33
View File
@@ -0,0 +1,33 @@
/**
* Header reading for the device API.
*
* The firmwares are not consistent: the TRMNL documentation shows
* `ACCESS_TOKEN` and `BATTERY_VOLTAGE`, the Seeed sources show `Access-Token`
* and `Battery-Voltage`. HTTP header names are case-insensitive but underscores
* and hyphens are different names, so every field is read under both spellings.
* Being liberal here costs nothing; being wrong costs a blank shop window.
*/
export function deviceHeader(request: Request, name: string): string | null {
const hyphen = name.replace(/_/g, '-');
const underscore = name.replace(/-/g, '_');
return request.headers.get(hyphen) ?? request.headers.get(underscore);
}
export function deviceNumber(request: Request, name: string): number | null {
const raw = deviceHeader(request, name);
if (raw === null || raw.trim() === '') {
return null;
}
const value = Number(raw);
return Number.isFinite(value) ? value : null;
}
/** The caller's address, as seen through whatever proxy is in front of us. */
export function clientIp(request: Request): string {
const forwarded = request.headers.get('x-forwarded-for');
if (forwarded) {
return forwarded.split(',')[0]?.trim() ?? 'unknown';
}
return request.headers.get('x-real-ip') ?? 'unknown';
}
+130
View File
@@ -0,0 +1,130 @@
import { describe, expect, it } from 'vitest';
import type { ResolvedDay, ShopStatus, ShopStatusKind } from '@/lib/schedule/types';
import {
CHANGE_MARGIN_SEC,
MAX_REFRESH_SEC,
MIN_REFRESH_SEC,
computeRefreshRate,
} from './refresh';
const ZURICH = 'Europe/Zurich';
const OPEN_SEC = 600;
const CLOSED_SEC = 7200;
const DAY: ResolvedDay = {
date: '2026-09-22',
dayOfWeek: 2,
isOpen: true,
slots: [],
isException: false,
exceptionKind: null,
noteFr: null,
noteEn: null,
};
function status(
kind: ShopStatusKind,
nextChangeAt: ShopStatus['nextChangeAt'] = null,
): ShopStatus {
return { status: kind, today: DAY, nextChangeAt, nextOpening: nextChangeAt };
}
function rate(now: string, value: ShopStatus): number {
return computeRefreshRate({
now: new Date(now),
status: value,
timezone: ZURICH,
openSec: OPEN_SEC,
closedSec: CLOSED_SEC,
});
}
describe('computeRefreshRate', () => {
it('uses the short interval while the shop is trading', () => {
// 12:00 local, closing at 18:30: far from any change, so the base wins.
expect(rate('2026-09-22T10:00:00Z', status('OPEN', { date: '2026-09-22', time: '18:30' }))).toBe(
OPEN_SEC,
);
});
it('uses the long interval overnight', () => {
expect(
rate('2026-09-22T21:00:00Z', status('CLOSED', { date: '2026-09-23', time: '10:00' })),
).toBe(CLOSED_SEC);
});
it('treats opening soon as a trading moment', () => {
// Someone is standing at the window right now; the screen must not be stale.
expect(
rate('2026-09-22T07:40:00Z', status('OPENING_SOON', { date: '2026-09-22', time: '10:00' })),
).toBeLessThanOrEqual(OPEN_SEC);
});
it('never sleeps through a change of state', () => {
// 17:00 local, closing at 18:30 is 90 minutes away, well inside the long
// interval. The device must still wake just after the change.
const seconds = rate(
'2026-09-22T15:00:00Z',
status('CLOSED', { date: '2026-09-22', time: '18:30' }),
);
expect(seconds).toBe(Math.min(CLOSED_SEC, 90 * 60 + CHANGE_MARGIN_SEC));
});
it('wakes just after the change rather than exactly on it', () => {
// Closing in ten minutes: waking at the stroke of 18:30 risks redrawing
// the old state, so add the margin.
const seconds = rate(
'2026-09-22T16:20:00Z',
status('OPEN', { date: '2026-09-22', time: '18:30' }),
);
expect(seconds).toBe(130 * 60 > OPEN_SEC ? OPEN_SEC : 130 * 60 + CHANGE_MARGIN_SEC);
});
it('shortens the long interval for a change that falls inside it', () => {
// Closed, reopening in 30 minutes, base interval 2 hours.
const seconds = rate(
'2026-09-22T07:30:00Z',
status('CLOSED', { date: '2026-09-22', time: '10:00' }),
);
expect(seconds).toBe(30 * 60 + CHANGE_MARGIN_SEC);
});
it('falls back to the base interval when nothing is scheduled ahead', () => {
expect(rate('2026-09-22T10:00:00Z', status('CLOSED', null))).toBe(CLOSED_SEC);
});
it('ignores a change that has already passed', () => {
// A stale next-change must not produce a negative or zero interval.
expect(
rate('2026-09-22T16:00:00Z', status('CLOSED', { date: '2026-09-22', time: '10:00' })),
).toBe(CLOSED_SEC);
});
it('never returns less than the floor', () => {
const seconds = rate(
'2026-09-22T10:00:00Z',
status('OPEN', { date: '2026-09-22', time: '12:00' }),
);
expect(seconds).toBeGreaterThanOrEqual(MIN_REFRESH_SEC);
});
it('never returns more than the ceiling', () => {
expect(
computeRefreshRate({
now: new Date('2026-09-22T10:00:00Z'),
status: status('CLOSED', null),
timezone: ZURICH,
openSec: OPEN_SEC,
closedSec: 999_999,
}),
).toBe(MAX_REFRESH_SEC);
});
it('handles a change several days out without overflowing', () => {
expect(
rate('2026-09-26T17:00:00Z', status('CLOSED', { date: '2026-09-29', time: '10:00' })),
).toBe(CLOSED_SEC);
});
});
+76
View File
@@ -0,0 +1,76 @@
/**
* How long to let the panel sleep.
*
* In BYOS there is no way to push: the device sleeps, wakes, asks, and sleeps
* again. The only lever is how long it sleeps for, so this is the entire
* freshness-versus-battery trade-off of the product, in one function.
*
* Two rules:
* - sleep briefly while the shop is trading, and at length overnight;
* - never sleep through a change of state. If the door opens in twenty
* minutes, wake in twenty-one, whatever the base interval says.
*/
import { civilDaysBetween, minutesOfTime, toCivilDate, toCivilTime } from '@/lib/schedule/civil';
import type { ShopStatus } from '@/lib/schedule/types';
/** Below this the panel would spend its life awake. */
export const MIN_REFRESH_SEC = 60;
/** A panel that has not checked in for six hours is indistinguishable from a dead one. */
export const MAX_REFRESH_SEC = 21_600;
/** Wake just after the change, not exactly on it. */
export const CHANGE_MARGIN_SEC = 60;
export type RefreshInput = {
now: Date;
status: ShopStatus;
timezone: string;
openSec: number;
closedSec: number;
};
export function computeRefreshRate({
now,
status,
timezone,
openSec,
closedSec,
}: RefreshInput): number {
// "Opening soon" gets the short interval too: that is the moment the screen
// is about to be wrong, and the moment someone is standing at the window.
const busy =
status.status === 'OPEN' || status.status === 'CLOSING_SOON' || status.status === 'OPENING_SOON';
let seconds = busy ? openSec : closedSec;
if (status.nextChangeAt) {
const untilChange = secondsUntil(now, status.nextChangeAt, timezone);
if (untilChange > 0) {
seconds = Math.min(seconds, untilChange + CHANGE_MARGIN_SEC);
}
}
return clamp(Math.round(seconds));
}
function clamp(seconds: number): number {
return Math.min(MAX_REFRESH_SEC, Math.max(MIN_REFRESH_SEC, seconds));
}
/**
* Seconds from now until a wall-clock moment.
*
* Measured on the wall clock, which is off by an hour on the two nights a year
* the clocks change. That only shifts one wake-up, and the alternative — a
* real timezone conversion back to an instant — buys nothing the panel can
* perceive.
*/
function secondsUntil(now: Date, target: { date: string; time: string }, timezone: string): number {
const today = toCivilDate(now, timezone);
const nowMinutes = minutesOfTime(toCivilTime(now, timezone));
const days = civilDaysBetween(today, target.date);
const minutes = days * 1440 + minutesOfTime(target.time) - nowMinutes;
return minutes * 60 - now.getUTCSeconds();
}
+45
View File
@@ -0,0 +1,45 @@
/**
* Resolving which device is calling.
*
* The panel cannot sign in through the identity provider, so these routes are
* the only ones outside OIDC. They are kept narrow on purpose: a bearer token
* compared in constant time, and nothing else.
*/
import { prisma } from '@/lib/db';
import { hashToken, normaliseMac, tokenMatches } from './auth';
import { deviceHeader } from './headers';
export type DeviceRow = Awaited<ReturnType<typeof prisma.device.findFirst>>;
export async function authenticateDevice(request: Request): Promise<NonNullable<DeviceRow> | null> {
const token = deviceHeader(request, 'access-token') ?? bearer(request);
if (!token) {
return null;
}
// When the firmware sends its MAC, look the device up by it and compare the
// token in constant time. That is the path the spec asks for.
const mac = normaliseMac(deviceHeader(request, 'id'));
if (mac) {
const device = await prisma.device.findUnique({ where: { macAddress: mac } });
if (device && device.isActive && tokenMatches(token, device.apiKeyHash)) {
return device;
}
// Fall through: some firmware revisions omit ID on /api/log.
}
// Looking the row up by the digest reveals nothing the digest does not
// already contain, and the database index does the work.
const device = await prisma.device.findFirst({ where: { apiKeyHash: hashToken(token) } });
return device && device.isActive ? device : null;
}
function bearer(request: Request): string | null {
const header = request.headers.get('authorization');
if (!header?.toLowerCase().startsWith('bearer ')) {
return null;
}
return header.slice(7).trim() || null;
}
+49
View File
@@ -0,0 +1,49 @@
/**
* A small in-memory sliding-window limiter.
*
* Deliberately per-process and not backed by Redis: this application runs as a
* single container serving one shop and a handful of devices. The job here is
* to stop a firmware stuck in a retry loop from hammering the renderer, not to
* survive a distributed attack.
*/
const windows = new Map<string, number[]>();
export type RateLimitResult = {
allowed: boolean;
/** Seconds until the caller may try again; 0 when allowed. */
retryAfter: number;
};
export function rateLimit(key: string, limit: number, windowMs: number): RateLimitResult {
const now = Date.now();
const cutoff = now - windowMs;
const hits = (windows.get(key) ?? []).filter((timestamp) => timestamp > cutoff);
if (hits.length >= limit) {
windows.set(key, hits);
const oldest = hits[0] ?? now;
return { allowed: false, retryAfter: Math.ceil((oldest + windowMs - now) / 1000) };
}
hits.push(now);
windows.set(key, hits);
// Opportunistic sweep: without it a long-running process would hold a key
// for every IP that ever called, forever.
if (windows.size > 1000) {
for (const [existing, timestamps] of windows) {
if (timestamps.every((timestamp) => timestamp <= cutoff)) {
windows.delete(existing);
}
}
}
return { allowed: true, retryAfter: 0 };
}
/** Test seam: forget every window. */
export function resetRateLimits(): void {
windows.clear();
}
+5
View File
@@ -91,6 +91,11 @@ export function civilDayOfWeek(date: CivilDate): number {
return new Date(civilToUtcMs(date)).getUTCDay();
}
/** Whole days from `a` to `b`; negative when `b` is earlier. */
export function civilDaysBetween(a: CivilDate, b: CivilDate): number {
return Math.round((civilToUtcMs(b) - civilToUtcMs(a)) / MS_PER_DAY);
}
/** Chronological comparator; civil dates are lexicographically ordered too. */
export function compareCivil(a: CivilDate, b: CivilDate): number {
return a < b ? -1 : a > b ? 1 : 0;
+149
View File
@@ -0,0 +1,149 @@
/**
* The only place that turns database rows into a ScheduleContext.
*
* Keeping every query here is what lets `resolver.ts` stay pure. Nothing below
* makes a scheduling decision; it loads, narrows and converts.
*/
import { prisma } from '@/lib/db';
import { addCivilDays, startOfCivilWeek, toCivilDate, type CivilDate } from './civil';
import type { ScheduleContext, Slot } from './types';
/**
* How far either side of today to load.
*
* Back to the Monday of the current week, because the screen draws it; forward
* past the resolver's fourteen-day search, so a reopening is never missed for
* want of a row.
*/
const LOOK_BACK_DAYS = 7;
const LOOK_AHEAD_DAYS = 21;
export type LoadedSettings = {
shopName: string;
timezone: string;
countryIsoCode: string;
subdivisionCode: string;
refreshRateOpenSec: number;
refreshRateClosedSec: number;
imageFormat: 'bmp' | 'png';
};
const FALLBACK_SETTINGS: LoadedSettings = {
shopName: 'ITA ITO',
timezone: 'Europe/Zurich',
countryIsoCode: 'CH',
subdivisionCode: 'CH-GE',
refreshRateOpenSec: 600,
refreshRateClosedSec: 7200,
imageFormat: 'bmp',
};
export async function loadSettings(): Promise<LoadedSettings> {
const row = await prisma.settings.findUnique({ where: { id: 'singleton' } });
if (!row) {
// A freshly created database must still serve a screen rather than a 500.
return FALLBACK_SETTINGS;
}
return {
shopName: row.shopName,
timezone: row.timezone,
countryIsoCode: row.countryIsoCode,
subdivisionCode: row.subdivisionCode,
refreshRateOpenSec: row.refreshRateOpenSec,
refreshRateClosedSec: row.refreshRateClosedSec,
imageFormat: row.imageFormat === 'png' ? 'png' : 'bmp',
};
}
export async function loadScheduleContext(
now: Date,
settings: LoadedSettings,
): Promise<ScheduleContext> {
const today = toCivilDate(now, settings.timezone);
// The window starts at the Monday of the current week or earlier, whichever
// reaches further back, so the week strip is always fully covered.
const from = min(startOfCivilWeek(today), addCivilDays(today, -LOOK_BACK_DAYS));
const to = addCivilDays(today, LOOK_AHEAD_DAYS);
const [weekly, exceptions, vacations, holidays] = await Promise.all([
prisma.weeklySchedule.findMany({ orderBy: { dayOfWeek: 'asc' } }),
prisma.scheduleException.findMany({
where: { date: { gte: asDate(from), lte: asDate(to) } },
}),
prisma.vacationPeriod.findMany({
where: { startDate: { lte: asDate(to) }, endDate: { gte: asDate(from) } },
}),
prisma.publicHoliday.findMany({
where: {
date: { gte: asDate(from), lte: asDate(to) },
subdivisionCode: settings.subdivisionCode,
},
}),
]);
return {
timezone: settings.timezone,
weekly: weekly.map((day) => ({
dayOfWeek: day.dayOfWeek,
isClosed: day.isClosed,
slots: asSlots(day.slots),
})),
exceptions: exceptions.map((exception) => ({
date: asCivil(exception.date),
isClosed: exception.isClosed,
slots: exception.slots === null ? null : asSlots(exception.slots),
reason: exception.reason,
noteFr: exception.noteFr,
noteEn: exception.noteEn,
source: exception.source,
})),
vacations: vacations.map((period) => ({
startDate: asCivil(period.startDate),
endDate: asCivil(period.endDate),
labelFr: period.labelFr,
labelEn: period.labelEn,
})),
holidays: holidays.map((holiday) => ({
date: asCivil(holiday.date),
nameFr: holiday.nameFr,
nameEn: holiday.nameEn,
isAutoClosed: holiday.isAutoClosed,
})),
};
}
/**
* A `@db.Date` column comes back as midnight UTC, so the first ten characters
* of the ISO string are the civil date with no timezone maths involved.
*/
function asCivil(value: Date): CivilDate {
return value.toISOString().slice(0, 10);
}
function asDate(value: CivilDate): Date {
return new Date(`${value}T00:00:00.000Z`);
}
function min(a: CivilDate, b: CivilDate): CivilDate {
return a < b ? a : b;
}
/**
* Slots live in a JSON column, so they arrive untyped. Anything malformed is
* dropped rather than allowed to reach the resolver: a bad row should cost one
* day's hours, not the whole screen.
*/
function asSlots(value: unknown): Slot[] {
if (!Array.isArray(value)) {
return [];
}
return value.filter(
(slot): slot is Slot =>
typeof slot === 'object' &&
slot !== null &&
typeof (slot as Slot).open === 'string' &&
typeof (slot as Slot).close === 'string',
);
}
+121
View File
@@ -0,0 +1,121 @@
/**
* Assembles, renders and stores the current panel image.
*
* The image is addressed by the hash of its own bytes. That single decision
* buys three things: the device skips the redraw when the name has not changed
* (which is where the battery life comes from), the URL is safe to cache
* forever, and it cannot be enumerated.
*/
import { createHash } from 'node:crypto';
import { prisma } from '@/lib/db';
import { loadScheduleContext, loadSettings, type LoadedSettings } from '@/lib/schedule/context';
import { getCurrentStatus } from '@/lib/schedule/resolver';
import type { ScheduleContext, ShopStatus } from '@/lib/schedule/types';
import type { ScreenPayload } from './contract';
import { encodeScreen } from './encode';
import { renderScreenSvg } from './render';
import { buildScreenPayload, type MessageCandidate } from './viewmodel';
/** Long enough that a collision is not a thing worth thinking about. */
const HASH_LENGTH = 16;
/** How many rendered images to keep. Enough to cover a device mid-fetch. */
const KEEP_IMAGES = 20;
export type CurrentScreen = {
payload: ScreenPayload;
settings: LoadedSettings;
context: ScheduleContext;
status: ShopStatus;
};
export async function buildCurrentScreen(now: Date, baseUrl: string): Promise<CurrentScreen> {
const settings = await loadSettings();
const context = await loadScheduleContext(now, settings);
const messages = await loadMessages();
return {
payload: buildScreenPayload({
now,
ctx: context,
shopName: settings.shopName,
logoUrl: `${baseUrl}/brand/logo-eink.png`,
messages,
}),
settings,
context,
status: getCurrentStatus(now, context),
};
}
export type StoredImage = {
hash: string;
format: 'bmp' | 'png';
filename: string;
};
/**
* Renders the payload and stores the bytes under their own hash.
*
* Re-rendering an unchanged screen produces the same hash and the same row, so
* this is idempotent by construction: nothing accumulates while the shop's
* hours stay put.
*/
export async function renderAndStore(
payload: ScreenPayload,
format: 'bmp' | 'png',
): Promise<StoredImage> {
const svg = await renderScreenSvg(payload);
const bytes = encodeScreen(svg, format);
const hash = createHash('sha256').update(bytes).digest('hex').slice(0, HASH_LENGTH);
const filename = `${hash}.${format}`;
await prisma.screenImage.upsert({
where: { hash },
update: {},
// Prisma's Bytes maps to Uint8Array; Buffer is one, but its backing store
// is typed loosely enough that TypeScript wants it said explicitly.
create: { hash, format, bytes: new Uint8Array(bytes) },
});
await pruneOldImages();
return { hash, format, filename };
}
export async function findStoredImage(hash: string): Promise<{ bytes: Buffer; format: string } | null> {
const row = await prisma.screenImage.findUnique({ where: { hash } });
if (!row) {
return null;
}
return { bytes: Buffer.from(row.bytes), format: row.format };
}
async function pruneOldImages(): Promise<void> {
const keep = await prisma.screenImage.findMany({
orderBy: { createdAt: 'desc' },
take: KEEP_IMAGES,
select: { hash: true },
});
await prisma.screenImage.deleteMany({
where: { hash: { notIn: keep.map((row) => row.hash) } },
});
}
async function loadMessages(): Promise<MessageCandidate[]> {
const rows = await prisma.message.findMany({
where: { isActive: true },
orderBy: { priority: 'desc' },
});
return rows.map((row) => ({
textFr: row.textFr,
textEn: row.textEn,
startsAt: row.startsAt,
endsAt: row.endsAt,
priority: row.priority,
isActive: row.isActive,
}));
}