Pre-Hook Event

Overview

Our Pre-Hook Event feature has been designed to offer customers increased control over user-generated content, community access, and the moderation of sensitive material. This enhancement not only provides a safer environment for applications but also empowers users to create custom moderation rules tailored to their specific requirements.

The Pre-Hook Event feature delivers a range of functionalities that users can employ to establish a more controlled environment within their applications. By enabling the Pre-Hook Event feature through network settings and adjusting the configuration parameters as needed, users can define custom rules and implement APIs to create custom use cases for enhanced moderation. This may include measures such as denying entrance to specific channels for certain users or modifying messages containing sensitive words before they are sent.

The system is designed to trigger pre-hook events for major available actions. Users can monitor the three response types provided by the APIs (allow, deny, and API timeout) and implement proper error handling measures to manage API error cases, ensuring a seamless user experience.

Please note that this feature is only available for customers who are on the max plan.

Configurations

To make the most of the Pre-Hook Event feature, follow these steps to implement it in your application:

  1. Enable the Feature: Access your network settings through the pre-hook configuration API and enable the Pre-Hook Event feature. While doing so, adjust the configuration parameters, such as enabled, callbackUrl, and defaultAction, according to your requirements.

  2. Create Custom Rules: Develop custom moderation rules based on your application's specific needs. These rules will help you address unique use cases and strengthen your moderation measures.

  3. Implement APIs: Use the provided APIs to create custom use cases for enhanced moderation. These use cases can include denying entrance to specific channels for certain users, modifying messages containing sensitive words before they are sent, and more.

  4. Monitor API Responses: Keep track of the three response types provided by the APIs: allow, deny, and API timeout. These responses will give you insight into the success or failure of your custom rules and actions. Here are the example of request and response of pre-hook event.

Timeout of the provided pre-hook callback is 3 seconds. If it exceeds the timeout, it will execute the provided default action instead.

Request:

{
  "eventName": "message.shouldCreate",
  "data": {
    "key": "value"
  },
  "actor": {
    "_id": "string",
    "userId": "string"
  }
}

Response:

{
  "action": "allow",
  "data": {
    "key": "modified value"
  },
  "message": "string"
}
  1. Error Handling: Ensure that you have a robust error handling mechanism in place to manage API error cases effectively. Proper error handling will contribute to a seamless user experience and prevent potential disruptions.

Implementation

The following sections explain the components, response handling, and error handling involved in the Pre-Hook Event feature.

Components

The external system's response must include the following components:

  1. HTTP status code = 200

  2. Response object with three possible scenarios:

    a. Allow the action without modification: { "action" : "allow" }

    b. Allow the action with modification: { "action" : "allow", "data" : { ... } // Modified data object }

    c. Deny the action: { "action" : "deny", "message" : "this is an error message" }

  3. Signature key to ensure the security between the server and the client.

If a modified data object is returned, its data schema must match the original one.

Security

The security of the pre-hook events feature is ensured through the use of a signature key, which are crucial components in maintaining the confidentiality and integrity of the communication between the server and the client.

Secret Key

  1. Upon configuring and enabling the pre-hook feature for the first time, a secret key is generated. This secret key is a randomly generated 16-byte hexadecimal string.

  2. The secret key serves as a shared symmetric key between the server and the client, which is used for authentication purposes.

  3. In case the secret key is leaked, it can be regenerated to maintain security.

  4. Only network administrators are allowed to access and update the pre-hook setting and regenerate the secret key.

  5. The secret key is available in the update setting API response only when enabling the feature for the first time or when regenerating the secret key. It is not available in the get setting API or when updating other fields.

Signature Key

  1. The signature key is used to authenticate the payload on the external system.

  2. It is computed using the HMAC Base64 digest of the request body. The HMAC Base64 digest is generated by performing the SHA-256 hash function with the secret key as the HMAC key, the request body as the payload, and digested as a Base64 string. Here's an example of generating a signature key from a secret key:

function genSignature(secretKey: string, payload: any): string {
  const hmac = crypto.createHmac('sha256', secretKey);
  hmac.update(JSON.stringify(payload));
  return hmac.digest('base64');
}

const payload = {
  eventName: 'message.shouldCreate',
  data: {
    ...
  },
  actor: {
    _id: 'privateId',
    userId: 'publicId'
  }
}
genSignature('secret', payload)
  1. The signature key is included in the request header, ensuring secure communication between the server and the client.

  2. To verify the signature key on the client side, they could do this by computing the hash with the above method and comparing it with the one in the request header. Here is an example

const signatureKey = req.headers['ASC-Signature-Key'];
const payload = req.body

const hmac = crypto.createHmac('sha256', secretKey);
hmac.update(JSON.stringify(payload));
const hash = hmac.digest('base64');

if (hash !== signatureKey) {
  throw new Error('Invalid signature!')
}

Example of an HTTP request with a signature key attached:

curl --location --request POST '<<CALLBACK_URL>>' \
--header 'ASC-Signature-Key: <<SIGNATURE_KEY>>' \
--header 'Content-Type: application/json' \
--data-raw '{
  "eventName": "channel.shouldCreate",
  "actor": {
    "_id": "63aab2059c25c70d98c32ecc",
    "userId": "sam"
  },
  "data": {
    "key": "value"
  }
}'

