All files / admin list-content-reports.js

100% Statements 49/49
92.85% Branches 26/28
100% Functions 15/15
100% Lines 46/46

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                                        1x 1x 1x 1x             1x             1x   1x   1x         1x       10x 10x   10x 11x 11x 11x 11x   10x         5x                     5x         5x             5x         12x 12x 12x         6x 6x 3x               6x                                         1x 15x 15x         7x                     6x 6x   6x     6x     6x 5x     6x 5x       6x       6x         9x 8x           1x 1x              
/**
 * List Content Reports (Platform Admin) Lambda
 * GET /v1/platform-admin/content-reports?status=&limit=&cursor=
 *
 * Requires `isPlatformAdmin: true`. The reports users filed on a comment, a
 * direct message conversation or a store pack (content-reports/create.js):
 * the open ones (`status=open`, the default) or the decided ones
 * (`status=closed`, with their decision), newest first, cursor-paginated
 * through the `listIndex` GSI — never a Scan. Each row is enriched with:
 * - the reporter's and the reported user's name and email
 * - the reported user's standing: strikes still counting, restriction, ban
 *   (UC-REPORT-005.1)
 * - the reporter's record over 12 months: how many reports they filed, how
 *   many were dismissed, whether they were warned or had reporting suspended
 *   (UC-REPORT-011.1), through the `reporterIndex` GSI
 * - how many reports of the same content the list holds (`targetReportCount`)
 *
 * @implements UC-REPORT-004.1, UC-REPORT-005.1, UC-REPORT-011.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, QueryCommand } = require('@aws-sdk/lib-dynamodb')
const { requirePlatformAdmin } = require('../utils/requirePlatformAdmin')
const { batchGetByIds } = require('../utils/platformAdminList')
const {
  REPORT_LIST_KEY,
  REPORT_CLOSED_LIST_KEY,
  REPORT_STATUS,
  STRIKE_WINDOW_MS,
  reportingSuspendedUntil
} = require('../utils/contentReports')
const {
  InvalidParamsError,
  encodeCursor,
  parseListParams,
  toUserSummary,
  toStanding
} = require('../utils/adminReportViews')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
 
const corsHeaders = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
const LIST_KEYS = { open: REPORT_LIST_KEY, closed: REPORT_CLOSED_LIST_KEY }
 
/** Sums the pages of a COUNT Query. */
async function countQuery(input) {
  let count = 0
  let dismissed = 0
  let ExclusiveStartKey
  do {
    const page = await docClient.send(new QueryCommand({ ...input, ExclusiveStartKey }))
    count += page.Count || 0
    dismissed += (page.Items || []).filter((item) => item.status === REPORT_STATUS.DISMISSED).length
    ExclusiveStartKey = page.LastEvaluatedKey
  } while (ExclusiveStartKey)
  return { count, dismissed }
}
 
/** The reports a user filed over the strike window, and how many were dismissed. */
async function reporterRecord(reporterId, now) {
  const { count, dismissed } = await countQuery({
    TableName: process.env.CONTENT_REPORTS_TABLE_NAME,
    IndexName: 'reporterIndex',
    KeyConditionExpression: 'reporterId = :reporterId AND createdAt >= :since',
    ExpressionAttributeNames: { '#status': 'status' },
    ExpressionAttributeValues: {
      ':reporterId': reporterId,
      ':since': new Date(now - STRIKE_WINDOW_MS).toISOString()
    },
    ProjectionExpression: '#status'
  })
  return { reports: count, dismissed }
}
 
/** The reports of one target in the list asked for. */
async function targetCount(targetKey, listKey) {
  const { count } = await countQuery({
    TableName: process.env.CONTENT_REPORTS_TABLE_NAME,
    KeyConditionExpression: 'targetKey = :targetKey',
    FilterExpression: 'listKey = :listKey',
    ExpressionAttributeValues: { ':targetKey': targetKey, ':listKey': listKey },
    Select: 'COUNT'
  })
  return count
}
 
/** One Query per distinct key of the page, at once. */
async function mapDistinct(keys, load) {
  const distinct = [...new Set(keys.filter(Boolean))]
  const values = await Promise.all(distinct.map(load))
  return new Map(distinct.map((key, index) => [key, values[index]]))
}
 
/** How the reporter reports: what the admin weighs a warning against. */
function toReporterStanding(userId, users, records) {
  const user = users.get(userId)
  if (!user) return null
  return {
    ...records.get(userId),
    reportingWarnedAt: user.reportingWarnedAt || null,
    reportingSuspendedUntil: reportingSuspendedUntil(user)
  }
}
 
function toAdminReport(report, users, records, counts) {
  return {
    id: report.id,
    targetType: report.targetType,
    target: report.target || {},
    reason: report.reason,
    details: report.details || null,
    reporter: toUserSummary(report.reporterId, users),
    reporterStanding: toReporterStanding(report.reporterId, users, records),
    reportedUser: toUserSummary(report.reportedUserId, users),
    reportedUserStanding: toStanding(report.reportedUserId, users),
    snapshot: report.snapshot || {},
    status: report.status || REPORT_STATUS.OPEN,
    decision: report.decision || null,
    // A dismissal overturned on appeal: the reports are open again (UC-REPORT-010.1)
    previousDecision: report.previousDecision || null,
    targetKey: report.targetKey,
    targetReportCount: counts.get(report.targetKey) ?? 1,
    createdAt: report.createdAt
  }
}
 
exports.handler = requirePlatformAdmin(async (event) => {
  try {
    const { listKey, limit, cursor } = parseListParams(event, LIST_KEYS, [
      'targetKey',
      'reporterId'
    ])
 
    const page = await docClient.send(
      new QueryCommand({
        TableName: process.env.CONTENT_REPORTS_TABLE_NAME,
        IndexName: 'listIndex',
        KeyConditionExpression: 'listKey = :listKey',
        ExpressionAttributeValues: { ':listKey': listKey },
        ScanIndexForward: false,
        Limit: limit,
        ExclusiveStartKey: cursor
      })
    )
    const reports = page.Items || []
    const now = Date.now()
 
    const [users, records, counts] = await Promise.all([
      batchGetByIds(
        process.env.USERS_TABLE_NAME,
        reports.flatMap((report) => [report.reporterId, report.reportedUserId]).filter(Boolean)
      ),
      mapDistinct(
        reports.map((report) => report.reporterId),
        (reporterId) => reporterRecord(reporterId, now)
      ),
      mapDistinct(
        reports.map((report) => report.targetKey),
        (targetKey) => targetCount(targetKey, listKey)
      )
    ])
 
    return {
      statusCode: 200,
      headers: corsHeaders,
      body: JSON.stringify({
        items: reports.map((report) => toAdminReport(report, users, records, counts)),
        nextCursor: page.LastEvaluatedKey ? encodeCursor(page.LastEvaluatedKey) : null
      })
    }
  } catch (error) {
    if (error instanceof InvalidParamsError) {
      return {
        statusCode: 400,
        headers: corsHeaders,
        body: JSON.stringify({ error: error.message })
      }
    }
    console.error('Error listing content reports:', error)
    return {
      statusCode: 500,
      headers: corsHeaders,
      body: JSON.stringify({ error: 'Failed to list reports' })
    }
  }
})