Module: Clerk::Tunnel

Defined in:
lib/clerk/tunnel.rb

Class Method Summary collapse

Class Method Details

.acc_pathObject



22
23
24
# File 'lib/clerk/tunnel.rb', line 22

def self.acc_path
  data_dir.join("account.key")
end

.crt_pathObject



7
8
9
# File 'lib/clerk/tunnel.rb', line 7

def self.crt_path
  data_dir.join("dev.crt")
end

.crt_ready?Boolean

Returns:

  • (Boolean)


30
31
32
# File 'lib/clerk/tunnel.rb', line 30

def self.crt_ready?
  File.exist? key_path and File.exist? crt_path
end

.data_dirObject



3
4
5
# File 'lib/clerk/tunnel.rb', line 3

def self.data_dir
  Rails.root.join(".clerk")
end

.executable_typeObject



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/clerk/tunnel.rb', line 179

def self.executable_type
  @@executable_type ||= begin
    platform = begin
      case RbConfig::CONFIG['host_os'].downcase
      when /linux/
        "linux"
      when /darwin/
        "darwin"
      when /bsd/
        "freebsd"
      when /mingw|mswin/
        "windows"
      else
        "linux"
      end
    end

    cpu = begin
      case RbConfig::CONFIG['host_cpu'].downcase
      when /amd64|x86_64/
        "amd64"
      when /^arm/
        RbConfig::CONFIG['host_cpu'].include?("64") ? "arm64" : "arm"
      else
        "386"
      end
    end

    executable_type = :"#{platform}_#{cpu}" 
  end
end

.key_pathObject



11
12
13
# File 'lib/clerk/tunnel.rb', line 11

def self.key_path
  data_dir.join("dev.key")
end

.ngrok_pathObject



15
16
17
# File 'lib/clerk/tunnel.rb', line 15

def self.ngrok_path
  data_dir.join("clerk_#{executable_type}")
end

.ngrok_ready?Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/clerk/tunnel.rb', line 34

def self.ngrok_ready?
  File.exist? ngrok_path
end

.ngrok_zip_pathObject



18
19
20
# File 'lib/clerk/tunnel.rb', line 18

def self.ngrok_zip_path
  data_dir.join("clerk_#{executable_type}.zip")
end

.patch_ngrok_gemObject



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/clerk/tunnel.rb', line 235

def self.patch_ngrok_gem
  # Patch ngrok tunnel gem to work with TLS
  ::Ngrok::Tunnel.class_eval do
    def self.start(params = {})
      init(params)

      if stopped?
        @params[:log] = (@params[:log]) ? File.open(@params[:log], 'w+') : Tempfile.new('ngrok')
        @pid = spawn("exec #{Clerk::Tunnel.ngrok_path} tls " + ngrok_exec_params)
        at_exit { Ngrok::Tunnel.stop }
        begin
          fetch_urls
        rescue => e

        end
      end

      @status = :running
      @ngrok_url.gsub("tls", "https")
    end  

    private

      def self.ngrok_exec_params
        exec_params = "-log=stdout -log-level=debug "
        exec_params << "-region=#{@params[:region]} " if @params[:region]
        exec_params << "-host-header=#{@params[:host_header]} " if @params[:host_header]
        exec_params << "-authtoken=#{@params[:authtoken]} " if @params[:authtoken]
        exec_params << "-subdomain=#{@params[:subdomain]} " if @params[:subdomain]
        exec_params << "-hostname=#{@params[:hostname]} " if @params[:hostname]
        exec_params << "-crt=#{@params[:crt]} " if @params[:crt]
        exec_params << "-key=#{@params[:key]} " if @params[:key]
        exec_params << "-inspect=#{@params[:inspect]} " if @params.has_key? :inspect
        exec_params << "-config=#{@params[:config]} #{@params[:addr]} > #{@params[:log].path}"
      end          

      def self.fetch_urls
        @params[:timeout].times do
          log_content = @params[:log].read

          result = log_content.scan(/URL:(.+)\sProto:(tls)\s/)
          if !result.empty?
            result = Hash[*result.flatten].invert
            @ngrok_url = result['tls']
            return @ngrok_url if @ngrok_url
          end

          error = log_content.scan(/msg="command failed" err="([^"]+)"/).flatten
          unless error.empty?
            self.stop
            raise Ngrok::Error, error.first
          end

          sleep 1
          @params[:log].rewind
        end
        self.stop
        raise Ngrok::FetchUrlError, "Unable to fetch external url"
      end          
  end
