All files / entities subscribe.js

100% Statements 37/37
94.73% Branches 18/19
100% Functions 1/1
100% Lines 37/37

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                                            1x 1x         1x 1x   1x 1x   1x         1x 13x 13x 13x   13x 1x             12x 1x             11x             10x 1x             9x     9x 1x                 8x             8x 1x             7x 7x                         7x                 7x 7x         7x   6x   6x           2x         1x             1x 1x               1x  
/**
 * POST /v1/entities/{entityId}/subscription
 *
 * Subscribe the calling user to an entity so that new items created in it
 * show up in their home-page recent-activity feed (GET /v1/feed). Eligible
 * entities are: any public entity (regardless of owning flow), or any private
 * entity owned by the caller's *currently active* flow — exactly the same
 * rule shared/auth-helper.js's canAccessEntity() uses to gate item reads
 * (entity.flowId === auth.flowId), not "any flow the caller happens to be a
 * member of". A private entity is only ever readable while its owning flow
 * is the active one, so subscription eligibility must match: this carries no
 * new access, only convenience, and must not create a way to read another
 * flow's private data merely by having once been a member of it.
 *
 * Unlike Link (entities/link.js), this is a personal, user-scoped action with
 * no RBAC permission requirement and no functional data dependency — there is
 * no harm or ambiguity in following your own entity's activity, unlike Link
 * where linking your own entity would be a meaningless self-reference.
 *
 * @implements UC-CATALOG-005.1
 */
 
const { getActiveFlowId } = require('../shared/activeFlow')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  GetCommand,
  TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const { buildSubscriberCountUpdate } = require('../utils/entitySubscriberCount')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const CORS_HEADERS = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
const subscribeEntityHandler = async (event) => {
  try {
    const entityId = event.pathParameters?.entityId
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    if (!userId) {
      return {
        statusCode: 401,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Unauthorized' })
      }
    }
 
    if (!entityId) {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Missing entity id' })
      }
    }
 
    const entityResult = await docClient.send(
      new GetCommand({
        TableName: process.env.ENTITIES_TABLE_NAME,
        Key: { id: entityId }
      })
    )
 
    if (!entityResult.Item) {
      return {
        statusCode: 404,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Entity not found' })
      }
    }
 
    const entity = entityResult.Item
 
    // The active flow (a membership read) only matters for a private entity
    if (entity.visibility !== 'public' && entity.flowId !== (await getActiveFlowId(event))) {
      return {
        statusCode: 403,
        headers: CORS_HEADERS,
        body: JSON.stringify({
          error: 'Can only subscribe to public entities or entities in your active flow'
        })
      }
    }
 
    const existingSubscription = await docClient.send(
      new GetCommand({
        TableName: process.env.ENTITY_SUBSCRIPTIONS_TABLE_NAME,
        Key: { userId, entityId }
      })
    )
 
    if (existingSubscription.Item) {
      return {
        statusCode: 409,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Already subscribed to this entity' })
      }
    }
 
    const now = new Date().toISOString()
    const subscription = {
      userId,
      entityId,
      subscribedAt: now,
      entityFlowId: entity.flowId
    }
 
    // The subscription Put and the subscriber-count +1 must succeed or fail
    // together — otherwise a crash between the two would leave the counter
    // permanently out of sync with the actual subscription rows. The
    // ConditionExpression (rather than relying solely on the pre-check Get
    // above) also closes the race where two concurrent subscribe requests
    // both pass that check.
    const transactItems = [
      {
        Put: {
          TableName: process.env.ENTITY_SUBSCRIPTIONS_TABLE_NAME,
          Item: subscription,
          ConditionExpression: 'attribute_not_exists(userId)'
        }
      }
    ]
    Eif (process.env.ENTITY_SUBSCRIBER_COUNT_TABLE_NAME) {
      transactItems.push(
        buildSubscriberCountUpdate(process.env.ENTITY_SUBSCRIBER_COUNT_TABLE_NAME, entityId, 1)
      )
    }
 
    await docClient.send(new TransactWriteCommand({ TransactItems: transactItems }))
 
    console.log('[subscribe] Entity subscribed:', { userId, entityId })
 
    return {
      statusCode: 201,
      headers: CORS_HEADERS,
      body: JSON.stringify(subscription)
    }
  } catch (error) {
    if (
      error.name === 'ConditionalCheckFailedException' ||
      (error.name === 'TransactionCanceledException' &&
        error.CancellationReasons?.[0]?.Code === 'ConditionalCheckFailed')
    ) {
      return {
        statusCode: 409,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Already subscribed to this entity' })
      }
    }
 
    console.error('[subscribe] Exception:', error.message, error.stack)
    return {
      statusCode: 500,
      headers: CORS_HEADERS,
      body: JSON.stringify({ error: 'Failed to subscribe to entity' })
    }
  }
}
 
module.exports = { subscribeEntityHandler }