require "json" require "openssl" require "pstore" require "net/http" require "time" # One receiver/store per Nuntio workspace and downstream destination. class NuntioReceiver PROVIDERS = { "x" => "X", "facebook" => "Facebook", "instagram" => "Instagram", "linkedin" => "LinkedIn", "pinterest" => "Pinterest", "tiktok" => "TikTok", "youtube" => "YouTube", "reddit" => "Reddit" }.freeze STATES = { "published" => "was published", "failed" => "could not finish publishing", "uncertain" => "needs checking on the platform", "held" => "is on hold", "cancelled" => "was cancelled" }.freeze MAX_BYTES = 1_048_576 def initialize(secret:, account:, destination:, store:) raise ArgumentError, "Use the Nuntio signing key" unless secret.match?(/\A[0-9a-f]{64}\z/) @secret, @account, @store = secret, account, PStore.new(store, true) @destination = URI(destination) raise ArgumentError, "Use a supported HTTPS destination" unless @destination.is_a?(URI::HTTPS) && @destination.port == 443 && @destination.userinfo.nil? && @destination.query.nil? && @destination.fragment.nil? @slack = @destination.host == "hooks.slack.com" && @destination.path.match?(%r{\A/services/[A-Za-z0-9]+/[A-Za-z0-9]+/[A-Za-z0-9]+\z}) discord = @destination.host == "discord.com" && @destination.path.match?(%r{\A/api/webhooks/[0-9]+/[A-Za-z0-9_.-]+\z}) raise ArgumentError, "Use a Slack or Discord incoming webhook" unless @slack || discord @destination.query = "wait=true" if discord end def call(env) return response(404) unless env["REQUEST_METHOD"] == "POST" && env["PATH_INFO"] == "/nuntio" return response(415) unless env.fetch("CONTENT_TYPE", "").split(";").first == "application/json" body = env.fetch("rack.input").read(MAX_BYTES + 1) || "" return response(422) if body.empty? return response(413) if body.bytesize > MAX_BYTES timestamp, event = env["HTTP_NUNTIO_TIMESTAMP"].to_s, env["HTTP_NUNTIO_EVENT"].to_s signature = env["HTTP_NUNTIO_SIGNATURE"].to_s return response(401) unless timestamp.match?(/\A[0-9]{1,12}\z/) && (Time.now.to_i - timestamp.to_i).abs <= 300 && event.match?(/\A[0-9a-f-]{36}\z/i) && signature.match?(/\Av1=[0-9a-f]{64}\z/) digest = OpenSSL::HMAC.hexdigest("SHA256", @secret, "nuntio.webhook.v1\n#{timestamp}\n#{event}\n#{body}") return response(401) unless OpenSSL.fixed_length_secure_compare(digest, signature.delete_prefix("v1=")) payload = JSON.parse(body) return response(422) unless payload.is_a?(Hash) && payload["event_id"] == event && payload["account_id"] == @account && STATES.key?(payload["state"]) && payload["type"] == "publication.#{payload['state']}" && PROVIDERS.key?(payload["provider"]) checksum = OpenSSL::Digest::SHA256.hexdigest(body) claim = @store.transaction do if prior = @store[event] prior.fetch("checksum") == checksum ? :duplicate : :conflict else @store[event] = { "checksum" => checksum, "state" => "claimed", "received_at" => Time.now.utc.iso8601 } :new end end return response(409) if claim == :conflict return response(202) if claim == :duplicate result = forward(payload) @store.transaction { @store[event] = @store.fetch(event).merge(result) } response(202) rescue JSON::ParserError response(422) rescue PStore::Error, SystemCallError, IOError response(503) end private def forward(payload) text = "Your #{PROVIDERS.fetch(payload.fetch('provider'))} post #{STATES.fetch(payload.fetch('state'))}. Open Nuntio → Publications to check it." text = "Test: #{text}" if payload["test"] == true content = @slack ? { text: text } : { content: text, allowed_mentions: { parse: [] } } request = Net::HTTP::Post.new(@destination, "Content-Type" => "application/json") request.body = JSON.generate(content) http = Net::HTTP.new(@destination.host, @destination.port) http.use_ssl = true http.open_timeout = 5 http.read_timeout = 10 http.write_timeout = 10 http.max_retries = 0 status, body = nil, +"" http.request(request) do |incoming| status = incoming.code.to_i incoming.read_body do |chunk| body << chunk raise IOError, "Response too large" if body.bytesize > 8192 end end confirmed = if @slack status == 200 && body.strip == "ok" else data = JSON.parse(body) if status == 200 status == 200 && data.is_a?(Hash) && data["id"].to_s.match?(/\A[0-9]+\z/) end { "state" => confirmed ? "delivered" : "needs_check", "status" => status } rescue JSON::ParserError, OpenSSL::SSL::SSLError, Timeout::Error, SocketError, SystemCallError, IOError, EOFError { "state" => "needs_check" } end def response(status) [ status, { "content-type" => "text/plain", "cache-control" => "no-store" }, [ "#{status}\n" ] ] end end