end

.patch_rack_requestsObject

This configured puma to terminate TLS, but since Puma’s TLS terminator has a bug we moved it to ngrok github.com/puma/puma/issues/1670 def self.configure_puma_options

server = ObjectSpace.each_object(Rails::Server).first
server_options = server.instance_variable_get(:@options).dup
if !server.send(:use_puma?)
  raise "Sorry, Clerk cannot boot with a custom host: #{server_options[:Host]}"
elsif server_options[:user_supplied_options].include? :Host
  raise "Sorry, Clerk currently only supports Rails using the Puma server."
else
  server_options[:user_supplied_options] << :Host
  server_options[:Host] = "ssl://127.0.0.1:#{server_options[:Port]}?key=.clerk/dev.key&cert=.clerk/dev.crt"
  server.instance_variable_set(:@options, server_options)
end

end



227
228
229
230
231
232
233
# File 'lib/clerk/tunnel.rb', line 227

def self.patch_rack_requests
  ::ActionDispatch::Request.class_eval do
    def scheme
      "https"
    end
  end
end

.ready?Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/clerk/tunnel.rb', line 26

def self.ready?
  crt_ready? and ngrok_ready?
end

.setup!Object



38
39
40
41
42
# File 'lib/clerk/tunnel.rb', line 38

def self.setup!
  setup_crt! unless self.crt_ready?
  setup_ngrok! unless self.ngrok_ready?
  puts "=> [Clerk] Setup done."
end

.setup_crt!Object



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/clerk/tunnel.rb', line 79

def self.setup_crt!
  puts "=> [Clerk] First boot detected. Initializing environment."
  require 'acme-client'
  require 'openssl'

  Dir.mkdir(data_dir) unless Dir.exist? data_dir

  puts "=> [Clerk] Authenticating with Let's Encrypt."
  if File.exist? acc_path
    acc_private_key = OpenSSL::PKey::RSA.new(File.read(acc_path))
    client = ::Acme::Client.new(private_key: acc_private_key, directory: 'https://acme-v02.api.letsencrypt.org/directory')
    client.kid #Load existing account
  else 
    acc_private_key = OpenSSL::PKey::RSA.new(4096)

    client = ::Acme::Client.new(private_key: acc_private_key, directory: 'https://acme-v02.api.letsencrypt.org/directory')

     = client.(contact: 'mailto:[email protected]', terms_of_service_agreed: true)
    
    File.write(acc_path, acc_private_key.to_pem)
  end

  puts "=> [Clerk] Beginning new certificate order for #{Clerk.config.app_host}."
  order = client.new_order(identifiers: [Clerk.config.app_host])
  challenge = order.authorizations.first.dns

  puts "=> [Clerk] Completing DNS challenge."
  record_name = "#{challenge.record_name}.#{Clerk.config.app_host.gsub(".clerkdev.com", "")}"      
  config_data = Clerk.api.post('/api/acme_challenge', { 
    name: record_name, 
    type: challenge.record_type, 
    content: challenge.record_content
  })

  puts "=> [Clerk] Waiting for DNS to process. This may take a few minutes."
  confirm_url = URI.parse("https://dns.google.com/resolve?name=#{challenge.record_name}.#{Clerk.config.app_host}&type=TXT")
  while true
    confirm_check = JSON.parse(Net::HTTP.get(confirm_url))
    break if confirm_check.dig("Answer", 0, "data")=="\"#{challenge.record_content}\""
    sleep(5)
    puts "=> [Clerk] Checking processing status..."
  end

  sleep(5) # Sometimes google returns correctly before.  Add an extra 10 seconds.
  puts "=> [Clerk] Checking processing status..."
  sleep(5)

  puts "=> [Clerk] Validating DNS challenge."
  challenge.request_validation

  while challenge.status == 'pending'
    sleep(2)
    puts "=> [Clerk] Checking validation status..."
    challenge.reload
  end

  puts "=> [Clerk] Validation complete. Requesting certificate."
  crt_private_key = OpenSSL::PKey::RSA.new(4096)
  File.write(key_path, crt_private_key.to_pem)
  
  csr = Acme::Client::CertificateRequest.new(private_key: crt_private_key, subject: { common_name: Clerk.config.app_host })
  order.finalize(csr: csr)
  sleep(1) while order.status == 'processing'

  File.write(crt_path, order.certificate)
  puts "=> [Clerk] Certificate created."
