didww-v3 6.2.1 → 7.0.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.
Files changed (105) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/tests.yml +8 -6
  3. data/.rubocop.yml +0 -110
  4. data/CHANGELOG.md +61 -0
  5. data/FILTERS.md +36 -12
  6. data/Gemfile +0 -2
  7. data/README.md +427 -56
  8. data/didww-v3.gemspec +11 -8
  9. data/docs/resource_relationships.md +35 -15
  10. data/examples/README.md +54 -61
  11. data/examples/capacity_pools.rb +28 -10
  12. data/examples/countries.rb +1 -1
  13. data/examples/did_groups.rb +1 -1
  14. data/examples/did_reservations.rb +35 -37
  15. data/examples/did_sms_routing.rb +91 -0
  16. data/examples/did_trunk_assignment.rb +106 -80
  17. data/examples/emergency_calling_services.rb +3 -3
  18. data/examples/emergency_requirements.rb +3 -3
  19. data/examples/emergency_scenario.rb +11 -11
  20. data/examples/emergency_verifications.rb +7 -5
  21. data/examples/exports.rb +1 -1
  22. data/examples/exports_sms.rb +72 -0
  23. data/examples/identity_address_proofs.rb +118 -0
  24. data/examples/includes.rb +65 -0
  25. data/examples/orders.rb +8 -6
  26. data/examples/orders_all_item_types.rb +63 -125
  27. data/examples/orders_emergency.rb +3 -3
  28. data/examples/{orders_by_sku.rb → orders_sku.rb} +12 -10
  29. data/examples/prices_download.rb +45 -0
  30. data/examples/prices_lookup.rb +43 -0
  31. data/examples/regions.rb +1 -1
  32. data/examples/sample.pdf +14 -0
  33. data/examples/sender_id_verifications.rb +63 -0
  34. data/examples/shared_capacity_groups.rb +44 -35
  35. data/examples/sms_trunk_groups.rb +71 -0
  36. data/examples/sms_trunks.rb +84 -0
  37. data/examples/test_readme.rb +1216 -0
  38. data/examples/trunks.rb +115 -0
  39. data/examples/upload_file.rb +44 -0
  40. data/examples/voice_in_trunk_groups.rb +57 -33
  41. data/examples/voice_in_trunk_sip_registration.rb +4 -1
  42. data/examples/voice_out_trunks.rb +11 -1
  43. data/examples/webhook.rb +51 -0
  44. data/lib/didww/auth/bearer_middleware.rb +74 -0
  45. data/lib/didww/auth/memory_store.rb +40 -0
  46. data/lib/didww/auth/token.rb +45 -0
  47. data/lib/didww/auth/token_provider.rb +215 -0
  48. data/lib/didww/base_middleware.rb +7 -8
  49. data/lib/didww/callback/request_validator.rb +2 -1
  50. data/lib/didww/client.rb +122 -13
  51. data/lib/didww/complex_objects/authentication_methods/generic.rb +6 -0
  52. data/lib/didww/complex_objects/configurations/base.rb +0 -18
  53. data/lib/didww/complex_objects/configurations/pstn_configuration.rb +0 -4
  54. data/lib/didww/complex_objects/configurations/sip_configuration.rb +86 -38
  55. data/lib/didww/complex_objects/emergency_order_item.rb +1 -1
  56. data/lib/didww/complex_objects/export_filters.rb +72 -6
  57. data/lib/didww/complex_objects/generic_order_item.rb +15 -0
  58. data/lib/didww/complex_objects/sms_trunk_configuration.rb +33 -0
  59. data/lib/didww/complex_objects/sms_trunk_configurations/base.rb +26 -0
  60. data/lib/didww/complex_objects/sms_trunk_configurations/generic.rb +32 -0
  61. data/lib/didww/complex_objects/sms_trunk_configurations/http_in.rb +75 -0
  62. data/lib/didww/complex_objects/sms_trunk_configurations/http_out.rb +35 -0
  63. data/lib/didww/complex_objects/sms_trunk_configurations/smpp_esme.rb +37 -0
  64. data/lib/didww/complex_objects/sms_trunk_configurations/smpp_smsc.rb +56 -0
  65. data/lib/didww/complex_objects/sms_trunk_configurations/sms_to_email.rb +27 -0
  66. data/lib/didww/errors.rb +103 -0
  67. data/lib/didww/http.rb +34 -0
  68. data/lib/didww/prices/lookup_result.rb +37 -0
  69. data/lib/didww/prices/price.rb +56 -0
  70. data/lib/didww/prices/price_file.rb +51 -0
  71. data/lib/didww/prices/service.rb +248 -0
  72. data/lib/didww/prices/sms_in_price.rb +43 -0
  73. data/lib/didww/prices/sms_out_price.rb +52 -0
  74. data/lib/didww/prices/voice_in_price.rb +48 -0
  75. data/lib/didww/prices/voice_out_price.rb +88 -0
  76. data/lib/didww/prices.rb +82 -0
  77. data/lib/didww/resource/address_requirement.rb +13 -3
  78. data/lib/didww/resource/base.rb +5 -2
  79. data/lib/didww/resource/concerns/number_types.rb +24 -0
  80. data/lib/didww/resource/did.rb +42 -3
  81. data/lib/didww/resource/did_group.rb +12 -1
  82. data/lib/didww/resource/emergency_calling_service.rb +10 -5
  83. data/lib/didww/resource/emergency_requirement.rb +27 -14
  84. data/lib/didww/resource/encrypted_file.rb +19 -6
  85. data/lib/didww/resource/export.rb +59 -12
  86. data/lib/didww/resource/identity.rb +9 -4
  87. data/lib/didww/resource/order.rb +1 -0
  88. data/lib/didww/resource/proof_type.rb +1 -1
  89. data/lib/didww/resource/sender_id_verification.rb +114 -0
  90. data/lib/didww/resource/sms_trunk.rb +76 -0
  91. data/lib/didww/resource/sms_trunk_group.rb +31 -0
  92. data/lib/didww/resource/sms_trunk_regenerate_credential.rb +16 -0
  93. data/lib/didww/resource/voice_in_trunk.rb +24 -1
  94. data/lib/didww/resource/voice_out_trunk.rb +72 -0
  95. data/lib/didww/types/ip_addresses.rb +1 -1
  96. data/lib/didww/types/strings.rb +1 -1
  97. data/lib/didww/types.rb +3 -1
  98. data/lib/didww/version.rb +1 -1
  99. data/lib/didww.rb +7 -0
  100. metadata +62 -24
  101. data/examples/identities_and_proofs.rb +0 -67
  102. data/examples/voice_in_trunks.rb +0 -108
  103. data/lib/didww/resource/did_group_type.rb +0 -10
  104. data/lib/didww/resource/exclusive_relationship.rb +0 -54
  105. data/lib/didww/resource/pop.rb +0 -10
