Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 | 4x 4x 4x 4x 76x 68x 4x 4x 4x 4x 4x 4x 27x 9x 9x 9x 8x 18x 18x 18x 9x 18x 18x 5x 5x 5x 18x 11x 4x 9x 9x 8x 8x 8x 8x 1x 1x 4x 17x 17x 17x 16x 15x 15x 14x 14x 14x 14x 14x 14x 6x 6x 6x 2x 2x 14x 1x 1x 4x 20x 20x 20x 20x 2x 18x 2x 16x 15x 15x 15x 1x 14x 1x 13x 1x 12x 12x 12x 11x 11x 4x 11x 11x 11x 11x 4x 4x 4x 2x 2x 11x 1x 1x 4x 5x 5x 5x 5x 4x 4x 4x 4x 1x 1x 4x 4x 4x 4x 4x 3x 3x 1x 3x 3x 1x 1x 4x 10x 10x 10x 10x 10x 9x 9x 9x 36x 25x 10x 10x 10x 9x 9x 9x 9x 9x 9x 2x 2x 9x 1x 1x 4x 3x 3x 3x 3x 3x 2x 2x 2x 4x 4x 2x 2x 2x 2x 2x 4x 4x 2x 2x 2x 1x 1x 4x | /**
* Admin ban routes — device/network ban CRUD, bulk unban.
*
* GET /admin/bans → List all active bans
* POST /admin/bans/device → Ban a device
* POST /admin/bans/network → Ban a network (ip/subnet/asn)
* DELETE /admin/bans/device/:deviceId → Unban device
* DELETE /admin/bans/network/:banId → Unban network
* POST /admin/bans/unban-all/:uniqueId → Remove all bans for a user
* GET /admin/bans/user/:uniqueId → Get all bans for a user
*/
const router = require('express').Router();
const { db } = require('../utils/firebase');
const { requireAdmin } = require('../middleware/auth');
// Phase 2H finding #2 dedup: scope admin guard by path prefix.
const _adminGuardWrapper = async (req, res, next) => {
if (await requireAdmin(req, res)) return;
next();
};
router.use('/admin/bans', _adminGuardWrapper);
const { generateId, now } = require('../utils/helpers');
const { sendSystemPm } = require('../utils/system-pm');
const { clearBanCache, isBanActive } = require('../utils/bans');
const { syncBannedClaim } = require('../utils/banned-claim');
const log = require('../utils/log');
// ─── Helpers ─────────────────────────────────────────────────────
/**
* Parse a duration string (e.g. '24h', '7d', '30d', 'permanent') into
* an ISO-8601 expiry timestamp, or null for permanent bans.
*/
function parseExpiry(duration) {
if (!duration || duration === 'permanent') return null;
const units = { h: 3600000, d: 86400000 };
const match = duration.match(/^(\d+)([hd])$/);
if (!match) return null;
return new Date(Date.now() + Number.parseInt(match[1], 10) * units[match[2]]).toISOString();
}
/**
* Every enumerable user a device-ban mutation affects (SHY-0150): the
* explicitly linked account AND the device's bound owner — an admin may ban
* hardware without linking it, but the bound account's claim standing still
* flips. Never throws: the ban mutation has already committed, and the lazy
* middleware sync self-heals anything missed here.
*/
async function syncClaimsForDeviceBan(deviceId, linkedUniqueId) {
try {
const targets = new Set();
// Same truthiness the ban docs store (`linkedUniqueId || null`).
if (linkedUniqueId) {
targets.add(String(linkedUniqueId));
}
const bindingSnap = await db.doc(`deviceBindings/${deviceId}`).get();
if (bindingSnap.exists) {
const binding = bindingSnap.data() || {};
const owner = binding.uniqueId ?? binding.userId ?? null;
if (owner !== null && owner !== undefined) targets.add(String(owner));
}
for (const target of targets) {
await syncBannedClaim(target);
}
} catch (err) {
log.error('banned-claim', 'device-ban claim sync failed — lazy path will self-heal', {
deviceId,
error: err.message,
});
}
}
// ─── List all active bans ────────────────────────────────────────
router.get('/admin/bans', async (req, res) => {
try {
const [deviceSnap, networkSnap] = await Promise.all([
db.collection('deviceBans').get(),
db.collection('networkBans').get(),
]);
// ONE definition of "active" — the same predicate the gate enforces with.
// These filters used to inline `new Date(x).getTime() > now`, which for a
// corrupt expiry is `NaN > now === false`: the console would show a ban as
// gone while the gate was still enforcing it (reviewer R8-I1).
const deviceBans = deviceSnap.docs.map((d) => ({ ...d.data(), id: d.id })).filter(isBanActive);
const networkBans = networkSnap.docs
.map((d) => ({ ...d.data(), id: d.id }))
.filter(isBanActive);
res.json({ deviceBans, networkBans });
} catch (err) {
log.error('admin-bans', 'Error listing bans', { error: err.message });
res.status(500).json({ error: 'Internal server error' });
}
});
// ─── Ban a device ────────────────────────────────────────────────
router.post('/admin/bans/device', async (req, res) => {
try {
const { deviceId, reason, duration, linkedUniqueId } = req.body || {};
if (!deviceId) return res.status(400).json({ error: 'deviceId is required' });
if (!reason) return res.status(400).json({ error: 'reason is required' });
const expiresAt = parseExpiry(duration);
await db.doc(`deviceBans/${deviceId}`).set({
deviceId,
reason,
duration: duration || 'permanent',
expiresAt,
linkedUniqueId: linkedUniqueId || null,
createdAt: now(),
createdBy: req.auth.uid,
});
// Full clear (not per-uid): the ban may target a device bound to a
// user other than linkedUniqueId — the gate must see it on the
// target's NEXT request (SHY-0149 mid-session AC).
clearBanCache();
// SHY-0150: mint the `banned` claim (+ revoke refresh tokens) for the
// linked account and/or the device's bound owner, so the rules layer
// denies their direct Firestore writes too. AFTER clearBanCache — the
// recompute must read the standing this mutation just created.
await syncClaimsForDeviceBan(deviceId, linkedUniqueId);
// Audit log
await db.doc(`adminAuditLog/${generateId()}`).set({
adminId: req.auth.uid,
action: 'BAN_DEVICE',
targetDeviceId: deviceId,
details: `Reason: ${reason}, Duration: ${duration || 'permanent'}`,
createdAt: now(),
});
// Send system PM if linked to a user (non-blocking). Track failure so
// the admin UI's PartialFailureToast.buildPartialFailureMessage() can
// surface it via the standard `pms: { failed, total }` shape.
let pmFailed = 0;
let pmTotal = 0;
if (linkedUniqueId) {
pmTotal = 1;
try {
await sendSystemPm(linkedUniqueId, 'A restriction has been placed on your account.');
} catch (e) {
log.warn('system-pm', 'Failed to send', { uniqueId: linkedUniqueId, error: e.message });
pmFailed = 1;
}
}
res.json({ success: true, pms: { failed: pmFailed, total: pmTotal } });
} catch (err) {
log.error('admin-bans', 'Error banning device', { error: err.message });
res.status(500).json({ error: 'Internal server error' });
}
});
// ─── Ban a network ───────────────────────────────────────────────
router.post('/admin/bans/network', async (req, res) => {
try {
const { type, value, reason, duration, linkedUniqueId } = req.body || {};
const validTypes = ['ip', 'subnet', 'asn'];
if (!type || !validTypes.includes(type)) {
return res.status(400).json({ error: 'type must be one of: ip, subnet, asn' });
}
if (!value || typeof value !== 'string')
return res.status(400).json({ error: 'value is required' });
if (!reason) return res.status(400).json({ error: 'reason is required' });
// Validate format based on type
const IP_REGEX = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
const CIDR_REGEX = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/\d{1,2}$/;
if (type === 'ip' && !IP_REGEX.test(value)) {
return res.status(400).json({ error: 'Invalid IP address format' });
}
if (type === 'subnet' && !CIDR_REGEX.test(value)) {
return res.status(400).json({ error: 'Invalid CIDR subnet format (e.g. 192.168.0.0/24)' });
}
if (type === 'asn' && !/^\d+$/.test(value)) {
return res.status(400).json({ error: 'ASN must be numeric' });
}
const banId = generateId();
const expiresAt = parseExpiry(duration);
await db.doc(`networkBans/${banId}`).set({
type,
value,
reason,
duration: duration || 'permanent',
expiresAt,
linkedUniqueId: linkedUniqueId || null,
createdAt: now(),
createdBy: req.auth.uid,
});
// Invalidate the gate's cached active-networkBans list immediately.
clearBanCache();
// SHY-0150: a LINKED network ban has an enumerable target — mint its
// claim now. An unlinked one has none (structural limit): the lazy
// middleware sync mints from the live verdict when the banned network
// next calls the API.
if (linkedUniqueId) {
await syncBannedClaim(String(linkedUniqueId));
}
// Audit log
await db.doc(`adminAuditLog/${generateId()}`).set({
adminId: req.auth.uid,
action: 'BAN_NETWORK',
targetValue: value,
details: `Type: ${type}, Reason: ${reason}, Duration: ${duration || 'permanent'}`,
createdAt: now(),
});
// Send system PM if linked to a user (non-blocking). Track failure so
// the admin UI's PartialFailureToast.buildPartialFailureMessage() can
// surface it via the standard `pms: { failed, total }` shape.
let pmFailed = 0;
let pmTotal = 0;
if (linkedUniqueId) {
pmTotal = 1;
try {
await sendSystemPm(linkedUniqueId, 'A restriction has been placed on your account.');
} catch (e) {
log.warn('system-pm', 'Failed to send', { uniqueId: linkedUniqueId, error: e.message });
pmFailed = 1;
}
}
res.json({ success: true, pms: { failed: pmFailed, total: pmTotal } });
} catch (err) {
log.error('admin-bans', 'Error banning network', { error: err.message });
res.status(500).json({ error: 'Internal server error' });
}
});
// ─── Unban device ────────────────────────────────────────────────
router.delete('/admin/bans/device/:deviceId', async (req, res) => {
try {
// Capture the linked account BEFORE the delete — it is the recompute
// target once the ban is gone (SHY-0150).
const banSnap = await db.doc(`deviceBans/${req.params.deviceId}`).get();
const linkedUniqueId = banSnap.exists ? banSnap.data().linkedUniqueId : null;
await db.doc(`deviceBans/${req.params.deviceId}`).delete();
// An unban must lift the gate as promptly as a ban engages it.
clearBanCache();
// SHY-0150: RECOMPUTE (never blind-clear) — another active ban keeps
// the claim. AFTER clearBanCache so the recompute reads fresh standing.
await syncClaimsForDeviceBan(req.params.deviceId, linkedUniqueId);
await db.doc(`adminAuditLog/${generateId()}`).set({
adminId: req.auth.uid,
action: 'UNBAN_DEVICE',
targetDeviceId: req.params.deviceId,
createdAt: now(),
});
res.json({ success: true });
} catch (err) {
log.error('admin-bans', 'Error unbanning device', {
deviceId: req.params.deviceId,
error: err.message,
});
res.status(500).json({ error: 'Internal server error' });
}
});
// ─── Unban network ───────────────────────────────────────────────
router.delete('/admin/bans/network/:banId', async (req, res) => {
try {
// Capture the linked account BEFORE the delete (SHY-0150 recompute).
const banSnap = await db.doc(`networkBans/${req.params.banId}`).get();
const linkedUniqueId = banSnap.exists ? banSnap.data().linkedUniqueId : null;
await db.doc(`networkBans/${req.params.banId}`).delete();
// An unban must lift the gate as promptly as a ban engages it.
clearBanCache();
// SHY-0150: RECOMPUTE (never blind-clear) — another active ban keeps
// the claim.
if (linkedUniqueId) {
await syncBannedClaim(String(linkedUniqueId));
}
await db.doc(`adminAuditLog/${generateId()}`).set({
adminId: req.auth.uid,
action: 'UNBAN_NETWORK',
targetBanId: req.params.banId,
createdAt: now(),
});
res.json({ success: true });
} catch (err) {
log.error('admin-bans', 'Error unbanning network', {
banId: req.params.banId,
error: err.message,
});
res.status(500).json({ error: 'Internal server error' });
}
});
// ─── Unban all for user ──────────────────────────────────────────
router.post('/admin/bans/unban-all/:uniqueId', async (req, res) => {
try {
const uniqueId = req.params.uniqueId;
const numericId = Number(uniqueId);
const stringId = String(uniqueId);
const [deviceSnapStr, deviceSnapNum, networkSnapStr, networkSnapNum] = await Promise.all([
db.collection('deviceBans').where('linkedUniqueId', '==', stringId).get(),
db.collection('deviceBans').where('linkedUniqueId', '==', numericId).get(),
db.collection('networkBans').where('linkedUniqueId', '==', stringId).get(),
db.collection('networkBans').where('linkedUniqueId', '==', numericId).get(),
]);
// Deduplicate by doc id in case both queries match the same doc
const seen = new Set();
const allDocs = [];
for (const snap of [deviceSnapStr, deviceSnapNum, networkSnapStr, networkSnapNum]) {
for (const d of snap.docs) {
if (!seen.has(d.id)) {
seen.add(d.id);
allDocs.push(d);
}
}
}
await Promise.all(allDocs.map((d) => d.ref.delete()));
// An unban must lift the gate as promptly as a ban engages it.
clearBanCache();
// SHY-0150: RECOMPUTE — an UNLINKED hardware ban on a still-bound
// device survives unban-all (its queries only see linked docs), and
// the recompute correctly keeps the claim in that case.
await syncBannedClaim(String(uniqueId));
await db.doc(`adminAuditLog/${generateId()}`).set({
adminId: req.auth.uid,
action: 'UNBAN_ALL',
targetUserId: uniqueId,
details: `Removed ${allDocs.length} ban(s)`,
createdAt: now(),
});
// Send system PM about restriction lifted. Track failure for admin UI.
let pmFailed = 0;
try {
await sendSystemPm(uniqueId, 'A restriction on your account has been lifted.');
} catch (e) {
log.warn('system-pm', 'Failed to send', { uniqueId, error: e.message });
pmFailed = 1;
}
res.json({
success: true,
removed: allDocs.length,
pms: { failed: pmFailed, total: 1 },
});
} catch (err) {
log.error('admin-bans', 'Error unbanning all for user', {
uniqueId: req.params.uniqueId,
error: err.message,
});
res.status(500).json({ error: 'Internal server error' });
}
});
// ─── Get bans for user ───────────────────────────────────────────
router.get('/admin/bans/user/:uniqueId', async (req, res) => {
try {
const uniqueId = req.params.uniqueId;
const numericId = Number(uniqueId);
const stringId = String(uniqueId);
const [deviceSnapStr, deviceSnapNum, networkSnapStr, networkSnapNum] = await Promise.all([
db.collection('deviceBans').where('linkedUniqueId', '==', stringId).get(),
db.collection('deviceBans').where('linkedUniqueId', '==', numericId).get(),
db.collection('networkBans').where('linkedUniqueId', '==', stringId).get(),
db.collection('networkBans').where('linkedUniqueId', '==', numericId).get(),
]);
// Deduplicate by doc id in case both queries match the same doc
const seenDevice = new Set();
const deviceBans = [];
for (const snap of [deviceSnapStr, deviceSnapNum]) {
for (const d of snap.docs) {
if (!seenDevice.has(d.id)) {
seenDevice.add(d.id);
deviceBans.push({ ...d.data(), id: d.id });
}
}
}
const seenNetwork = new Set();
const networkBans = [];
for (const snap of [networkSnapStr, networkSnapNum]) {
for (const d of snap.docs) {
if (!seenNetwork.has(d.id)) {
seenNetwork.add(d.id);
networkBans.push({ ...d.data(), id: d.id });
}
}
}
res.json({ deviceBans, networkBans });
} catch (err) {
log.error('admin-bans', 'Error getting bans for user', {
uniqueId: req.params.uniqueId,
error: err.message,
});
res.status(500).json({ error: 'Internal server error' });
}
});
module.exports = router;
|