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
+275
View File
@@ -0,0 +1,275 @@
import { beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { GET as display } from '@/app/api/display/route';
import { GET as image } from '@/app/api/device/image/[hash]/route';
import { POST as log } from '@/app/api/log/route';
import { GET as setup } from '@/app/api/setup/route';
import { prisma } from '@/lib/db';
import { resetRateLimits } from '@/lib/ratelimit';
import { deviceRequest, hasDatabase, resetDatabase } from './helpers';
const MAC = 'FE:68:44:CE:CA:C3';
describe.skipIf(!hasDatabase)('device API', () => {
beforeAll(async () => {
await resetDatabase();
});
beforeEach(async () => {
await prisma.deviceLog.deleteMany();
await prisma.device.deleteMany();
await prisma.screenImage.deleteMany();
await prisma.scheduleException.deleteMany();
resetRateLimits();
});
async function pair(): Promise<{ token: string; friendlyId: string }> {
const response = await setup(deviceRequest('/api/setup', { ID: MAC }));
const body = (await response.json()) as { api_key: string; friendly_id: string };
return { token: body.api_key, friendlyId: body.friendly_id };
}
describe('GET /api/setup', () => {
it('registers an unknown device and hands it a token', async () => {
const response = await setup(deviceRequest('/api/setup', { ID: MAC }));
const body = (await response.json()) as Record<string, unknown>;
expect(response.status).toBe(200);
expect(body.status).toBe(200);
expect(String(body.api_key)).toHaveLength(43);
expect(String(body.friendly_id)).toMatch(/^[A-Z2-9]{6}$/);
// Only the digest is kept: the plaintext must not be recoverable.
const stored = await prisma.device.findUnique({ where: { macAddress: MAC } });
expect(stored?.apiKeyHash).toMatch(/^[0-9a-f]{64}$/);
expect(stored?.apiKeyHash).not.toBe(body.api_key);
});
it('recognises the same device however the firmware spells its MAC', async () => {
const { friendlyId } = await pair();
const again = await setup(deviceRequest('/api/setup', { id: 'fe-68-44-ce-ca-c3' }));
const body = (await again.json()) as Record<string, unknown>;
expect(body.friendly_id).toBe(friendlyId);
// The token was issued once and only its digest kept, so it cannot be
// handed out a second time.
expect(body.api_key).toBe('');
expect(await prisma.device.count()).toBe(1);
});
it('refuses a missing or malformed MAC', async () => {
const body = (await (await setup(deviceRequest('/api/setup'))).json()) as { status: number };
expect(body.status).toBe(404);
expect(await prisma.device.count()).toBe(0);
});
});
describe('GET /api/display', () => {
it('refuses a request with no token', async () => {
await pair();
expect((await display(deviceRequest('/api/display'))).status).toBe(401);
});
it('refuses a request with the wrong token', async () => {
await pair();
const response = await display(
deviceRequest('/api/display', { 'Access-Token': 'not-the-token', ID: MAC }),
);
expect(response.status).toBe(401);
});
it('refuses a deactivated device', async () => {
const { token } = await pair();
await prisma.device.update({ where: { macAddress: MAC }, data: { isActive: false } });
const response = await display(deviceRequest('/api/display', { 'Access-Token': token }));
expect(response.status).toBe(401);
});
it('answers a paired device with an image and a wake interval', async () => {
const { token } = await pair();
const response = await display(
deviceRequest('/api/display', { 'Access-Token': token, ID: MAC }),
);
const body = (await response.json()) as Record<string, unknown>;
expect(response.status).toBe(200);
expect(body.filename).toMatch(/^[0-9a-f]{16}\.bmp$/);
expect(body.image_url).toBe(`https://trmnl.example.test/api/device/image/${body.filename}`);
expect(body.refresh_rate).toBeGreaterThan(0);
expect(body.update_firmware).toBe(false);
expect(body.special_function).toBe('none');
});
it('records the telemetry the firmware sends', async () => {
const { token } = await pair();
await display(
deviceRequest('/api/display', {
'Access-Token': token,
ID: MAC,
'FW-Version': '1.5.2',
'Battery-Voltage': '3.94',
'Percent-Charged': '82',
RSSI: '-62',
}),
);
const device = await prisma.device.findUnique({ where: { macAddress: MAC } });
expect(device?.fwVersion).toBe('1.5.2');
expect(device?.batteryVoltage).toBeCloseTo(3.94);
expect(device?.percentCharged).toBe(82);
expect(device?.rssi).toBe(-62);
expect(device?.lastSeenAt).toBeInstanceOf(Date);
});
it('accepts the underscore spelling of the token header', async () => {
// The TRMNL docs show ACCESS_TOKEN, the Seeed sources Access-Token.
const { token } = await pair();
const response = await display(deviceRequest('/api/display', { ACCESS_TOKEN: token }));
expect(response.status).toBe(200);
});
it('returns the same filename while nothing changes', async () => {
// This is the battery test: an unchanged filename means the firmware
// skips the redraw entirely.
const { token } = await pair();
const headers = { 'Access-Token': token, ID: MAC };
const first = (await (await display(deviceRequest('/api/display', headers))).json()) as {
filename: string;
};
const second = (await (await display(deviceRequest('/api/display', headers))).json()) as {
filename: string;
};
expect(second.filename).toBe(first.filename);
// And it stored one image, not two.
expect(await prisma.screenImage.count()).toBe(1);
});
it('returns a different filename once the hours change', async () => {
const { token } = await pair();
const headers = { 'Access-Token': token, ID: MAC };
const before = (await (await display(deviceRequest('/api/display', headers))).json()) as {
filename: string;
};
const today = new Date();
await prisma.scheduleException.create({
data: {
date: new Date(
`${today.toISOString().slice(0, 10)}T00:00:00.000Z`,
),
isClosed: false,
slots: [{ open: '14:00', close: '18:00' }],
reason: 'SPECIAL_EVENT',
noteFr: 'Ouverture exceptionnelle',
source: 'MANUAL',
},
});
const after = (await (await display(deviceRequest('/api/display', headers))).json()) as {
filename: string;
};
expect(after.filename).not.toBe(before.filename);
});
});
describe('GET /api/device/image/[hash]', () => {
it('serves the image the device was pointed at', async () => {
const { token } = await pair();
const { filename } = (await (
await display(deviceRequest('/api/display', { 'Access-Token': token }))
).json()) as { filename: string };
const response = await image(deviceRequest(`/api/device/image/${filename}`), {
params: Promise.resolve({ hash: filename }),
});
const bytes = Buffer.from(await response.arrayBuffer());
expect(response.status).toBe(200);
expect(response.headers.get('content-type')).toBe('image/bmp');
expect(response.headers.get('cache-control')).toContain('immutable');
// A real 1-bit 800x480 bitmap, header and all.
expect(bytes.subarray(0, 2).toString('ascii')).toBe('BM');
expect(bytes.readInt32LE(18)).toBe(800);
expect(bytes.readInt32LE(22)).toBe(480);
expect(bytes.readUInt16LE(28)).toBe(1);
});
it('returns 404 for an unknown image', async () => {
const response = await image(deviceRequest('/api/device/image/0000000000000000.bmp'), {
params: Promise.resolve({ hash: '0000000000000000.bmp' }),
});
expect(response.status).toBe(404);
});
it('returns 404 for anything that is not a hash', async () => {
const response = await image(deviceRequest('/api/device/image/x'), {
params: Promise.resolve({ hash: '../../etc/passwd' }),
});
expect(response.status).toBe(404);
});
});
describe('POST /api/log', () => {
it('refuses a request with no token', async () => {
const response = await log(
deviceRequest('/api/log', {}, { method: 'POST', body: '{"logs":[]}' }),
);
expect(response.status).toBe(401);
});
it('stores what the firmware reports', async () => {
const { token } = await pair();
const response = await log(
deviceRequest(
'/api/log',
{ 'Access-Token': token, 'Content-Type': 'application/json' },
{
method: 'POST',
body: JSON.stringify({
logs: [{ message: 'wifi connected', level: 'warn', created_at: 1790000000 }],
}),
},
),
);
expect(response.status).toBe(204);
const entries = await prisma.deviceLog.findMany();
expect(entries).toHaveLength(1);
expect(entries[0]?.message).toBe('wifi connected');
expect(entries[0]?.level).toBe('WARN');
});
it('answers 204 to a malformed body rather than making the device retry', async () => {
const { token } = await pair();
const response = await log(
deviceRequest('/api/log', { 'Access-Token': token }, { method: 'POST', body: 'not json' }),
);
expect(response.status).toBe(204);
expect(await prisma.deviceLog.count()).toBe(0);
});
it('caps how much a single call can write', async () => {
const { token } = await pair();
await log(
deviceRequest(
'/api/log',
{ 'Access-Token': token },
{
method: 'POST',
body: JSON.stringify({
logs: Array.from({ length: 200 }, (_, index) => ({ message: `line ${index}` })),
}),
},
),
);
expect(await prisma.deviceLog.count()).toBe(50);
});
});
});
+50
View File
@@ -0,0 +1,50 @@
import { prisma } from '@/lib/db';
/** Integration tests need a real database; without one they refuse to run. */
export const hasDatabase = Boolean(process.env.TEST_DATABASE_URL);
const WEEK = [
{ dayOfWeek: 0, isClosed: true, slots: [] },
{ dayOfWeek: 1, isClosed: true, slots: [] },
{ dayOfWeek: 2, isClosed: false, slots: [{ open: '10:00', close: '18:30' }] },
{
dayOfWeek: 3,
isClosed: false,
slots: [
{ open: '10:00', close: '13:00' },
{ open: '14:00', close: '18:30' },
],
},
{ dayOfWeek: 4, isClosed: false, slots: [{ open: '10:00', close: '18:30' }] },
{ dayOfWeek: 5, isClosed: false, slots: [{ open: '10:00', close: '18:30' }] },
{ dayOfWeek: 6, isClosed: false, slots: [{ open: '10:00', close: '18:30' }] },
];
/** Empties every table and re-seeds the reference week. */
export async function resetDatabase(): Promise<void> {
await prisma.deviceLog.deleteMany();
await prisma.device.deleteMany();
await prisma.screenImage.deleteMany();
await prisma.scheduleException.deleteMany();
await prisma.vacationPeriod.deleteMany();
await prisma.publicHoliday.deleteMany();
await prisma.message.deleteMany();
await prisma.weeklySchedule.deleteMany();
await prisma.settings.deleteMany();
await prisma.settings.create({ data: { id: 'singleton' } });
for (const day of WEEK) {
await prisma.weeklySchedule.create({ data: day });
}
}
export function deviceRequest(
path: string,
headers: Record<string, string> = {},
init: RequestInit = {},
): Request {
return new Request(`https://trmnl.example.test${path}`, {
headers: { host: 'trmnl.example.test', ...headers },
...init,
});
}