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