acmesmith-cloudflare 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 696f366e01d4dc4201f12264d39af5e42b183b33224277aa2f0c3eb8002b262d
4
+ data.tar.gz: 97a3a228fc2c53d22443e66965de3ae2788aa52f7129fb58977e93cd484a1917
5
+ SHA512:
6
+ metadata.gz: b8f8cccb781fedf2419ee5e7f613c10a9b28d6d826a940109ee94a8fd1977a059d0e9c2115a34f0f23a7f424052234d87ab53e344583df4b7287294acc17c0b2
7
+ data.tar.gz: 6ab49890092ed70f5a51df7aa979dee68a464e0d9667891f51775ed96b09398825759a7139edb56152684d4fba174ecf2be3f3326888d5636522732a5420db32
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Daisuke Aritomo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # Acmesmith::Cloudflare
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/acmesmith/cloudflare`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ ```bash
14
+ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
15
+ ```
16
+
17
+ If bundler is not being used to manage dependencies, install the gem by executing:
18
+
19
+ ```bash
20
+ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/acmesmith-cloudflare.
data/Rakefile ADDED
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ task default: %i[]
@@ -0,0 +1,188 @@
1
+ require 'acmesmith/challenge_responders/base'
2
+ require 'acmesmith/cloudflare/client'
3
+
4
+ module Acmesmith
5
+ module ChallengeResponders
6
+ class Cloudflare < Base
7
+ class ZoneNotFound < StandardError; end
8
+ class AmbiguousZones < StandardError; end
9
+
10
+ DEFAULT_COMMENT = 'Managed by acmesmith for ACME dns-01'.freeze
11
+
12
+ def support?(type)
13
+ type == 'dns-01'
14
+ end
15
+
16
+ def cap_respond_all?
17
+ true
18
+ end
19
+
20
+ def initialize(api_token:, zone_id_map: {}, substitution_map: {}, ttl: 60, wait_time_seconds: 30, api_base: nil, client: nil)
21
+ @client = client || ::Acmesmith::Cloudflare::Client.new(api_token: api_token, api_base: api_base)
22
+ @zone_id_map = normalize_keys(zone_id_map)
23
+ @substitution_map = normalize_keys(substitution_map)
24
+ @ttl = ttl
25
+ @wait_time_seconds = wait_time_seconds
26
+
27
+ @zones_by_name = {}
28
+ @created_record_ids = Hash.new { |hash, key| hash[key] = [] }
29
+ end
30
+
31
+ def respond_all(*domain_and_challenges)
32
+ domain_and_challenges = apply_substitution_for_domain_and_challenges(domain_and_challenges)
33
+
34
+ puts "=> Requesting DNS record changes on Cloudflare"
35
+ puts
36
+
37
+ domain_and_challenges.each do |domain, challenge|
38
+ zone_id = find_zone_id(domain)
39
+ record_name = record_name_for(domain, challenge)
40
+
41
+ print " * #{record_name} #{challenge.record_type} #{challenge.record_content} ..."
42
+ response = @client.create_dns_record(
43
+ zone_id: zone_id,
44
+ name: record_name,
45
+ type: challenge.record_type,
46
+ content: challenge.record_content,
47
+ ttl: @ttl,
48
+ comment: DEFAULT_COMMENT,
49
+ )
50
+ record_id = response.fetch('result').fetch('id')
51
+ @created_record_ids[record_identity(zone_id, record_name, challenge.record_type, challenge.record_content)] << record_id
52
+ puts " [ ok ] #{record_id}"
53
+ end
54
+
55
+ puts
56
+ wait_for_sync
57
+ end
58
+
59
+ def cleanup_all(*domain_and_challenges)
60
+ domain_and_challenges = apply_substitution_for_domain_and_challenges(domain_and_challenges)
61
+
62
+ puts "=> Removing DNS record changes from Cloudflare"
63
+ puts
64
+
65
+ domain_and_challenges.each do |domain, challenge|
66
+ zone_id = find_zone_id(domain)
67
+ record_name = record_name_for(domain, challenge)
68
+ record_ids = take_record_ids(zone_id, record_name, challenge.record_type, challenge.record_content)
69
+ record_ids = find_record_ids(zone_id, record_name, challenge.record_type, challenge.record_content) if record_ids.empty?
70
+
71
+ if record_ids.empty?
72
+ puts " * #{record_name} #{challenge.record_type} #{challenge.record_content} [ not found ]"
73
+ next
74
+ end
75
+
76
+ record_ids.each do |record_id|
77
+ print " * deleting #{record_name} #{challenge.record_type} #{challenge.record_content} ..."
78
+ @client.delete_dns_record(zone_id: zone_id, record_id: record_id)
79
+ puts " [ ok ] #{record_id}"
80
+ end
81
+ end
82
+
83
+ puts
84
+ end
85
+
86
+ private
87
+
88
+ def wait_for_sync
89
+ return unless @wait_time_seconds.to_i.positive?
90
+
91
+ puts "=> Waiting #{@wait_time_seconds} seconds for DNS changes to be seen"
92
+ sleep @wait_time_seconds
93
+ puts
94
+ end
95
+
96
+ def apply_substitution_for_domain_and_challenges(domain_and_challenges)
97
+ domain_and_challenges.map do |domain, challenge|
98
+ [@substitution_map.fetch(normalize_domain(domain), domain), challenge]
99
+ end
100
+ end
101
+
102
+ def record_name_for(domain, challenge)
103
+ "#{challenge.record_name}.#{normalize_domain(domain)}"
104
+ end
105
+
106
+ def find_zone_id(domain)
107
+ labels = normalize_domain(domain).split('.')
108
+
109
+ 0.upto(labels.size - 1) do |i|
110
+ candidate = labels[i..-1].join('.')
111
+ mapped_zone_id = @zone_id_map[candidate]
112
+ return mapped_zone_id if mapped_zone_id
113
+ end
114
+
115
+ 0.upto(labels.size - 1) do |i|
116
+ candidate = labels[i..-1].join('.')
117
+ zones = zones_for_name(candidate)
118
+ next if zones.empty?
119
+ raise AmbiguousZones, "multiple zones found for #{domain.inspect}: #{zones.map { |zone| zone['id'] }.inspect}, set zone_id_map to identify" if zones.size != 1
120
+
121
+ return zones.first.fetch('id')
122
+ end
123
+
124
+ raise ZoneNotFound, "zone not found for #{domain.inspect}"
125
+ end
126
+
127
+ def zones_for_name(name)
128
+ @zones_by_name[name] ||= begin
129
+ response = @client.list_zones(name: name)
130
+ Array(response['result']).select do |zone|
131
+ normalize_domain(zone.fetch('name')) == name
132
+ end
133
+ end
134
+ end
135
+
136
+ def record_identity(zone_id, record_name, record_type, record_content)
137
+ [zone_id, normalize_domain(record_name), record_type, record_content].join("\0")
138
+ end
139
+
140
+ def take_record_ids(zone_id, record_name, record_type, record_content)
141
+ @created_record_ids.delete(record_identity(zone_id, record_name, record_type, record_content)) || []
142
+ end
143
+
144
+ def find_record_ids(zone_id, record_name, record_type, record_content)
145
+ each_dns_record(zone_id, type: record_type).select do |record|
146
+ normalize_domain(record.fetch('name')) == normalize_domain(record_name) &&
147
+ record.fetch('type') == record_type &&
148
+ record.fetch('content') == record_content
149
+ end.map { |record| record.fetch('id') }
150
+ end
151
+
152
+ def each_dns_record(zone_id, type:)
153
+ page = 1
154
+ per_page = 100
155
+ records = []
156
+
157
+ loop do
158
+ response = @client.list_dns_records(
159
+ zone_id: zone_id,
160
+ page: page,
161
+ per_page: per_page,
162
+ type: type,
163
+ )
164
+ current_records = Array(response['result'])
165
+ records.concat(current_records)
166
+
167
+ result_info = response['result_info'] || {}
168
+ total_pages = result_info['total_pages'].to_i
169
+ break if current_records.empty?
170
+ break if total_pages.positive? && page >= total_pages
171
+ break if current_records.size < per_page
172
+
173
+ page += 1
174
+ end
175
+
176
+ records
177
+ end
178
+
179
+ def normalize_keys(hash)
180
+ hash.map { |key, value| [normalize_domain(key), value] }.to_h
181
+ end
182
+
183
+ def normalize_domain(domain)
184
+ domain.to_s.sub(/\.+$/, '').downcase
185
+ end
186
+ end
187
+ end
188
+ end
@@ -0,0 +1,96 @@
1
+ require 'json'
2
+ require 'net/http'
3
+ require 'uri'
4
+
5
+ module Acmesmith
6
+ module Cloudflare
7
+ class APIError < StandardError; end
8
+
9
+ DEFAULT_API_BASE = 'https://api.cloudflare.com/client/v4'.freeze
10
+
11
+ class Client
12
+ def initialize(api_token:, api_base: nil)
13
+ @api_token = api_token
14
+ @api_base = (api_base || DEFAULT_API_BASE).sub(%r{/*$}, '')
15
+ end
16
+
17
+ def list_zones(name:)
18
+ get('/zones', query: {
19
+ name: name,
20
+ status: 'active',
21
+ per_page: '50',
22
+ })
23
+ end
24
+
25
+ def list_dns_records(zone_id:, page: 1, per_page: 100, type: nil)
26
+ query = {
27
+ page: page.to_s,
28
+ per_page: per_page.to_s,
29
+ }
30
+ query[:type] = type if type
31
+
32
+ get("/zones/#{zone_id}/dns_records", query: query)
33
+ end
34
+
35
+ def create_dns_record(zone_id:, name:, type:, content:, ttl:, comment: nil)
36
+ payload = {
37
+ type: type,
38
+ name: name,
39
+ content: content,
40
+ ttl: ttl,
41
+ proxied: false,
42
+ }
43
+ payload[:comment] = comment if comment
44
+
45
+ post("/zones/#{zone_id}/dns_records", body: payload)
46
+ end
47
+
48
+ def delete_dns_record(zone_id:, record_id:)
49
+ delete("/zones/#{zone_id}/dns_records/#{record_id}")
50
+ end
51
+
52
+ private
53
+
54
+ def get(path, query: nil)
55
+ request(Net::HTTP::Get, path, query: query)
56
+ end
57
+
58
+ def post(path, body: nil)
59
+ request(Net::HTTP::Post, path, body: body)
60
+ end
61
+
62
+ def delete(path)
63
+ request(Net::HTTP::Delete, path)
64
+ end
65
+
66
+ def request(request_class, path, query: nil, body: nil)
67
+ uri = URI.parse("#{@api_base}#{path}")
68
+ uri.query = URI.encode_www_form(query) if query && !query.empty?
69
+
70
+ request = request_class.new(uri)
71
+ request['Authorization'] = "Bearer #{@api_token}"
72
+ request['Accept'] = 'application/json'
73
+ if body
74
+ request['Content-Type'] = 'application/json'
75
+ request.body = JSON.dump(body)
76
+ end
77
+
78
+ response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
79
+ http.request(request)
80
+ end
81
+
82
+ begin
83
+ payload = JSON.parse(response.body)
84
+ rescue JSON::ParserError
85
+ raise APIError, "Cloudflare API #{request.method} #{path} returned invalid JSON (HTTP #{response.code})"
86
+ end
87
+
88
+ return payload if response.is_a?(Net::HTTPSuccess) && payload['success']
89
+
90
+ details = Array(payload['errors']).map { |err| err['message'] || err.inspect }.join(', ')
91
+ details = response.body if details.empty?
92
+ raise APIError, "Cloudflare API #{request.method} #{path} failed (HTTP #{response.code}): #{details}"
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Acmesmith
4
+ module Cloudflare
5
+ VERSION = "0.1.0"
6
+ end
7
+ end
@@ -0,0 +1,8 @@
1
+ require_relative "cloudflare/client"
2
+ require_relative "cloudflare/version"
3
+ require_relative "challenge_responders/cloudflare"
4
+
5
+ module Acmesmith
6
+ module Cloudflare
7
+ end
8
+ end
@@ -0,0 +1,6 @@
1
+ module Acmesmith
2
+ module Cloudflare
3
+ VERSION: String
4
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
5
+ end
6
+ end
metadata ADDED
@@ -0,0 +1,64 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: acmesmith-cloudflare
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Daisuke Aritomo
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: acmesmith
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '0'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '0'
26
+ email:
27
+ - osyoyu@osyoyu.com
28
+ executables: []
29
+ extensions: []
30
+ extra_rdoc_files: []
31
+ files:
32
+ - LICENSE
33
+ - README.md
34
+ - Rakefile
35
+ - lib/acmesmith/challenge_responders/cloudflare.rb
36
+ - lib/acmesmith/cloudflare.rb
37
+ - lib/acmesmith/cloudflare/client.rb
38
+ - lib/acmesmith/cloudflare/version.rb
39
+ - sig/acmesmith/cloudflare.rbs
40
+ homepage: https://github.com/osyoyu/acmesmith-cloudflare
41
+ licenses:
42
+ - MIT
43
+ metadata:
44
+ allowed_push_host: https://rubygems.org
45
+ homepage_uri: https://github.com/osyoyu/acmesmith-cloudflare
46
+ source_code_uri: https://github.com/osyoyu/acmesmith-cloudflare
47
+ rdoc_options: []
48
+ require_paths:
49
+ - lib
50
+ required_ruby_version: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: 3.2.0
55
+ required_rubygems_version: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - ">="
58
+ - !ruby/object:Gem::Version
59
+ version: '0'
60
+ requirements: []
61
+ rubygems_version: 4.1.0.dev
62
+ specification_version: 4
63
+ summary: An Acmesmith challenge-response plugin for Cloudflare DNS.
64
+ test_files: []