Brian Armstrong
Brian Armstrong

Reputation: 19873

Rack middleware to to prepend while(1); to all ajax/json requests

I'd like to do something similar to what Google/Facebook do in this post: Why does Google prepend while(1); to their JSON responses?

Adding while(1); to the beginning of script and json posts, using Rack middleware in a rails app. This way we can go back to doing ajax GET requests (which may or may not have an authentity_token or or sensitive data embedded in the response).

We also have an API which needs to not use this, so I am thinking some url matching where the middleware does not kick in.

Can anyone point me in the right direction what this code might look like? Thanks!

Upvotes: 1

Views: 528

Answers (1)

Anton
Anton

Reputation: 3036

There's quite a lot of questions molded into one, I think.

The middleware itself would look something(haven't checked it, but it feels right) like this:

class AntiHijackingMiddleware
 def call(env)
    status, headers, body = @app.call(env) # save initial state

    if env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest" && headers['Content-type'].to_s.include?("application/json")
        body = "while(1);"+body
        headers['Content-Length'] = Rack::Utils.bytesize(body.to_s).to_s
    end

    [status, headers, body]
 end
end

You can add additional conditions on env["REQUEST_URI"] to do url matching.

Adding it to Rails' middleware stack is boilerplate.

Upvotes: 2

Related Questions