@@ -0,0 +1,115 @@
1
+ # frozen_string_literal: true
2
+ # Voice IN trunks: lists trunks with their configurations, finds one, creates a
3
+ # SIP trunk and a PSTN trunk, updates both and deletes both.
4
+ #
5
+ # The configuration type of a trunk cannot change; a configuration sent on
6
+ # update replaces the members it carries. SIP registration has its own example,
7
+ # voice_in_trunk_sip_registration.rb.
8
+ #
9
+ # Usage: DIDWW_API_KEY=your_api_key ruby examples/trunks.rb
10
+
11
+ require 'bundler/setup'
12
+ require 'didww'
13
+ require 'securerandom'
14
+
15
+ DIDWW::Client.configure do |client|
16
+ client.api_key = ENV.fetch('DIDWW_API_KEY') { abort 'Please set DIDWW_API_KEY' }
17
+ client.api_mode = :sandbox
18
+ end
19
+
20
+ sip_class = DIDWW::ComplexObject::SipConfiguration
21
+ suffix = SecureRandom.hex(4)
22
+
23
+ # List voice in trunks with included relationships
24
+ puts '=== Existing Trunks ==='
25
+ trunks = DIDWW::Client.voice_in_trunks
26
+ .includes(:voice_in_trunk_group)
27
+ .page(1).per(10)
28
+ .all
29
+
30
+ puts "Found #{trunks.size} trunks"
31
+ trunks.each do |trunk|
32
+ puts "#{trunk.name} [#{trunk.configuration_type_human}]"
33
+ puts " ID: #{trunk.id}"
34
+ puts " Priority / weight: #{trunk.priority} / #{trunk.weight}"
35
+ puts " CLI format: #{trunk.cli_format}"
36
+ puts " Ringing timeout: #{trunk.ringing_timeout}"
37
+ puts " POP: #{trunk.pop || 'chosen by DIDWW'}"
38
+ puts " Trunk group: #{trunk.voice_in_trunk_group.name}" if trunk.voice_in_trunk_group
39
+ config = trunk.configuration
40
+ if config.is_a?(sip_class)
41
+ # Codec names in priority order, the first is the highest
42
+ puts " Codecs: #{Array(config.codecs).join(', ')}"
43
+ puts " ICE / RTCP mux / RTCP feedback: #{config.ice_mode} / #{config.rtcp_mux_mode} / #{config.rtcp_feedback_mode}"
44
+ puts " SIP registration: #{config.enabled_sip_registration.inspect}"
45
+ elsif config.is_a?(DIDWW::ComplexObject::PstnConfiguration)
46
+ puts " Forwards to: #{config.dst}"
47
+ end
48
+ end
49
+
50
+ # Find a specific trunk by ID
51
+ unless trunks.empty?
52
+ puts "\n=== Specific Trunk ==="
53
+ found = DIDWW::Client.voice_in_trunks.find(trunks.first.id).first
54
+ puts "#{found.name} (#{found.id}), created at #{found.created_at}"
55
+ end
56
+
57
+ # Create a SIP trunk
58
+ puts "\n=== Creating SIP Trunk ==="
59
+ sip_trunk = DIDWW::Client.voice_in_trunks.new(
60
+ name: "Ruby SIP Trunk #{suffix}",
61
+ priority: 1,
62
+ weight: 100,
63
+ cli_format: DIDWW::Resource::VoiceInTrunk::CLI_FORMAT_E164,
64
+ ringing_timeout: 30,
65
+ capacity_limit: 10,
66
+ pop: DIDWW::Resource::VoiceInTrunk::POP_FRA, # optional; leave it nil to let DIDWW choose
67
+ configuration: sip_class.new(
68
+ username: sip_class::DID_PLACEHOLDER, # the dialed DID is sent as the R-URI user
69
+ host: 'sip.example.com',
70
+ port: 5060,
71
+ # Codecs by name, in priority order; left out, DIDWW applies its default list
72
+ codecs: [sip_class::CODEC_PCMU, sip_class::CODEC_PCMA, sip_class::CODEC_TELEPHONE_EVENT],
73
+ ice_mode: sip_class::ICE_MODE_ACCEPT,
74
+ transport_protocol_id: 1, # UDP, see sip_class::TRANSPORT_PROTOCOLS
75
+ rerouting_disconnect_code_ids: [84, 100] # 480 Temporarily Unavailable, 503 Service Unavailable
76
+ )
77
+ )
78
+ abort "Error creating SIP trunk: #{sip_trunk.errors.full_messages}" unless sip_trunk.save
79
+ puts "Created SIP trunk: #{sip_trunk.id} - #{sip_trunk.name} (pop #{sip_trunk.pop})"
80
+
81
+ pstn_trunk = nil
82
+ begin
83
+ # Update the SIP trunk: only the changed attributes are sent
84
+ puts "\n=== Updating SIP Trunk ==="
85
+ sip_trunk.description = 'Updated by Ruby example'
86
+ sip_trunk.ringing_timeout = 25
87
+ sip_trunk.configuration = sip_class.new(codecs: [sip_class::CODEC_PCMA, sip_class::CODEC_TELEPHONE_EVENT])
88
+ abort "Error updating SIP trunk: #{sip_trunk.errors.full_messages}" unless sip_trunk.save
89
+ puts "Updated SIP trunk: #{sip_trunk.description}, ringing timeout #{sip_trunk.ringing_timeout}"
90
+ puts " Codecs: #{Array(sip_trunk.configuration.codecs).join(', ')}"
91
+
92
+ # Create a PSTN trunk: calls are forwarded to a phone number
93
+ puts "\n=== Creating PSTN Trunk ==="
94
+ pstn_trunk = DIDWW::Client.voice_in_trunks.new(
95
+ name: "Ruby PSTN Trunk #{suffix}",
96
+ ringing_timeout: 30,
97
+ configuration: DIDWW::ComplexObject::PstnConfiguration.new(dst: '12125551234')
98
+ )
99
+ abort "Error creating PSTN trunk: #{pstn_trunk.errors.full_messages}" unless pstn_trunk.save
100
+ puts "Created PSTN trunk: #{pstn_trunk.id} - #{pstn_trunk.name}"
101
+ puts " Config type: #{pstn_trunk.configuration.type}"
102
+ puts " DST: #{pstn_trunk.configuration.dst}"
103
+
104
+ # Update the PSTN trunk: rename it and forward to another number
105
+ puts "\n=== Updating PSTN Trunk ==="
106
+ pstn_trunk.name = "Ruby PSTN Trunk #{suffix} (v2)"
107
+ pstn_trunk.configuration = DIDWW::ComplexObject::PstnConfiguration.new(dst: '12125550000')
108
+ abort "Error updating PSTN trunk: #{pstn_trunk.errors.full_messages}" unless pstn_trunk.save
109
+ puts "Updated PSTN trunk: #{pstn_trunk.name} -> #{pstn_trunk.configuration.dst}"
110
+ ensure
111
+ puts "\n=== Deleting Trunks ==="
112
+ [sip_trunk, pstn_trunk].compact.select(&:persisted?).each do |trunk|
113
+ puts trunk.destroy ? "Deleted trunk #{trunk.id}" : "Error deleting trunk #{trunk.id}: #{trunk.errors.full_messages}"
114
+ end
115
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+ # Encrypts a file with the DIDWW public keys and uploads it to encrypted_files.
3
+ # The printed ID is what a proof takes in its files (see identity_address_proofs.rb).
4
+ #
5
+ # DIDWW::Encrypt fetches the two public keys (GET /public_keys, sent without a
6
+ # token) and encrypts the file on the client: AES-256-CBC for the content, the
7
+ # AES key wrapped with RSA-OAEP for each public key. One file per upload request.
8
+ #
9
+ # Usage: DIDWW_API_KEY=your_api_key ruby examples/upload_file.rb [file]
10
+ # (defaults to examples/sample.pdf)
11
+
12
+ require 'bundler/setup'
13
+ require 'didww'
14
+ require 'stringio'
15
+
16
+ DIDWW::Client.configure do |client|
17
+ client.api_key = ENV.fetch('DIDWW_API_KEY') { abort 'Please set DIDWW_API_KEY' }
18
+ client.api_mode = :sandbox
19
+ end
20
+
21
+ path = ARGV.first || File.join(__dir__, 'sample.pdf')
22
+ name = File.basename(path)
23
+ content = File.binread(path)
24
+ puts "File: #{path} (#{content.bytesize} bytes)"
25
+
26
+ enc = DIDWW::Encrypt.new
27
+ encrypted = enc.encrypt(content)
28
+ puts "Encrypted: #{encrypted.bytesize} bytes"
29
+ puts "Fingerprint: #{enc.encryption_fingerprint}"
30
+
31
+ # A StringIO (or a File / Tempfile) can be rewound, so the upload is retried
32
+ # once with a new token when the first one is refused with 401.
33
+ file_id = DIDWW::Resource::EncryptedFile.upload(
34
+ encryption_fingerprint: enc.encryption_fingerprint,
35
+ file: Faraday::Multipart::FilePart.new(StringIO.new(encrypted), 'application/octet-stream', "#{name}.enc"),
36
+ description: name
37
+ )
38
+
39
+ puts 'Upload successful!'
40
+ puts "Encrypted file ID: #{file_id}"
41
+
42
+ # EncryptedFile.upload_file(file, fingerprint) does the same for an object with
43
+ # #tempfile, #content_type and #original_filename, such as a Rack upload. It
44
+ # sends the file as it is, so the file must be encrypted already.
@@ -1,5 +1,9 @@
1
1
  # frozen_string_literal: true