Response Handling

  1. If the action is "allow", the system continues with the remaining application flow, using either the modified data payload (if provided) or the original payload.

  2. If the action is "deny", the system returns an error to the caller with code 400000 as a BadRequestError:

    {
      "errorCode" : 400000,
      "message" : "error message from deny action or BusinessError if null"
    }

Error Handling

In cases where the response object doesn't adhere to the specified format, or the request takes longer than 3 seconds, the system executes the following error handling flow:

  1. Log the error with the endpoint URL, response status code, response object (trimmed to 300 characters length), or null if the request times out, and the error reason.

  2. Use the default action (allow or deny) as configured in the setting. If the "deny" action is configured, the system returns an error to the caller with code 500401 as a BusinessError:

    {
      "errorCode" : 500401,
      "message" : "error message from BusinessError due to external system error"
    }

If the pre-hook service is unavailable or unresponsive due to reaching maximum capacity or other internal server problems, the system executes the following error handling flow:

Use the default action (allow or deny) as configured in the setting. If the "deny" action is configured, the system returns an error to the caller with code 500000 as a BusinessError:

{
  "errorCode" : 500000,
  "message" : "error message from BusinessError due to internal error"
}

Once the pre-hook process is completed, the system logs the pre-hook URL, response action, and response duration.

Supported Events

ModuleEventRequest DataModifiable Response DataREST API Endpoint

Chat

message.shouldCreate

  • Message Data

  • Sender ID

  • Channel ID

  • Message Data

POST /api/v5/messages or /api/v3/messages

message.shouldUpdate

  • Message Data

  • Sender ID

  • Channel ID

  • Message Data

PUT /api/v5/messages or /api/v3/messages

message.shouldFlag

  • Message Data

  • Sender ID

  • Flag Count

  • Message Data

POST /api/v5/messages/{messageId}/flag or /api/v3/messages/{messageId}/flag

message.shouldUnflag

  • Message Data

  • Sender ID

  • Flag count

  • Message Data

DELETE /api/v5/messages/{messageId}/unflag or /api/v3/messages/{messageId}/unflag

channel.shouldCreate

  • Channel Data

  • Creator ID

  • Channel Data

POST /api/v3/channels or /api/v3/channels/conversation

channel.shouldJoin

  • Channel ID

  • User ID

-

POST /api/v3/channels/{channelId}/join

channel.shouldLeave

  • Channel Data

  • User ID

  • Channel Data

DELETE /api/v3/channels/{channelId}/leave

Social

post.shouldCreate

  • Post Data

  • Creator ID

  • Entity ID

  • Post Data

POST /api/v4/posts

post.shouldUpdate

  • Post Data

  • Creator ID

  • Entity ID

  • Post Data

PUT /api/v4/posts/{postId}

post.shouldFlag

-

-

POST /api/v3/posts/flag

post.shouldUnFlag

-

-

DELETE /api/v3/posts/unflag

comment.shouldCreate

  • Comment Data

  • Creator ID

  • Post ID

  • Comment Data

POST /api/v3/comments

comment.shouldUpdate

  • Comment Data

  • Creator ID

  • Post ID

Comment Data

PUT /api/v3/comments

comment.shouldFlag

-

-

POST /api/v3/comments/flag

comment.shouldUnFlag

-

-

DELETE /api/v3/comments/unflag

community.shouldJoin

  • Community ID

  • User ID

-

POST /api/v3/communities/{communityId}/join

community.shouldLeave

  • Community ID

  • User ID

-

DELETE /api/v3/communities/{communityId}/leave

community.shouldCreate

  • Community Data

  • Creator ID

  • Community Data

POST /api/v3/communities

community.shouldUpdate

  • Community Data

  • Creator ID

  • Community Data

reaction.shouldCreate

-

-

POST /api/v2/reactions

follow.shouldUnfollow

  • Follow Data

-

DELETE /api/v4/me/following/{userId}

follow.shouldRequest

  • Follow Data

-

POST /api/v4/me/following/{userId}

Core

user.shouldFlag

-

-

POST /api/v4/me/flags/{userId}

user.shouldUnflag

-

-

DELETE /api/v4/me/flags/{userId}

Last updated

#3026: New Content: Technical FAQ

Change request updated