You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

449 lines
14 KiB

  1. # frozen_string_literal: true
  2. require 'tty-command'
  3. require 'tty-prompt'
  4. namespace :mastodon do
  5. desc 'Configure the instance for production use'
  6. task :setup do
  7. prompt = TTY::Prompt.new
  8. env = {}
  9. begin
  10. prompt.say('Your instance is identified by its domain name. Changing it afterward will break things.')
  11. env['LOCAL_DOMAIN'] = prompt.ask('Domain name:') do |q|
  12. q.required true
  13. q.modify :strip
  14. q.validate(/\A[a-z0-9\.\-]+\z/i)
  15. q.messages[:valid?] = 'Invalid domain. If you intend to use unicode characters, enter punycode here'
  16. end
  17. prompt.say "\n"
  18. prompt.say('Single user mode disables registrations and redirects the landing page to your public profile.')
  19. env['SINGLE_USER_MODE'] = prompt.yes?('Do you want to enable single user mode?', default: false)
  20. %w(SECRET_KEY_BASE OTP_SECRET).each do |key|
  21. env[key] = SecureRandom.hex(64)
  22. end
  23. vapid_key = Webpush.generate_key
  24. env['VAPID_PRIVATE_KEY'] = vapid_key.private_key
  25. env['VAPID_PUBLIC_KEY'] = vapid_key.public_key
  26. prompt.say "\n"
  27. using_docker = prompt.yes?('Are you using Docker to run Mastodon?')
  28. db_connection_works = false
  29. prompt.say "\n"
  30. loop do
  31. env['DB_HOST'] = prompt.ask('PostgreSQL host:') do |q|
  32. q.required true
  33. q.default using_docker ? 'db' : '/var/run/postgresql'
  34. q.modify :strip
  35. end
  36. env['DB_PORT'] = prompt.ask('PostgreSQL port:') do |q|
  37. q.required true
  38. q.default 5432
  39. q.convert :int
  40. end
  41. env['DB_NAME'] = prompt.ask('Name of PostgreSQL database:') do |q|
  42. q.required true
  43. q.default using_docker ? 'postgres' : 'mastodon_production'
  44. q.modify :strip
  45. end
  46. env['DB_USER'] = prompt.ask('Name of PostgreSQL user:') do |q|
  47. q.required true
  48. q.default using_docker ? 'postgres' : 'mastodon'
  49. q.modify :strip
  50. end
  51. env['DB_PASS'] = prompt.ask('Password of PostgreSQL user:') do |q|
  52. q.echo false
  53. end
  54. # The chosen database may not exist yet. Connect to default database
  55. # to avoid "database does not exist" error.
  56. db_options = {
  57. adapter: :postgresql,
  58. database: 'postgres',
  59. host: env['DB_HOST'],
  60. port: env['DB_PORT'],
  61. user: env['DB_USER'],
  62. password: env['DB_PASS'],
  63. }
  64. begin
  65. ActiveRecord::Base.establish_connection(db_options)
  66. ActiveRecord::Base.connection
  67. prompt.ok 'Database configuration works! 🎆'
  68. db_connection_works = true
  69. break
  70. rescue StandardError => e
  71. prompt.error 'Database connection could not be established with this configuration, try again.'
  72. prompt.error e.message
  73. break unless prompt.yes?('Try again?')
  74. end
  75. end
  76. prompt.say "\n"
  77. loop do
  78. env['REDIS_HOST'] = prompt.ask('Redis host:') do |q|
  79. q.required true
  80. q.default using_docker ? 'redis' : 'localhost'
  81. q.modify :strip
  82. end
  83. env['REDIS_PORT'] = prompt.ask('Redis port:') do |q|
  84. q.required true
  85. q.default 6379
  86. q.convert :int
  87. end
  88. env['REDIS_PASSWORD'] = prompt.ask('Redis password:') do |q|
  89. q.required false
  90. q.default nil
  91. q.modify :strip
  92. end
  93. redis_options = {
  94. host: env['REDIS_HOST'],
  95. port: env['REDIS_PORT'],
  96. password: env['REDIS_PASSWORD'],
  97. driver: :hiredis,
  98. }
  99. begin
  100. redis = Redis.new(redis_options)
  101. redis.ping
  102. prompt.ok 'Redis configuration works! 🎆'
  103. break
  104. rescue StandardError => e
  105. prompt.error 'Redis connection could not be established with this configuration, try again.'
  106. prompt.error e.message
  107. break unless prompt.yes?('Try again?')
  108. end
  109. end
  110. prompt.say "\n"
  111. if prompt.yes?('Do you want to store uploaded files on the cloud?', default: false)
  112. case prompt.select('Provider', ['Amazon S3', 'Wasabi', 'Minio', 'Google Cloud Storage'])
  113. when 'Amazon S3'
  114. env['S3_ENABLED'] = 'true'
  115. env['S3_PROTOCOL'] = 'https'
  116. env['S3_BUCKET'] = prompt.ask('S3 bucket name:') do |q|
  117. q.required true
  118. q.default "files.#{env['LOCAL_DOMAIN']}"
  119. q.modify :strip
  120. end
  121. env['S3_REGION'] = prompt.ask('S3 region:') do |q|
  122. q.required true
  123. q.default 'us-east-1'
  124. q.modify :strip
  125. end
  126. env['S3_HOSTNAME'] = prompt.ask('S3 hostname:') do |q|
  127. q.required true
  128. q.default 's3-us-east-1.amazonaws.com'
  129. q.modify :strip
  130. end
  131. env['AWS_ACCESS_KEY_ID'] = prompt.ask('S3 access key:') do |q|
  132. q.required true
  133. q.modify :strip
  134. end
  135. env['AWS_SECRET_ACCESS_KEY'] = prompt.ask('S3 secret key:') do |q|
  136. q.required true
  137. q.modify :strip
  138. end
  139. when 'Wasabi'
  140. env['S3_ENABLED'] = 'true'
  141. env['S3_PROTOCOL'] = 'https'
  142. env['S3_REGION'] = 'us-east-1'
  143. env['S3_HOSTNAME'] = 's3.wasabisys.com'
  144. env['S3_ENDPOINT'] = 'https://s3.wasabisys.com/'
  145. env['S3_BUCKET'] = prompt.ask('Wasabi bucket name:') do |q|
  146. q.required true
  147. q.default "files.#{env['LOCAL_DOMAIN']}"
  148. q.modify :strip
  149. end
  150. env['AWS_ACCESS_KEY_ID'] = prompt.ask('Wasabi access key:') do |q|
  151. q.required true
  152. q.modify :strip
  153. end
  154. env['AWS_SECRET_ACCESS_KEY'] = prompt.ask('Wasabi secret key:') do |q|
  155. q.required true
  156. q.modify :strip
  157. end
  158. when 'Minio'
  159. env['S3_ENABLED'] = 'true'
  160. env['S3_PROTOCOL'] = 'https'
  161. env['S3_REGION'] = 'us-east-1'
  162. env['S3_ENDPOINT'] = prompt.ask('Minio endpoint URL:') do |q|
  163. q.required true
  164. q.modify :strip
  165. end
  166. env['S3_PROTOCOL'] = env['S3_ENDPOINT'].start_with?('https') ? 'https' : 'http'
  167. env['S3_HOSTNAME'] = env['S3_ENDPOINT'].gsub(/\Ahttps?:\/\//, '')
  168. env['S3_BUCKET'] = prompt.ask('Minio bucket name:') do |q|
  169. q.required true
  170. q.default "files.#{env['LOCAL_DOMAIN']}"
  171. q.modify :strip
  172. end
  173. env['AWS_ACCESS_KEY_ID'] = prompt.ask('Minio access key:') do |q|
  174. q.required true
  175. q.modify :strip
  176. end
  177. env['AWS_SECRET_ACCESS_KEY'] = prompt.ask('Minio secret key:') do |q|
  178. q.required true
  179. q.modify :strip
  180. end
  181. when 'Google Cloud Storage'
  182. env['S3_ENABLED'] = 'true'
  183. env['S3_PROTOCOL'] = 'https'
  184. env['S3_HOSTNAME'] = 'storage.googleapis.com'
  185. env['S3_ENDPOINT'] = 'https://storage.googleapis.com'
  186. env['S3_MULTIPART_THRESHOLD'] = 50.megabytes
  187. env['S3_BUCKET'] = prompt.ask('GCS bucket name:') do |q|
  188. q.required true
  189. q.default "files.#{env['LOCAL_DOMAIN']}"
  190. q.modify :strip
  191. end
  192. env['S3_REGION'] = prompt.ask('GCS region:') do |q|
  193. q.required true
  194. q.default 'us-west1'
  195. q.modify :strip
  196. end
  197. env['AWS_ACCESS_KEY_ID'] = prompt.ask('GCS access key:') do |q|
  198. q.required true
  199. q.modify :strip
  200. end
  201. env['AWS_SECRET_ACCESS_KEY'] = prompt.ask('GCS secret key:') do |q|
  202. q.required true
  203. q.modify :strip
  204. end
  205. end
  206. if prompt.yes?('Do you want to access the uploaded files from your own domain?')
  207. env['S3_ALIAS_HOST'] = prompt.ask('Domain for uploaded files:') do |q|
  208. q.required true
  209. q.default "files.#{env['LOCAL_DOMAIN']}"
  210. q.modify :strip
  211. end
  212. end
  213. end
  214. prompt.say "\n"
  215. loop do
  216. if prompt.yes?('Do you want to send e-mails from localhost?', default: false)
  217. env['SMTP_SERVER'] = 'localhost'
  218. env['SMTP_PORT'] = 25
  219. env['SMTP_AUTH_METHOD'] = 'none'
  220. env['SMTP_OPENSSL_VERIFY_MODE'] = 'none'
  221. else
  222. env['SMTP_SERVER'] = prompt.ask('SMTP server:') do |q|
  223. q.required true
  224. q.default 'smtp.mailgun.org'
  225. q.modify :strip
  226. end
  227. env['SMTP_PORT'] = prompt.ask('SMTP port:') do |q|
  228. q.required true
  229. q.default 587
  230. q.convert :int
  231. end
  232. env['SMTP_LOGIN'] = prompt.ask('SMTP username:') do |q|
  233. q.modify :strip
  234. end
  235. env['SMTP_PASSWORD'] = prompt.ask('SMTP password:') do |q|
  236. q.echo false
  237. end
  238. env['SMTP_AUTH_METHOD'] = prompt.ask('SMTP authentication:') do |q|
  239. q.required
  240. q.default 'plain'
  241. q.modify :strip
  242. end
  243. env['SMTP_OPENSSL_VERIFY_MODE'] = prompt.select('SMTP OpenSSL verify mode:', %w(none peer client_once fail_if_no_peer_cert))
  244. end
  245. env['SMTP_FROM_ADDRESS'] = prompt.ask('E-mail address to send e-mails "from":') do |q|
  246. q.required true
  247. q.default "Mastodon <notifications@#{env['LOCAL_DOMAIN']}>"
  248. q.modify :strip
  249. end
  250. break unless prompt.yes?('Send a test e-mail with this configuration right now?')
  251. send_to = prompt.ask('Send test e-mail to:', required: true)
  252. begin
  253. ActionMailer::Base.smtp_settings = {
  254. port: env['SMTP_PORT'],
  255. address: env['SMTP_SERVER'],
  256. user_name: env['SMTP_LOGIN'].presence,
  257. password: env['SMTP_PASSWORD'].presence,
  258. domain: env['LOCAL_DOMAIN'],
  259. authentication: env['SMTP_AUTH_METHOD'] == 'none' ? nil : env['SMTP_AUTH_METHOD'] || :plain,
  260. openssl_verify_mode: env['SMTP_OPENSSL_VERIFY_MODE'],
  261. enable_starttls_auto: true,
  262. }
  263. ActionMailer::Base.default_options = {
  264. from: env['SMTP_FROM_ADDRESS'],
  265. }
  266. mail = ActionMailer::Base.new.mail to: send_to, subject: 'Test', body: 'Mastodon SMTP configuration works!'
  267. mail.deliver
  268. break
  269. rescue StandardError => e
  270. prompt.error 'E-mail could not be sent with this configuration, try again.'
  271. prompt.error e.message
  272. break unless prompt.yes?('Try again?')
  273. end
  274. end
  275. prompt.say "\n"
  276. prompt.say 'This configuration will be written to .env.production'
  277. if prompt.yes?('Save configuration?')
  278. cmd = TTY::Command.new(printer: :quiet)
  279. env_contents = env.each_pair.map do |key, value|
  280. if value.is_a?(String) && value =~ /[\s\#\\"]/
  281. if value =~ /[']/
  282. value = value.to_s.gsub(/[\\"\$]/) { |x| "\\#{x}" }
  283. "#{key}=\"#{value}\""
  284. else
  285. "#{key}='#{value}'"
  286. end
  287. else
  288. "#{key}=#{value}"
  289. end
  290. end.join("\n")
  291. File.write(Rails.root.join('.env.production'), "# Generated with mastodon:setup on #{Time.now.utc}\n\n" + env_contents + "\n")
  292. if using_docker
  293. prompt.ok 'Below is your configuration, save it to an .env.production file outside Docker:'
  294. prompt.say "\n"
  295. prompt.say File.read(Rails.root.join('.env.production'))
  296. prompt.say "\n"
  297. prompt.ok 'It is also saved within this container so you can proceed with this wizard.'
  298. end
  299. prompt.say "\n"
  300. prompt.say 'Now that configuration is saved, the database schema must be loaded.'
  301. prompt.warn 'If the database already exists, this will erase its contents.'
  302. if prompt.yes?('Prepare the database now?')
  303. prompt.say 'Running `RAILS_ENV=production rails db:setup` ...'
  304. prompt.say "\n\n"
  305. if cmd.run!({ RAILS_ENV: 'production', SAFETY_ASSURED: 1 }, :rails, 'db:setup').failure?
  306. prompt.error 'That failed! Perhaps your configuration is not right'
  307. else
  308. prompt.ok 'Done!'
  309. end
  310. end
  311. prompt.say "\n"
  312. prompt.say 'The final step is compiling CSS/JS assets.'
  313. prompt.say 'This may take a while and consume a lot of RAM.'
  314. if prompt.yes?('Compile the assets now?')
  315. prompt.say 'Running `RAILS_ENV=production rails assets:precompile` ...'
  316. prompt.say "\n\n"
  317. if cmd.run!({ RAILS_ENV: 'production' }, :rails, 'assets:precompile').failure?
  318. prompt.error 'That failed! Maybe you need swap space?'
  319. else
  320. prompt.say 'Done!'
  321. end
  322. end
  323. prompt.say "\n"
  324. prompt.ok 'All done! You can now power on the Mastodon server 🐘'
  325. prompt.say "\n"
  326. if db_connection_works && prompt.yes?('Do you want to create an admin user straight away?')
  327. env.each_pair do |key, value|
  328. ENV[key] = value.to_s
  329. end
  330. require_relative '../../config/environment'
  331. disable_log_stdout!
  332. username = prompt.ask('Username:') do |q|
  333. q.required true
  334. q.default 'admin'
  335. q.validate(/\A[a-z0-9_]+\z/i)
  336. q.modify :strip
  337. end
  338. email = prompt.ask('E-mail:') do |q|
  339. q.required true
  340. q.modify :strip
  341. end
  342. password = SecureRandom.hex(16)
  343. user = User.new(admin: true, email: email, password: password, confirmed_at: Time.now.utc, account_attributes: { username: username })
  344. user.save(validate: false)
  345. prompt.ok "You can login with the password: #{password}"
  346. prompt.warn 'You can change your password once you login.'
  347. end
  348. else
  349. prompt.warn 'Nothing saved. Bye!'
  350. end
  351. rescue TTY::Reader::InputInterrupt
  352. prompt.ok 'Aborting. Bye!'
  353. end
  354. end
  355. namespace :webpush do
  356. desc 'Generate VAPID key'
  357. task generate_vapid_key: :environment do
  358. vapid_key = Webpush.generate_key
  359. puts "VAPID_PRIVATE_KEY=#{vapid_key.private_key}"
  360. puts "VAPID_PUBLIC_KEY=#{vapid_key.public_key}"
  361. end
  362. end
  363. end
  364. def disable_log_stdout!
  365. dev_null = Logger.new('/dev/null')
  366. Rails.logger = dev_null
  367. ActiveRecord::Base.logger = dev_null
  368. HttpLog.configuration.logger = dev_null
  369. Paperclip.options[:log] = false
  370. end