fix(docker): replace better-sqlite3 with pure-JS JSON token store
All checks were successful
Build and Push Docker Image / build (push) Successful in 28s
CI / Security audit (push) Successful in 38s

better-sqlite3 is a native C++ addon that requires compilation on Alpine
(musl libc, no pre-built binaries exist) and fails on Debian slim too
because prebuild-install cannot detect the libc type correctly.

Replace with a pure-JS JSON file token store (server/utils/tokenStore.js):
- Atomic writes via temp file + rename (no corruption on crash)
- Same API: storeToken/getToken/clearToken
- TTL enforcement on read and hourly prune
- Zero native code, zero build tools required

Dockerfile:
- Revert to node:22-alpine (was node:22-slim)
- Remove build tools (python3/make/g++) — no longer needed
- Restore wget HEALTHCHECK (available in Alpine busybox)

docker-compose.yaml: restore wget healthcheck

package.json: remove better-sqlite3 dependency
This commit is contained in:
2026-05-17 07:13:56 +01:00
parent 49327cf9ae
commit 37c1b64982
5 changed files with 77 additions and 483 deletions

View File

@@ -1,83 +1,97 @@
/**
* Persistent token store backed by SQLite (better-sqlite3).
* Persistent token store backed by a JSON file.
*
* Survives process restarts — Emby tokens remain valid across deploys
* and container restarts, so users do not need to re-login after an
* update. Tokens are stored in DATA_DIR/tokens.db (default: /app/data
* inside the container, or ./data locally).
* Pure JavaScript — no native addons, no build tools required.
* Survives process restarts so users are not logged out on redeploy.
*
* Schema: tokens(userId TEXT PK, accessToken TEXT, createdAt INTEGER)
* Tokens are stored in DATA_DIR/tokens.json (default: ./data locally,
* /app/data in the container). Writes are atomic: data is written to a
* temp file then renamed so a crash mid-write never corrupts the store.
*
* Expired rows (older than TOKEN_TTL_DAYS) are pruned on startup and
* once per hour, preventing unbounded growth.
* Format: { "<userId>": { accessToken: "...", createdAt: <unix ms> } }
*
* Expired entries (older than TOKEN_TTL_DAYS) are pruned on startup
* and once per hour.
*/
const Database = require('better-sqlite3');
const path = require('path');
const fs = require('fs');
const TOKEN_TTL_DAYS = 31; // slightly longer than max cookie lifetime
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, '../../data');
const TOKEN_TTL_DAYS = 31; // slightly longer than max cookie lifetime (30d)
const TOKEN_TTL_MS = TOKEN_TTL_DAYS * 24 * 60 * 60 * 1000;
// Ensure data directory exists (non-root writable in container)
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, '../../data');
if (!fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR, { recursive: true });
}
const DB_PATH = path.join(DATA_DIR, 'tokens.db');
const db = new Database(DB_PATH);
const STORE_PATH = path.join(DATA_DIR, 'tokens.json');
const STORE_TMP = STORE_PATH + '.tmp';
// WAL mode for better concurrent read performance
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
db.exec(`
CREATE TABLE IF NOT EXISTS tokens (
userId TEXT PRIMARY KEY,
accessToken TEXT NOT NULL,
createdAt INTEGER NOT NULL DEFAULT (strftime('%s','now'))
)
`);
const storeToken = db.prepare(
`INSERT OR REPLACE INTO tokens (userId, accessToken, createdAt)
VALUES (?, ?, strftime('%s','now'))`
);
const getTokenStmt = db.prepare(
`SELECT accessToken FROM tokens WHERE userId = ?`
);
const clearTokenStmt = db.prepare(
`DELETE FROM tokens WHERE userId = ?`
);
const pruneStmt = db.prepare(
`DELETE FROM tokens WHERE createdAt < strftime('%s','now') - ?`
);
const TTL_SECONDS = TOKEN_TTL_DAYS * 24 * 60 * 60;
function prune() {
const result = pruneStmt.run(TTL_SECONDS);
if (result.changes > 0) {
console.log(`[TokenStore] Pruned ${result.changes} expired token(s)`);
// Load store from disk, return empty object on any error
function load() {
try {
return JSON.parse(fs.readFileSync(STORE_PATH, 'utf8'));
} catch {
return {};
}
}
// Prune on startup and every hour
prune();
setInterval(prune, 60 * 60 * 1000).unref();
// Atomic write: write to .tmp then rename to avoid partial-write corruption
function save(data) {
try {
fs.writeFileSync(STORE_TMP, JSON.stringify(data), 'utf8');
fs.renameSync(STORE_TMP, STORE_PATH);
} catch (err) {
console.error('[TokenStore] Failed to persist token store:', err.message);
}
}
function prune(data) {
const cutoff = Date.now() - TOKEN_TTL_MS;
let pruned = 0;
for (const userId of Object.keys(data)) {
if (data[userId].createdAt < cutoff) {
delete data[userId];
pruned++;
}
}
if (pruned > 0) {
console.log(`[TokenStore] Pruned ${pruned} expired token(s)`);
}
return data;
}
// Prune on startup
let store = prune(load());
save(store);
// Prune once per hour (unref so it doesn't keep the process alive)
setInterval(() => {
store = prune(load());
save(store);
}, 60 * 60 * 1000).unref();
module.exports = {
storeToken(userId, accessToken) {
storeToken.run(userId, accessToken);
store[userId] = { accessToken, createdAt: Date.now() };
save(store);
},
getToken(userId) {
const row = getTokenStmt.get(userId);
return row ? { accessToken: row.accessToken } : null;
const entry = store[userId];
if (!entry) return null;
// Also honour TTL on read in case pruning hasn't run yet
if (Date.now() - entry.createdAt > TOKEN_TTL_MS) {
delete store[userId];
save(store);
return null;
}
return { accessToken: entry.accessToken };
},
clearToken(userId) {
clearTokenStmt.run(userId);
if (store[userId]) {
delete store[userId];
save(store);
}
}
};