All files / admin restrict-reporting.js

100% Statements 46/46
94.44% Branches 17/18
100% Functions 3/3
100% Lines 41/41

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                                    1x         1x 1x 1x         1x   1x   1x         1x   14x               2x 2x 2x     1x 14x 14x 14x     13x 13x   1x   12x 12x   6x     6x 6x   5x 5x       5x 2x 2x 2x           3x 2x 2x 2x       2x     4x 4x                               3x   3x   1x 1x      
/**
 * Restrict Reporting (Platform Admin) Lambda
 * POST /v1/platform-admin/users/{userId}/reporting
 *
 * Requires `isPlatformAdmin: true`. The answer to reports filed in bad faith
 * (DSA Art. 23), after a look at the reporter's record on the Reports tab:
 * - `{ action: 'warn' }`: the user is told their reports are often unfounded,
 *   and that reporting may be suspended
 * - `{ action: 'suspend', days }`: until then, their reports are refused
 *   (`403 REPORTING_SUSPENDED`); only after a warning (`409 NOT_WARNED`
 *   otherwise). A longer suspension already running is kept.
 * Both take an optional `note`, and notify the user, in one transaction with
 * the row's update. Lifting the user's sanctions ends a suspension
 * (admin/lift-user-sanctions.js).
 *
 * @implements UC-REPORT-011.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  GetCommand,
  TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const { requirePlatformAdmin } = require('../utils/requirePlatformAdmin')
const { validateReportingActionInput } = require('../utils/contentReports')
const {
  NOTIFICATION_TYPE,
  buildNotificationWrites,
  pushNotification
} = require('../utils/notifications')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
 
const corsHeaders = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
const DAY_MS = 24 * 60 * 60 * 1000
 
const respond = (statusCode, body) => ({
  statusCode,
  headers: corsHeaders,
  body: JSON.stringify(body)
})
 
/** The suspension's end: a longer one already running is kept. */
function suspensionEnd(user, days, now) {
  const requested = now + days * DAY_MS
  const current = Date.parse(user.reportingSuspendedUntil)
  return new Date(Number.isFinite(current) && current > requested ? current : requested)
}
 
exports.handler = requirePlatformAdmin(async (event) => {
  try {
    const userId = event.pathParameters?.userId
    if (!userId) return respond(400, { error: 'Missing userId' })
 
    let payload
    try {
      payload = JSON.parse(event.body || '{}')
    } catch {
      return respond(400, { error: 'Invalid JSON body' })
    }
    const input = validateReportingActionInput(payload)
    if (!input.valid) return respond(400, { error: input.error })
 
    const result = await docClient.send(
      new GetCommand({ TableName: process.env.USERS_TABLE_NAME, Key: { id: userId } })
    )
    const user = result.Item
    if (!user) return respond(404, { error: 'User not found' })
 
    const now = Date.now()
    const at = new Date(now).toISOString()
    let update
    let notification
    let standing
    if (input.action === 'warn') {
      update = { expression: 'SET reportingWarnedAt = :at', values: { ':at': at } }
      notification = { type: NOTIFICATION_TYPE.REPORTING_WARNING, data: { note: input.note } }
      standing = {
        reportingWarnedAt: at,
        reportingSuspendedUntil: user.reportingSuspendedUntil || null
      }
    } else {
      // Art. 23: a suspension comes after a warning
      if (!user.reportingWarnedAt) return respond(409, { error: 'NOT_WARNED' })
      const until = suspensionEnd(user, input.days, now).toISOString()
      update = { expression: 'SET reportingSuspendedUntil = :until', values: { ':until': until } }
      notification = {
        type: NOTIFICATION_TYPE.REPORTING_SUSPENDED,
        data: { note: input.note, suspendedUntil: until }
      }
      standing = { reportingWarnedAt: user.reportingWarnedAt, reportingSuspendedUntil: until }
    }
 
    const told = buildNotificationWrites(userId, notification)
    await docClient.send(
      new TransactWriteCommand({
        TransactItems: [
          {
            Update: {
              TableName: process.env.USERS_TABLE_NAME,
              Key: { id: userId },
              UpdateExpression: update.expression,
              ConditionExpression: 'attribute_exists(id)',
              ExpressionAttributeValues: update.values
            }
          },
          ...told.writes
        ]
      })
    )
    await pushNotification(userId, told.notification)
 
    return respond(200, { id: userId, ...standing })
  } catch (error) {
    console.error('Error restricting reporting:', error)
    return respond(500, { error: 'Failed to restrict reporting' })
  }
})