2
- # CRUD for trunk groups with trunk relationships.
2
+ # Voice IN trunk groups: creates two SIP trunks and a trunk group with them,
3
+ # lists groups with their trunks, renames the group, and deletes the group and
4
+ # the trunks, also when a step fails.
5
+ #
6
+ # Deleting a group also deletes the trunks in it.
3
7
  #
4
8
  # Usage: DIDWW_API_KEY=your_api_key ruby examples/voice_in_trunk_groups.rb
5
9
 
@@ -12,43 +16,63 @@ DIDWW::Client.configure do |client|
12
16
  client.api_mode = :sandbox
13
17
  end
14
18
 
15
- # List trunk groups
16
- puts '=== Existing Trunk Groups ==='
17
- trunk_groups = DIDWW::Client.voice_in_trunk_groups
18
- .includes(:voice_in_trunks)
19
- .all
19
+ sip_class = DIDWW::ComplexObject::SipConfiguration
20
+ suffix = SecureRandom.hex(4)
20
21
 
21
- puts "Found #{trunk_groups.size} trunk groups"
22
- trunk_groups.first(3).each do |group|
23
- trunks_count = group.voice_in_trunks ? group.voice_in_trunks.size : 0
24
- puts "#{group.name} (#{trunks_count} trunks)"
25
- end
22
+ trunks = []
23
+ group = nil
24
+ begin
25
+ # Create two trunks
26
+ puts '=== Creating Trunks ==='
27
+ [
28
+ ['A', 'sip-a.example.com', [sip_class::CODEC_PCMU, sip_class::CODEC_PCMA]],
29
+ ['B', 'sip-b.example.com', [sip_class::CODEC_PCMU]]
30
+ ].each do |label, host, codecs|
31
+ trunk = DIDWW::Client.voice_in_trunks.new(
32
+ name: "Group Trunk #{label} #{suffix}",
33
+ configuration: sip_class.new(host: host, port: 5060, codecs: codecs, transport_protocol_id: 1) # UDP
34
+ )
35
+ raise "Error creating trunk #{label}: #{trunk.errors.full_messages}" unless trunk.save
36
+ trunks << trunk
37
+ puts "Created trunk #{label}: #{trunk.id}"
38
+ end
26
39
 
