neet/masto.js

Empty string as JSON in the follow request

Closed this issue ยท 1 comments

Describe the behavior

I found the the follow request sent from masto.js had the header content-type: application/json. Meanwhile, the request body is empty if no extra parameter is given.

The header content-type: application/json may lead the server to parse the request body as JSON. However, an empty string is not a valid JSON. The server may consider the follow request as broken or invalid, and won't handle it.

Example

I ran the following code to send out a follow request.

import { login } from 'masto';

const masto = await login({
  url: "https://mydomain.com",
	accessToken: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
});

const follow = await masto.v1.accounts.follow('YYYYYYYYYYYYYYYYYYYYYYYYYY')

The follow request I captured was the following:

POST /api/v1/accounts/YYYYYYYYYYYYYYYYYYYYYYYYYY/follow HTTP/1.0
Host: mydomain.com
Connection: upgrade
X-Forwarded-For: ZZZ.ZZ.Z.Z
X-Forwarded-Proto: https
Content-Length: 0
authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
content-type: application/json
accept: */*
accept-language: *
sec-fetch-mode: cors
user-agent: undici
accept-encoding: br, gzip, deflate


Remark

The official mastodon server seems to accept request with content-type: application/json and empty request body. However, it may make other Mastodon-compatible servers confused. For example, GoToSocial (a fediverse backend server implemented with Mastodon API) tries to parse the request body due to the existence of content-type: application/json in the request header. Then the empty string as JSON triggered a bad request error, and the server dropped the request.

Suggestion

According to the spec of JSON, an empty string is not a valid JSON. It may make the server confused. I suggest to add {}, which is the minimal valid JSON, at the request body when there is no parameter in the request body. (The Mastodon Official iOS app also does the same way. See this)

Related issues

I first discovered this issue from an issue in the GoToSocial repository: [bug] Follow button on Elk not working. I thought it was the problem on the Elk client, so I created an issue in the repository of the Elk client: Follow request body contains empty string as JSON. After some investigation, I found that the Elk client is using Masto.js to handle the Mastodon API. I think it is better to fix it here.

I also tested with an other client, Phanpy, which uses Masto.js to handle the Mastodon API, and I got the same result (i.e. The follow request was dropped by the GoToSocial server since it contained content-type: application/json and an empty request body.)

Version

Masto.js v5.7.0

๐ŸŽ‰ This issue has been resolved in version 5.9.2 ๐ŸŽ‰

The release is available on:

Your semantic-release bot ๐Ÿ“ฆ๐Ÿš€