Replace project with current server release and Windows setup

Import the 2026-10-09 source release, Fastify/SQLite backend, restored source
assets, and analytics-enabled server build. Replace files from the previous
release while retaining the existing repository history.

Make builds portable across Windows and Linux, configure local startup,
normalize Windows static asset paths, and fix test fixture cleanup and file
URL handling. Exclude local environment settings, databases, dependencies,
validation output, and TypeScript build cache from version control.

Validation: npm ci, static and server builds, 106 arrival tests, and actual
local HTTP checks passed. The full suite passed 467 of 470 tests; three tests
still require QA fixtures omitted from the supplied release, documented in
README-서버실행.md.
This commit is contained in:
2026-10-09 16:43:35 +09:00
parent 71c8d3b7ff
commit e358e24436
642 changed files with 35202 additions and 17642 deletions
+105
View File
@@ -0,0 +1,105 @@
import Fastify, { LogController } from 'fastify';
import fastifyStatic from '@fastify/static';
import rateLimitPlugin from '@fastify/rate-limit';
import { realpath, stat } from 'node:fs/promises';
import { basename, extname, join, relative, sep } from 'node:path';
import { isInside, parsePublicOrigin } from './config.mjs';
const VISITOR_PATTERN = '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$';
const DOG_PATTERN = '^[0-9a-f]{64}$';
const isApi = path => path === '/api' || path.startsWith('/api/');
const errorNames = { 400: 'Invalid request', 403: 'Forbidden', 404: 'Not found', 413: 'Request too large', 415: 'Unsupported media type', 429: 'Too many requests', 503: 'Service unavailable' };
function sendError(reply, status) {
return reply.code(status).header('Cache-Control', 'no-store').send({ error: errorNames[status] ?? 'Request failed' });
}
function bodySchema(key, pattern, length) {
return { type: 'object', additionalProperties: false, required: [key], properties: { [key]: { type: 'string', pattern, minLength: length, maxLength: length } } };
}
function blockedPath(path) {
const parts = path.split('/').filter(Boolean);
return parts.some(p => p === '..' || p.startsWith('.') || /\.(?:sqlite3?|db)(?:-(?:wal|shm|journal))?$/i.test(p)) ||
['server', 'node_modules'].includes(parts[0]) || /^(?:config(?:\..*)?|package(?:-lock)?\.json)$/i.test(basename(path));
}
/** Build an injectable app only; this module never opens a listener. */
export async function buildApp({ store, distRoot, publicOrigin, rateLimit = { max: 60, timeWindow: 60000 } }) {
const origin = parsePublicOrigin(publicOrigin);
const root = await realpath(distRoot);
const app = Fastify({ logger: false, logController: new LogController({ disableRequestLogging: true }), trustProxy: false, bodyLimit: 1024, frameworkErrors: (_error, _request, reply) => sendError(reply, 400), ajv: { customOptions: { removeAdditional: false, coerceTypes: false } } });
let closed = false;
app.addHook('onClose', async () => { if (!closed) { closed = true; store.close(); } });
app.setErrorHandler((error, _request, reply) => {
const status = error.validation ? 400 : [400, 403, 404, 413, 415, 429].includes(error.statusCode) ? error.statusCode : 503;
return sendError(reply, status);
});
app.addHook('onRequest', async (request, reply) => {
// This same-origin service accepts origin-form targets only. Fastify also
// routes absolute-form targets, which must not escape path-based guards.
if (!request.raw.url.startsWith('/') || request.raw.url.startsWith('//')) return sendError(reply, 400);
const rawPath = request.raw.url.split('?')[0];
let path;
try { path = decodeURIComponent(rawPath); } catch { return sendError(reply, 400); }
if (path.includes('\\') || path.includes('\0') || blockedPath(path)) return sendError(reply, 404);
if (isApi(path)) {
reply.header('Cache-Control', 'no-store');
// Origin is abuse friction, not authentication. Missing Origin is permitted.
if (request.headers.origin !== undefined && request.headers.origin !== origin) return sendError(reply, 403);
}
});
await app.register(rateLimitPlugin, {
global: true, max: rateLimit.max, timeWindow: rateLimit.timeWindow,
allowList: request => !isApi(decodeURIComponent(request.raw.url.split('?')[0])),
keyGenerator: request => request.ip,
errorResponseBuilder: () => Object.assign(new Error('Too many requests'), { statusCode: 429 }),
});
// Fastify's default text parser would otherwise accept text/plain before schema validation.
app.removeContentTypeParser('text/plain');
await app.register(fastifyStatic, {
root, serve: false, dotfiles: 'deny', cacheControl: false,
setHeaders(reply, path) {
const name = basename(path);
// Vite writes generated bundles/images directly under assets with an eight-character hash.
// Copied public assets in nested folders (notably existing GLB models) remain revalidated.
const hashedBuildAsset = /^assets[\\/][^\\/]+-[A-Za-z0-9_-]{8}\.(?:m?js|css|png|jpe?g|webp|svg|woff2?|wasm)$/.test(relative(root, path));
reply.header('Cache-Control', /\.html?$/i.test(name) ? 'no-store' : hashedBuildAsset ? 'public,max-age=31536000,immutable' : 'no-cache');
},
});
app.post('/api/visits', { schema: { body: bodySchema('visitor_id', VISITOR_PATTERN, 36) } }, async (request, reply) => {
store.recordVisit(request.body.visitor_id);
return reply.code(204).send();
});
app.post('/api/arrivals', { schema: { body: bodySchema('dog_id', DOG_PATTERN, 64) } }, async (request, reply) => {
store.recordArrival(request.body.dog_id);
return reply.code(204).send();
});
app.get('/api/arrivals/count', async (_request, reply) => {
const count = store.arrivalCount();
if (!Number.isSafeInteger(count) || count < 0) throw new Error('Invalid aggregate');
return reply.send({ count });
});
const notFound = (_request, reply) => sendError(reply, 404);
app.all('/api', { onRequest: notFound }, notFound);
app.all('/api/*', { onRequest: notFound }, notFound);
app.setNotFoundHandler(notFound);
app.get('/*', async (request, reply) => {
const path = decodeURIComponent(request.raw.url.split('?')[0]);
if (isApi(path)) return sendError(reply, 404);
const requested = path === '/' ? '/index.html' : path;
let file;
try {
file = await realpath(join(root, requested));
if (!isInside(root, file) || !(await stat(file)).isFile()) return sendError(reply, 404);
} catch (error) {
if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error;
const acceptsHTML = (request.headers.accept ?? '').split(',').some(value => /^text\/html(?:\s*;|\s*$)/i.test(value.trim()) && !/;\s*q=0(?:\.0*)?(?:\s*;|\s*$)/i.test(value));
if (!acceptsHTML || extname(path) || /^\/(?:assets|fonts|models|workers|wasm)(?:\/|$)/.test(path)) return sendError(reply, 404);
file = await realpath(join(root, 'index.html'));
if (!isInside(root, file)) return sendError(reply, 404);
}
const filePath = relative(root, file).split(sep).join('/');
if (blockedPath(filePath)) return sendError(reply, 404);
return reply.sendFile(filePath);
});
await app.ready();
return app;
}
+16
View File
@@ -0,0 +1,16 @@
import { pathToFileURL } from 'node:url';
import { openReadOnlyStore } from './db.mjs';
export async function createBackup(args, env = process.env) {
if (args.length !== 2 || args[0] !== '--output') throw new Error('Invalid arguments');
const store = openReadOnlyStore(env.DB_PATH);
try { await store.backup(args[1]); }
finally { store.close(); }
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
createBackup(process.argv.slice(2)).then(() => { process.stdout.write('{"ok":true}\n'); }).catch(() => {
process.stderr.write('Backup failed; check existing DB_PATH and a new absolute private --output path\n');
process.exitCode = 1;
});
}
+61
View File
@@ -0,0 +1,61 @@
import { existsSync, lstatSync, realpathSync } from 'node:fs';
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
export const SOURCE_ROOT = realpathSync(fileURLToPath(new URL('..', import.meta.url)));
/** Resolve even a not-yet-created leaf through its nearest existing parent. */
export function canonicalPath(value) {
if (typeof value !== 'string' || !isAbsolute(value)) throw new Error('An absolute path is required');
let existing = resolve(value);
const missing = [];
while (!existsSync(existing)) {
// Do not treat a dangling symlink as a new directory or database.
try { if (lstatSync(existing).isSymbolicLink()) throw new Error('Invalid path'); } catch (error) { if (error.code !== 'ENOENT') throw error; }
const parent = dirname(existing);
if (parent === existing) throw new Error('Invalid path');
missing.unshift(existing.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
existing = parent;
}
return join(realpathSync(existing), ...missing);
}
export function isInside(root, path) {
const rel = relative(root, path);
return rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel));
}
export function privateDatabasePath(value, distRoot = join(SOURCE_ROOT, 'dist')) {
// better-sqlite3 trims filenames. Reject aliases before filesystem/native work
// so exclusive backup reservation, path checks and SQLite address the same file.
if (typeof value !== 'string' || value !== value.trim()) throw new Error('Invalid database path');
const path = canonicalPath(value);
if (path !== path.trim()) throw new Error('Invalid database path');
if ([SOURCE_ROOT, canonicalPath(distRoot), canonicalPath(join(SOURCE_ROOT, 'public'))].some(root => isInside(root, path))) {
throw new Error('Database must be outside source and public files');
}
return path;
}
export function parsePublicOrigin(value) {
if (typeof value !== 'string' || value.trim() !== value) throw new Error('Invalid PUBLIC_ORIGIN');
let url;
try { url = new URL(value); } catch { throw new Error('Invalid PUBLIC_ORIGIN'); }
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.pathname !== '/' || url.search || url.hash || !url.hostname) {
throw new Error('Invalid PUBLIC_ORIGIN');
}
return url.origin;
}
export function readConfig(env = process.env) {
const distRoot = join(SOURCE_ROOT, 'dist');
const dbPath = privateDatabasePath(env.DB_PATH, distRoot);
const portText = env.PORT ?? '3000';
if (!/^[0-9]+$/.test(portText) || +portText < 1 || +portText > 65535) throw new Error('Invalid PORT');
const port = +portText;
const host = env.HOST ?? '127.0.0.1';
if (!host || typeof host !== 'string' || /\s/.test(host)) throw new Error('Invalid HOST');
if (env.NODE_ENV === 'production' && !env.PUBLIC_ORIGIN) throw new Error('PUBLIC_ORIGIN is required in production');
const publicOrigin = parsePublicOrigin(env.PUBLIC_ORIGIN ?? `http://127.0.0.1:${port}`);
return { dbPath, distRoot, host, port, publicOrigin };
}
+114
View File
@@ -0,0 +1,114 @@
import Database from 'better-sqlite3';
import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync } from 'node:fs';
import { dirname } from 'node:path';
import { privateDatabasePath } from './config.mjs';
const INITIAL_SQL = readFileSync(new URL('./migrations/001-initial.sql', import.meta.url), 'utf8');
const COLUMNS = {
visitors_daily: ['visitor_id', 'visit_date', 'first_seen_at', 'last_seen_at'],
arrivals: ['dog_id', 'first_arrived_at'],
};
const seoulDate = new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Seoul', year: 'numeric', month: '2-digit', day: '2-digit' });
export function monthRange(month) {
if (typeof month !== 'string' || !/^(?!0000)[0-9]{4}-(0[1-9]|1[0-2])$/.test(month)) throw new Error('Invalid month; use YYYY-MM');
const year = +month.slice(0, 4);
const number = +month.slice(5);
// Lexicographic upper sentinel keeps the valid 9999-12 month queryable.
const next = number < 12 ? `${month.slice(0, 4)}-${String(number + 1).padStart(2, '0')}` : year < 9999 ? `${String(year + 1).padStart(4, '0')}-01` : '9999-13';
return [`${month}-01`, `${next}-01`];
}
export function assertSchema(db) {
if (db.pragma('user_version', { simple: true }) !== 1) throw new Error('Unsupported database schema');
for (const [table, columns] of Object.entries(COLUMNS)) {
const actual = db.pragma(`table_info(${table})`);
if (actual.map(c => c.name).join() !== columns.join() || actual.some(c => c.type !== 'TEXT' || c.notnull !== 1)) throw new Error('Unsupported database schema');
const keys = actual.filter(c => c.pk).sort((a, b) => a.pk - b.pk).map(c => c.name);
if (keys.join() !== (table === 'arrivals' ? 'dog_id' : 'visitor_id,visit_date')) throw new Error('Unsupported database schema');
}
}
/** Exported for migration rollback verification against a disposable database. */
export function migrateDatabase(db, migrations = [{ version: 1, sql: INITIAL_SQL }]) {
const current = db.pragma('user_version', { simple: true });
const latest = migrations.at(-1)?.version ?? 0;
if (current > latest) throw new Error('Unsupported database version');
db.transaction(() => {
let version = current;
for (const migration of migrations) {
if (migration.version <= version) continue;
if (migration.version !== version + 1) throw new Error('Invalid migration order');
db.exec(migration.sql);
db.pragma(`user_version = ${migration.version}`);
version = migration.version;
}
}).immediate();
}
function privateParent(path) {
const parent = dirname(path);
mkdirSync(parent, { recursive: true, mode: 0o700 });
if (process.platform !== 'win32' && (statSync(parent).mode & 0o077)) throw new Error('Database directory must be private');
}
function safeCount(row) {
if (!Number.isSafeInteger(row.count) || row.count < 0) throw new Error('Invalid aggregate');
return row.count;
}
export function openStore({ dbPath, now = () => new Date(), busyTimeoutMs = 1000 }) {
if (!Number.isInteger(busyTimeoutMs) || busyTimeoutMs < 0 || busyTimeoutMs > 10000) throw new Error('Invalid busy timeout');
const path = privateDatabasePath(dbPath);
privateParent(path);
if (!existsSync(path)) closeSync(openSync(path, 'wx', 0o600));
if (process.platform !== 'win32') chmodSync(path, statSync(path).mode & 0o600);
const db = new Database(path, { timeout: busyTimeoutMs });
try {
db.pragma('journal_mode = WAL');
migrateDatabase(db);
assertSchema(db);
const visit = db.prepare('INSERT INTO visitors_daily (visitor_id, visit_date, first_seen_at, last_seen_at) VALUES (?, ?, ?, ?) ON CONFLICT(visitor_id, visit_date) DO UPDATE SET last_seen_at = excluded.last_seen_at');
const arrival = db.prepare('INSERT INTO arrivals (dog_id, first_arrived_at) VALUES (?, ?) ON CONFLICT(dog_id) DO NOTHING');
const count = db.prepare('SELECT COUNT(*) AS count FROM arrivals');
const monthly = db.prepare('SELECT COUNT(DISTINCT visitor_id) AS count FROM visitors_daily WHERE visit_date >= ? AND visit_date < ?');
return {
recordVisit(visitorId) {
const at = now();
const timestamp = at.toISOString();
const parts = Object.fromEntries(seoulDate.formatToParts(at).map(p => [p.type, p.value]));
visit.run(visitorId, `${parts.year.padStart(4, '0')}-${parts.month}-${parts.day}`, timestamp, timestamp);
},
recordArrival(dogId) { arrival.run(dogId, now().toISOString()); },
arrivalCount() { return safeCount(count.get()); },
monthlyVisitors(month) { return safeCount(monthly.get(...monthRange(month))); },
backup(destination) { return backupDatabase(db, path, destination); },
close() { if (db.open) db.close(); },
};
} catch (error) { db.close(); throw error; }
}
export function openReadOnlyStore(dbPath) {
const path = privateDatabasePath(dbPath);
const db = new Database(path, { readonly: true, fileMustExist: true, timeout: 1000 });
try {
assertSchema(db);
const count = db.prepare('SELECT COUNT(*) AS count FROM arrivals');
const monthly = db.prepare('SELECT COUNT(DISTINCT visitor_id) AS count FROM visitors_daily WHERE visit_date >= ? AND visit_date < ?');
return {
arrivalCount() { return safeCount(count.get()); },
monthlyVisitors(month) { return safeCount(monthly.get(...monthRange(month))); },
backup(destination) { return backupDatabase(db, path, destination); },
close() { if (db.open) db.close(); },
};
} catch (error) { db.close(); throw error; }
}
async function backupDatabase(db, source, destination) {
const target = privateDatabasePath(destination);
if (target === source) throw new Error('Backup must use a different path');
privateParent(target);
// Reserve exclusively before the async backup, so an existing backup is never replaced.
closeSync(openSync(target, 'wx', 0o600));
try { await db.backup(target); }
catch (error) { try { unlinkSync(target); } catch {} throw error; }
}
+33
View File
@@ -0,0 +1,33 @@
import { pathToFileURL } from 'node:url';
import { readConfig } from './config.mjs';
import { openStore } from './db.mjs';
import { buildApp } from './app.mjs';
export async function startServer(env = process.env) {
const config = readConfig(env);
const store = openStore({ dbPath: config.dbPath });
let app;
let stopping;
const shutdown = () => {
stopping ??= app.close().catch(() => { process.stderr.write('Server shutdown failed\n'); process.exitCode = 1; });
return stopping;
};
try {
app = await buildApp({ store, distRoot: config.distRoot, publicOrigin: config.publicOrigin });
app.addHook('onClose', async () => {
process.removeListener('SIGTERM', shutdown);
process.removeListener('SIGINT', shutdown);
});
await app.listen({ host: config.host, port: config.port });
process.once('SIGTERM', shutdown);
process.once('SIGINT', shutdown);
} catch (error) {
if (app) await app.close(); else store.close();
throw error;
}
return app;
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
startServer().catch(() => { process.stderr.write('Server startup failed; check configuration, private storage and build\n'); process.exitCode = 1; });
}
+16
View File
@@ -0,0 +1,16 @@
import { pathToFileURL } from 'node:url';
import { monthRange, openReadOnlyStore } from './db.mjs';
export function readMetrics(args, env = process.env) {
if (args.length !== 2 || args[0] !== '--month') throw new Error('Invalid arguments');
const month = args[1];
monthRange(month);
const store = openReadOnlyStore(env.DB_PATH);
try { return { month, monthlyVisitors: store.monthlyVisitors(month), arrivals: store.arrivalCount() }; }
finally { store.close(); }
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
try { process.stdout.write(`${JSON.stringify(readMetrics(process.argv.slice(2)))}\n`); }
catch { process.stderr.write('Metrics unavailable; check --month YYYY-MM and existing DB_PATH\n'); process.exitCode = 1; }
}
+12
View File
@@ -0,0 +1,12 @@
CREATE TABLE visitors_daily (
visitor_id TEXT NOT NULL,
visit_date TEXT NOT NULL,
first_seen_at TEXT NOT NULL,
last_seen_at TEXT NOT NULL,
PRIMARY KEY (visitor_id, visit_date)
);
CREATE INDEX visitors_daily_visit_date ON visitors_daily (visit_date);
CREATE TABLE arrivals (
dog_id TEXT PRIMARY KEY NOT NULL,
first_arrived_at TEXT NOT NULL
);