27
- # Create a new trunk group (2026-04-16 external_reference_id for customer tagging)
28
- puts "\n=== Creating Trunk Group ==="
29
- suffix = SecureRandom.hex(4)
30
- trunk_group = DIDWW::Client.voice_in_trunk_groups.new(
31
- name: "Ruby Trunk Group #{suffix}",
32
- capacity_limit: 20,
33
- external_reference_id: "ruby-tg-#{suffix}"
34
- )
40
+ # Create a trunk group with both trunks (2026-04-16 external_reference_id for customer tagging)
41
+ puts "\n=== Creating Trunk Group ==="
42
+ group = DIDWW::Client.voice_in_trunk_groups.new(
43
+ name: "Ruby Trunk Group #{suffix}",
44
+ capacity_limit: 10,
45
+ external_reference_id: "ruby-tg-#{suffix}"
46
+ )
47
+ group.voice_in_trunks = trunks
48
+ raise "Error creating trunk group: #{group.errors.full_messages}" unless group.save
49
+ puts "Created trunk group: #{group.id} - #{group.name}"
35
50
 
36
- if trunk_group.save
37
- puts "Created trunk group: #{trunk_group.id} - #{trunk_group.name}"
38
- puts " External reference: #{trunk_group.external_reference_id}"
51
+ # List trunk groups with included trunks
52
+ puts "\n=== Trunk Groups ==="
53
+ groups = DIDWW::Client.voice_in_trunk_groups
54
+ .includes(:voice_in_trunks)
55
+ .all
56
+ puts "Found #{groups.size} trunk groups"
57
+ groups.each do |g|
58
+ names = (g.voice_in_trunks || []).map(&:name)
59
+ puts " #{g.name} (#{names.size} trunks: #{names.join(', ')}) external_reference_id=#{g.external_reference_id}"
60
+ end
39
61
 
