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:
@@ -0,0 +1,42 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { findStoredImage } from '@/lib/screen/service';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
const CONTENT_TYPES: Record<string, string> = {
|
||||
bmp: 'image/bmp',
|
||||
png: 'image/png',
|
||||
};
|
||||
|
||||
/**
|
||||
* Serves a rendered panel image.
|
||||
*
|
||||
* The path is the hash of the bytes, so the content can never change under a
|
||||
* given URL: it is safe to cache forever, and it cannot be enumerated. No
|
||||
* authentication — the firmware fetches it as a plain image, and an
|
||||
* unguessable immutable URL is the protection.
|
||||
*/
|
||||
export async function GET(_request: Request, { params }: { params: Promise<{ hash: string }> }) {
|
||||
const { hash: raw } = await params;
|
||||
const [hash, extension] = raw.split('.');
|
||||
|
||||
if (!hash || !/^[0-9a-f]{8,64}$/.test(hash)) {
|
||||
return new NextResponse(null, { status: 404 });
|
||||
}
|
||||
|
||||
const image = await findStoredImage(hash);
|
||||
if (!image) {
|
||||
return new NextResponse(null, { status: 404 });
|
||||
}
|
||||
|
||||
const contentType = CONTENT_TYPES[extension ?? image.format] ?? 'application/octet-stream';
|
||||
|
||||
return new NextResponse(new Uint8Array(image.bytes), {
|
||||
headers: {
|
||||
'Content-Type': contentType,
|
||||
'Content-Length': String(image.bytes.length),
|
||||
'Cache-Control': 'public, max-age=31536000, immutable',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { publicBaseUrl } from '@/lib/config';
|
||||
import { clientIp, deviceHeader, deviceNumber } from '@/lib/device/headers';
|
||||
import { computeRefreshRate } from '@/lib/device/refresh';
|
||||
import { authenticateDevice } from '@/lib/device/session';
|
||||
import { prisma } from '@/lib/db';
|
||||
import { rateLimit } from '@/lib/ratelimit';
|
||||
import { buildCurrentScreen, renderAndStore } from '@/lib/screen/service';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
/**
|
||||
* The only call that matters. The panel wakes, asks what to show, and goes
|
||||
* back to sleep for `refresh_rate` seconds.
|
||||
*
|
||||
* `filename` is the hash of the image bytes: when it matches what the firmware
|
||||
* already has, it skips the redraw. That is where the battery life comes from,
|
||||
* so the renderer must stay byte-stable for unchanged content.
|
||||
*/
|
||||
export async function GET(request: Request) {
|
||||
const limit = rateLimit(`display:${clientIp(request)}`, 60, 60_000);
|
||||
if (!limit.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Trop de requêtes' },
|
||||
{ status: 429, headers: { 'Retry-After': String(limit.retryAfter) } },
|
||||
);
|
||||
}
|
||||
|
||||
const device = await authenticateDevice(request);
|
||||
if (!device) {
|
||||
return NextResponse.json({ error: 'Jeton invalide' }, { status: 401 });
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const baseUrl = publicBaseUrl(request);
|
||||
const { payload, settings, status } = await buildCurrentScreen(now, baseUrl);
|
||||
const image = await renderAndStore(payload, settings.imageFormat);
|
||||
|
||||
const refreshRate = computeRefreshRate({
|
||||
now,
|
||||
status,
|
||||
timezone: settings.timezone,
|
||||
openSec: settings.refreshRateOpenSec,
|
||||
closedSec: settings.refreshRateClosedSec,
|
||||
});
|
||||
|
||||
await prisma.device.update({
|
||||
where: { id: device.id },
|
||||
data: {
|
||||
lastSeenAt: now,
|
||||
fwVersion: deviceHeader(request, 'fw-version'),
|
||||
batteryVoltage: deviceNumber(request, 'battery-voltage'),
|
||||
percentCharged: roundOrNull(deviceNumber(request, 'percent-charged')),
|
||||
rssi: roundOrNull(deviceNumber(request, 'rssi')),
|
||||
lastFilename: image.filename,
|
||||
lastRefreshRate: refreshRate,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
image_url: `${baseUrl}/api/device/image/${image.filename}`,
|
||||
filename: image.filename,
|
||||
refresh_rate: refreshRate,
|
||||
// Firmware updates are not this application's business: it drives a
|
||||
// display, it does not manage the fleet.
|
||||
update_firmware: false,
|
||||
reset_firmware: false,
|
||||
firmware_url: null,
|
||||
firmware_version: null,
|
||||
special_function: 'none',
|
||||
image_url_timeout: 0,
|
||||
},
|
||||
{ headers: { 'Cache-Control': 'no-store' } },
|
||||
);
|
||||
}
|
||||
|
||||
function roundOrNull(value: number | null): number | null {
|
||||
return value === null ? null : Math.round(value);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { authenticateDevice } from '@/lib/device/session';
|
||||
import { clientIp } from '@/lib/device/headers';
|
||||
import { prisma } from '@/lib/db';
|
||||
import { rateLimit } from '@/lib/ratelimit';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
/** Never let a firmware in a retry loop fill the table in one request. */
|
||||
const MAX_ENTRIES_PER_CALL = 50;
|
||||
|
||||
type IncomingLog = {
|
||||
message?: unknown;
|
||||
level?: unknown;
|
||||
created_at?: unknown;
|
||||
};
|
||||
|
||||
/**
|
||||
* Firmware-side logs. Answered with 204 whatever happens to the contents: a
|
||||
* device that cannot file a log must not conclude the server is down and
|
||||
* start retrying, and these records are diagnostics, not data.
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
const limit = rateLimit(`log:${clientIp(request)}`, 30, 60_000);
|
||||
if (!limit.allowed) {
|
||||
return new NextResponse(null, { status: 429 });
|
||||
}
|
||||
|
||||
const device = await authenticateDevice(request);
|
||||
if (!device) {
|
||||
return NextResponse.json({ error: 'Jeton invalide' }, { status: 401 });
|
||||
}
|
||||
|
||||
let entries: IncomingLog[] = [];
|
||||
try {
|
||||
const body: unknown = await request.json();
|
||||
const logs = (body as { logs?: unknown } | null)?.logs;
|
||||
if (Array.isArray(logs)) {
|
||||
entries = logs.slice(0, MAX_ENTRIES_PER_CALL) as IncomingLog[];
|
||||
}
|
||||
} catch {
|
||||
// A malformed body is a diagnostic in itself; 204 keeps the device calm.
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
if (entries.length > 0) {
|
||||
await prisma.deviceLog.createMany({
|
||||
data: entries.map((entry) => ({
|
||||
deviceId: device.id,
|
||||
level: levelOf(entry.level),
|
||||
message: String(entry.message ?? '').slice(0, 2000) || '(vide)',
|
||||
payload: entry as object,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
function levelOf(value: unknown): 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' {
|
||||
const level = String(value ?? '').toUpperCase();
|
||||
return level === 'DEBUG' || level === 'WARN' || level === 'ERROR' ? level : 'INFO';
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { publicBaseUrl } from '@/lib/config';
|
||||
import { generateDeviceToken, generateFriendlyId, hashToken, normaliseMac } from '@/lib/device/auth';
|
||||
import { clientIp, deviceHeader } from '@/lib/device/headers';
|
||||
import { prisma } from '@/lib/db';
|
||||
import { rateLimit } from '@/lib/ratelimit';
|
||||
import { buildCurrentScreen, renderAndStore } from '@/lib/screen/service';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
/**
|
||||
* First contact. The firmware sends its MAC in the `ID` header and expects a
|
||||
* token back, which it then stores and presents on every later call.
|
||||
*
|
||||
* A device that is already registered is answered with an empty `api_key`: we
|
||||
* only ever stored the digest, so the original cannot be handed out again. If
|
||||
* a panel ever loses its token, an administrator re-pairs it from the settings
|
||||
* page — which is the correct outcome, not a gap.
|
||||
*/
|
||||
export async function GET(request: Request) {
|
||||
const limit = rateLimit(`setup:${clientIp(request)}`, 10, 60_000);
|
||||
if (!limit.allowed) {
|
||||
return NextResponse.json(
|
||||
{ status: 429, message: 'Trop de tentatives' },
|
||||
{ status: 429, headers: { 'Retry-After': String(limit.retryAfter) } },
|
||||
);
|
||||
}
|
||||
|
||||
const mac = normaliseMac(deviceHeader(request, 'id'));
|
||||
if (!mac) {
|
||||
return NextResponse.json(
|
||||
{ status: 404, message: 'Adresse MAC absente ou invalide' },
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
|
||||
const baseUrl = publicBaseUrl(request);
|
||||
const existing = await prisma.device.findUnique({ where: { macAddress: mac } });
|
||||
|
||||
if (existing) {
|
||||
return NextResponse.json({
|
||||
status: 200,
|
||||
api_key: '',
|
||||
friendly_id: existing.friendlyId,
|
||||
image_url: await welcomeImageUrl(baseUrl),
|
||||
message: 'Appareil déjà appairé',
|
||||
});
|
||||
}
|
||||
|
||||
const token = generateDeviceToken();
|
||||
const device = await prisma.device.create({
|
||||
data: {
|
||||
macAddress: mac,
|
||||
friendlyId: await uniqueFriendlyId(),
|
||||
apiKeyHash: hashToken(token),
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
status: 200,
|
||||
api_key: token,
|
||||
friendly_id: device.friendlyId,
|
||||
image_url: await welcomeImageUrl(baseUrl),
|
||||
message: 'Bienvenue',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Never let a rendering failure cost us the pairing.
|
||||
*
|
||||
* The token is issued once and only its digest is kept, so if the response
|
||||
* that carries it fails the device is stranded: registered, but holding no
|
||||
* credential, and unable to register again. The welcome image is worth far
|
||||
* less than that, and the next /api/display call will produce one anyway.
|
||||
*/
|
||||
async function welcomeImageUrl(baseUrl: string): Promise<string> {
|
||||
try {
|
||||
const { payload, settings } = await buildCurrentScreen(new Date(), baseUrl);
|
||||
const image = await renderAndStore(payload, settings.imageFormat);
|
||||
return `${baseUrl}/api/device/image/${image.filename}`;
|
||||
} catch (error) {
|
||||
console.error('Could not render the welcome image', error);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
async function uniqueFriendlyId(): Promise<string> {
|
||||
for (let attempt = 0; attempt < 10; attempt += 1) {
|
||||
const candidate = generateFriendlyId();
|
||||
const taken = await prisma.device.findUnique({ where: { friendlyId: candidate } });
|
||||
if (!taken) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
throw new Error('Could not allocate a friendly id');
|
||||
}
|
||||
Reference in New Issue
Block a user