Sichtungen
Der Ordner demo-kit/ simuliert das Gerät für die Demo auf der Startseite. Auf dem Gerät wird er nicht benötigt.
Der Ordner demo-kit/ simuliert das Gerät für die Demo auf der Startseite. Auf dem Gerät wird er nicht benötigt.
// The field log's web server: a nature journal of sightings (birds, butterflies, whatever was seen)
// kept in memory, with its own screen (docs/device-ui/README.md). It knows nothing about Connectivitizer; index.mjs makes it reachable.
//
// It will run unattended as a demo device that anyone with the right account can reach, so
// everything it keeps is bounded: at most MAX_ENTRIES entries (the oldest go first), photos, voice
// notes and notes of a limited size, and entries are forgotten after KEEP_HOURS. Nothing is written
// to disk.
//
// node server.mjs [port] the server alone on 127.0.0.1 (default 8770), without Connectivitizer
import { randomBytes } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { createServer } from 'node:http';
import { fileURLToPath } from 'node:url';
export const LIMITS = Object.freeze({
maxEntries: 30,
maxNoteChars: 1000,
maxSpeciesChars: 80,
maxCount: 999,
maxPhotoBytes: 1_500_000,
maxAudioBytes: 1_000_000,
maxJsonBytes: 16 * 1024,
keepHours: 24,
});
// What the page may upload, recognised by the first bytes as well as by the Content-Type.
const PHOTO_TYPES = {
'image/jpeg': (b) => b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff,
'image/png': (b) => b.length > 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])),
'image/webp': (b) => b.length > 12 && b.toString('latin1', 0, 4) === 'RIFF' && b.toString('latin1', 8, 12) === 'WEBP',
};
const AUDIO_TYPES = {
'audio/webm': (b) => b.length > 4 && b[0] === 0x1a && b[1] === 0x45 && b[2] === 0xdf && b[3] === 0xa3,
'audio/ogg': (b) => b.length > 4 && b.toString('latin1', 0, 4) === 'OggS',
'audio/mp4': (b) => b.length > 12 && b.toString('latin1', 4, 8) === 'ftyp',
'audio/mpeg': (b) => b.length > 3 && (b.toString('latin1', 0, 3) === 'ID3' || (b[0] === 0xff && (b[1] & 0xe0) === 0xe0)),
'audio/wav': (b) => b.length > 12 && b.toString('latin1', 0, 4) === 'RIFF' && b.toString('latin1', 8, 12) === 'WAVE',
};
const AUDIO_ALIASES = { 'audio/x-m4a': 'audio/mp4', 'audio/aac': 'audio/mp4', 'audio/x-wav': 'audio/wav', 'audio/wave': 'audio/wav', 'video/webm': 'audio/webm' };
const page = readFileSync(fileURLToPath(new URL('ui/field-log.html', import.meta.url)));
// The app's bar in the page's light colours; the page switches it to the dark ones itself
// (connectivitizer.setTheme) when the phone is set to dark.
const manifest = readFileSync(fileURLToPath(new URL('ui/manifest.json', import.meta.url)), 'utf8').trim();
// Opened straight from this server in a browser, the page gets about the policy the app gives it
// (docs/device-ui/README.md, "What the page can and cannot do"), so that breaking it shows here too.
// In the app and in `cz ui` the policy is theirs.
const pagePolicy =
"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; media-src data: blob:; font-src data:; connect-src 'self'; form-action 'none'; base-uri 'none'; frame-ancestors 'none'";
/** One sentence in plain text, as every error of this server is. */
class Refusal extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
/** The body of a request, at most `limit` bytes; more is refused with 413 and `tooLarge`. */
function readBody(request, limit, tooLarge) {
const declared = Number(request.headers['content-length']);
if (Number.isFinite(declared) && declared > limit) {
request.resume();
return Promise.reject(new Refusal(413, tooLarge));
}
return new Promise((resolve, reject) => {
const chunks = [];
let size = 0;
let refused = false;
request.on('data', (chunk) => {
if (refused) return;
size += chunk.length;
if (size > limit) {
refused = true;
chunks.length = 0;
reject(new Refusal(413, tooLarge));
return;
}
chunks.push(chunk);
});
request.on('end', () => refused || resolve(Buffer.concat(chunks, size)));
request.on('error', reject);
});
}
/** `image/jpeg; q=1` -> `image/jpeg`. */
const baseType = (header) => String(header ?? '').split(';')[0].trim().toLowerCase();
function readLocation(value) {
if (value === undefined || value === null) return null;
if (typeof value !== 'object') throw new Refusal(400, 'The location has to be an object with lat, lon and accuracy.');
const { lat, lon, accuracy } = value;
const isNumber = (n) => typeof n === 'number' && Number.isFinite(n);
if (!isNumber(lat) || lat < -90 || lat > 90) throw new Refusal(400, 'The latitude has to be a number from -90 to 90.');
if (!isNumber(lon) || lon < -180 || lon > 180) throw new Refusal(400, 'The longitude has to be a number from -180 to 180.');
if (accuracy !== undefined && accuracy !== null && (!isNumber(accuracy) || accuracy < 0 || accuracy > 1_000_000)) {
throw new Refusal(400, 'The accuracy has to be a number of metres from 0 to 1000000.');
}
const round = (n, places) => Math.round(n * 10 ** places) / 10 ** places;
return { lat: round(lat, 6), lon: round(lon, 6), accuracy: isNumber(accuracy) ? Math.round(accuracy) : null };
}
function readNote(value, limits) {
if (value === undefined || value === null) return '';
if (typeof value !== 'string') throw new Refusal(400, 'The note has to be text.');
// Line breaks and tabs stay; other control characters go.
const note = value.replace(/\r\n?/g, '\n').replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '').trim();
if ([...note].length > limits.maxNoteChars) throw new Refusal(413, `The note is longer than ${limits.maxNoteChars} characters.`);
return note;
}
function readSpecies(value, limits) {
if (value === undefined || value === null) return '';
if (typeof value !== 'string') throw new Refusal(400, 'The species has to be text.');
// One line: control characters go, runs of spaces become one.
const species = value.replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim();
if ([...species].length > limits.maxSpeciesChars) throw new Refusal(400, `The species is longer than ${limits.maxSpeciesChars} characters.`);
return species;
}
function readCount(value, limits) {
if (value === undefined || value === null) return null;
if (!Number.isInteger(value) || value < 1 || value > limits.maxCount) throw new Refusal(400, `The count has to be a whole number from 1 to ${limits.maxCount}.`);
return value;
}
/** A JSON object from the body of a request, or a refusal that says what is wrong. */
async function readEntryJson(request, limits) {
if (baseType(request.headers['content-type']) !== 'application/json') throw new Refusal(415, 'Send the entry as application/json.');
const body = await readBody(request, limits.maxJsonBytes, `The entry is too large; a note can have at most ${limits.maxNoteChars} characters.`);
let value;
try {
value = JSON.parse(body.toString('utf8'));
} catch {
throw new Refusal(400, 'The entry is not valid JSON.');
}
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Refusal(400, 'The entry has to be a JSON object.');
return value;
}
/**
* The field log's HTTP server, not yet listening. `options` overrides LIMITS (for tests) and
* `now` the clock.
*/
export function createFieldLogServer(options = {}) {
const limits = { ...LIMITS, ...options };
const now = options.now ?? Date.now;
const started = now();
/**
* Newest first. Each: { id, createdAt, note, species, count, location, photo: {type, data}|null,
* audio: {type, data}|null, sample }. species is '' and count null when the person gave none.
*/
let entries = [];
if (options.sample !== false) {
// One entry to start with, so that a fresh device already shows what an entry looks like and
// has an "Open in map" link. It is not forgotten after KEEP_HOURS, only deleted or pushed out.
entries.push({
id: randomBytes(6).toString('hex'),
createdAt: new Date(started).toISOString(),
note: 'Example entry: a blackbird singing from the top of a lime tree in the Tiergarten, Berlin. Add your own sightings above, and delete this one whenever you like.',
species: 'Blackbird',
count: 1,
location: { lat: 52.514548, lon: 13.350095, accuracy: 15 },
photo: null,
audio: null,
sample: true,
});
}
const forgetOld = () => {
const oldest = now() - limits.keepHours * 3_600_000;
entries = entries.filter((entry) => entry.sample || Date.parse(entry.createdAt) >= oldest);
};
const describe = (entry) => ({
id: entry.id,
createdAt: entry.createdAt,
note: entry.note,
species: entry.species ?? '',
count: entry.count ?? null,
location: entry.location,
photo: entry.photo && { type: entry.photo.type, size: entry.photo.data.length },
audio: entry.audio && { type: entry.audio.type, size: entry.audio.data.length },
sample: entry.sample || undefined,
});
const find = (id) => {
forgetOld();
const entry = entries.find((candidate) => candidate.id === id);
if (!entry) throw new Refusal(404, 'There is no such entry; it may have been deleted or pushed out by newer ones.');
return entry;
};
const json = (response, status, value) => {
const body = JSON.stringify(value);
response.writeHead(status, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body), 'Cache-Control': 'no-store' }).end(body);
};
async function handle(request, response) {
const url = new URL(request.url, 'http://field-log');
const path = url.pathname;
const method = request.method;
// A browser sends a request from another site with Sec-Fetch-Site: cross-site. The app's bridge
// and `cz ui` do not; a browser that opened the page from this server says same-origin.
if (method !== 'GET' && method !== 'HEAD' && request.headers['sec-fetch-site'] === 'cross-site') {
throw new Refusal(403, 'Requests from other sites are refused.');
}
if (method === 'GET' && path === '/.cz/ui.json') {
response.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }).end(manifest);
return;
}
if (method === 'GET' && path === '/.cz/ui.html') {
response
.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': page.length, 'Cache-Control': 'no-store', 'Content-Security-Policy': pagePolicy, 'X-Content-Type-Options': 'nosniff' })
.end(page);
return;
}
if (method === 'GET' && path === '/info') {
forgetOld();
json(response, 200, {
name: 'Sightings',
entries: entries.length,
uptimeSeconds: Math.floor((now() - started) / 1000),
limits: { maxEntries: limits.maxEntries, maxNoteChars: limits.maxNoteChars, maxSpeciesChars: limits.maxSpeciesChars, maxCount: limits.maxCount, maxPhotoBytes: limits.maxPhotoBytes, maxAudioBytes: limits.maxAudioBytes, keepHours: limits.keepHours },
appsConnected: options.appsConnected?.() ?? 0,
});
return;
}
if (path === '/entries') {
if (method === 'GET') {
forgetOld();
json(response, 200, entries.map(describe));
return;
}
if (method === 'POST') {
const value = await readEntryJson(request, limits);
const entry = {
id: randomBytes(6).toString('hex'),
createdAt: new Date(now()).toISOString(),
note: readNote(value.note, limits),
species: readSpecies(value.species, limits),
count: readCount(value.count, limits),
location: readLocation(value.location),
photo: null,
audio: null,
sample: false,
};
forgetOld();
entries.unshift(entry);
// The oldest go first, the example entry among them.
entries.length = Math.min(entries.length, limits.maxEntries);
console.log(`Entry ${entry.id} added (${entries.length} kept).`);
json(response, 201, describe(entry));
return;
}
throw new Refusal(405, 'Use GET or POST here.');
}
const match = /^\/entries\/([0-9a-f]{12})(?:\/(photo|audio))?$/.exec(path);
if (!match) throw new Refusal(404, 'There is nothing at this address.');
const [, id, part] = match;
if (!part) {
if (method === 'GET') return json(response, 200, describe(find(id)));
if (method === 'PUT') {
// A change of the words: what the body names is replaced, what it leaves out stays.
find(id);
const value = await readEntryJson(request, limits);
const change = {};
if ('note' in value) change.note = readNote(value.note, limits);
if ('species' in value) change.species = readSpecies(value.species, limits);
if ('count' in value) change.count = readCount(value.count, limits);
if ('location' in value) change.location = readLocation(value.location);
// The entry may have been deleted while the request was on its way.
const entry = Object.assign(find(id), change);
console.log(`Entry ${id} changed.`);
return json(response, 200, describe(entry));
}
if (method === 'DELETE') {
find(id);
entries = entries.filter((entry) => entry.id !== id);
console.log(`Entry ${id} deleted (${entries.length} kept).`);
response.writeHead(204).end();
return;
}
throw new Refusal(405, 'Use GET, PUT or DELETE here.');
}
const isPhoto = part === 'photo';
if (method === 'GET') {
const media = find(id)[part];
if (!media) throw new Refusal(404, isPhoto ? 'This entry has no photo.' : 'This entry has no voice note.');
response
.writeHead(200, { 'Content-Type': media.type, 'Content-Length': media.data.length, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Content-Disposition': 'inline' })
.end(media.data);
return;
}
if (method === 'PUT') {
find(id);
let type = baseType(request.headers['content-type']);
if (!isPhoto) type = AUDIO_ALIASES[type] ?? type;
const known = isPhoto ? PHOTO_TYPES : AUDIO_TYPES;
if (!known[type]) {
throw new Refusal(415, isPhoto ? 'A photo has to be a JPEG, PNG or WebP picture.' : 'A voice note has to be WebM, Ogg, MP4, MP3 or WAV audio.');
}
const limit = isPhoto ? limits.maxPhotoBytes : limits.maxAudioBytes;
const tooLarge = isPhoto
? `The photo is larger than ${(limits.maxPhotoBytes / 1_000_000).toFixed(1)} MB.`
: `The voice note is larger than ${(limits.maxAudioBytes / 1_000_000).toFixed(1)} MB.`;
const data = await readBody(request, limit, tooLarge);
if (!known[type](data)) throw new Refusal(415, isPhoto ? `This is not a ${type} picture.` : `This is not ${type} audio.`);
// The entry may have been deleted while the upload was on its way.
const entry = find(id);
entry[part] = { type, data };
json(response, 200, describe(entry));
return;
}
if (method === 'DELETE') {
const entry = find(id);
entry[part] = null;
json(response, 200, describe(entry));
return;
}
throw new Refusal(405, 'Use GET, PUT or DELETE here.');
}
const server = createServer((request, response) => {
handle(request, response).catch((error) => {
const status = error instanceof Refusal ? error.status : 500;
if (status === 500) console.error(error);
const text = error instanceof Refusal ? error.message : 'Something went wrong on the device.';
if (response.headersSent) {
response.destroy();
return;
}
// After a refused upload the rest of the body is not read; the connection goes with the answer.
response.writeHead(status, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store', Connection: 'close' }).end(text);
});
});
// Slow or stalled uploads do not hold the server forever.
server.requestTimeout = 60_000;
server.headersTimeout = 15_000;
return server;
}
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
const port = Number(process.argv[2] ?? process.env.FIELD_LOG_PORT ?? 8770);
const server = createFieldLogServer();
server.listen(port, '127.0.0.1', () => console.log(`Sightings (field log) on http://127.0.0.1:${server.address().port}/.cz/ui.html (without Connectivitizer). Ctrl+C stops.`));
}