40
- # Update trunk group
62
+ # Rename the group: only the name is sent
41
63
  puts "\n=== Updating Trunk Group ==="
42
- trunk_group.capacity_limit = 30
43
- if trunk_group.save
44
- puts "Updated trunk group: #{trunk_group.name} (capacity_limit: #{trunk_group.capacity_limit})"
45
-
46
- # Delete trunk group
47
- puts "\n=== Deleting Trunk Group ==="
48
- if trunk_group.destroy
49
- puts 'Trunk group deleted'
64
+ group.name = "Updated Group #{suffix}"
65
+ raise "Error updating trunk group: #{group.errors.full_messages}" unless group.save
66
+ puts "Updated name: #{group.name}"
67
+ ensure
68
+ puts "\n=== Cleaning Up ==="
69
+ if group&.persisted?
70
+ # Deleting the group also deletes its trunks
71
+ puts group.destroy ? 'Deleted trunk group (and its trunks)' : "Error deleting trunk group: #{group.errors.full_messages}"
72
+ else
73
+ # Without a group the trunks are deleted one by one
74
+ trunks.each do |trunk|
75
+ puts trunk.destroy ? "Deleted trunk #{trunk.id}" : "Error deleting trunk #{trunk.id}: #{trunk.errors.full_messages}"
50
76
  end
