54 lines
1.9 KiB
JavaScript
54 lines
1.9 KiB
JavaScript
"use strict";
|
|
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
const crypto = require("node:crypto");
|
|
const { atomicWriteFileSync } = require("./atomic-file");
|
|
|
|
function createFileSessionRevocations({ directory, ttlMs, now = Date.now, writeFile = atomicWriteFileSync } = {}) {
|
|
if (!directory || !Number.isFinite(ttlMs) || ttlMs <= 0) throw new TypeError("A directory and positive revocation lifetime are required");
|
|
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
const markerPath = (sid) => {
|
|
const id = String(sid || "").trim();
|
|
if (!id) throw new TypeError("A session identifier is required");
|
|
return path.join(directory, crypto.createHash("sha256").update(id).digest("hex") + ".json");
|
|
};
|
|
const readExpiry = (filePath) => {
|
|
const raw = fs.readFileSync(filePath, "utf8");
|
|
try {
|
|
const expiry = JSON.parse(raw)?.expiresAt;
|
|
return typeof expiry === "number" && Number.isFinite(expiry) && expiry > 0 ? expiry : Infinity;
|
|
} catch {
|
|
return Infinity;
|
|
}
|
|
};
|
|
return {
|
|
// adpanel:file-session-revocation - logout must survive process restart;
|
|
// marker names contain only hashed SIDs and replacement is atomic.
|
|
write(sid) {
|
|
writeFile(markerPath(sid), JSON.stringify({ expiresAt: now() + ttlMs }), { mode: 0o600 });
|
|
return true;
|
|
},
|
|
has(sid) {
|
|
try {
|
|
return readExpiry(markerPath(sid)) > now();
|
|
} catch (error) {
|
|
if (error.code === "ENOENT") return false;
|
|
throw error;
|
|
}
|
|
},
|
|
sweep() {
|
|
for (const filename of fs.readdirSync(directory)) {
|
|
if (!/^[a-f0-9]{64}\.json$/.test(filename)) continue;
|
|
const filePath = path.join(directory, filename);
|
|
try {
|
|
if (readExpiry(filePath) <= now()) fs.unlinkSync(filePath);
|
|
} catch (error) {
|
|
if (error.code !== "ENOENT") throw error;
|
|
}
|
|
}
|
|
},
|
|
};
|
|
}
|
|
|
|
module.exports = { createFileSessionRevocations }; |