sgx_jmp.rb

  1# frozen_string_literal: true
  2
  3require "pg/em/connection_pool"
  4require "bandwidth"
  5require "bigdecimal"
  6require "blather/client/dsl" # Require this first to not auto-include
  7require "blather/client"
  8require "braintree"
  9require "date"
 10require "dhall"
 11require "em-hiredis"
 12require "em_promise"
 13require "ougai"
 14require "ruby-bandwidth-iris"
 15require "sentry-ruby"
 16require "statsd-instrument"
 17
 18$stdout.sync = true
 19LOG = Ougai::Logger.new($stdout)
 20LOG.level = ENV.fetch("LOG_LEVEL", "info")
 21LOG.formatter = Ougai::Formatters::Readable.new(
 22	nil,
 23	nil,
 24	plain: !$stdout.isatty
 25)
 26Blather.logger = LOG
 27EM::Hiredis.logger = LOG
 28StatsD.logger = LOG
 29LOG.info "Starting"
 30
 31Sentry.init do |config|
 32	config.logger = LOG
 33	config.breadcrumbs_logger = [:sentry_logger]
 34end
 35
 36module SentryOugai
 37	class SentryLogger
 38		include Sentry::Breadcrumb::SentryLogger
 39		include Singleton
 40	end
 41
 42	def _log(severity, message=nil, ex=nil, data=nil, &block)
 43		super
 44		SentryLogger.instance.add_breadcrumb(severity, message || ex.to_s, &block)
 45	end
 46end
 47LOG.extend SentryOugai
 48
 49CONFIG =
 50	Dhall::Coder
 51	.new(safe: Dhall::Coder::JSON_LIKE + [Symbol, Proc])
 52	.load(
 53		"(#{ARGV[0]}) : #{__dir__}/config-schema.dhall",
 54		transform_keys: ->(k) { k&.to_sym }
 55	)
 56WEB_LISTEN =
 57	if CONFIG[:web].is_a?(Hash)
 58		[CONFIG[:web][:interface], CONFIG[:web][:port]]
 59	else
 60		[CONFIG[:web]]
 61	end
 62
 63singleton_class.class_eval do
 64	include Blather::DSL
 65	Blather::DSL.append_features(self)
 66end
 67
 68require_relative "lib/polyfill"
 69require_relative "lib/alt_top_up_form"
 70require_relative "lib/add_bitcoin_address"
 71require_relative "lib/backend_sgx"
 72require_relative "lib/bwmsgsv2_repo"
 73require_relative "lib/bandwidth_tn_order"
 74require_relative "lib/btc_sell_prices"
 75require_relative "lib/buy_account_credit_form"
 76require_relative "lib/configure_calls_form"
 77require_relative "lib/command"
 78require_relative "lib/command_list"
 79require_relative "lib/customer"
 80require_relative "lib/customer_info_form"
 81require_relative "lib/customer_repo"
 82require_relative "lib/electrum"
 83require_relative "lib/expiring_lock"
 84require_relative "lib/em"
 85require_relative "lib/form_to_h"
 86require_relative "lib/low_balance"
 87require_relative "lib/port_in_order"
 88require_relative "lib/payment_methods"
 89require_relative "lib/paypal_done"
 90require_relative "lib/registration"
 91require_relative "lib/transaction"
 92require_relative "lib/tel_selections"
 93require_relative "lib/session_manager"
 94require_relative "lib/statsd"
 95require_relative "web"
 96
 97ELECTRUM = Electrum.new(**CONFIG[:electrum])
 98EM::Hiredis::Client.load_scripts_from("./redis_lua")
 99
