From e2622959a2234c7679c5c3eb18ba8642a1ce3a13 Mon Sep 17 00:00:00 2001 From: Paul Duncan Date: Sun, 17 Oct 2021 16:44:32 -0400 Subject: add bin/hook --- bin/hook/fire.rb | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100755 bin/hook/fire.rb (limited to 'bin/hook/fire.rb') diff --git a/bin/hook/fire.rb b/bin/hook/fire.rb new file mode 100755 index 0000000..5cd6022 --- /dev/null +++ b/bin/hook/fire.rb @@ -0,0 +1,54 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# bin/hook/fire.rb: trigger deploy webhook. +# +# Requires that the following environment variables are set: +# +# * HOOK_URL: Webhook URL +# * HOOK_HMAC_KEY: Hook HMAC-SHA256 key. +# + +require 'openssl' +require 'json' +require 'time' +require 'uri' +require 'net/http' +require 'pp' + +# get hook URL and HMAC key +hook_url = ENV.fetch('HOOK_URL') +key = ENV.fetch('HOOK_HMAC_KEY') + +# get name of HMAC header, or default to X-Hub-Signature if unspecified +header_name = ENV.fetch('HOOK_HMAC_HEADER', 'X-Hub-Signature') + +# build body +body = JSON({ + # current timestamp, in ISO8601/RFC3339 format + time: Time.now.iso8601, + + # random nonce + nonce: OpenSSL::Digest::SHA256.hexdigest(OpenSSL::Random.random_bytes(32)), +}) + +# calculate hmac +hmac = OpenSSL::HMAC.hexdigest('SHA256', key, body) + +# parse uri +uri = URI.parse(hook_url) + +# build request +req = Net::HTTP::Post.new(uri.path) +# req[header_name] = hmac +req[header_name] = 'sha256=%s' % [hmac] +req['Content-Type'] = 'application/json' +req.body = body + +# build connection +http = Net::HTTP.new(uri.host, uri.port) +http.use_ssl = true + +# send request +pp http.request(req) -- cgit v1.2.3