preaction / Mercury

A message broker for WebSockets
Other
10 stars 8 forks source link

JSON Schema for messages #39

Open preaction opened 7 years ago

preaction commented 7 years ago

It would be interesting if we could optionally validate messages coming from clients to make sure that they don't send terrible messages that could hurt other clients. The prevailing standard for this in JSON would be JSON Schema. We could use the JSON::Validator module to validate the messages as we go through.

Admins could define the schema in the config file in a schemas key. This key is mapped to a hash of path prefixes, which are mapped to JSON schemas. This way users can define schemas at any level of the tree that apply to all lower branches/leaves (unless there is a more-specific schema for that branch/leaf).

{
  "schemas": {
    "/bus/chat": {
      "type": "object",
      "properties": {
        "user": {
          "description": "The user who sent the chat message",
          "type": "string",
          "required": true,
        },
        "text": {
          "description": "The text the user is sending",
          "type": "string",
          "required": true,
        },
      },
    },
  },
}

To access these schemas for validation, we should create a /schema GET endpoint, which gives the entire schema, or /schema/#endpoint which gets the schema that applies to the given endpoint (walking up the tree to find it if necessary).

This requires that, for these endpoints, the message be JSON, but this is optional so I think it's fine. If we could validate other formats, that'd be amazing.