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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 26x 20x 20x 21x 21x 21x 20x 6x 6x 2x 4x 4x 13x 13x 13x 2x 2x 2x 12x 12x 12x 12x 2x 2x 2x 12x 3x 3x 12x 46x 58x 2x 2x 3x 3x 3x 3x 2x 2x 1x 1x 26x 26x 26x 1x 25x 25x 20x 20x 51x 19x 18x 18x 7x 1x 6x 2x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 12x 12x 12x 12x 12x 15x 15x 16x 16x 16x 46x 46x 46x 46x 16x 16x 2x 1x 1x 13x 55x 13x 13x 1x 1x | /**
* Decide Content Reports (Platform Admin) Lambda
* POST /v1/platform-admin/content-reports/decision
*
* Requires `isPlatformAdmin: true`. Closes every open report of one target
* (all its reporters at once) with the admin's decision:
* - `dismissed`: nothing wrong found
* - `actioned`: the content broke the rules. Its author gets a strike and a
* sanction (`warning`, `restriction` for some days, or `ban`), and is told
* what was decided and why, and how to contest it (the DSA's statement of
* reasons). `removed: true` says the admin removed the content first, with
* the existing delete routes; checked here, so a user is never told content
* was removed while it is still online.
* Every reporter is told the outcome. The decision gets an id, which the
* notifications carry: the author, or a reporter of a dismissed report, may
* appeal it (content-reports/appeal.js).
*
* The reports, the sanction and the notifications are one transaction,
* conditioned on the reports still being open: two admins deciding the same
* target at once cannot both sanction its author. A ban also disables the
* account in Cognito and signs it out everywhere, before that transaction (both
* are idempotent, so a failed request can be sent again), and is emailed: a
* banned user cannot sign in to read a notification.
*
* @implements UC-REPORT-005.1, UC-REPORT-006.1, UC-REPORT-007.1, UC-REPORT-008.1
*/
const { randomUUID } = require('crypto')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
DynamoDBDocumentClient,
GetCommand,
QueryCommand,
TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const {
CognitoIdentityProviderClient,
AdminDisableUserCommand,
AdminUserGlobalSignOutCommand
} = require('@aws-sdk/client-cognito-identity-provider')
const { requirePlatformAdmin } = require('../utils/requirePlatformAdmin')
const {
REPORT_TARGET_TYPE,
REPORT_LIST_KEY,
REPORT_CLOSED_LIST_KEY,
REPORT_STATUS,
validateDecisionInput,
reportExcerpt
} = require('../utils/contentReports')
const { COMMENT_STATUS } = require('../utils/comments')
const { getPack } = require('../utils/packs')
const {
NOTIFICATION_TYPE,
buildNotificationWrites,
pushNotification
} = require('../utils/notifications')
const { sendEmail, pickEmailLanguage } = require('../utils/email')
const { renderAccountBannedEmail } = require('../utils/emailTemplates/accountBanned')
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
const cognitoClient = new CognitoIdentityProviderClient({})
const corsHeaders = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
const DAY_MS = 24 * 60 * 60 * 1000
/**
* Reporters closed per transaction: 1 update + 2 notification writes each,
* under DynamoDB's 100 items with room for the author's 3 writes.
*/
const REPORTERS_PER_TRANSACTION = 30
const respond = (statusCode, body) => ({
statusCode,
headers: corsHeaders,
body: JSON.stringify(body)
})
/** Every report of the target, whatever its status: one partition. */
async function listTargetReports(targetKey) {
const reports = []
let ExclusiveStartKey
do {
const page = await docClient.send(
new QueryCommand({
TableName: process.env.CONTENT_REPORTS_TABLE_NAME,
KeyConditionExpression: 'targetKey = :targetKey',
ExpressionAttributeValues: { ':targetKey': targetKey },
ExclusiveStartKey
})
)
reports.push(...(page.Items || []))
ExclusiveStartKey = page.LastEvaluatedKey
} while (ExclusiveStartKey)
return reports
}
/** Whether the reported content is gone: deleted, or turned into a tombstone. */
async function isContentRemoved(report) {
const { target } = report
if (report.targetType === REPORT_TARGET_TYPE.PACK) {
return !(await getPack(docClient, target.packId))
}
const result = await docClient.send(
new GetCommand({
TableName: process.env.COMMENTS_TABLE_NAME,
Key: { itemId: target.packId || target.itemId, id: target.commentId }
})
)
return !result.Item || result.Item.status === COMMENT_STATUS.DELETED
}
async function getUser(userId) {
Iif (!userId) return null
const result = await docClient.send(
new GetCommand({ TableName: process.env.USERS_TABLE_NAME, Key: { id: userId } })
)
return result.Item || null
}
/** The restriction's end: a longer one already running is kept. */
function restrictionEnd(user, days, now) {
const requested = now + days * DAY_MS
const current = Date.parse(user.restrictedUntil)
return new Date(Number.isFinite(current) && current > requested ? current : requested)
}
/** The author's row: a strike, and the sanction on top. */
function buildSanctionUpdate(user, decision, decidedAt, now) {
const sets = ['strikes = list_append(if_not_exists(strikes, :empty), :strike)']
const values = { ':empty': [], ':strike': [decidedAt] }
let restrictedUntil = null
if (decision.sanction === 'restriction') {
restrictedUntil = restrictionEnd(user, decision.restrictionDays, now).toISOString()
sets.push('restrictedUntil = :until')
values[':until'] = restrictedUntil
}
if (decision.sanction === 'ban') {
sets.push('bannedAt = if_not_exists(bannedAt, :now)')
values[':now'] = decidedAt
}
return {
restrictedUntil,
write: {
Update: {
TableName: process.env.USERS_TABLE_NAME,
Key: { id: user.id },
UpdateExpression: `SET ${sets.join(', ')}`,
ConditionExpression: 'attribute_exists(id)',
ExpressionAttributeValues: values
}
}
}
}
/** Closes one report, as long as it is still open. */
function buildReportClose(report, status, decisionRecord) {
return {
Update: {
TableName: process.env.CONTENT_REPORTS_TABLE_NAME,
Key: { targetKey: report.targetKey, reporterId: report.reporterId },
UpdateExpression: 'SET #status = :status, listKey = :closed, decision = :decision',
ConditionExpression: 'listKey = :open',
ExpressionAttributeNames: { '#status': 'status' },
ExpressionAttributeValues: {
':status': status,
':closed': REPORT_CLOSED_LIST_KEY,
':open': REPORT_LIST_KEY,
':decision': decisionRecord
}
}
}
}
/** What both kinds of notification say about the content itself. */
function contentData(report) {
return {
targetType: report.targetType,
contentExcerpt: reportExcerpt(report),
...(report.snapshot?.name !== undefined && { packName: report.snapshot.name })
}
}
function isConditionFailure(error) {
return (
error.name === 'TransactionCanceledException' &&
(error.CancellationReasons || []).some((reason) => reason.Code === 'ConditionalCheckFailed')
)
}
async function disableAccount(userId) {
const poolId = process.env.COGNITO_USER_POOL_ID
await cognitoClient.send(new AdminDisableUserCommand({ UserPoolId: poolId, Username: userId }))
await cognitoClient.send(
new AdminUserGlobalSignOutCommand({ UserPoolId: poolId, Username: userId })
)
}
/** Best-effort: the decision is written already, and the user may have no email. */
async function emailBan(user, report, decision) {
if (!user.email) return
try {
await sendEmail({
to: user.email,
...renderAccountBannedEmail({
lang: pickEmailLanguage(user.languagePreferences),
reason: report.reason,
excerpt: reportExcerpt(report),
note: decision.note,
contactEmail: process.env.SUPPORT_EMAIL
})
})
} catch (error) {
console.error('[decide-content-report] Ban email failed:', error.message)
}
}
exports.handler = requirePlatformAdmin(async (event) => {
try {
let payload
try {
payload = JSON.parse(event.body || '{}')
} catch {
return respond(400, { error: 'Invalid JSON body' })
}
const decision = validateDecisionInput(payload)
if (!decision.valid) return respond(400, { error: decision.error })
const reports = await listTargetReports(decision.targetKey)
if (reports.length === 0) return respond(404, { error: 'Report not found' })
const open = reports.filter((report) => report.listKey === REPORT_LIST_KEY)
if (open.length === 0) return respond(409, { error: 'REPORT_DECIDED' })
const [first] = open
if (decision.removed) {
// A conversation belongs to its two participants: nothing for an admin to remove
if (first.targetType === REPORT_TARGET_TYPE.CONVERSATION) {
return respond(400, { error: 'A conversation cannot be removed' })
}
if (!(await isContentRemoved(first))) {
return respond(409, { error: 'CONTENT_NOT_REMOVED' })
}
}
const now = Date.now()
const decidedAt = new Date(now).toISOString()
const decidedBy = event.requestContext.authorizer.claims.sub
// What an appeal names (UC-REPORT-009.1), with the target
const decisionId = randomUUID()
const appealRef = { targetKey: decision.targetKey, decisionId }
const actioned = decision.outcome === REPORT_STATUS.ACTIONED
// A deleted account has nobody left to sanction or to tell
const author = actioned ? await getUser(first.reportedUserId) : null
if (author && decision.sanction === 'ban') await disableAccount(author.id)
const authorWrites = []
const pushes = []
let restrictedUntil = null
if (author) {
const sanction = buildSanctionUpdate(author, decision, decidedAt, now)
restrictedUntil = sanction.restrictedUntil
const told = buildNotificationWrites(author.id, {
type: NOTIFICATION_TYPE.MODERATION_DECISION,
data: {
...contentData(first),
reason: first.reason,
removed: decision.removed,
sanction: decision.sanction,
restrictedUntil,
note: decision.note,
contactEmail: process.env.SUPPORT_EMAIL,
...appealRef
}
})
authorWrites.push(sanction.write, ...told.writes)
pushes.push([author.id, told.notification])
}
const decisionRecord = {
id: decisionId,
outcome: decision.outcome,
removed: decision.removed,
sanction: decision.sanction,
restrictedUntil,
note: decision.note,
decidedBy,
decidedAt
}
for (let start = 0; start < open.length; start += REPORTERS_PER_TRANSACTION) {
const chunk = open.slice(start, start + REPORTERS_PER_TRANSACTION)
const writes = start === 0 ? [...authorWrites] : []
for (const report of chunk) {
writes.push(buildReportClose(report, decision.outcome, decisionRecord))
const told = buildNotificationWrites(report.reporterId, {
type: NOTIFICATION_TYPE.REPORT_DECIDED,
data: { ...contentData(report), outcome: decision.outcome, ...appealRef }
})
writes.push(...told.writes)
pushes.push([report.reporterId, told.notification])
}
try {
await docClient.send(new TransactWriteCommand({ TransactItems: writes }))
} catch (error) {
// Another admin decided first: the first chunk wrote nothing
if (start === 0 && isConditionFailure(error)) {
return respond(409, { error: 'REPORT_DECIDED' })
}
throw error
}
}
await Promise.all(
pushes.map(([userId, notification]) => pushNotification(userId, notification))
)
if (author && decision.sanction === 'ban') await emailBan(author, first, decision)
return respond(200, {
targetKey: decision.targetKey,
status: decision.outcome,
decided: open.length,
decision: decisionRecord
})
} catch (error) {
console.error('Error deciding content reports:', error)
return respond(500, { error: 'Failed to decide reports' })
}
})
|