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 | 157x 157x 157x 157x 157x 157x 157x 157x 13x 13x 13x 337x 337x 6x 37x 34x 36x 20x 47x 27x 81x 81x 81x 67x 67x 81x 81x 81x 37x 35x 33x 33x 79x 11x 11x 11x 11x 8x 8x 8x 8x 8x 8x 7x 90x 89x 88x 1x 87x 87x 87x 87x 85x 85x 85x 84x 84x 82x 14x 13x 68x 67x 66x 1x 65x 65x 65x 65x 65x 65x 64x 64x 14x 6x 157x | /**
* Ending a suspension, stated once (SHY-0605).
*
* Five routes end a suspension: the two admin unsuspends, an approved appeal,
* the owner's lift of an expired one, and identity-graph unsuspend-all. Each
* used to write its own end, and none put everything back: the bio and
* sign-in photo stayed blank, the suspension warning kept the GCS at 0, and
* only one of them lifted the auto-applied bans or unflagged the suggestions.
* Every end path calls this instead, so each puts back the same things.
*
* The user is written LAST. A step that fails leaves the user suspended, and
* calling this again finishes the job: a revoked warning is skipped, lifted
* bans and unflagged suggestions are not found again.
*/
const { db } = require('./firebase');
const { generateId, now } = require('./helpers');
const { revokeWarning } = require('./warnings');
const { liftAutoAppliedBans } = require('./auto-bans');
const { unflagUnsuspendedUserSuggestions } = require('./flag-suspended-user-suggestions');
const { suspensionEndedFields, profileToRestore } = require('./suspension');
const { clearSuspensionCache } = require('../middleware/auth');
const { appealedSuspension } = require('./appeals');
/** An ending that stopped before the user was written. `step` names where. */
class SuspensionEndError extends Error {
/**
* @param {'warnings'|'bans'|'suggestions'|'user'} step
* @param {string} message
* @param {Error} [cause]
*/
constructor(step, message, cause) {
super(message, cause ? { cause } : undefined);
this.name = 'SuspensionEndError';
this.step = step;
}
}
async function atStep(step, work) {
try {
return await work();
} catch (err) {
throw new SuspensionEndError(step, err && err.message ? err.message : String(err), err);
}
}
/**
* Revoke the warnings one run of suspensions wrote, giving their GCS back.
*
* Only `source` is filtered in the query: an equality on `revoked` would skip
* a stored warning that lacks the field. A run starts at its FIRST suspend: a
* second suspend moves the start date past the first warning, which holds the
* real deduction. A warning names its run (`suspensionRunStartedAt`, written
* since SHY-0605) and is matched on it, so another run's warning is never
* revoked: it ended without an upheld appeal, or has not been appealed yet. A
* warning written before it named its run is matched by date instead: made at
* or after the run's start. With no start known, nothing is revoked.
*
* @param {string} id
* @param {number|null} runStart when the run began (ms)
* @param {string} actor
* @returns {Promise<{ revokedWarnings: number, gcsRestored: number }>}
*/
async function revokeRunsWarnings(id, runStart, actor) {
if (runStart === null) return { revokedWarnings: 0, gcsRestored: 0 };
return revokeSuspensionWarnings(id, actor, (warning) => {
if ((warning.suspensionRunStartedAt ?? null) === null) return warning.createdAt >= runStart;
return warning.suspensionRunStartedAt === runStart;
});
}
/**
* Give back what one run of suspensions held for an earlier suspension's
* upheld appeal (`holdScoreForRunInForce`), on ANY ending.
*
* A hold is not the suspension's own deduction: the suspension took nothing
* of its own, it only kept the score at 0 while in force. So however it ends,
* the held points come back (Shyden, 2026-10-18: "Release on any ending").
* What a suspension took for itself still needs an upheld appeal.
*
* @returns {Promise<{ revokedWarnings: number, gcsRestored: number }>}
*/
function releaseRunsHolds(id, runStart, actor) {
return revokeSuspensionWarnings(
id,
actor,
(warning) => warning.hold === true && (warning.suspensionRunStartedAt ?? null) === runStart,
);
}
/**
* Revoke the unrevoked suspension warnings `matches` picks, one at a time.
*
* @param {string} id
* @param {string} actor
* @param {(warning: object) => boolean} matches
* @returns {Promise<{ revokedWarnings: number, gcsRestored: number }>}
*/
async function revokeSuspensionWarnings(id, actor, matches) {
const warnings = await atStep('warnings', () =>
db.collection(`users/${id}/warnings`).where('source', '==', 'suspension').get(),
);
const open = warnings.docs.filter((d) => {
const warning = d.data();
return warning.revoked !== true && matches(warning);
});
let revokedWarnings = 0;
let gcsRestored = 0;
// One at a time: each revoke reads the GCS the last one wrote.
for (const warning of open) {
const result = await atStep('warnings', () => revokeWarning(id, warning.id, { actor }));
if (!result.alreadyRevoked) {
revokedWarnings += 1;
gcsRestored += result.restoredGcs - result.previousGcs;
}
}
return { revokedWarnings, gcsRestored };
}
/**
* Take the score back to 0 for the suspension in force.
*
* Every suspension holds the score at 0 while it is in force (Shyden,
* 2026-10-18). One that began with the score already at 0 took nothing, so
* when an earlier suspension's upheld appeal gives points back, this takes them
* again on a warning of the run in force: if that suspension's appeal is
* upheld too, they come back then. It reads the score afresh rather than
* counting what was just given back, so an approval retried after a failed
* hold still ends at 0.
*
* @returns {Promise<number>} the points held
*/
async function holdScoreForRunInForce(id, user, runStartedAt, actor) {
const userRef = db.doc(`users/${id}`);
const fresh = (await atStep('warnings', () => userRef.get())).data();
const gcs = fresh.gcsScore ?? fresh.gcs_score ?? 100;
if (gcs <= 0) return 0;
const reason = user.suspensionReason ?? user.suspension_reason ?? null;
const timestamp = now();
const batch = db.batch();
batch.set(db.doc(`users/${id}/warnings/${generateId()}`), {
reason: reason ? `Account suspended: ${reason}` : 'Account suspended',
severity: 5,
gcsDeduction: gcs,
gcsBefore: gcs,
gcsAfter: 0,
adminNote: 'Held by the suspension in force when an earlier suspension’s appeal was upheld',
issuedBy: actor,
issuedByName: null,
source: 'suspension',
// A hold, not this suspension's own deduction: any ending gives it back.
hold: true,
suspensionRunStartedAt: runStartedAt,
linkedReportId: null,
revoked: false,
revokedAt: null,
revokedBy: null,
createdAt: timestamp,
});
batch.update(userRef, { gcsScore: 0, gcsLastDeductionAt: timestamp });
await atStep('warnings', () => batch.commit());
return gcs;
}
/**
* End a user's suspension and put back everything it took.
*
* @param {string|number} uniqueId the suspended user
* @param {{ actor: string, trigger: string, extra?: object,
* restoreGcs?: boolean, appeal?: object }} options
* `actor` is recorded on the audit entry and every revoke (an admin uid, or
* `system:suspension-expired`); `trigger` names the end path (UNSUSPEND,
* APPEAL_APPROVED, ...); `extra` is written over the cleared fields.
* `restoreGcs` gives back the GCS the appealed suspension took: ONLY an
* upheld appeal passes it (Shyden, 2026-10-17), with the `appeal` itself.
* Any other ending leaves the GCS and the suspension warning as they are.
* An appeal belongs to the one suspension it answers and never reaches
* another (Shyden, 2026-10-18; `appealedSuspension`): its GCS comes back
* even when that suspension has already ended (a timed one can run out
* while its appeal waits), and the suspension in force is ended only when
* it is that one. A later suspension in force holds what comes back.
* @returns {Promise<{ alreadyEnded: true, revokedWarnings?: number,
* gcsRestored?: number, gcsHeld?: number } | { alreadyEnded: false,
* restored: string[], revokedWarnings: number, gcsRestored: number,
* bansLifted: number, suggestions: object }>} `alreadyEnded` is true when
* the suspension this call answers is no longer in force.
* @throws {SuspensionEndError} when a step fails; the user is left suspended
*/
async function endSuspension(
uniqueId,
{ actor, trigger, extra = {}, restoreGcs = false, appeal } = {},
) {
if (!actor) throw new TypeError('endSuspension: actor is required');
if (!trigger) throw new TypeError('endSuspension: trigger is required');
if (restoreGcs && !appeal) {
throw new TypeError('endSuspension: an upheld appeal needs the appeal');
}
const id = String(uniqueId);
const userRef = db.doc(`users/${id}`);
const snap = await userRef.get();
if (!snap.exists) return { alreadyEnded: true };
const user = snap.data();
const suspended = (user.isSuspended ?? user.is_suspended) === true;
if (!suspended && !restoreGcs) return { alreadyEnded: true };
const answered = restoreGcs
? appealedSuspension(user, appeal)
: { runStartedAt: null, inForce: true };
const { revokedWarnings, gcsRestored } = restoreGcs
? await revokeRunsWarnings(id, answered.runStartedAt, actor)
: await releaseRunsHolds(
id,
user.suspensionRunStartedAt ?? user.suspensionStartDate ?? null,
actor,
);
if (!answered.inForce) {
const gcsHeld = suspended
? await holdScoreForRunInForce(
id,
user,
user.suspensionRunStartedAt ?? user.suspensionStartDate ?? null,
actor,
)
: 0;
return { alreadyEnded: true, revokedWarnings, gcsRestored, gcsHeld };
}
const bansLifted = await atStep('bans', () => liftAutoAppliedBans(id, actor));
const suggestions = await atStep('suggestions', () => unflagUnsuspendedUserSuggestions(id));
if (suggestions.partial) {
throw new SuspensionEndError(
'suggestions',
suggestions.error || 'some suggestions stayed flagged',
);
}
const restore = profileToRestore(user);
const restored = Object.keys(restore);
const batch = db.batch();
batch.update(userRef, suspensionEndedFields({ ...restore, ...extra }));
// The shape the admin audit log page reads (SHY-0622): it orders by
// `timestamp` and drops entries without it.
batch.set(db.doc(`adminAuditLog/${generateId()}`), {
adminUid: actor,
action: 'END_SUSPENSION',
actionType: 'end_suspension',
targetType: 'user',
targetId: id,
details: {
trigger,
restored,
revokedWarnings,
gcsRestored,
bansLifted,
unflagged: suggestions.unflaggedCount,
},
timestamp: now(),
});
await atStep('user', () => batch.commit());
clearSuspensionCache(Number(id));
return { alreadyEnded: false, restored, revokedWarnings, gcsRestored, bansLifted, suggestions };
}
/**
* The 500 body for an ending that stopped at a step, or null for any other
* error. Every end path answers a failed ending the same way.
*
* @param {unknown} err
* @returns {{ error: string, step: string } | null}
*/
function suspensionEndFailure(err) {
if (!(err instanceof SuspensionEndError)) return null;
return {
error: 'The suspension could not be fully ended. The user is still suspended.',
step: err.step,
};
}
module.exports = { endSuspension, SuspensionEndError, suspensionEndFailure };
|