51
77
  end
52
- else
53
- puts "Error creating trunk group: #{trunk_group.errors.full_messages}"
54
78
  end
@@ -35,7 +35,10 @@ trunk = DIDWW::Client.voice_in_trunks.new(
35
35
  c.enabled_sip_registration = true
36
36
  c.use_did_in_ruri = true
37
37
  c.cnam_lookup = false
38
- c.codec_ids = [9, 7]
38
+ c.codecs = [
39
+ DIDWW::ComplexObject::SipConfiguration::CODEC_PCMU,
40
+ DIDWW::ComplexObject::SipConfiguration::CODEC_G723
41
+ ]
39
42
  c.transport_protocol_id = 1
40
43
  end
41
44
  )
@@ -39,6 +39,8 @@ trunks.first(5).each do |trunk|
39
39
  puts " External Reference ID: #{trunk.external_reference_id}"
40
40
  puts " Emergency Enable All: #{trunk.emergency_enable_all}"
41
41
  puts " RTP Timeout: #{trunk.rtp_timeout}"
42
+ puts " Codecs: #{trunk.codecs&.join(', ')}"
43
+ puts " ICE / RTCP-mux / RTCP feedback: #{trunk.ice_mode} / #{trunk.rtcp_mux_mode} / #{trunk.rtcp_feedback_mode}"
42
44
  puts ''
43
45
  end
44
46
 
@@ -58,7 +60,14 @@ voice_out_trunk = DIDWW::Client.voice_out_trunks.new(
58
60
  default_dst_action: DIDWW::Resource::VoiceOutTrunk::DEFAULT_DST_ACTION_ALLOW_ALL,
59
61
  on_cli_mismatch_action: DIDWW::Resource::VoiceOutTrunk::ON_CLI_MISMATCH_ACTION_REJECT_CALL,
60
62
  external_reference_id: "ruby-example-#{suffix}",
61
- rtp_timeout: 60
63
+ rtp_timeout: 60,
64
+ # Codecs in priority order: the first has the highest priority.
65
+ codecs: [
66
+ DIDWW::Resource::VoiceOutTrunk::CODEC_OPUS,
67
+ DIDWW::Resource::VoiceOutTrunk::CODEC_PCMA,
68
+ DIDWW::Resource::VoiceOutTrunk::CODEC_TELEPHONE_EVENT
69
+ ],
70
+ ice_mode: DIDWW::Resource::VoiceOutTrunk::ICE_MODE_ACCEPT
62
71
  )
