From 9efdfc8ee91f2f5efb56cbf8f38e2a8babb94129 Mon Sep 17 00:00:00 2001 From: martbost Date: Fri, 13 Nov 2026 09:11:30 -0600 Subject: [PATCH] Data safety (2026-11-13 incident: a deploy read a half-written rotator.json, the store fell back to empty and its next save wiped 294 spin links): safefs.js makes every .json write inside DATA_DIR atomic (temp file + rename); LinkSpin's rotator refuses to start empty when rotator.json exists but will not parse Co-Authored-By: Claude Opus 5.5 --- safefs.js | 27 +++++++++++++++++++++++++++ server.js | 1 + 2 files changed, 28 insertions(+) create mode 100644 safefs.js diff --git a/safefs.js b/safefs.js new file mode 100644 index 0000000..e838d8b --- /dev/null +++ b/safefs.js @@ -0,0 +1,27 @@ +// Atomic JSON data files (2026-11-13 incident). Every store here saves with fs.writeFileSync(file.json, ...), which truncates +// the file and then writes it. During a deploy the old and new app copies share the volume for a few seconds; the new copy read +// rotator.json while the old one was half way through writing it, JSON.parse failed, the store fell back to EMPTY and its next +// save wrote that empty list over 294 spin links. This makes every .json write inside DATA_DIR atomic (write a temp file in the +// same folder, then rename it over the real one), so a reader only ever sees the old file or the new one, never half of one. +// The SAME file ships in InstantAdPay and LinkSpin; server.js installs it right after DATA_DIR is known. +'use strict'; +const fs = require('fs'); +const path = require('path'); + +let installed = false; +function install(dataDir) { + if (installed) return; installed = true; + const root = path.resolve(dataDir) + path.sep; + const orig = fs.writeFileSync; + fs.writeFileSync = function (file, data, opts) { + const flag = opts && typeof opts === 'object' ? opts.flag : null; + if (typeof file === 'string' && /\.json$/i.test(file) && (!flag || flag === 'w') && path.resolve(file).startsWith(root)) { + const tmp = file + '.tmp-' + process.pid + '-' + Math.random().toString(36).slice(2, 8); + try { orig.call(fs, tmp, data, opts); fs.renameSync(tmp, file); } + catch (e) { try { fs.unlinkSync(tmp); } catch (x) {} throw e; } + return; + } + return orig.apply(fs, arguments); + }; +} +module.exports = { install }; diff --git a/server.js b/server.js index e8397cf..b501b2d 100644 --- a/server.js +++ b/server.js @@ -131,6 +131,7 @@ const PORT = Number(process.env.PORT || 3000); const ROOT = __dirname; const PUBLIC_DIR = path.join(ROOT, 'public'); const DATA_DIR = process.env.DATA_DIR || path.join(ROOT, 'data'); +require('./safefs').install(DATA_DIR); // every .json data file is written atomically (2026-11-13 rotator.json loss) const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'changeme'; const ADMIN_EMAIL = String(process.env.ADMIN_EMAIL || '').trim().toLowerCase(); // Admin portal sessions: email-code sign-in allowlisted to ADMIN_EMAIL, kept