100Faraday.default_adapter = :em_synchrony
101BandwidthIris::Client.global_options = {
102	account_id: CONFIG[:creds][:account],
103	username: CONFIG[:creds][:username],
104	password: CONFIG[:creds][:password]
105}
106BANDWIDTH_VOICE = Bandwidth::Client.new(
107	voice_basic_auth_user_name: CONFIG[:creds][:username],
108	voice_basic_auth_password: CONFIG[:creds][:password]
109).voice_client.client
110
111def new_sentry_hub(stanza, name: nil)
112	hub = Sentry.get_current_hub&.new_from_top
113	raise "Sentry.init has not been called" unless hub
114
115	hub.push_scope
116	hub.current_scope.clear_breadcrumbs
117	hub.current_scope.set_transaction_name(name) if name
118	hub.current_scope.set_user(jid: stanza.from.stripped.to_s)
119	hub
120end
121
122class AuthError < StandardError; end
123
124# Braintree is not async, so wrap in EM.defer for now
125class AsyncBraintree
126	def initialize(environment:, merchant_id:, public_key:, private_key:, **)
127		@gateway = Braintree::Gateway.new(
128			environment: environment,
129			merchant_id: merchant_id,
130			public_key: public_key,
131			private_key: private_key
132		)
133		@gateway.config.logger = LOG
134	end
135
136	def respond_to_missing?(m, *)
137		@gateway.respond_to?(m) || super
138	end
139
140	def method_missing(m, *args)
141		return super unless respond_to_missing?(m, *args)
142
143		EM.promise_defer(klass: PromiseChain) do
144			@gateway.public_send(m, *args)
145		end
146	end
147
148	class PromiseChain < EMPromise
149		def respond_to_missing?(*)
150			false && super # We don't actually know what we respond to...
151		end
152
153		def method_missing(m, *args)
154			return super if respond_to_missing?(m, *args)
155
156			self.then { |o| o.public_send(m, *args) }
157		end
158	end
159end
160
161BRAINTREE = AsyncBraintree.new(**CONFIG[:braintree])
162
163def panic(e, hub=nil)
164	(Thread.current[:log] || LOG).fatal(
165		"Error raised during event loop: #{e.class}",
166		e
167	)
168	if e.is_a?(::Exception)
169		(hub || Sentry).capture_exception(e, hint: { background: false })
170	else
171		(hub || Sentry).capture_message(e.to_s, hint: { background: false })
172	end
173	exit 1
174end
175
176EM.error_handler(&method(:panic))
177
178def poll_for_notify(db)
179	db.wait_for_notify_defer.then { |notify|
180		CustomerRepo.new.find(notify[:extra])
181	}.then(&LowBalance.method(:for)).then(&:notify!).then {
182		poll_for_notify(db)
183	}.catch(&method(:panic))
184end
185
186when_ready do
187	LOG.info "Ready"
188	BLATHER = self
189	REDIS = EM::Hiredis.connect
190	TEL_SELECTIONS = TelSelections.new
191	BTC_SELL_PRICES = BTCSellPrices.new(REDIS, CONFIG[:oxr_app_id])
192	DB = PG::EM::ConnectionPool.new(dbname: "jmp") { |conn|
193		conn.type_map_for_results = PG::BasicTypeMapForResults.new(conn)
194		conn.type_map_for_queries = PG::BasicTypeMapForQueries.new(conn)
195	}
196
197	DB.hold do |conn|
198		conn.query("LISTEN low_balance")
199		conn.query("SELECT customer_id FROM balances WHERE balance < 5").each do |c|
200			conn.query("SELECT pg_notify('low_balance', $1)", c.values)
201		end
202		poll_for_notify(conn)
203	end
204
205	EM.add_periodic_timer(3600) do
206		ping = Blather::Stanza::Iq::Ping.new(:get, CONFIG[:server][:host])
207		ping.from = CONFIG[:component][:jid]
208		self << ping
209	end
210
211	Web.run(LOG.child, *WEB_LISTEN)
212end
213
214# workqueue_count MUST be 0 or else Blather uses threads!
215setup(
216	CONFIG[:component][:jid],
217	CONFIG[:component][:secret],
218	CONFIG[:server][:host],
219	CONFIG[:server][:port],
220	nil,
221	nil,
222	workqueue_count: 0
223)
224
225message to: /\Aaccount@/, body: /./ do |m|
226	StatsD.increment("deprecated_account_bot")
227
228	self << m.reply.tap { |out|
229		out.body = "This bot is deprecated. Please talk to xmpp:cheogram.com"
230	}
231end
232
233before(
234	:iq,
235	type: [:error, :result],
236	to: /\Acustomer_/,
237	from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/
238) { |iq| halt if IQ_MANAGER.fulfill(iq) }
239
240before nil, to: /\Acustomer_/, from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/ do |s|
241	StatsD.increment("stanza_customer")
242
243	sentry_hub = new_sentry_hub(s, name: "stanza_customer")
244	CustomerRepo.new.find(
245		s.to.node.delete_prefix("customer_")
246	).then { |customer|
247		sentry_hub.current_scope.set_user(
248			id: customer.customer_id,
249			jid: s.from.stripped.to_s
250		)
251		customer.stanza_to(s)
252	}.catch { |e| panic(e, sentry_hub) }
253	halt
254end
255
256ADDRESSES_NS = "http://jabber.org/protocol/address"
257message(
258	to: /\A#{CONFIG[:component][:jid]}\Z/,
259	from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/
260) do |m|
261	StatsD.increment("inbound_group_text")
262	sentry_hub = new_sentry_hub(m, name: "inbound_group_text")
263
264	address = m.find("ns:addresses", ns: ADDRESSES_NS).first
265		&.find("ns:address", ns: ADDRESSES_NS)
266		&.find { |el| el["jid"].to_s.start_with?("customer_") }
267	pass unless address
268
269	CustomerRepo.new.find_by_jid(address["jid"]).then { |customer|
270		m.from = m.from.with(domain: CONFIG[:component][:jid])
271		m.to = m.to.with(domain: customer.jid.domain)
272		address["jid"] = customer.jid.to_s
273		BLATHER << m
274	}.catch_only(CustomerRepo::NotFound) { |e|
275		BLATHER << m.as_error("forbidden", :auth, e.message)
276	}.catch { |e| panic(e, sentry_hub) }
277end
278
279# Ignore groupchat messages
280# Especially if we have the component join MUC for notifications
281message(type: :groupchat) { true }
282
283def billable_message(m)
284	(m.body && !m.body.empty?) || m.find("ns:x", ns: OOB.registered_ns).first
285end
286
287message do |m|
288	StatsD.increment("message")
289
290	sentry_hub = new_sentry_hub(m, name: "message")
291	today = Time.now.utc.to_date
292	CustomerRepo.new.find_by_jid(m.from.stripped).then { |customer|
293		sentry_hub.current_scope.set_user(
294			id: customer.customer_id, jid: m.from.stripped.to_s
295		)
296		EMPromise.all([
297			(customer.incr_message_usage if billable_message(m)),
298			customer.stanza_from(m)
299		]).then { customer }
300	}.then { |customer|
301		customer.message_usage((today..(today - 30))).then do |usage|
302			next unless usage > 500
303
304			ExpiringLock.new("jmp_usage_notify-#{customer.customer_id}").with do
305				BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
306				BLATHER.say(
307					CONFIG[:notify_admin], "#{customer.customer_id} has used #{usage} " \
308					"messages since #{today - 30}", :groupchat
309				)
310			end
311		end
312	}.catch_only(CustomerRepo::NotFound) { |e|
313		BLATHER << m.as_error("forbidden", :auth, e.message)
314	}.catch { |e| panic(e, sentry_hub) }
315end
316
317message :error? do |m|
318	StatsD.increment("message_error")
319
320	LOG.error "MESSAGE ERROR", stanza: m
321end
322
323IQ_MANAGER = SessionManager.new(self, :id)
324COMMAND_MANAGER = SessionManager.new(
325	self,
326	:sessionid,
327	timeout: 60 * 60,
328	error_if: ->(s) { s.cancel? }
329)
330
331disco_info to: Blather::JID.new(CONFIG[:component][:jid]) do |iq|
332	reply = iq.reply
333	reply.identities = [{
334		name: "JMP.chat",
335		type: "sms",
336		category: "gateway"
337	}]
338	reply.features = [
339		"http://jabber.org/protocol/disco#info",
340		"http://jabber.org/protocol/commands"
341	]
342	form = Blather::Stanza::X.find_or_create(reply.query)
343	form.type = "result"
344	form.fields = [
345		{
346			var: "FORM_TYPE",
347			type: "hidden",
348			value: "http://jabber.org/network/serverinfo"
349		}
350	] + CONFIG[:xep0157]
351	self << reply
352end
353
354disco_info do |iq|
355	reply = iq.reply
356	reply.identities = [{
357		name: "JMP.chat",
358		type: "sms",
359		category: "client"
360	}]
361	reply.features = [
362		"urn:xmpp:receipts"
363	]
364	self << reply
365end
366
367disco_items node: "http://jabber.org/protocol/commands" do |iq|
368	StatsD.increment("command_list")
369
370	sentry_hub = new_sentry_hub(iq, name: iq.node)
371	reply = iq.reply
372	reply.node = "http://jabber.org/protocol/commands"
373
374	CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new).find_by_jid(
375		iq.from.stripped
376	).catch {
377		nil
378	}.then { |customer|
379		CommandList.for(customer)
380	}.then { |list|
381		reply.items = list.map { |item|
382			Blather::Stanza::DiscoItems::Item.new(
383				iq.to,
384				item[:node],
385				item[:name]
386			)
387		}
388		self << reply
389	}.catch { |e| panic(e, sentry_hub) }
390end
391
392iq "/iq/ns:services", ns: "urn:xmpp:extdisco:2" do |iq|
393	StatsD.increment("extdisco")
394
395	reply = iq.reply
396	reply << Nokogiri::XML::Builder.new {
397		services(xmlns: "urn:xmpp:extdisco:2") do
398			service(
399				type: "sip",
400				host: CONFIG[:sip_host]
401			)
402		end
403	}.doc.root
404
405	self << reply
406end
407
408Command.new(
409	"jabber:iq:register",
410	"Register",
411	list_for: ->(*) { true },
412	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
413) {
414	Command.customer.catch {
415		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Customer.create"))
416		Command.execution.customer_repo.create(Command.execution.iq.from.stripped)
417	}.then { |customer|
418		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Registration.for"))
419		Registration.for(customer, TEL_SELECTIONS).then(&:write)
420	}.then {
421		StatsD.increment("registration.completed")
422	}.catch_only(Command::Execution::FinalStanza) do |e|
423		StatsD.increment("registration.completed")
424		EMPromise.reject(e)
425	end
426}.register(self).then(&CommandList.method(:register))
427
428Command.new(
429	"info",
430	"Show Account Info",
431	list_for: ->(*) { true },
432	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
433) {
434	Command.customer.then(&:info).then do |info|
435		Command.finish do |reply|
436			form = Blather::Stanza::X.new(:result)
437			form.title = "Account Info"
438			form.fields = info.fields
439			reply.command << form
440		end
441	end
442}.register(self).then(&CommandList.method(:register))
443
444Command.new(
445	"usage",
446	"Show Monthly Usage"
447) {
448	report_for = (Date.today..(Date.today << 1))
449
450	Command.customer.then { |customer|
451		customer.usage_report(report_for)
452	}.then do |usage_report|
453		Command.finish do |reply|
454			reply.command << usage_report.form
455		end
456	end
457}.register(self).then(&CommandList.method(:register))
458
459Command.new(
460	"configure calls",
461	"Configure Calls",
462	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
463) {
464	Command.customer.then do |customer|
465		cc_form = ConfigureCallsForm.new(customer)
466		Command.reply { |reply|
467			reply.allowed_actions = [:next]
468			reply.command << cc_form.render
469		}.then { |iq|
470			EMPromise.all(cc_form.parse(iq.form).map { |k, v|
471				Command.execution.customer_repo.public_send("put_#{k}", customer, v)
472			})
473		}.then { Command.finish("Configuration saved!") }
474	end
475}.register(self).then(&CommandList.method(:register))
476
477Command.new(
478	"ogm",
479	"Record Voicemail Greeting",
480	list_for: ->(fwd: nil, **) { !!fwd },
481	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
482) {
483	Command.customer.then do |customer|
484		customer.fwd.create_call(CONFIG[:creds][:account]) do |cc|
485			cc.from = customer.registered?.phone
486			cc.application_id = CONFIG[:sip][:app]
487			cc.answer_url = "#{CONFIG[:web_root]}/ogm/start?" \
488			                "customer_id=#{customer.customer_id}"
489		end
490		Command.finish("You will now receive a call.")
491	end
492}.register(self).then(&CommandList.method(:register))
493
494Command.new(
495	"migrate billing",
496	"Switch from PayPal or expired trial to new billing",
497	list_for: ->(tel:, customer:, **) { tel && !customer&.currency },
498	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
499) {
500	EMPromise.all([
501		Command.customer,
502		Command.reply do |reply|
503			reply.allowed_actions = [:next]
504			reply.command << FormTemplate.render("migrate_billing")
505		end
506	]).then do |(customer, iq)|
507		Registration::Payment.for(
508			iq, customer, customer.registered?.phone,
509			final_message: PaypalDone::MESSAGE,
510			finish: PaypalDone
511		).then(&:write).catch_only(Command::Execution::FinalStanza) do |s|
512			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
513			BLATHER.say(
514				CONFIG[:notify_admin],
515				"#{customer.customer_id} migrated to #{customer.currency}",
516				:groupchat
517			)
518			EMPromise.reject(s)
519		end
520	end
521}.register(self).then(&CommandList.method(:register))
522
523Command.new(
524	"credit cards",
525	"Credit Card Settings and Management"
526) {
527	Command.customer.then do |customer|
528		url = CONFIG[:credit_card_url].call(
529			customer.jid.to_s.gsub("\\", "%5C"),
530			customer.customer_id
531		)
532		desc = "Manage credits cards and settings"
533		Command.finish("#{desc}: #{url}") do |reply|
534			oob = OOB.find_or_create(reply.command)
535			oob.url = url
536			oob.desc = desc
537		end
538	end
539}.register(self).then(&CommandList.method(:register))
540
541Command.new(
542	"top up",
543	"Buy Account Credit by Credit Card",
544	list_for: ->(payment_methods: [], **) { !payment_methods.empty? },
545	format_error: ->(e) { "Failed to buy credit, system said: #{e.message}" }
546) {
547	Command.customer.then { |customer|
548		BuyAccountCreditForm.for(customer).then do |credit_form|
549			Command.reply { |reply|
550				reply.allowed_actions = [:complete]
551				credit_form.add_to_form(reply.form)
552			}.then do |iq|
553				Transaction.sale(customer, **credit_form.parse(iq.form))
554			end
555		end
556	}.then { |transaction|
557		transaction.insert.then do
558			Command.finish("#{transaction} added to your account balance.")
559		end
560	}.catch_only(BuyAccountCreditForm::AmountValidationError) do |e|
561		Command.finish(e.message, type: :error)
562	end
563}.register(self).then(&CommandList.method(:register))
564
565Command.new(
566	"alt top up",
567	"Buy Account Credit by Bitcoin, Mail, or Interac eTransfer",
568	list_for: ->(customer:, **) { !!customer&.currency }
569) {
570	Command.customer.then { |customer|
571		EMPromise.all([AltTopUpForm.for(customer), customer])
572	}.then do |(alt_form, customer)|
573		Command.reply { |reply|
574			reply.allowed_actions = [:complete]
575			reply.command << alt_form.form
576		}.then do |iq|
577			AddBitcoinAddress.for(iq, alt_form, customer).write
578		end
579	end
580}.register(self).then(&CommandList.method(:register))
581
582Command.new(
583	"referral codes",
584	"Refer a friend for free credit"
585) {
586	Command.customer.then(&:unused_invites).then do |invites|
587		if invites.empty?
588			Command.finish("You have no more invites right now, try again later.")
589		else
590			Command.finish do |reply|
591				reply.form.type = :result
592				reply.form.title = "Unused Invite Codes"
593				reply.form.instructions =
594					"Each of these codes is single use and gives the person using " \
595					"them a free month of JMP service. You will receive credit " \
596					"equivalent to one month of free service if they later become " \
597					"a paying customer."
598				FormTable.new(
599					invites.map { |i| [i] },
600					code: "Invite Code"
601				).add_to_form(reply.form)
602			end
603		end
604	end
605}.register(self).then(&CommandList.method(:register))
606
607Command.new(
608	"reset sip account",
609	"Create or Reset SIP Account",
610	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
611) {
612	Command.customer.then do |customer|
613		sip_account = customer.reset_sip_account
614		Command.reply { |reply|
615			reply.allowed_actions = [:next]
616			form = sip_account.form
617			form.type = :form
618			form.fields += [{
619				type: :boolean, var: "change_fwd",
620				label: "Should inbound calls forward to this SIP account?"
621			}]
622			reply.command << form
623		}.then do |fwd|
624			if ["1", "true"].include?(fwd.form.field("change_fwd")&.value.to_s)
625				Command.execution.customer_repo.put_fwd(
626					customer,
627					customer.fwd.with(uri: sip_account.uri)
628				).then { Command.finish("Inbound calls will now forward to SIP.") }
629			else
630				Command.finish
631			end
632		end
633	end
634}.register(self).then(&CommandList.method(:register))
635
636Command.new(
637	"lnp",
638	"Port in your number from another carrier",
639	list_for: ->(**) { true }
640) {
641	using FormToH
642
643	EMPromise.all([
644		Command.customer,
645		Command.reply do |reply|
646			reply.allowed_actions = [:next]
647			reply.command << FormTemplate.render("lnp")
648		end
649	]).then do |(customer, iq)|
650		order = PortInOrder.new(iq.form.to_h.slice(
651			"BillingTelephoneNumber", "Subscriber", "WirelessInfo"
652		).merge("CustomerOrderId" => customer.customer_id))
653		order_id = BandwidthIris::PortIn.create(order.to_h)[:order_id]
654		url = "https://dashboard.bandwidth.com/portal/r/a/" \
655		      "#{CONFIG[:creds][:account]}/orders/portIn/#{order_id}"
656		BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
657		BLATHER.say(
658			CONFIG[:notify_admin],
659			"New port-in request for #{customer.customer_id}: #{url}",
660			:groupchat
661		)
662		Command.finish(
663			"Your port-in request has been accepted, " \
664			"support will contact you with next steps"
665		)
666	end
667}.register(self).then(&CommandList.method(:register))
668
669Command.new(
670	"customer info",
671	"Show Customer Info",
672	list_for: ->(customer: nil, **) { customer&.admin? }
673) {
674	Command.customer.then do |customer|
675		raise AuthError, "You are not an admin" unless customer&.admin?
676
677		customer_info = CustomerInfoForm.new
678		Command.reply { |reply|
679			reply.allowed_actions = [:next]
680			reply.command << customer_info.picker_form
681		}.then { |response|
682			customer_info.find_customer(response)
683		}.then do |target_customer|
684			target_customer.admin_info.then do |info|
685				Command.finish do |reply|
686					form = Blather::Stanza::X.new(:result)
687					form.title = "Customer Info"
688					form.fields = info.fields
689					reply.command << form
690				end
691			end
692		end
693	end
694}.register(self).then(&CommandList.method(:register))
695
696def reply_with_note(iq, text, type: :info)
697	reply = iq.reply
698	reply.status = :completed
699	reply.note_type = type
700	reply.note_text = text
701
702	self << reply
703end
704
705command :execute?, node: "web-register" do |iq|
706	StatsD.increment("command", tags: ["node:#{iq.node}"])
707
708	sentry_hub = new_sentry_hub(iq, name: iq.node)
709
710	begin
711		jid = iq.form.field("jid")&.value.to_s.strip
712		tel = iq.form.field("tel")&.value.to_s.strip
713		sentry_hub.current_scope.set_user(jid: jid, tel: tel)
714		if iq.from.stripped != CONFIG[:web_register][:from]
715			BLATHER << iq.as_error("forbidden", :auth)
716		elsif jid == "" || tel !~ /\A\+\d+\Z/
717			reply_with_note(iq, "Invalid JID or telephone number.", type: :error)
718		else
719			IQ_MANAGER.write(Blather::Stanza::Iq::Command.new.tap { |cmd|
720				cmd.to = CONFIG[:web_register][:to]
721				cmd.node = "push-register"
722				cmd.form.fields = [{ var: "to", value: jid }]
723				cmd.form.type = "submit"
724			}).then { |result|
725				TEL_SELECTIONS.set(result.form.field("from")&.value.to_s.strip, tel)
726			}.then {
727				BLATHER << iq.reply.tap { |reply| reply.status = :completed }
728			}.catch { |e| panic(e, sentry_hub) }
729		end
730	rescue StandardError => e
731		sentry_hub.capture_exception(e)
732	end
733end
734
735command sessionid: /./ do |iq|
736	COMMAND_MANAGER.fulfill(iq)
737end
738
739iq type: [:result, :error] do |iq|
740	IQ_MANAGER.fulfill(iq)
741end
742
743iq type: [:get, :set] do |iq|
744	StatsD.increment("unknown_iq")
745
746	self << Blather::StanzaError.new(iq, "feature-not-implemented", :cancel)
747end