63
72
 
64
73
  if voice_out_trunk.save
@@ -68,6 +77,7 @@ if voice_out_trunk.save
68
77
  puts " Username: #{voice_out_trunk.authentication_method.username}"
69
78
  puts " Status: #{voice_out_trunk.status}"
70
79
  puts " External Reference: #{voice_out_trunk.external_reference_id}"
80
+ puts " Codecs: #{voice_out_trunk.codecs.join(', ')}"
71
81
 
72
82
  # Update trunk - change name and tech_prefix
73
83
  puts "\n=== Updating Voice Out Trunk ==="
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+ # Validates the signature of a DIDWW callback with DIDWW::Callback::RequestValidator.
3
+ #
4
+ # DIDWW signs every callback with the callback secret enabled in the User Panel
5
+ # and sends the signature in the X-DIDWW-Signature header. The signature is the
6
+ # hex HMAC-SHA1, keyed with the secret, of:
7
+ # * the callback URL, normalized to scheme://host:port/path?query - the port is
8
+ # always written, also the default one (https://example.com:443/...)
9
+ # * followed by the payload's keys and values, sorted by key and concatenated
10
+ # (status=completed&id=42 contributes "id42statuscompleted")
11
+ #
12
+ # This example builds a sample callback, signs it that way, and validates it
13
+ # and a tampered copy. It runs offline: no API key and no request is needed.
14
+ #
15
+ # Usage: ruby examples/webhook.rb
16
+
17
+ require 'bundler/setup'
18
+ require 'didww'
19
+ require 'openssl'
20
+ require 'uri'
21
+
22
+ callback_secret = 'your-callback-secret'
23
+ callback_url = 'https://example.com/webhooks/didww?account=main'
24
+ payload = {
25
+ 'id' => '7ae7c48f-d48a-499f-9dc1-c9217014b457',
26
+ 'type' => 'orders',
27
+ 'status' => 'completed'
28
+ }
29
+
30
+ # Signs a callback the way DIDWW does
31
+ def sign_callback(secret, url, payload)
32
+ uri = URI(url)
33
+ normalized_url = "#{uri.scheme}://#{uri.host}:#{uri.port}#{uri.path}"
34
+ normalized_url += "?#{uri.query}" if uri.query
35
+ data = normalized_url + payload.sort.flatten.join
36
+ OpenSSL::HMAC.hexdigest('SHA1', secret, data)
37
+ end
38
+
39
+ signature = sign_callback(callback_secret, callback_url, payload)
40
+ puts '=== Callback ==='
41
+ puts "URL: #{callback_url}"
42
+ puts "Payload: #{payload}"
43
+ puts "#{DIDWW::Callback::RequestValidator::HEADER}: #{signature}"
44
+
45
+ validator = DIDWW::Callback::RequestValidator.new(callback_secret)
46
+
47
+ puts "\n=== Validation ==="
48
+ puts "Signed payload -> valid: #{validator.validate(callback_url, payload, signature)}"
49
+
50
+ tampered = payload.merge('status' => 'canceled')
51
+ puts "Tampered payload -> valid: #{validator.validate(callback_url, tampered, signature)}"
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+ require 'faraday'
3
+
4
+ module DIDWW
5
+ module Auth
6
+ class BearerMiddleware < Faraday::Middleware
7
+ # Options: audience [String] production hostname of the service called.
8
+
9
+ UNAUTHENTICATED_PATH_SUFFIX = '/public_keys'
10
+ REWIND_ERRORS = [
11
+ IOError,
12
+ SystemCallError
13
+ ].freeze
14
+
15
+ def call(env)
16
+ return @app.call(env) if env.url.path.to_s.end_with?(UNAUTHENTICATED_PATH_SUFFIX)
17
+
18
+ env.request_headers.delete('If-None-Match')
19
+ token = authorize!(env)
20
+ request_body = snapshot(env.request_body)
21
+ response = @app.call(env)
22
+ return response unless response.status == 401
23
+
24
+ DIDWW::Client.token_provider.invalidate(audience, token.access_token)
25
+ return response unless restore!(env, request_body)
26
+
27
+ token = authorize!(env)
28
+ @app.call(env).tap do |retried|
29
+ DIDWW::Client.token_provider.invalidate(audience, token.access_token) if retried.status == 401
30
+ end
31
+ end
32
+
33
+ private
34
+
35
+ def audience
36
+ options.fetch(:audience)
37
+ end
38
+
39
+ def authorize!(env)
40
+ DIDWW::Client.token_provider.token_for(audience).tap do |token|
41
+ env.request_headers['Authorization'] = "Bearer #{token.access_token}"
42
+ end
43
+ end
44
+
45
+ def snapshot(body)
46
+ body.is_a?(String) ? body.dup : body
47
+ end
48
+
49
+ def restore!(env, request_body)
50
+ return false unless rewind_body(request_body)
51
+
52
+ env.status = nil
53
+ env.reason_phrase = nil
54
+ env.response_headers = nil
55
+ env.response_body = nil
56
+ env.request_body = request_body
57
+ true
58
+ end
59
+
60
+ def rewind_body(body)
61
+ if body.nil? || body.is_a?(String)
62
+ true
63
+ elsif body.respond_to?(:rewind)
64
+ body.rewind
65
+ true
66
+ else
67
+ false
68
+ end
69
+ rescue *REWIND_ERRORS
70
+ false
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+ module DIDWW
3
+ module Auth
4
+ class MemoryStore
5
+ # Any object responding to read(key), write(key, value, expires_in:) and
6
+ # delete(key) can replace it, e.g. an ActiveSupport::Cache::Store.
7
+
8
+ def initialize(clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
9
+ @clock = clock
10
+ @lock = Mutex.new
11
+ @entries = {}
12
+ end
13
+
14
+ def read(key)
15
+ @lock.synchronize do
16
+ value, expires_at = @entries[key]
17
+ if expires_at && expires_at <= @clock.call
18
+ @entries.delete(key)
19
+ nil
20
+ else
21
+ value
22
+ end
23
+ end
24
+ end
25
+
26
+ def write(key, value, expires_in: nil)
27
+ @lock.synchronize { @entries[key] = [value, expires_in && @clock.call + expires_in] }
28
+ true
29
+ end
30
+
31
+ def delete(key)
32
+ @lock.synchronize { !@entries.delete(key).nil? }
33
+ end
34
+
35
+ def inspect
36
+ "#<#{self.class.name} entries=#{@lock.synchronize { @entries.size }}>"
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+ module DIDWW
3
+ module Auth
4
+ class Token
5
+ ATTRIBUTES = %w[
6
+ access_token
7
+ token_type
8
+ expires_in
9
+ aud
10
+ scope
11
+ api_version
12
+ minted_at
13
+ ].freeze
14
+
15
+ attr_reader(*ATTRIBUTES)
16
+
17
+ # @param hash [Hash] Token response body or a hash produced by #to_h
18
+ # @return [DIDWW::Auth::Token]
19
+ def self.from_h(hash)
20
+ attributes = hash.transform_keys(&:to_s).slice(*ATTRIBUTES)
21
+ new(**attributes.transform_keys(&:to_sym))
22
+ end
23
+
24
+ def initialize(access_token: nil, token_type: nil, expires_in: nil, aud: nil, scope: nil, api_version: nil, minted_at: nil)
25
+ @access_token = access_token
26
+ @token_type = token_type
27
+ @expires_in = expires_in
28
+ @aud = Array(aud)
29
+ @scope = scope
30
+ @api_version = api_version
31
+ @minted_at = minted_at
32
+ end
33
+
34
+ # String keys, so stores that serialize to JSON round-trip it.
35
+ # @return [Hash]
36
+ def to_h
37
+ ATTRIBUTES.to_h { |name| [name, public_send(name)] }
38
+ end
39
+
40
+ def inspect
41
+ "#<#{self.class.name} aud=#{aud.inspect} scope=#{scope.inspect} api_version=#{api_version.inspect} expires_in=#{expires_in.inspect}>"
42
+ end
43
+ end
44
+ end
45
+ end