end

.setup_ngrok!Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/clerk/tunnel.rb', line 44

def self.setup_ngrok!
  ngrok_paths = {
    darwin_amd64: "/c/4VmDzA7iaHb/ngrok-stable-darwin-amd64.zip",
    darwin_386: "/c/4VmDzA7iaHb/ngrok-stable-darwin-386.zip",
    windows_amd64: "/c/4VmDzA7iaHb/ngrok-stable-windows-amd64.zip",
    windows_386: "/c/4VmDzA7iaHb/ngrok-stable-windows-386.zip",
    freebsd_amd64: "/c/4VmDzA7iaHb/ngrok-stable-freebsd-amd64.zip",
    freebsd_386: "/c/4VmDzA7iaHb/ngrok-stable-freebsd-386.zip",
    linux_amd64: "/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip",
    linux_386: "/c/4VmDzA7iaHb/ngrok-stable-linux-386.zip",
    linux_arm: "/c/4VmDzA7iaHb/ngrok-stable-linux-arm.zip",
    linux_arm64: "/a/nmkK3DkqZEB/ngrok-2.2.8-linux-arm64.zip",
  }

  puts "=> [Clerk] Downloading tunnnel executable."
  require 'zip'
  http = Net::HTTP.new("bin.equinox.io", 443)
  http.use_ssl = true
  resp = http.get(ngrok_paths[executable_type])
  open(ngrok_zip_path, "wb") do |file|
    file.write(resp.body)
  end

  puts "=> [Clerk] Unzipping tunnnel executable."
  Zip::File.open(ngrok_zip_path) do |zipfile|
    zipfile.each do |file|
      if file.name == "ngrok"
        zipfile.extract(file, ngrok_path)
      end
    end
  end

  File.delete(ngrok_zip_path) 
end

.start!Object



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/clerk/tunnel.rb', line 147

def self.start!
  self.patch_rack_requests

  server = ObjectSpace.each_object(Rails::Server).first
  server_options = server.instance_variable_get(:@options).dup
  if !server.send(:use_puma?)
    raise "Sorry, Clerk currently only supports Rails using the Puma server."
  elsif server_options[:user_supplied_options].include? :Host
    raise "Sorry, Clerk cannot boot with a custom host: #{server_options[:Host]}"
  else
    server_options[:user_supplied_options] << :Host
    server_options[:Host] = "127.0.0.1"
    # server_options[:Host] = "ssl://127.0.0.1:#{server_options[:Port]}?key=.clerk/dev.key&cert=.clerk/dev.crt"
    server.instance_variable_set(:@options, server_options)
  end

  require 'ngrok/tunnel'
  self.patch_ngrok_gem
  puts "=> Booting https://#{Clerk.config.app_host} with Clerk"
  options = {
    addr: server_options[:Port],
    authtoken: Clerk.config.tunnel_key,
    hostname: Clerk.config.app_host,
    region: "us",
    crt: Rails.root.join(".clerk/dev.crt"),
    key: Rails.root.join(".clerk/dev.key")
  }
  Ngrok::Tunnel.start(options)
end