Shuu12121/CodeModernBERT-Crow-v3-large-len1024
Fill-Mask • 0.3B • Updated
• 46
repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/senders/http_sender.rb | app/senders/http_sender.rb | # frozen_string_literal: true
class HTTPSender < BaseSender
def initialize(endpoint, options = {})
super()
@endpoint = endpoint
@options = options
@log_id = SecureRandom.alphanumeric(8).upcase
end
def send_message(message)
start_time = Time.now
result = SendResult.new
result.log_id = @log_id
request_options = {}
request_options[:sign] = true
request_options[:timeout] = @endpoint.timeout || 5
case @endpoint.encoding
when "BodyAsJSON"
request_options[:json] = parameters(message, flat: false).to_json
when "FormData"
request_options[:params] = parameters(message, flat: true)
end
log "Sending request to #{@endpoint.url}"
response = Postal::HTTP.post(@endpoint.url, request_options)
result.secure = !!response[:secure] # rubocop:disable Style/DoubleNegation
result.details = "Received a #{response[:code]} from #{@endpoint.url}"
log " -> Received: #{response[:code]}"
if response[:body]
log " -> Body: #{response[:body][0, 255]}"
result.output = response[:body].to_s[0, 500].strip
end
if response[:code] >= 200 && response[:code] < 300
# This is considered a success
result.type = "Sent"
elsif response[:code] >= 500 && response[:code] < 600
# This is temporary. They might fix their server so it should soft fail.
result.type = "SoftFail"
result.retry = true
elsif response[:code].negative?
# Connection/SSL etc... errors
result.type = "SoftFail"
result.retry = true
result.connect_error = true
elsif response[:code] == 429
# Rate limit exceeded, treat as a hard fail and don't send bounces
result.type = "HardFail"
result.suppress_bounce = true
else
# This is permanent. Any other error isn't cool with us.
result.type = "HardFail"
end
result.time = (Time.now - start_time).to_f.round(2)
result
end
private
def log(text)
Postal.logger.info text, id: @log_id, component: "http-sender"
end
def parameters(message, options = {})
case @endpoint.format
when "Hash"
hash = {
id: message.id,
rcpt_to: message.rcpt_to,
mail_from: message.mail_from,
token: message.token,
subject: message.subject,
message_id: message.message_id,
timestamp: message.timestamp.to_f,
size: message.size,
spam_status: message.spam_status,
bounce: message.bounce,
received_with_ssl: message.received_with_ssl,
to: message.headers["to"]&.last,
cc: message.headers["cc"]&.last,
from: message.headers["from"]&.last,
date: message.headers["date"]&.last,
in_reply_to: message.headers["in-reply-to"]&.last,
references: message.headers["references"]&.last,
html_body: message.html_body,
attachment_quantity: message.attachments.size,
auto_submitted: message.headers["auto-submitted"]&.last,
reply_to: message.headers["reply-to"]
}
if @endpoint.strip_replies
hash[:plain_body], hash[:replies_from_plain_body] = ReplySeparator.separate(message.plain_body)
else
hash[:plain_body] = message.plain_body
end
if @endpoint.include_attachments?
if options[:flat]
message.attachments.each_with_index do |a, i|
hash["attachments[#{i}][filename]"] = a.filename
hash["attachments[#{i}][content_type]"] = a.content_type
hash["attachments[#{i}][size]"] = a.body.to_s.bytesize.to_s
hash["attachments[#{i}][data]"] = Base64.encode64(a.body.to_s)
end
else
hash[:attachments] = message.attachments.map do |a|
{
filename: a.filename,
content_type: a.mime_type,
size: a.body.to_s.bytesize,
data: Base64.encode64(a.body.to_s)
}
end
end
end
hash
when "RawMessage"
{
id: message.id,
rcpt_to: message.rcpt_to,
mail_from: message.mail_from,
message: Base64.encode64(message.raw_message),
base64: true,
size: message.size.to_i
}
else
{}
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/senders/base_sender.rb | app/senders/base_sender.rb | # frozen_string_literal: true
class BaseSender
def start
end
def send_message(message)
end
def finish
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/senders/smtp_sender.rb | app/senders/smtp_sender.rb | # frozen_string_literal: true
class SMTPSender < BaseSender
attr_reader :endpoints
# @param domain [String] the domain to send mesages to
# @param source_ip_address [IPAddress] the IP address to send messages from
# @param log_id [String] an ID to use when logging requests
def initialize(domain, source_ip_address = nil, servers: nil, log_id: nil, rcpt_to: nil)
super()
@domain = domain
@source_ip_address = source_ip_address
@rcpt_to = rcpt_to
# An array of servers to forcefully send the message to
@servers = servers
# Stores all connection errors which we have seen during this send sesssion.
@connection_errors = []
# Stores all endpoints that we have attempted to deliver mail to
@endpoints = []
# Generate a log ID which can be used if none has been provided to trace
# this SMTP session.
@log_id = log_id || SecureRandom.alphanumeric(8).upcase
end
def start
servers = @servers || self.class.smtp_relays || resolve_mx_records_for_domain || []
servers.each do |server|
server.endpoints.each do |endpoint|
result = connect_to_endpoint(endpoint)
return endpoint if result
end
end
false
end
def send_message(message)
# If we don't have a current endpoint than we should raise an error.
if @current_endpoint.nil?
return create_result("SoftFail") do |r|
r.retry = true
r.details = "No SMTP servers were available for #{@domain}."
if @endpoints.empty?
r.details += " No hosts to try."
else
hostnames = @endpoints.map { |e| e.server.hostname }.uniq
r.details += " Tried #{hostnames.to_sentence}."
end
r.output = @connection_errors.join(", ")
r.connect_error = true
end
end
mail_from = determine_mail_from_for_message(message)
raw_message = message.raw_message
# Append the Resent-Sender header to the mesage to include the
# MAIL FROM if the installation is configured to use that?
if Postal::Config.postal.use_resent_sender_header?
raw_message = "Resent-Sender: #{mail_from}\r\n" + raw_message
end
rcpt_to = determine_rcpt_to_for_message(message)
logger.info "Sending message #{message.server.id}::#{message.id} to #{rcpt_to}"
send_message_to_smtp_client(raw_message, mail_from, rcpt_to)
end
def finish
@endpoints.each(&:finish_smtp_session)
end
private
# Take a message and attempt to send it to the SMTP server that we are
# currently connected to. If there is a connection error, we will just
# reset the client and retry again once.
#
# @param raw_message [String] the raw message to send
# @param mail_from [String] the MAIL FROM address to use
# @param rcpt_to [String] the RCPT TO address to use
# @param retry_on_connection_error [Boolean] if true, we will retry the connection if there is an error
#
# @return [SendResult]
def send_message_to_smtp_client(raw_message, mail_from, rcpt_to, retry_on_connection_error: true)
start_time = Time.now
smtp_result = @current_endpoint.send_message(raw_message, mail_from, [rcpt_to])
logger.info "Accepted by #{@current_endpoint} for #{rcpt_to}"
create_result("Sent", start_time) do |r|
r.details = "Message for #{rcpt_to} accepted by #{@current_endpoint}"
r.details += " (from #{@current_endpoint.smtp_client.source_address})" if @current_endpoint.smtp_client.source_address
r.output = smtp_result.string
end
rescue Net::SMTPServerBusy, Net::SMTPAuthenticationError, Net::SMTPSyntaxError, Net::SMTPUnknownError, Net::ReadTimeout => e
logger.error "#{e.class}: #{e.message}"
@current_endpoint.reset_smtp_session
create_result("SoftFail", start_time) do |r|
r.details = "Temporary SMTP delivery error when sending to #{@current_endpoint}"
r.output = e.message
if e.message =~ /(\d+) seconds/
r.retry = ::Regexp.last_match(1).to_i + 10
elsif e.message =~ /(\d+) minutes/
r.retry = (::Regexp.last_match(1).to_i * 60) + 10
else
r.retry = true
end
end
rescue Net::SMTPFatalError => e
logger.error "#{e.class}: #{e.message}"
@current_endpoint.reset_smtp_session
create_result("HardFail", start_time) do |r|
r.details = "Permanent SMTP delivery error when sending to #{@current_endpoint}"
r.output = e.message
end
rescue StandardError => e
logger.error "#{e.class}: #{e.message}"
@current_endpoint.reset_smtp_session
if defined?(Sentry)
# Sentry.capture_exception(e, extra: { log_id: @log_id, server_id: message.server.id, message_id: message.id })
end
create_result("SoftFail", start_time) do |r|
r.type = "SoftFail"
r.retry = true
r.details = "An error occurred while sending the message to #{@current_endpoint}"
r.output = e.message
end
end
# Return the MAIL FROM which should be used for the given message
#
# @param message [MessageDB::Message]
# @return [String]
def determine_mail_from_for_message(message)
return "" if message.bounce
# If the domain has a valid custom return path configured, return
# that.
if message.domain.return_path_status == "OK"
return "#{message.server.token}@#{message.domain.return_path_domain}"
end
"#{message.server.token}@#{Postal::Config.dns.return_path_domain}"
end
# Return the RCPT TO to use for the given message in this sending session
#
# @param message [MessageDB::Message]
# @return [String]
def determine_rcpt_to_for_message(message)
return @rcpt_to if @rcpt_to
message.rcpt_to
end
# Return an array of server hostnames which should receive this message
#
# @return [Array<String>]
def resolve_mx_records_for_domain
hostnames = DNSResolver.local.mx(@domain, raise_timeout_errors: true).map(&:last)
return [SMTPClient::Server.new(@domain)] if hostnames.empty?
hostnames.map { |hostname| SMTPClient::Server.new(hostname) }
end
# Attempt to begin an SMTP sesssion for the given endpoint. If successful, this endpoint
# becomes the current endpoints for the SMTP sender.
#
# Returns true if the session was established.
# Returns false if the session could not be established.
#
# @param endpoint [SMTPClient::Endpoint]
# @return [Boolean]
def connect_to_endpoint(endpoint, allow_ssl: true)
if @source_ip_address && @source_ip_address.ipv6.blank? && endpoint.ipv6?
# Don't try to use IPv6 if the IP address we're sending from doesn't support it.
return false
end
# Add this endpoint to the list of endpoints that we have attempted to connect to
@endpoints << endpoint unless @endpoints.include?(endpoint)
endpoint.start_smtp_session(allow_ssl: allow_ssl, source_ip_address: @source_ip_address)
logger.info "Connected to #{endpoint}"
@current_endpoint = endpoint
true
rescue StandardError => e
# Disconnect the SMTP client if we get any errors to avoid leaving
# a connection around.
endpoint.finish_smtp_session
# If we get an SSL error, we can retry a connection without
# ssl.
if e.is_a?(OpenSSL::SSL::SSLError) && endpoint.server.ssl_mode == "Auto"
logger.error "SSL error (#{e.message}), retrying without SSL"
return connect_to_endpoint(endpoint, allow_ssl: false)
end
# Otherwise, just log the connection error and return false
logger.error "Cannot connect to #{endpoint} (#{e.class}: #{e.message})"
@connection_errors << e.message unless @connection_errors.include?(e.message)
false
end
# Create a new result object
#
# @param type [String] the type of result
# @param start_time [Time] the time the operation started
# @yieldparam [SendResult] the result object
# @yieldreturn [void]
#
# @return [SendResult]
def create_result(type, start_time = nil)
result = SendResult.new
result.type = type
result.log_id = @log_id
result.secure = @current_endpoint&.smtp_client&.secure_socket? ? true : false
yield result if block_given?
if start_time
result.time = (Time.now - start_time).to_f.round(2)
end
result
end
def logger
@logger ||= Postal.logger.create_tagged_logger(log_id: @log_id)
end
class << self
# Return an array of SMTP relays as configured. Returns nil
# if no SMTP relays are configured.
#
def smtp_relays
return @smtp_relays if instance_variable_defined?("@smtp_relays")
relays = Postal::Config.postal.smtp_relays
return nil if relays.nil?
relays = relays.filter_map do |relay|
next unless relay.host.present?
SMTPClient::Server.new(relay.host, port: relay.port, ssl_mode: relay.ssl_mode)
end
@smtp_relays = relays.empty? ? nil : relays
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/senders/send_result.rb | app/senders/send_result.rb | # frozen_string_literal: true
class SendResult
attr_accessor :type
attr_accessor :details
attr_accessor :retry
attr_accessor :output
attr_accessor :secure
attr_accessor :connect_error
attr_accessor :log_id
attr_accessor :time
attr_accessor :suppress_bounce
def initialize
@details = ""
yield self if block_given?
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/services/webhook_delivery_service.rb | app/services/webhook_delivery_service.rb | # frozen_string_literal: true
class WebhookDeliveryService
RETRIES = { 1 => 2.minutes, 2 => 3.minutes, 3 => 6.minutes, 4 => 10.minutes, 5 => 15.minutes }.freeze
def initialize(webhook_request:)
@webhook_request = webhook_request
end
def call
logger.tagged(webhook: @webhook_request.webhook_id, webhook_request: @webhook_request.id) do
generate_payload
send_request
record_attempt
appreciate_http_result
update_webhook_request
end
end
def success?
@success == true
end
private
def generate_payload
@payload = {
event: @webhook_request.event,
timestamp: @webhook_request.created_at.to_f,
payload: @webhook_request.payload,
uuid: @webhook_request.uuid
}.to_json
end
def send_request
@http_result = Postal::HTTP.post(@webhook_request.url,
sign: true,
json: @payload,
timeout: 5)
@success = (@http_result[:code] >= 200 && @http_result[:code] < 300)
end
def record_attempt
@webhook_request.attempts += 1
if success?
@webhook_request.retry_after = nil
else
@webhook_request.retry_after = RETRIES[@webhook_request.attempts]&.from_now
end
@attempt = @webhook_request.server.message_db.webhooks.record(
event: @webhook_request.event,
url: @webhook_request.url,
webhook_id: @webhook_request.webhook_id,
attempt: @webhook_request.attempts,
timestamp: Time.now.to_f,
payload: @webhook_request.payload.to_json,
uuid: @webhook_request.uuid,
status_code: @http_result[:code],
body: @http_result[:body],
will_retry: @webhook_request.retry_after.present?
)
end
def appreciate_http_result
if success?
logger.info "Received #{@http_result[:code]} status code. That's OK."
@webhook_request.destroy!
@webhook_request.webhook&.update_column(:last_used_at, Time.current)
return
end
logger.error "Received #{@http_result[:code]} status code. That's not OK."
@webhook_request.error = "Couldn't send to URL. Code received was #{@http_result[:code]}"
end
def update_webhook_request
if @webhook_request.retry_after
logger.info "Will retry #{@webhook_request.retry_after} (this was attempt #{@webhook_request.attempts})"
@webhook_request.locked_by = nil
@webhook_request.locked_at = nil
@webhook_request.save!
return
end
logger.info "Have tried #{@webhook_request.attempts} times. Giving up."
@webhook_request.destroy!
end
def logger
Postal.logger
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/util/has_prometheus_metrics.rb | app/util/has_prometheus_metrics.rb | # frozen_string_literal: true
module HasPrometheusMetrics
def register_prometheus_counter(name, **kwargs)
counter = Prometheus::Client::Counter.new(name, **kwargs)
registry.register(counter)
end
def register_prometheus_histogram(name, **kwargs)
histogram = Prometheus::Client::Histogram.new(name, **kwargs)
registry.register(histogram)
end
def increment_prometheus_counter(name, labels: {})
counter = registry.get(name)
return if counter.nil?
counter.increment(labels: labels)
end
def observe_prometheus_histogram(name, time, labels: {})
histogram = registry.get(name)
return if histogram.nil?
histogram.observe(time, labels: labels)
end
private
def registry
Prometheus::Client.registry
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/util/user_creator.rb | app/util/user_creator.rb | # frozen_string_literal: true
require "highline"
module UserCreator
class << self
def start(&block)
cli = HighLine.new
puts "\e[32mPostal User Creator\e[0m"
puts "Enter the information required to create a new Postal user."
puts "This tool is usually only used to create your initial admin user."
puts
user = User.new
user.email_address = cli.ask("E-Mail Address".ljust(20, " ") + ": ")
user.first_name = cli.ask("First Name".ljust(20, " ") + ": ")
user.last_name = cli.ask("Last Name".ljust(20, " ") + ": ")
user.password = cli.ask("Initial Password".ljust(20, " ") + ": ") { |value| value.echo = "*" }
block.call(user) if block_given?
puts
if user.save
puts "User has been created with e-mail address \e[32m#{user.email_address}\e[0m"
else
puts "\e[31mFailed to create user\e[0m"
user.errors.full_messages.each do |error|
puts " * #{error}"
end
end
puts
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/util/health_server.rb | app/util/health_server.rb | # frozen_string_literal: true
require "socket"
require "rackup/handler/webrick"
require "prometheus/client/formats/text"
class HealthServer
def initialize(name: "unnamed-process")
@name = name
end
def call(env)
case env["PATH_INFO"]
when "/health"
ok
when "/metrics"
metrics
when "/"
root
else
not_found
end
end
private
def root
[200, { "Content-Type" => "text/plain" }, ["#{@name} (pid: #{Process.pid}, host: #{hostname})"]]
end
def ok
[200, { "Content-Type" => "text/plain" }, ["OK"]]
end
def not_found
[404, { "Content-Type" => "text/plain" }, ["Not Found"]]
end
def metrics
registry = Prometheus::Client.registry
body = Prometheus::Client::Formats::Text.marshal(registry)
[200, { "Content-Type" => "text/plain" }, [body]]
end
def hostname
Socket.gethostname
rescue StandardError
"unknown-hostname"
end
class << self
def run(default_port:, default_bind_address:, **options)
port = ENV.fetch("HEALTH_SERVER_PORT", default_port)
bind_address = ENV.fetch("HEALTH_SERVER_BIND_ADDRESS", default_bind_address)
Rackup::Handler::WEBrick.run(new(**options),
Port: port,
BindAddress: bind_address,
AccessLog: [],
Logger: LoggerProxy.new)
rescue Errno::EADDRINUSE
Postal.logger.info "health server port (#{bind_address}:#{port}) is already " \
"in use, not starting health server"
end
def start(**options)
thread = Thread.new { run(**options) }
thread.abort_on_exception = false
thread
end
end
class LoggerProxy
[:info, :debug, :warn, :error, :fatal].each do |severity|
define_method(severity) do |message|
add(severity, message)
end
define_method("#{severity}?") do
severity != :debug
end
end
def add(severity, message)
return if severity == :debug
case message
when /\AWEBrick::HTTPServer#start:.*port=(\d+)/
Postal.logger.info "started health server on port #{::Regexp.last_match(1)}", component: "health-server"
when /\AWEBrick::HTTPServer#start done/
Postal.logger.info "stopped health server", component: "health-server"
when /\AWEBrick [\d.]+/,
/\Aruby ([\d.]+)/,
/\ARackup::Handler::WEBrick is mounted/,
/\Aclose TCPSocket/,
/\Agoing to shutdown/
# Don't actually print routine messages to avoid too much
# clutter when processes start it
else
Postal.logger.debug message, component: "health-server"
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/helpers/application_helper.rb | app/helpers/application_helper.rb | # frozen_string_literal: true
module ApplicationHelper
def format_delivery_details(server, text)
text.gsub!(/<msg:(\d+)>/) do
id = ::Regexp.last_match(1).to_i
link_to("message ##{id}", organization_server_message_path(server.organization, server, id), class: "u-link")
end
text.html_safe
end
def style_width(width, options = {})
width = 100 if width > 100.0
width = 0 if width < 0.0
style = "width:#{width}%;"
if options[:color]
if width >= 100
style += " background-color:#e2383a;"
elsif width >= 90
style += " background-color:#e8581f;"
end
end
style
end
def domain_options_for_select(server, selected_domain = nil, options = {})
String.new.tap do |s|
s << "<option></option>"
server_domains = server.domains.verified.order(:name)
unless server_domains.empty?
s << "<optgroup label='Server Domains'>"
server_domains.each do |domain|
selected = domain == selected_domain ? "selected='selected'" : ""
s << "<option value='#{domain.id}' #{selected}>#{domain.name}</option>"
end
s << "</optgroup>"
end
organization_domains = server.organization.domains.verified.order(:name)
unless organization_domains.empty?
s << "<optgroup label='Organization Domains'>"
organization_domains.each do |domain|
selected = domain == selected_domain ? "selected='selected'" : ""
s << "<option value='#{domain.id}' #{selected}>#{domain.name}</option>"
end
s << "</optgroup>"
end
end.html_safe
end
def endpoint_options_for_select(server, selected_value = nil, options = {})
String.new.tap do |s|
s << "<option></option>"
http_endpoints = server.http_endpoints.order(:name).to_a
if http_endpoints.present?
s << "<optgroup label='HTTP Endpoints'>"
http_endpoints.each do |endpoint|
value = "#{endpoint.class}##{endpoint.uuid}"
selected = value == selected_value ? "selected='selected'" : ""
s << "<option value='#{value}' #{selected}>#{endpoint.description}</option>"
end
s << "</optgroup>"
end
smtp_endpoints = server.smtp_endpoints.order(:name).to_a
if smtp_endpoints.present?
s << "<optgroup label='SMTP Endpoints'>"
smtp_endpoints.each do |endpoint|
value = "#{endpoint.class}##{endpoint.uuid}"
selected = value == selected_value ? "selected='selected'" : ""
s << "<option value='#{value}' #{selected}>#{endpoint.description}</option>"
end
s << "</optgroup>"
end
address_endpoints = server.address_endpoints.order(:address).to_a
if address_endpoints.present?
s << "<optgroup label='Address Endpoints'>"
address_endpoints.each do |endpoint|
value = "#{endpoint.class}##{endpoint.uuid}"
selected = value == selected_value ? "selected='selected'" : ""
s << "<option value='#{value}' #{selected}>#{endpoint.address}</option>"
end
s << "</optgroup>"
end
unless options[:other] == false
s << "<optgroup label='Other Options'>"
Route::MODES.each do |mode|
next if mode == "Endpoint"
selected = (selected_value == mode ? "selected='selected'" : "")
text = t("route_modes.#{mode.underscore}")
s << "<option value='#{mode}' #{selected}>#{text}</option>"
end
s << "</optgroup>"
end
end.html_safe
end
def postal_version_string
string = Postal.version
string += " (#{Postal.branch})" if Postal.branch &&
Postal.branch != "main"
string
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/scheduled_tasks/application_scheduled_task.rb | app/scheduled_tasks/application_scheduled_task.rb | # frozen_string_literal: true
class ApplicationScheduledTask
def initialize(logger:)
@logger = logger
end
def call
raise NotImplementedError
end
attr_reader :logger
class << self
def next_run_after
quarter_past_each_hour
end
private
def quarter_past_each_hour
time = Time.current
time = time.change(min: 15, sec: 0)
time += 1.hour if time < Time.current
time
end
def quarter_to_each_hour
time = Time.current
time = time.change(min: 45, sec: 0)
time += 1.hour if time < Time.current
time
end
def three_am
time = Time.current
time = time.change(hour: 3, min: 0, sec: 0)
time += 1.day if time < Time.current
time
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/scheduled_tasks/prune_webhook_requests_scheduled_task.rb | app/scheduled_tasks/prune_webhook_requests_scheduled_task.rb | # frozen_string_literal: true
class PruneWebhookRequestsScheduledTask < ApplicationScheduledTask
def call
Server.all.each do |s|
logger.info "Pruning webhook requests for server #{s.id}"
s.message_db.webhooks.prune
end
end
def self.next_run_after
quarter_to_each_hour
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/scheduled_tasks/process_message_retention_scheduled_task.rb | app/scheduled_tasks/process_message_retention_scheduled_task.rb | # frozen_string_literal: true
class ProcessMessageRetentionScheduledTask < ApplicationScheduledTask
def call
Server.all.each do |server|
if server.raw_message_retention_days
# If the server has a maximum number of retained raw messages, remove any that are older than this
logger.info "Tidying raw messages (by days) for #{server.permalink} (ID: #{server.id}). Keeping #{server.raw_message_retention_days} days."
server.message_db.provisioner.remove_raw_tables_older_than(server.raw_message_retention_days)
end
if server.raw_message_retention_size
logger.info "Tidying raw messages (by size) for #{server.permalink} (ID: #{server.id}). Keeping #{server.raw_message_retention_size} MB of data."
server.message_db.provisioner.remove_raw_tables_until_less_than_size(server.raw_message_retention_size * 1024 * 1024)
end
if server.message_retention_days
logger.info "Tidying messages for #{server.permalink} (ID: #{server.id}). Keeping #{server.message_retention_days} days."
server.message_db.provisioner.remove_messages(server.message_retention_days)
end
end
end
def self.next_run_after
three_am
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/scheduled_tasks/check_all_dns_scheduled_task.rb | app/scheduled_tasks/check_all_dns_scheduled_task.rb | # frozen_string_literal: true
class CheckAllDNSScheduledTask < ApplicationScheduledTask
def call
Domain.where.not(dns_checked_at: nil).where("dns_checked_at <= ?", 1.hour.ago).each do |domain|
logger.info "checking DNS for domain: #{domain.name}"
domain.check_dns(:auto)
end
TrackDomain.where("dns_checked_at IS NULL OR dns_checked_at <= ?", 1.hour.ago).includes(:domain).each do |domain|
logger.info "checking DNS for track domain: #{domain.full_name}"
domain.check_dns
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/scheduled_tasks/prune_suppression_lists_scheduled_task.rb | app/scheduled_tasks/prune_suppression_lists_scheduled_task.rb | # frozen_string_literal: true
class PruneSuppressionListsScheduledTask < ApplicationScheduledTask
def call
Server.all.each do |s|
logger.info "Pruning suppression lists for server #{s.id}"
s.message_db.suppression_list.prune
end
end
def self.next_run_after
three_am
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/scheduled_tasks/tidy_queued_messages_task.rb | app/scheduled_tasks/tidy_queued_messages_task.rb | # frozen_string_literal: true
class TidyQueuedMessagesTask < ApplicationScheduledTask
def call
QueuedMessage.with_stale_lock.in_batches do |messages|
messages.each do |message|
logger.info "removing queued message #{message.id} (locked at #{message.locked_at} by #{message.locked_by})"
message.destroy
end
end
end
def self.next_run_after
quarter_to_each_hour
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/scheduled_tasks/action_deletions_scheduled_task.rb | app/scheduled_tasks/action_deletions_scheduled_task.rb | # frozen_string_literal: true
class ActionDeletionsScheduledTask < ApplicationScheduledTask
def call
Organization.deleted.each do |org|
logger.info "permanently removing organization #{org.id} (#{org.permalink})"
org.destroy
end
Server.deleted.each do |server|
logger.info "permanently removing server #{server.id} (#{server.full_permalink})"
server.destroy
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/scheduled_tasks/cleanup_authie_sessions_scheduled_task.rb | app/scheduled_tasks/cleanup_authie_sessions_scheduled_task.rb | # frozen_string_literal: true
require "authie/session"
class CleanupAuthieSessionsScheduledTask < ApplicationScheduledTask
def call
Authie::Session.cleanup
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/scheduled_tasks/expire_held_messages_scheduled_task.rb | app/scheduled_tasks/expire_held_messages_scheduled_task.rb | # frozen_string_literal: true
class ExpireHeldMessagesScheduledTask < ApplicationScheduledTask
def call
Server.all.each do |server|
messages = server.message_db.messages(where: {
status: "Held",
hold_expiry: { less_than: Time.now.to_f }
})
messages.each(&:cancel_hold)
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/scheduled_tasks/send_notifications_scheduled_task.rb | app/scheduled_tasks/send_notifications_scheduled_task.rb | # frozen_string_literal: true
class SendNotificationsScheduledTask < ApplicationScheduledTask
def call
Server.send_send_limit_notifications
end
def self.next_run_after
1.minute.from_now
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/credentials_controller.rb | app/controllers/credentials_controller.rb | # frozen_string_literal: true
class CredentialsController < ApplicationController
include WithinOrganization
before_action { @server = organization.servers.present.find_by_permalink!(params[:server_id]) }
before_action { params[:id] && @credential = @server.credentials.find_by_uuid!(params[:id]) }
def index
@credentials = @server.credentials.order(:name).to_a
end
def new
@credential = @server.credentials.build
end
def create
@credential = @server.credentials.build(params.require(:credential).permit(:type, :name, :key, :hold))
if @credential.save
redirect_to_with_json [organization, @server, :credentials]
else
render_form_errors "new", @credential
end
end
def update
if @credential.update(params.require(:credential).permit(:name, :key, :hold))
redirect_to_with_json [organization, @server, :credentials]
else
render_form_errors "edit", @credential
end
end
def destroy
@credential.destroy
redirect_to_with_json [organization, @server, :credentials]
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/help_controller.rb | app/controllers/help_controller.rb | # frozen_string_literal: true
class HelpController < ApplicationController
include WithinOrganization
before_action { @server = organization.servers.find_by_permalink!(params[:server_id]) }
def outgoing
@credentials = @server.credentials.group_by(&:type)
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/organizations_controller.rb | app/controllers/organizations_controller.rb | # frozen_string_literal: true
class OrganizationsController < ApplicationController
before_action :admin_required, only: [:new, :create, :delete, :destroy]
def index
if current_user.admin?
@organizations = Organization.present.order(:name).to_a
else
@organizations = current_user.organizations.present.order(:name).to_a
if @organizations.size == 1 && params[:nrd].nil?
redirect_to organization_root_path(@organizations.first)
end
end
end
def new
@organization = Organization.new
end
def edit
@organization_obj = current_user.organizations_scope.find(organization.id)
end
def create
@organization = Organization.new(params.require(:organization).permit(:name, :permalink))
@organization.owner = current_user
if @organization.save
redirect_to_with_json organization_root_path(@organization)
else
render_form_errors "new", @organization
end
end
def update
@organization_obj = current_user.organizations_scope.find(organization.id)
if @organization_obj.update(params.require(:organization).permit(:name, :time_zone))
redirect_to_with_json organization_settings_path(@organization_obj), notice: "Settings for #{@organization_obj.name} have been saved successfully."
else
render_form_errors "edit", @organization_obj
end
end
def destroy
if params[:confirm_text].blank? || params[:confirm_text].downcase.strip != organization.name.downcase.strip
respond_to do |wants|
alert_text = "The text you entered does not match the organization name. Please check and try again."
wants.html { redirect_to organization_delete_path(@organization), alert: alert_text }
wants.json { render json: { alert: alert_text } }
end
return
end
organization.soft_destroy
redirect_to_with_json root_path(nrd: 1), notice: "#{@organization.name} has been removed successfully."
end
private
def organization
return unless [:edit, :update, :delete, :destroy].include?(action_name.to_sym)
@organization ||= params[:org_permalink] ? current_user.organizations_scope.find_by_permalink!(params[:org_permalink]) : nil
end
helper_method :organization
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/domains_controller.rb | app/controllers/domains_controller.rb | # frozen_string_literal: true
class DomainsController < ApplicationController
include WithinOrganization
before_action do
if params[:server_id]
@server = organization.servers.present.find_by_permalink!(params[:server_id])
params[:id] && @domain = @server.domains.find_by_uuid!(params[:id])
else
params[:id] && @domain = organization.domains.find_by_uuid!(params[:id])
end
end
def index
if @server
@domains = @server.domains.order(:name).to_a
else
@domains = organization.domains.order(:name).to_a
end
end
def new
@domain = @server ? @server.domains.build : organization.domains.build
end
def create
scope = @server ? @server.domains : organization.domains
@domain = scope.build(params.require(:domain).permit(:name, :verification_method))
if current_user.admin?
@domain.verification_method = "DNS"
@domain.verified_at = Time.now
end
if @domain.save
if @domain.verified?
redirect_to_with_json [:setup, organization, @server, @domain]
else
redirect_to_with_json [:verify, organization, @server, @domain]
end
else
render_form_errors "new", @domain
end
end
def destroy
@domain.destroy
redirect_to_with_json [organization, @server, :domains]
end
def verify
if @domain.verified?
redirect_to [organization, @server, :domains], alert: "#{@domain.name} has already been verified."
return
end
return unless request.post?
case @domain.verification_method
when "DNS"
if @domain.verify_with_dns
redirect_to_with_json [:setup, organization, @server, @domain], notice: "#{@domain.name} has been verified successfully. You now need to configure your DNS records."
else
respond_to do |wants|
wants.html { flash.now[:alert] = "We couldn't verify your domain. Please double check you've added the TXT record correctly." }
wants.json { render json: { flash: { alert: "We couldn't verify your domain. Please double check you've added the TXT record correctly." } } }
end
end
when "Email"
if params[:code]
if @domain.verification_token == params[:code].to_s.strip
@domain.mark_as_verified
redirect_to_with_json [:setup, organization, @server, @domain], notice: "#{@domain.name} has been verified successfully. You now need to configure your DNS records."
else
respond_to do |wants|
wants.html { flash.now[:alert] = "Invalid verification code. Please check and try again." }
wants.json { render json: { flash: { alert: "Invalid verification code. Please check and try again." } } }
end
end
elsif params[:email_address].present?
raise Postal::Error, "Invalid email address" unless @domain.verification_email_addresses.include?(params[:email_address])
AppMailer.verify_domain(@domain, params[:email_address], current_user).deliver
if @domain.owner.is_a?(Server)
redirect_to_with_json verify_organization_server_domain_path(organization, @server, @domain, email_address: params[:email_address])
else
redirect_to_with_json verify_organization_domain_path(organization, @domain, email_address: params[:email_address])
end
end
end
end
def setup
return if @domain.verified?
redirect_to [:verify, organization, @server, @domain], alert: "You can't set up DNS for this domain until it has been verified."
end
def check
if @domain.check_dns(:manual)
redirect_to_with_json [organization, @server, :domains], notice: "Your DNS records for #{@domain.name} look good!"
else
redirect_to_with_json [:setup, organization, @server, @domain], alert: "There seems to be something wrong with your DNS records. Check below for information."
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/http_endpoints_controller.rb | app/controllers/http_endpoints_controller.rb | # frozen_string_literal: true
class HTTPEndpointsController < ApplicationController
include WithinOrganization
before_action { @server = organization.servers.present.find_by_permalink!(params[:server_id]) }
before_action { params[:id] && @http_endpoint = @server.http_endpoints.find_by_uuid!(params[:id]) }
def index
@http_endpoints = @server.http_endpoints.order(:name).to_a
end
def new
@http_endpoint = @server.http_endpoints.build
end
def create
@http_endpoint = @server.http_endpoints.build(safe_params)
if @http_endpoint.save
flash[:notice] = params[:return_notice] if params[:return_notice].present?
redirect_to_with_json [:return_to, [organization, @server, :http_endpoints]]
else
render_form_errors "new", @http_endpoint
end
end
def update
if @http_endpoint.update(safe_params)
redirect_to_with_json [organization, @server, :http_endpoints]
else
render_form_errors "edit", @http_endpoint
end
end
def destroy
@http_endpoint.destroy
redirect_to_with_json [organization, @server, :http_endpoints]
end
private
def safe_params
params.require(:http_endpoint).permit(:name, :url, :encoding, :format, :strip_replies, :include_attachments, :timeout)
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/ip_pools_controller.rb | app/controllers/ip_pools_controller.rb | # frozen_string_literal: true
class IPPoolsController < ApplicationController
before_action :admin_required
before_action { params[:id] && @ip_pool = IPPool.find_by_uuid!(params[:id]) }
def index
@ip_pools = IPPool.order(:name).to_a
end
def new
@ip_pool = IPPool.new
end
def create
@ip_pool = IPPool.new(safe_params)
if @ip_pool.save
redirect_to_with_json [:edit, @ip_pool], notice: "IP Pool has been added successfully. You can now add IP addresses to it."
else
render_form_errors "new", @ip_pool
end
end
def update
if @ip_pool.update(safe_params)
redirect_to_with_json [:edit, @ip_pool], notice: "IP Pool has been updated."
else
render_form_errors "edit", @ip_pool
end
end
def destroy
@ip_pool.destroy
redirect_to_with_json :ip_pools, notice: "IP pool has been removed successfully."
rescue ActiveRecord::DeleteRestrictionError
redirect_to_with_json [:edit, @ip_pool], alert: "IP pool cannot be removed because it still has associated addresses or servers."
end
private
def safe_params
params.require(:ip_pool).permit(:name, :default)
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/ip_addresses_controller.rb | app/controllers/ip_addresses_controller.rb | # frozen_string_literal: true
class IPAddressesController < ApplicationController
before_action :admin_required
before_action { @ip_pool = IPPool.find_by_uuid!(params[:ip_pool_id]) }
before_action { params[:id] && @ip_address = @ip_pool.ip_addresses.find(params[:id]) }
def new
@ip_address = @ip_pool.ip_addresses.build
end
def create
@ip_address = @ip_pool.ip_addresses.build(safe_params)
if @ip_address.save
redirect_to_with_json [:edit, @ip_pool]
else
render_form_errors "new", @ip_address
end
end
def update
if @ip_address.update(safe_params)
redirect_to_with_json [:edit, @ip_pool]
else
render_form_errors "edit", @ip_address
end
end
def destroy
@ip_address.destroy
redirect_to_with_json [:edit, @ip_pool]
end
private
def safe_params
params.require(:ip_address).permit(:ipv4, :ipv6, :hostname, :priority)
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/routes_controller.rb | app/controllers/routes_controller.rb | # frozen_string_literal: true
class RoutesController < ApplicationController
include WithinOrganization
before_action { @server = organization.servers.present.find_by_permalink!(params[:server_id]) }
before_action { params[:id] && @route = @server.routes.find_by_uuid!(params[:id]) }
def index
@routes = @server.routes.order(:name).includes(:domain, :endpoint).to_a
end
def new
@route = @server.routes.build
end
def create
@route = @server.routes.build(safe_params)
if @route.save
redirect_to_with_json [organization, @server, :routes]
else
render_form_errors "new", @route
end
end
def update
if @route.update(safe_params)
redirect_to_with_json [organization, @server, :routes]
else
render_form_errors "edit", @route
end
end
def destroy
@route.destroy
redirect_to_with_json [organization, @server, :routes]
end
private
def safe_params
params.require(:route).permit(:name, :domain_id, :spam_mode, :_endpoint, additional_route_endpoints_array: [])
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/webhooks_controller.rb | app/controllers/webhooks_controller.rb | # frozen_string_literal: true
class WebhooksController < ApplicationController
include WithinOrganization
before_action { @server = organization.servers.present.find_by_permalink!(params[:server_id]) }
before_action { params[:id] && @webhook = @server.webhooks.find_by_uuid!(params[:id]) }
def index
@webhooks = @server.webhooks.order(:url).to_a
end
def new
@webhook = @server.webhooks.build(all_events: true)
end
def create
@webhook = @server.webhooks.build(safe_params)
if @webhook.save
redirect_to_with_json [organization, @server, :webhooks]
else
render_form_errors "new", @webhook
end
end
def update
if @webhook.update(safe_params)
redirect_to_with_json [organization, @server, :webhooks]
else
render_form_errors "edit", @webhook
end
end
def destroy
@webhook.destroy
redirect_to_with_json [organization, @server, :webhooks]
end
def history
@current_page = params[:page] ? params[:page].to_i : 1
@requests = @server.message_db.webhooks.list(@current_page)
end
def history_request
@req = @server.message_db.webhooks.find(params[:uuid])
end
private
def safe_params
params.require(:webhook).permit(:name, :url, :all_events, :enabled, events: [])
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/users_controller.rb | app/controllers/users_controller.rb | # frozen_string_literal: true
class UsersController < ApplicationController
before_action :admin_required
before_action { params[:id] && @user = User.find_by!(uuid: params[:id]) }
def index
@users = User.order(:first_name, :last_name).includes(:organization_users)
end
def new
@user = User.new(admin: true)
end
def edit
end
def create
@user = User.new(params.require(:user).permit(:email_address, :first_name, :last_name, :password, :password_confirmation, :admin, organization_ids: []))
if @user.save
redirect_to_with_json :users, notice: "#{@user.name} has been created successfully."
else
render_form_errors "new", @user
end
end
def update
@user.attributes = params.require(:user).permit(:email_address, :first_name, :last_name, :admin, organization_ids: [])
if @user == current_user && !@user.admin?
respond_to do |wants|
wants.html { redirect_to users_path, alert: "You cannot change your own admin status" }
wants.json { render json: { form_errors: ["You cannot change your own admin status"] }, status: :unprocessable_entity }
end
return
end
if @user.save
redirect_to_with_json :users, notice: "Permissions for #{@user.name} have been updated successfully."
else
render_form_errors "edit", @user
end
end
def destroy
if @user == current_user
redirect_to_with_json :users, alert: "You cannot delete your own user."
return
end
@user.destroy!
redirect_to_with_json :users, notice: "#{@user.name} has been removed"
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/servers_controller.rb | app/controllers/servers_controller.rb | # frozen_string_literal: true
class ServersController < ApplicationController
include WithinOrganization
before_action :admin_required, only: [:advanced, :suspend, :unsuspend]
before_action { params[:id] && @server = organization.servers.present.find_by_permalink!(params[:id]) }
def index
@servers = organization.servers.present.order(:name).to_a
end
def show
if @server.created_at < 48.hours.ago
@graph_type = :daily
graph_data = @server.message_db.statistics.get(:daily, [:incoming, :outgoing, :bounces], Time.now, 30)
elsif @server.created_at < 24.hours.ago
@graph_type = :hourly
graph_data = @server.message_db.statistics.get(:hourly, [:incoming, :outgoing, :bounces], Time.now, 48)
else
@graph_type = :hourly
graph_data = @server.message_db.statistics.get(:hourly, [:incoming, :outgoing, :bounces], Time.now, 24)
end
@first_date = graph_data.first.first
@last_date = graph_data.last.first
@graph_data = graph_data.map(&:last)
@messages = @server.message_db.messages(order: "id", direction: "desc", limit: 6)
end
def new
@server = organization.servers.build
end
def create
@server = organization.servers.build(safe_params(:permalink))
if @server.save
redirect_to_with_json organization_server_path(organization, @server)
else
render_form_errors "new", @server
end
end
def update
extra_params = [:spam_threshold, :spam_failure_threshold, :postmaster_address]
if current_user.admin?
extra_params += [
:send_limit,
:allow_sender,
:privacy_mode,
:log_smtp_data,
:outbound_spam_threshold,
:message_retention_days,
:raw_message_retention_days,
:raw_message_retention_size,
]
end
if @server.update(safe_params(*extra_params))
redirect_to_with_json organization_server_path(organization, @server), notice: "Server settings have been updated"
else
render_form_errors "edit", @server
end
end
def destroy
if params[:confirm_text].blank? || params[:confirm_text].downcase.strip != @server.name.downcase.strip
respond_to do |wants|
alert_text = "The text you entered does not match the server name. Please check and try again."
wants.html { redirect_to organization_delete_path(@organization), alert: alert_text }
wants.json { render json: { alert: alert_text } }
end
return
end
@server.soft_destroy
redirect_to_with_json organization_root_path(organization), notice: "#{@server.name} has been deleted successfully"
end
def queue
@messages = @server.queued_messages.order(id: :desc).page(params[:page]).includes(:ip_address)
@messages_with_message = @messages.include_message
end
def suspend
@server.suspend(params[:reason])
redirect_to_with_json [organization, @server], notice: "Server has been suspended"
end
def unsuspend
@server.unsuspend
redirect_to_with_json [organization, @server], notice: "Server has been unsuspended"
end
private
def safe_params(*extras)
params.require(:server).permit(:name, :mode, :ip_pool_id, *extras)
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/address_endpoints_controller.rb | app/controllers/address_endpoints_controller.rb | # frozen_string_literal: true
class AddressEndpointsController < ApplicationController
include WithinOrganization
before_action { @server = organization.servers.present.find_by_permalink!(params[:server_id]) }
before_action { params[:id] && @address_endpoint = @server.address_endpoints.find_by_uuid!(params[:id]) }
def index
@address_endpoints = @server.address_endpoints.order(:address).to_a
end
def new
@address_endpoint = @server.address_endpoints.build
end
def create
@address_endpoint = @server.address_endpoints.build(safe_params)
if @address_endpoint.save
flash[:notice] = params[:return_notice] if params[:return_notice].present?
redirect_to_with_json [:return_to, [organization, @server, :address_endpoints]]
else
render_form_errors "new", @address_endpoint
end
end
def update
if @address_endpoint.update(safe_params)
redirect_to_with_json [organization, @server, :address_endpoints]
else
render_form_errors "edit", @address_endpoint
end
end
def destroy
@address_endpoint.destroy
redirect_to_with_json [organization, @server, :address_endpoints]
end
private
def safe_params
params.require(:address_endpoint).permit(:address)
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/track_domains_controller.rb | app/controllers/track_domains_controller.rb | # frozen_string_literal: true
class TrackDomainsController < ApplicationController
include WithinOrganization
before_action { @server = organization.servers.present.find_by_permalink!(params[:server_id]) }
before_action { params[:id] && @track_domain = @server.track_domains.find_by_uuid!(params[:id]) }
def index
@track_domains = @server.track_domains.order(:name).to_a
end
def new
@track_domain = @server.track_domains.build
end
def create
@track_domain = @server.track_domains.build(params.require(:track_domain).permit(:name, :domain_id, :track_loads, :track_clicks, :excluded_click_domains, :ssl_enabled))
if @track_domain.save
redirect_to_with_json [:return_to, [organization, @server, :track_domains]]
else
render_form_errors "new", @track_domain
end
end
def update
if @track_domain.update(params.require(:track_domain).permit(:track_loads, :track_clicks, :excluded_click_domains, :ssl_enabled))
redirect_to_with_json [organization, @server, :track_domains]
else
render_form_errors "edit", @track_domain
end
end
def destroy
@track_domain.destroy
redirect_to_with_json [organization, @server, :track_domains]
end
def check
if @track_domain.check_dns
redirect_to_with_json [organization, @server, :track_domains], notice: "Your CNAME for #{@track_domain.full_name} looks good!"
else
redirect_to_with_json [organization, @server, :track_domains], alert: "There seems to be something wrong with your DNS record. Check documentation for information."
end
end
def toggle_ssl
@track_domain.update(ssl_enabled: !@track_domain.ssl_enabled)
redirect_to_with_json [organization, @server, :track_domains], notice: "SSL settings for #{@track_domain.full_name} updated successfully."
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/ip_pool_rules_controller.rb | app/controllers/ip_pool_rules_controller.rb | # frozen_string_literal: true
class IPPoolRulesController < ApplicationController
include WithinOrganization
before_action do
if params[:server_id]
@server = organization.servers.present.find_by_permalink!(params[:server_id])
params[:id] && @ip_pool_rule = @server.ip_pool_rules.find_by_uuid!(params[:id])
else
params[:id] && @ip_pool_rule = organization.ip_pool_rules.find_by_uuid!(params[:id])
end
end
def index
if @server
@ip_pool_rules = @server.ip_pool_rules
else
@ip_pool_rules = organization.ip_pool_rules
end
end
def new
@ip_pool_rule = @server ? @server.ip_pool_rules.build : organization.ip_pool_rules.build
end
def create
scope = @server ? @server.ip_pool_rules : organization.ip_pool_rules
@ip_pool_rule = scope.build(safe_params)
if @ip_pool_rule.save
redirect_to_with_json [organization, @server, :ip_pool_rules]
else
render_form_errors "new", @ip_pool_rule
end
end
def update
if @ip_pool_rule.update(safe_params)
redirect_to_with_json [organization, @server, :ip_pool_rules]
else
render_form_errors "edit", @ip_pool_rule
end
end
def destroy
@ip_pool_rule.destroy
redirect_to_with_json [organization, @server, :ip_pool_rules]
end
private
def safe_params
params.require(:ip_pool_rule).permit(:from_text, :to_text, :ip_pool_id)
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/organization_ip_pools_controller.rb | app/controllers/organization_ip_pools_controller.rb | # frozen_string_literal: true
class OrganizationIPPoolsController < ApplicationController
include WithinOrganization
before_action :admin_required, only: [:assignments]
def index
@ip_pools = organization.ip_pools.order(:name)
end
def assignments
organization.ip_pool_ids = params[:ip_pools]
organization.save!
redirect_to [organization, :ip_pools], notice: "Organization IP pools have been updated successfully"
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/messages_controller.rb | app/controllers/messages_controller.rb | # frozen_string_literal: true
class MessagesController < ApplicationController
include WithinOrganization
before_action { @server = organization.servers.present.find_by_permalink!(params[:server_id]) }
before_action { params[:id] && @message = @server.message_db.message(params[:id].to_i) }
def new
if params[:direction] == "incoming"
@message = IncomingMessagePrototype.new(@server, request.ip, "web-ui", {})
@message.from = session[:test_in_from] || current_user.email_tag
@message.to = @server.routes.order(:name).first&.description
else
@message = OutgoingMessagePrototype.new(@server, request.ip, "web-ui", {})
@message.to = session[:test_out_to] || current_user.email_address
if domain = @server.domains.verified.order(:name).first
@message.from = "test@#{domain.name}"
end
end
@message.subject = "Test Message at #{Time.zone.now.to_fs(:long)}"
@message.plain_body = "This is a message to test the delivery of messages through Postal."
end
def create
if params[:direction] == "incoming"
session[:test_in_from] = params[:message][:from] if params[:message]
@message = IncomingMessagePrototype.new(@server, request.ip, "web-ui", params[:message])
@message.attachments = [{ name: "test.txt", content_type: "text/plain", data: "Hello world!" }]
else
session[:test_out_to] = params[:message][:to] if params[:message]
@message = OutgoingMessagePrototype.new(@server, request.ip, "web-ui", params[:message])
end
if result = @message.create_messages
if result.size == 1
redirect_to_with_json organization_server_message_path(organization, @server, result.first.last[:id]), notice: "Message was queued successfully"
else
redirect_to_with_json [:queue, organization, @server], notice: "Messages queued successfully "
end
else
respond_to do |wants|
wants.html do
flash.now[:alert] = "Your message could not be sent. Ensure that all fields are completed fully. #{result.errors.inspect}"
render "new"
end
wants.json do
render json: { flash: { alert: "Your message could not be sent. Please check all field are completed fully." } }
end
end
end
end
def outgoing
@searchable = true
get_messages("outgoing")
respond_to do |wants|
wants.html
wants.json do
render json: {
flash: flash.each_with_object({}) { |(type, message), hash| hash[type] = message },
region_html: render_to_string(partial: "index", formats: [:html])
}
end
end
end
def incoming
@searchable = true
get_messages("incoming")
respond_to do |wants|
wants.html
wants.json do
render json: {
flash: flash.each_with_object({}) { |(type, message), hash| hash[type] = message },
region_html: render_to_string(partial: "index", formats: [:html])
}
end
end
end
def held
get_messages("held")
end
def deliveries
render json: { html: render_to_string(partial: "deliveries", locals: { message: @message }) }
end
def html_raw
render html: @message.html_body_without_tracking_image.html_safe
end
def spam_checks
@spam_checks = @message.spam_checks.sort_by { |s| s["score"] }.reverse
end
def attachment
if @message.attachments.size > params[:attachment].to_i
attachment = @message.attachments[params[:attachment].to_i]
send_data attachment.body, content_type: attachment.mime_type, disposition: "download", filename: attachment.filename
else
redirect_to attachments_organization_server_message_path(organization, @server, @message.id), alert: "Attachment not found. Choose an attachment from the list below."
end
end
def download
if @message.raw_message
send_data @message.raw_message, filename: "Message-#{organization.permalink}-#{@server.permalink}-#{@message.id}.eml", content_type: "text/plain"
else
redirect_to organization_server_message_path(organization, @server, @message.id), alert: "We no longer have the raw message stored for this message."
end
end
def retry
if @message.raw_message?
if @message.queued_message
@message.queued_message.retry_now
flash[:notice] = "This message will be retried shortly."
elsif @message.held?
@message.add_to_message_queue(manual: true)
flash[:notice] = "This message has been released. Delivery will be attempted shortly."
else
@message.add_to_message_queue(manual: true)
flash[:notice] = "This message will be redelivered shortly."
end
else
flash[:alert] = "This message is no longer available."
end
redirect_to_with_json organization_server_message_path(organization, @server, @message.id)
end
def cancel_hold
@message.cancel_hold
redirect_to_with_json organization_server_message_path(organization, @server, @message.id)
end
def remove_from_queue
if @message.queued_message && !@message.queued_message.locked?
@message.queued_message.destroy
end
redirect_to_with_json organization_server_message_path(organization, @server, @message.id)
end
def suppressions
@suppressions = @server.message_db.suppression_list.all_with_pagination(params[:page])
end
def activity
@entries = @message.activity_entries
end
private
def get_messages(scope)
if scope == "held"
options = { where: { held: true } }
else
options = { where: { scope: scope, spam: false }, order: :timestamp, direction: "desc" }
if @query = (params[:query] || session["msg_query_#{@server.id}_#{scope}"]).presence
session["msg_query_#{@server.id}_#{scope}"] = @query
qs = QueryString.new(@query)
if qs.empty?
flash.now[:alert] = "It doesn't appear you entered anything to filter on. Please double check your query."
else
@queried = true
if qs[:order] == "oldest-first"
options[:direction] = "asc"
end
options[:where][:rcpt_to] = qs[:to] if qs[:to]
options[:where][:mail_from] = qs[:from] if qs[:from]
options[:where][:status] = qs[:status] if qs[:status]
options[:where][:token] = qs[:token] if qs[:token]
if qs[:msgid]
options[:where][:message_id] = qs[:msgid]
options[:where].delete(:spam)
options[:where].delete(:scope)
end
options[:where][:tag] = qs[:tag] if qs[:tag]
options[:where][:id] = qs[:id] if qs[:id]
options[:where][:spam] = true if qs[:spam] == "yes" || qs[:spam] == "y"
if qs[:before] || qs[:after]
options[:where][:timestamp] = {}
if qs[:before]
begin
options[:where][:timestamp][:less_than] = get_time_from_string(qs[:before]).to_f
rescue TimeUndetermined
flash.now[:alert] = "Couldn't determine time for before from '#{qs[:before]}'"
end
end
if qs[:after]
begin
options[:where][:timestamp][:greater_than] = get_time_from_string(qs[:after]).to_f
rescue TimeUndetermined
flash.now[:alert] = "Couldn't determine time for after from '#{qs[:after]}'"
end
end
end
end
else
session["msg_query_#{@server.id}_#{scope}"] = nil
end
end
@messages = @server.message_db.messages_with_pagination(params[:page], options)
end
class TimeUndetermined < Postal::Error; end
def get_time_from_string(string)
begin
if string =~ /\A(\d{2,4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})\z/
time = Time.new(::Regexp.last_match(1).to_i, ::Regexp.last_match(2).to_i, ::Regexp.last_match(3).to_i, ::Regexp.last_match(4).to_i, ::Regexp.last_match(5).to_i)
elsif string =~ /\A(\d{2,4})-(\d{2})-(\d{2})\z/
time = Time.new(::Regexp.last_match(1).to_i, ::Regexp.last_match(2).to_i, ::Regexp.last_match(3).to_i, 0)
else
time = Chronic.parse(string, context: :past)
end
rescue StandardError
time = nil
end
raise TimeUndetermined, "Couldn't determine a suitable time from '#{string}'" if time.nil?
time
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/well_known_controller.rb | app/controllers/well_known_controller.rb | # frozen_string_literal: true
class WellKnownController < ApplicationController
layout false
skip_before_action :set_browser_id
skip_before_action :login_required
skip_before_action :set_timezone
def jwks
render json: JWT::JWK::Set.new(Postal.signer.jwk).export.to_json
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/user_controller.rb | app/controllers/user_controller.rb | # frozen_string_literal: true
class UserController < ApplicationController
skip_before_action :login_required, only: [:new, :create, :join]
def new
@user_invite = UserInvite.active.find_by!(uuid: params[:invite_token])
@user = User.new
@user.email_address = @user_invite.email_address
render layout: "sub"
end
def edit
@user = User.find(current_user.id)
end
def create
@user_invite = UserInvite.active.find_by!(uuid: params[:invite_token])
@user = User.new(params.require(:user).permit(:first_name, :last_name, :email_address, :password, :password_confirmation))
@user.email_verified_at = Time.now
if @user.save
@user_invite.accept(@user)
self.current_user = @user
redirect_to root_path
else
render "new", layout: "sub"
end
end
def update
@user = User.find(current_user.id)
safe_params = [:first_name, :last_name, :time_zone, :email_address]
if @user.password? && Postal::Config.oidc.local_authentication_enabled?
safe_params += [:password, :password_confirmation]
if @user.authenticate_with_previous_password_first(params[:password])
@password_correct = true
else
respond_to do |wants|
wants.html do
flash.now[:alert] = "The current password you have entered is incorrect. Please check and try again."
render "edit"
end
wants.json do
render json: { alert: "The current password you've entered is incorrect. Please check and try again" }
end
end
return
end
end
@user.attributes = params.require(:user).permit(safe_params)
if @user.save
redirect_to_with_json settings_path, notice: "Your settings have been updated successfully."
else
render_form_errors "edit", @user
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/sessions_controller.rb | app/controllers/sessions_controller.rb | # frozen_string_literal: true
class SessionsController < ApplicationController
layout "sub"
before_action :require_local_authentication, only: [:create, :begin_password_reset, :finish_password_reset]
skip_before_action :login_required, only: [:new, :create, :begin_password_reset, :finish_password_reset, :ip, :raise_error, :create_from_oidc, :oauth_failure]
def create
login(User.authenticate(params[:email_address], params[:password]))
flash[:remember_login] = true
redirect_to_with_return_to root_path
rescue Postal::Errors::AuthenticationError
flash.now[:alert] = "The credentials you've provided are incorrect. Please check and try again."
render "new"
end
def destroy
auth_session.invalidate! if logged_in?
reset_session
redirect_to login_path
end
def persist
auth_session.persist! if logged_in?
render plain: "OK"
end
def begin_password_reset
return unless request.post?
user_scope = Postal::Config.oidc.enabled? ? User.with_password : User
user = user_scope.find_by(email_address: params[:email_address])
if user.nil?
redirect_to login_reset_path(return_to: params[:return_to]), alert: "No local user exists with that e-mail address. Please check and try again."
return
end
user.begin_password_reset(params[:return_to])
redirect_to login_path(return_to: params[:return_to]), notice: "Please check your e-mail and click the link in the e-mail we've sent you."
end
def finish_password_reset
@user = User.where(password_reset_token: params[:token]).where("password_reset_token_valid_until > ?", Time.now).first
if @user.nil?
redirect_to login_path(return_to: params[:return_to]), alert: "This link has expired or never existed. Please choose reset password to try again."
end
return unless request.post?
if params[:password].blank?
flash.now[:alert] = "You must enter a new password"
return
end
@user.password = params[:password]
@user.password_confirmation = params[:password_confirmation]
return unless @user.save
login(@user)
redirect_to_with_return_to root_path, notice: "Your new password has been set and you've been logged in."
end
def ip
render plain: "ip: #{request.ip} remote ip: #{request.remote_ip}"
end
def create_from_oidc
unless Postal::Config.oidc.enabled?
raise Postal::Error, "OIDC cannot be used unless enabled in the configuration"
end
auth = request.env["omniauth.auth"]
user = User.find_from_oidc(auth.extra.raw_info, logger: Postal.logger)
if user.nil?
redirect_to login_path, alert: "No user was found matching your identity. Please contact your administrator."
return
end
login(user)
flash[:remember_login] = true
redirect_to_with_return_to root_path
end
def oauth_failure
redirect_to login_path, alert: "An issue occurred while logging you in with OpenID. Please try again later or contact your administrator."
end
private
def require_local_authentication
return if Postal::Config.oidc.local_authentication_enabled?
redirect_to login_path, alert: "Local authentication is not enabled"
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/application_controller.rb | app/controllers/application_controller.rb | # frozen_string_literal: true
require "authie/session"
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :login_required
before_action :set_timezone
rescue_from Authie::Session::InactiveSession, with: :auth_session_error
rescue_from Authie::Session::ExpiredSession, with: :auth_session_error
rescue_from Authie::Session::BrowserMismatch, with: :auth_session_error
private
def login_required
return if logged_in?
redirect_to login_path(return_to: request.fullpath)
end
def admin_required
if logged_in?
unless current_user.admin?
render plain: "Not permitted"
end
else
redirect_to login_path(return_to: request.fullpath)
end
end
def require_organization_owner
return if organization.owner == current_user
redirect_to organization_root_path(organization), alert: "This page can only be accessed by the organization's owner (#{organization.owner.name})"
end
def auth_session_error(exception)
Rails.logger.info "AuthSessionError: #{exception.class}: #{exception.message}"
redirect_to login_path(return_to: request.fullpath)
end
def page_title
@page_title ||= ["Postal"]
end
helper_method :page_title
def redirect_to_with_return_to(url, *args)
redirect_to url_with_return_to(url), *args
end
def set_timezone
Time.zone = logged_in? ? current_user.time_zone : "UTC"
end
def append_info_to_payload(payload)
super
payload[:ip] = request.ip
payload[:user] = logged_in? ? current_user.id : nil
end
def url_with_return_to(url)
if params[:return_to].blank? || !params[:return_to].starts_with?("/")
url_for(url)
else
params[:return_to]
end
end
def redirect_to_with_json(url, flash_messages = {})
if url.is_a?(Array) && url[0] == :return_to
url = url_with_return_to(url[1])
else
url = url_for(url)
end
flash_messages.each do |key, value|
flash[key] = value
end
respond_to do |wants|
wants.html { redirect_to url }
wants.json { render json: { redirect_to: url } }
end
end
def render_form_errors(action_name, object)
respond_to do |wants|
wants.html { render action_name }
wants.json { render json: { form_errors: object.errors.map(&:full_message) }, status: :unprocessable_entity }
end
end
def flash_now(type, message, options = {})
respond_to do |wants|
wants.html do
flash.now[type] = message
if options[:render_action]
render options[:render_action]
end
end
wants.json { render json: { flash: { type => message } } }
end
end
def login(user)
if logged_in?
auth_session.invalidate!
reset_session
end
create_auth_session(user)
@current_user = user
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/smtp_endpoints_controller.rb | app/controllers/smtp_endpoints_controller.rb | # frozen_string_literal: true
class SMTPEndpointsController < ApplicationController
include WithinOrganization
before_action { @server = organization.servers.present.find_by_permalink!(params[:server_id]) }
before_action { params[:id] && @smtp_endpoint = @server.smtp_endpoints.find_by_uuid!(params[:id]) }
def index
@smtp_endpoints = @server.smtp_endpoints.order(:name).to_a
end
def new
@smtp_endpoint = @server.smtp_endpoints.build
end
def create
@smtp_endpoint = @server.smtp_endpoints.build(safe_params)
if @smtp_endpoint.save
flash[:notice] = params[:return_notice] if params[:return_notice].present?
redirect_to_with_json [:return_to, [organization, @server, :smtp_endpoints]]
else
render_form_errors "new", @smtp_endpoint
end
end
def update
if @smtp_endpoint.update(safe_params)
redirect_to_with_json [organization, @server, :smtp_endpoints]
else
render_form_errors "edit", @smtp_endpoint
end
end
def destroy
@smtp_endpoint.destroy
redirect_to_with_json [organization, @server, :smtp_endpoints]
end
private
def safe_params
params.require(:smtp_endpoint).permit(:name, :hostname, :port, :ssl_mode)
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/concerns/within_organization.rb | app/controllers/concerns/within_organization.rb | # frozen_string_literal: true
module WithinOrganization
extend ActiveSupport::Concern
included do
helper_method :organization
before_action :add_organization_to_page_title
end
private
def organization
@organization ||= current_user.organizations_scope.find_by_permalink!(params[:org_permalink])
end
def add_organization_to_page_title
page_title << organization.name
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/legacy_api/send_controller.rb | app/controllers/legacy_api/send_controller.rb | # frozen_string_literal: true
module LegacyAPI
class SendController < BaseController
ERROR_MESSAGES = {
"NoRecipients" => "There are no recipients defined to receive this message",
"NoContent" => "There is no content defined for this e-mail",
"TooManyToAddresses" => "The maximum number of To addresses has been reached (maximum 50)",
"TooManyCCAddresses" => "The maximum number of CC addresses has been reached (maximum 50)",
"TooManyBCCAddresses" => "The maximum number of BCC addresses has been reached (maximum 50)",
"FromAddressMissing" => "The From address is missing and is required",
"UnauthenticatedFromAddress" => "The From address is not authorised to send mail from this server",
"AttachmentMissingName" => "An attachment is missing a name",
"AttachmentMissingData" => "An attachment is missing data"
}.freeze
# Send a message with the given options
#
# URL: /api/v1/send/message
#
# Parameters: to => REQ: An array of emails addresses
# cc => An array of email addresses to CC
# bcc => An array of email addresses to BCC
# from => The name/email to send the email from
# sender => The name/email of the 'Sender'
# reply_to => The name/email of the 'Reply-to'
# plain_body => The plain body
# html_body => The HTML body
# bounce => Is this message a bounce?
# tag => A custom tag to add to the message
# custom_headers => A hash of custom headers
# attachments => An array of attachments
# (name, content_type and data (base64))
#
# Response: A array of hashes containing message information
# OR an error if there is an issue sending the message
#
def message
attributes = {}
attributes[:to] = api_params["to"]
attributes[:cc] = api_params["cc"]
attributes[:bcc] = api_params["bcc"]
attributes[:from] = api_params["from"]
attributes[:sender] = api_params["sender"]
attributes[:subject] = api_params["subject"]
attributes[:reply_to] = api_params["reply_to"]
attributes[:plain_body] = api_params["plain_body"]
attributes[:html_body] = api_params["html_body"]
attributes[:bounce] = api_params["bounce"] ? true : false
attributes[:tag] = api_params["tag"]
attributes[:custom_headers] = api_params["headers"] if api_params["headers"]
attributes[:attachments] = []
(api_params["attachments"] || []).each do |attachment|
next unless attachment.is_a?(Hash)
attributes[:attachments] << { name: attachment["name"], content_type: attachment["content_type"], data: attachment["data"], base64: true }
end
message = OutgoingMessagePrototype.new(@current_credential.server, request.ip, "api", attributes)
message.credential = @current_credential
if message.valid?
result = message.create_messages
render_success message_id: message.message_id, messages: result
else
render_error message.errors.first, message: ERROR_MESSAGES[message.errors.first]
end
end
# Send a message by providing a raw message
#
# URL: /api/v1/send/raw
#
# Parameters: rcpt_to => REQ: An array of email addresses to send
# the message to
# mail_from => REQ: the address to send the email from
# data => REQ: base64-encoded mail data
#
# Response: A array of hashes containing message information
# OR an error if there is an issue sending the message
#
def raw
unless api_params["rcpt_to"].is_a?(Array)
render_parameter_error "`rcpt_to` parameter is required but is missing"
return
end
if api_params["mail_from"].blank?
render_parameter_error "`mail_from` parameter is required but is missing"
return
end
if api_params["data"].blank?
render_parameter_error "`data` parameter is required but is missing"
return
end
# Decode the raw message
raw_message = Base64.decode64(api_params["data"])
# Parse through mail to get the from/sender headers
mail = Mail.new(raw_message.split("\r\n\r\n", 2).first)
from_headers = { "from" => mail.from, "sender" => mail.sender }
authenticated_domain = @current_credential.server.find_authenticated_domain_from_headers(from_headers)
# If we're not authenticated, don't continue
if authenticated_domain.nil?
render_error "UnauthenticatedFromAddress"
return
end
# Store the result ready to return
result = { message_id: nil, messages: {} }
if api_params["rcpt_to"].is_a?(Array)
api_params["rcpt_to"].uniq.each do |rcpt_to|
message = @current_credential.server.message_db.new_message
message.rcpt_to = rcpt_to
message.mail_from = api_params["mail_from"]
message.raw_message = raw_message
message.received_with_ssl = true
message.scope = "outgoing"
message.domain_id = authenticated_domain.id
message.credential_id = @current_credential.id
message.bounce = api_params["bounce"] ? true : false
message.save
result[:message_id] = message.message_id if result[:message_id].nil?
result[:messages][rcpt_to] = { id: message.id, token: message.token }
end
end
render_success result
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/legacy_api/base_controller.rb | app/controllers/legacy_api/base_controller.rb | # frozen_string_literal: true
module LegacyAPI
# The Legacy API is the Postal v1 API which existed from the start with main
# aim of allowing e-mails to sent over HTTP rather than SMTP. The API itself
# did not feature much functionality. This API was implemented using Moonrope
# which was a self documenting API tool, however, is now no longer maintained.
# In light of that, these controllers now implement the same functionality as
# the original Moonrope API without the actual requirement to use any of the
# Moonrope components.
#
# Important things to note about the API:
#
# * Moonrope allow params to be provided as JSON in the body of the request
# along with the application/json content type. It also allowed for params
# to be sent in the 'params' parameter when using the
# application/x-www-form-urlencoded content type. Both methods are supported.
#
# * Authentication is performed using a X-Server-API-Key variable.
#
# * The method used to make the request is not important. Most clients use POST
# but other methods should be supported. The routing for this legacvy
# API supports GET, POST, PUT and PATCH.
#
# * The status code for responses will always be 200 OK. The actual status of
# a request is determined by the value of the 'status' attribute in the
# returned JSON.
class BaseController < ActionController::Base
skip_before_action :set_browser_id
skip_before_action :verify_authenticity_token
before_action :start_timer
before_action :authenticate_as_server
private
# The Moonrope API spec allows for parameters to be provided in the body
# along with the application/json content type or they can be provided,
# as JSON, in the 'params' parameter when used with the
# application/x-www-form-urlencoded content type. This legacy API needs
# support both options for maximum compatibility.
#
# @return [Hash]
def api_params
if request.headers["content-type"] =~ /\Aapplication\/json/
return params.to_unsafe_hash
end
if params["params"].present?
return JSON.parse(params["params"])
end
{}
end
# The API returns a length of time to complete a request. We'll start
# a timer when the request starts and then use this method to calculate
# the time taken to complete the request.
#
# @return [void]
def start_timer
@start_time = Time.now.to_f
end
# The only method available to authenticate to the legacy API is using a
# credential from the server itself. This method will attempt to find
# that credential from the X-Server-API-Key header and will set the
# current_credential instance variable if a token is valid. Otherwise it
# will render an error to halt execution.
#
# @return [void]
def authenticate_as_server
key = request.headers["X-Server-API-Key"]
if key.blank?
render_error "AccessDenied",
message: "Must be authenticated as a server."
return
end
credential = Credential.where(type: "API", key: key).first
if credential.nil?
render_error "InvalidServerAPIKey",
message: "The API token provided in X-Server-API-Key was not valid.",
token: key
return
end
if credential.server.suspended?
render_error "ServerSuspended"
return
end
credential.use
@current_credential = credential
end
# Render a successful response to the client
#
# @param [Hash] data
# @return [void]
def render_success(data)
render json: { status: "success",
time: (Time.now.to_f - @start_time).round(3),
flags: {},
data: data }
end
# Render an error response to the client
#
# @param [String] code
# @param [Hash] data
# @return [void]
def render_error(code, data = {})
render json: { status: "error",
time: (Time.now.to_f - @start_time).round(3),
flags: {},
data: data.merge(code: code) }
end
# Render a parameter error response to the client
#
# @param [String] message
# @return [void]
def render_parameter_error(message)
render json: { status: "parameter-error",
time: (Time.now.to_f - @start_time).round(3),
flags: {},
data: { message: message } }
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/controllers/legacy_api/messages_controller.rb | app/controllers/legacy_api/messages_controller.rb | # frozen_string_literal: true
module LegacyAPI
class MessagesController < BaseController
# Returns details about a given message
#
# URL: /api/v1/messages/message
#
# Parameters: id => REQ: The ID of the message
# _expansions => An array of types of details t
# to return
#
# Response: A hash containing message information
# OR an error if the message does not exist.
#
def message
if api_params["id"].blank?
render_parameter_error "`id` parameter is required but is missing"
return
end
message = @current_credential.server.message(api_params["id"])
message_hash = { id: message.id, token: message.token }
expansions = api_params["_expansions"]
if expansions == true || (expansions.is_a?(Array) && expansions.include?("status"))
message_hash[:status] = {
status: message.status,
last_delivery_attempt: message.last_delivery_attempt&.to_f,
held: message.held,
hold_expiry: message.hold_expiry&.to_f
}
end
if expansions == true || (expansions.is_a?(Array) && expansions.include?("details"))
message_hash[:details] = {
rcpt_to: message.rcpt_to,
mail_from: message.mail_from,
subject: message.subject,
message_id: message.message_id,
timestamp: message.timestamp.to_f,
direction: message.scope,
size: message.size,
bounce: message.bounce,
bounce_for_id: message.bounce_for_id,
tag: message.tag,
received_with_ssl: message.received_with_ssl
}
end
if expansions == true || (expansions.is_a?(Array) && expansions.include?("inspection"))
message_hash[:inspection] = {
inspected: message.inspected,
spam: message.spam,
spam_score: message.spam_score.to_f,
threat: message.threat,
threat_details: message.threat_details
}
end
if expansions == true || (expansions.is_a?(Array) && expansions.include?("plain_body"))
message_hash[:plain_body] = message.plain_body
end
if expansions == true || (expansions.is_a?(Array) && expansions.include?("html_body"))
message_hash[:html_body] = message.html_body
end
if expansions == true || (expansions.is_a?(Array) && expansions.include?("attachments"))
message_hash[:attachments] = message.attachments.map do |attachment|
{
filename: attachment.filename.to_s,
content_type: attachment.mime_type,
data: Base64.encode64(attachment.body.to_s),
size: attachment.body.to_s.bytesize,
hash: Digest::SHA1.hexdigest(attachment.body.to_s)
}
end
end
if expansions == true || (expansions.is_a?(Array) && expansions.include?("headers"))
message_hash[:headers] = message.headers
end
if expansions == true || (expansions.is_a?(Array) && expansions.include?("raw_message"))
message_hash[:raw_message] = Base64.encode64(message.raw_message)
end
if expansions == true || (expansions.is_a?(Array) && expansions.include?("activity_entries"))
message_hash[:activity_entries] = {
loads: message.loads,
clicks: message.clicks
}
end
render_success message_hash
rescue Postal::MessageDB::Message::NotFound
render_error "MessageNotFound",
message: "No message found matching provided ID",
id: api_params["id"]
end
# Returns all the deliveries for a given message
#
# URL: /api/v1/messages/deliveries
#
# Parameters: id => REQ: The ID of the message
#
# Response: A array of hashes containing delivery information
# OR an error if the message does not exist.
#
def deliveries
if api_params["id"].blank?
render_parameter_error "`id` parameter is required but is missing"
return
end
message = @current_credential.server.message(api_params["id"])
deliveries = message.deliveries.map do |d|
{
id: d.id,
status: d.status,
details: d.details,
output: d.output&.strip,
sent_with_ssl: d.sent_with_ssl,
log_id: d.log_id,
time: d.time&.to_f,
timestamp: d.timestamp.to_f
}
end
render_success deliveries
rescue Postal::MessageDB::Message::NotFound
render_error "MessageNotFound",
message: "No message found matching provided ID",
id: api_params["id"]
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/track_domain.rb | app/models/track_domain.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: track_domains
#
# id :integer not null, primary key
# uuid :string(255)
# server_id :integer
# domain_id :integer
# name :string(255)
# dns_checked_at :datetime
# dns_status :string(255)
# dns_error :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# ssl_enabled :boolean default(TRUE)
# track_clicks :boolean default(TRUE)
# track_loads :boolean default(TRUE)
# excluded_click_domains :text(65535)
#
require "resolv"
class TrackDomain < ApplicationRecord
include HasUUID
belongs_to :server
belongs_to :domain
validates :name, presence: true, format: { with: /\A[a-z0-9-]+\z/ }, uniqueness: { scope: :domain_id, case_sensitive: false, message: "is already added" }
validates :domain_id, uniqueness: { scope: :server_id, case_sensitive: false, message: "already has a track domain for this server" }
validate :validate_domain_belongs_to_server
scope :ok, -> { where(dns_status: "OK") }
after_create :check_dns, unless: :dns_status
before_validation do
self.server = domain.server if domain && server.nil?
end
def full_name
"#{name}.#{domain.name}"
end
def excluded_click_domains_array
@excluded_click_domains_array ||= excluded_click_domains ? excluded_click_domains.split("\n").map(&:strip) : []
end
def dns_ok?
dns_status == "OK"
end
def check_dns
records = domain.resolver.cname(full_name)
if records.empty?
self.dns_status = "Missing"
self.dns_error = "There is no record at #{full_name}"
elsif records.size == 1 && records.first == Postal::Config.dns.track_domain
self.dns_status = "OK"
self.dns_error = nil
else
self.dns_status = "Invalid"
self.dns_error = "There is a CNAME record at #{full_name} but it points to #{records.first} which is incorrect. It should point to #{Postal::Config.dns.track_domain}."
end
self.dns_checked_at = Time.now
save!
dns_ok?
end
def use_ssl?
ssl_enabled?
end
def validate_domain_belongs_to_server
return unless domain && ![server, server.organization].include?(domain.owner)
errors.add :domain, "does not belong to the server or the server's organization"
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/address_endpoint.rb | app/models/address_endpoint.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: address_endpoints
#
# id :integer not null, primary key
# server_id :integer
# uuid :string(255)
# address :string(255)
# last_used_at :datetime
# created_at :datetime not null
# updated_at :datetime not null
#
class AddressEndpoint < ApplicationRecord
include HasUUID
belongs_to :server
has_many :routes, as: :endpoint
has_many :additional_route_endpoints, dependent: :destroy, as: :endpoint
validates :address, presence: true, format: { with: /@/ }, uniqueness: { scope: [:server_id], message: "has already been added", case_sensitive: false }
before_destroy :update_routes
def mark_as_used
update_column(:last_used_at, Time.now)
end
def update_routes
routes.each { |r| r.update(endpoint: nil, mode: "Reject") }
end
def description
address
end
def domain
address.split("@", 2).last
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/organization_ip_pool.rb | app/models/organization_ip_pool.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: organization_ip_pools
#
# id :integer not null, primary key
# organization_id :integer
# ip_pool_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class OrganizationIPPool < ApplicationRecord
belongs_to :organization
belongs_to :ip_pool
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/statistic.rb | app/models/statistic.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: statistics
#
# id :integer not null, primary key
# total_incoming :bigint default(0)
# total_messages :bigint default(0)
# total_outgoing :bigint default(0)
#
class Statistic < ApplicationRecord
def self.global
Statistic.first || Statistic.create
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/ip_pool.rb | app/models/ip_pool.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: ip_pools
#
# id :integer not null, primary key
# name :string(255)
# uuid :string(255)
# created_at :datetime
# updated_at :datetime
# default :boolean default(FALSE)
#
# Indexes
#
# index_ip_pools_on_uuid (uuid)
#
class IPPool < ApplicationRecord
include HasUUID
validates :name, presence: true
has_many :ip_addresses, dependent: :restrict_with_exception
has_many :servers, dependent: :restrict_with_exception
has_many :organization_ip_pools, dependent: :destroy
has_many :organizations, through: :organization_ip_pools
has_many :ip_pool_rules, dependent: :destroy
def self.default
where(default: true).order(:id).first
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/queued_message.rb | app/models/queued_message.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: queued_messages
#
# id :integer not null, primary key
# server_id :integer
# message_id :integer
# domain :string(255)
# locked_by :string(255)
# locked_at :datetime
# retry_after :datetime
# created_at :datetime
# updated_at :datetime
# ip_address_id :integer
# attempts :integer default(0)
# route_id :integer
# manual :boolean default(FALSE)
# batch_key :string(255)
#
# Indexes
#
# index_queued_messages_on_domain (domain)
# index_queued_messages_on_message_id (message_id)
# index_queued_messages_on_server_id (server_id)
#
class QueuedMessage < ApplicationRecord
include HasMessage
include HasLocking
belongs_to :server
belongs_to :ip_address, optional: true
before_create :allocate_ip_address
scope :ready_with_delayed_retry, -> { where("retry_after IS NULL OR retry_after < ?", 30.seconds.ago) }
scope :with_stale_lock, -> { where("locked_at IS NOT NULL AND locked_at < ?", Postal::Config.postal.queued_message_lock_stale_days.days.ago) }
def retry_now
update!(retry_after: nil)
end
def send_bounce
return unless message.send_bounces?
BounceMessage.new(server, message).queue
end
def allocate_ip_address
return unless Postal.ip_pools?
return if message.nil?
pool = server.ip_pool_for_message(message)
return if pool.nil?
self.ip_address = pool.ip_addresses.select_by_priority
end
def batchable_messages(limit = 10)
unless locked?
raise Postal::Error, "Must lock current message before locking any friends"
end
if batch_key.nil?
[]
else
time = Time.now
locker = Postal.locker_name
self.class.ready.where(batch_key: batch_key, ip_address_id: ip_address_id, locked_by: nil, locked_at: nil).limit(limit).update_all(locked_by: locker, locked_at: time)
QueuedMessage.where(batch_key: batch_key, ip_address_id: ip_address_id, locked_by: locker, locked_at: time).where.not(id: id)
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/worker_role.rb | app/models/worker_role.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: worker_roles
#
# id :bigint not null, primary key
# acquired_at :datetime
# role :string(255)
# worker :string(255)
#
# Indexes
#
# index_worker_roles_on_role (role) UNIQUE
#
class WorkerRole < ApplicationRecord
class << self
# Acquire or renew a lock for the given role.
#
# @param role [String] The name of the role to acquire
# @return [Symbol, false] True if the lock was acquired or renewed, false otherwise
def acquire(role)
# update our existing lock if we already have one
updates = where(role: role, worker: Postal.locker_name).update_all(acquired_at: Time.current)
return :renewed if updates.positive?
# attempt to steal a role from another worker
updates = where(role: role).where("acquired_at is null OR acquired_at < ?", 5.minutes.ago)
.update_all(acquired_at: Time.current, worker: Postal.locker_name)
return :stolen if updates.positive?
# attempt to create a new role for this worker
begin
create!(role: role, worker: Postal.locker_name, acquired_at: Time.current)
:created
rescue ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid
false
end
end
# Release a lock for the given role for the current process.
#
# @param role [String] The name of the role to release
# @return [Boolean] True if the lock was released, false otherwise
def release(role)
updates = where(role: role, worker: Postal.locker_name).delete_all
updates.positive?
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/organization_user.rb | app/models/organization_user.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: organization_users
#
# id :integer not null, primary key
# organization_id :integer
# user_id :integer
# created_at :datetime
# admin :boolean default(FALSE)
# all_servers :boolean default(TRUE)
# user_type :string(255)
#
class OrganizationUser < ApplicationRecord
belongs_to :organization
belongs_to :user, polymorphic: true, optional: true
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/ip_pool_rule.rb | app/models/ip_pool_rule.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: ip_pool_rules
#
# id :integer not null, primary key
# uuid :string(255)
# owner_type :string(255)
# owner_id :integer
# ip_pool_id :integer
# from_text :text(65535)
# to_text :text(65535)
# created_at :datetime not null
# updated_at :datetime not null
#
class IPPoolRule < ApplicationRecord
include HasUUID
belongs_to :owner, polymorphic: true
belongs_to :ip_pool
validate :validate_from_and_to_addresses
validate :validate_ip_pool_belongs_to_organization
def from
from_text ? from_text.gsub(/\r/, "").split(/\n/).map(&:strip) : []
end
def to
to_text ? to_text.gsub(/\r/, "").split(/\n/).map(&:strip) : []
end
def apply_to_message?(message)
if from.present? && message.headers["from"].present?
from.each do |condition|
if message.headers["from"].any? { |f| self.class.address_matches?(condition, f) }
return true
end
end
end
if to.present? && message.rcpt_to.present?
to.each do |condition|
if self.class.address_matches?(condition, message.rcpt_to)
return true
end
end
end
false
end
private
def validate_from_and_to_addresses
return unless from.empty? && to.empty?
errors.add :base, "At least one rule condition must be specified"
end
def validate_ip_pool_belongs_to_organization
org = owner.is_a?(Organization) ? owner : owner.organization
return unless ip_pool && ip_pool_id_changed? && !org.ip_pools.include?(ip_pool)
errors.add :ip_pool_id, "must belong to the organization"
end
class << self
def address_matches?(condition, address)
address = Postal::Helpers.strip_name_from_address(address)
if condition =~ /@/
parts = address.split("@")
domain = parts.pop
uname = parts.join("@")
uname, = uname.split("+", 2)
condition == "#{uname}@#{domain}"
else
# Match as a domain
condition == address.split("@").last
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/bounce_message.rb | app/models/bounce_message.rb | # frozen_string_literal: true
class BounceMessage
def initialize(server, message)
@server = server
@message = message
end
def raw_message
mail = Mail.new
mail.to = @message.mail_from
mail.from = "Mail Delivery Service <#{@message.route.description}>"
mail.subject = "Mail Delivery Failed (#{@message.subject})"
mail.text_part = body
mail.attachments["Original Message.eml"] = { mime_type: "message/rfc822", encoding: "quoted-printable", content: @message.raw_message }
mail.message_id = "<#{SecureRandom.uuid}@#{Postal::Config.dns.return_path_domain}>"
mail.to_s
end
def queue
message = @server.message_db.new_message
message.scope = "outgoing"
message.rcpt_to = @message.mail_from
message.mail_from = @message.route.description
message.domain_id = @message.domain&.id
message.raw_message = raw_message
message.bounce = true
message.bounce_for_id = @message.id
message.save
message.id
end
def postmaster_address
@server.postmaster_address || "postmaster@#{@message.domain&.name || Postal::Config.postal.web_hostname}"
end
private
def body
<<~BODY
This is the mail delivery service responsible for delivering mail to #{@message.route.description}.
The message you've sent cannot be delivered. Your original message is attached to this message.
For further assistance please contact #{postmaster_address}. Please include the details below to help us identify the issue.
Message Token: #{@message.token}@#{@server.token}
Orginal Message ID: #{@message.message_id}
Mail from: #{@message.mail_from}
Rcpt To: #{@message.rcpt_to}
BODY
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/outgoing_message_prototype.rb | app/models/outgoing_message_prototype.rb | # frozen_string_literal: true
require "resolv"
class OutgoingMessagePrototype
attr_accessor :from
attr_accessor :sender
attr_accessor :to
attr_accessor :cc
attr_accessor :bcc
attr_accessor :subject
attr_accessor :reply_to
attr_accessor :custom_headers
attr_accessor :plain_body
attr_accessor :html_body
attr_accessor :attachments
attr_accessor :tag
attr_accessor :credential
attr_accessor :bounce
def initialize(server, ip, source_type, attributes)
@server = server
@ip = ip
@source_type = source_type
@custom_headers = {}
@attachments = []
@message_id = "#{SecureRandom.uuid}@#{Postal::Config.dns.return_path_domain}"
attributes.each do |key, value|
instance_variable_set("@#{key}", value)
end
end
attr_reader :message_id
def from_address
Postal::Helpers.strip_name_from_address(@from)
end
def sender_address
Postal::Helpers.strip_name_from_address(@sender)
end
def domain
@domain ||= begin
d = find_domain
d == :none ? nil : d
end
end
def find_domain
domain = @server.authenticated_domain_for_address(@from)
if @server.allow_sender? && domain.nil?
domain = @server.authenticated_domain_for_address(@sender)
end
domain || :none
end
def to_addresses
@to.is_a?(String) ? @to.to_s.split(/,\s*/) : @to.to_a
end
def cc_addresses
@cc.is_a?(String) ? @cc.to_s.split(/,\s*/) : @cc.to_a
end
def bcc_addresses
@bcc.is_a?(String) ? @bcc.to_s.split(/,\s*/) : @bcc.to_a
end
def all_addresses
[to_addresses, cc_addresses, bcc_addresses].flatten
end
def create_messages
if valid?
all_addresses.each_with_object({}) do |address, hash|
if address = Postal::Helpers.strip_name_from_address(address)
hash[address] = create_message(address)
end
end
else
false
end
end
def valid?
validate
errors.empty?
end
def errors
@errors || {}
end
# rubocop:disable Lint/DuplicateMethods
def attachments
(@attachments || []).map do |attachment|
{
name: attachment[:name],
content_type: attachment[:content_type] || "application/octet-stream",
data: attachment[:base64] && attachment[:data] ? Base64.decode64(attachment[:data]) : attachment[:data]
}
end
end
# rubocop:enable Lint/DuplicateMethods
def validate
@errors = []
if to_addresses.empty? && cc_addresses.empty? && bcc_addresses.empty?
@errors << "NoRecipients"
end
if to_addresses.size > 50
@errors << "TooManyToAddresses"
end
if cc_addresses.size > 50
@errors << "TooManyCCAddresses"
end
if bcc_addresses.size > 50
@errors << "TooManyBCCAddresses"
end
if @plain_body.blank? && @html_body.blank?
@errors << "NoContent"
end
if from.blank?
@errors << "FromAddressMissing"
end
if domain.nil?
@errors << "UnauthenticatedFromAddress"
end
if attachments.present?
attachments.each do |attachment|
if attachment[:name].blank?
@errors << "AttachmentMissingName" unless @errors.include?("AttachmentMissingName")
elsif attachment[:data].blank?
@errors << "AttachmentMissingData" unless @errors.include?("AttachmentMissingData")
end
end
end
@errors
end
def raw_message
@raw_message ||= begin
mail = Mail.new
if @custom_headers.is_a?(Hash)
@custom_headers.each { |key, value| mail[key.to_s] = value.to_s }
end
mail.to = to_addresses.join(", ") if to_addresses.present?
mail.cc = cc_addresses.join(", ") if cc_addresses.present?
mail.from = @from
mail.sender = @sender
mail.subject = @subject
mail.reply_to = @reply_to
mail.part content_type: "multipart/alternative" do |p|
if @plain_body.present?
p.text_part = Mail::Part.new
p.text_part.body = @plain_body
end
if @html_body.present?
p.html_part = Mail::Part.new
p.html_part.content_type = "text/html; charset=UTF-8"
p.html_part.body = @html_body
end
end
attachments.each do |attachment|
mail.attachments[attachment[:name]] = {
mime_type: attachment[:content_type],
content: attachment[:data]
}
end
mail.header["Received"] = ReceivedHeader.generate(@server, @source_type, @ip, :http)
mail.message_id = "<#{@message_id}>"
mail.to_s
end
end
def create_message(address)
message = @server.message_db.new_message
message.scope = "outgoing"
message.rcpt_to = address
message.mail_from = from_address
message.domain_id = domain.id
message.raw_message = raw_message
message.tag = tag
message.credential_id = credential&.id
message.received_with_ssl = true
message.bounce = @bounce
message.save
{ id: message.id, token: message.token }
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/domain.rb | app/models/domain.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: domains
#
# id :integer not null, primary key
# server_id :integer
# uuid :string(255)
# name :string(255)
# verification_token :string(255)
# verification_method :string(255)
# verified_at :datetime
# dkim_private_key :text(65535)
# created_at :datetime
# updated_at :datetime
# dns_checked_at :datetime
# spf_status :string(255)
# spf_error :string(255)
# dkim_status :string(255)
# dkim_error :string(255)
# mx_status :string(255)
# mx_error :string(255)
# return_path_status :string(255)
# return_path_error :string(255)
# outgoing :boolean default(TRUE)
# incoming :boolean default(TRUE)
# owner_type :string(255)
# owner_id :integer
# dkim_identifier_string :string(255)
# use_for_any :boolean
#
# Indexes
#
# index_domains_on_server_id (server_id)
# index_domains_on_uuid (uuid)
#
require "resolv"
class Domain < ApplicationRecord
include HasUUID
include HasDNSChecks
VERIFICATION_EMAIL_ALIASES = %w[webmaster postmaster admin administrator hostmaster].freeze
VERIFICATION_METHODS = %w[DNS Email].freeze
belongs_to :server, optional: true
belongs_to :owner, optional: true, polymorphic: true
has_many :routes, dependent: :destroy
has_many :track_domains, dependent: :destroy
validates :name, presence: true, format: { with: /\A[a-z0-9\-.]*\z/ }, uniqueness: { case_sensitive: false, scope: [:owner_type, :owner_id], message: "is already added" }
validates :verification_method, inclusion: { in: VERIFICATION_METHODS }
random_string :dkim_identifier_string, type: :chars, length: 6, unique: true, upper_letters_only: true
before_create :generate_dkim_key
scope :verified, -> { where.not(verified_at: nil) }
before_save :update_verification_token_on_method_change
def verified?
verified_at.present?
end
def mark_as_verified
return false if verified?
self.verified_at = Time.now
save!
end
def parent_domains
parts = name.split(".")
parts[0, parts.size - 1].each_with_index.map do |_, i|
parts[i..].join(".")
end
end
def generate_dkim_key
self.dkim_private_key = OpenSSL::PKey::RSA.new(1024).to_s
end
def dkim_key
return nil unless dkim_private_key
@dkim_key ||= OpenSSL::PKey::RSA.new(dkim_private_key)
end
def to_param
uuid
end
def verification_email_addresses
parent_domains.map do |domain|
VERIFICATION_EMAIL_ALIASES.map do |a|
"#{a}@#{domain}"
end
end.flatten
end
def spf_record
"v=spf1 a mx include:#{Postal::Config.dns.spf_include} ~all"
end
def dkim_record
return if dkim_key.nil?
public_key = dkim_key.public_key.to_s.gsub(/-+[A-Z ]+-+\n/, "").gsub(/\n/, "")
"v=DKIM1; t=s; h=sha256; p=#{public_key};"
end
def dkim_identifier
return nil unless dkim_identifier_string
Postal::Config.dns.dkim_identifier + "-#{dkim_identifier_string}"
end
def dkim_record_name
identifier = dkim_identifier
return if identifier.nil?
"#{identifier}._domainkey"
end
def return_path_domain
"#{Postal::Config.dns.custom_return_path_prefix}.#{name}"
end
# Returns a DNSResolver instance that can be used to perform DNS lookups needed for
# the verification and DNS checking for this domain.
#
# @return [DNSResolver]
def resolver
return DNSResolver.local if Postal::Config.postal.use_local_ns_for_domain_verification?
@resolver ||= DNSResolver.for_domain(name)
end
def dns_verification_string
"#{Postal::Config.dns.domain_verify_prefix} #{verification_token}"
end
def verify_with_dns
return false unless verification_method == "DNS"
result = resolver.txt(name)
if result.include?(dns_verification_string)
self.verified_at = Time.now
return save
end
false
end
private
def update_verification_token_on_method_change
return unless verification_method_changed?
if verification_method == "DNS"
self.verification_token = SecureRandom.alphanumeric(32)
elsif verification_method == "Email"
self.verification_token = rand(999_999).to_s.ljust(6, "0")
else
self.verification_token = nil
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/incoming_message_prototype.rb | app/models/incoming_message_prototype.rb | # frozen_string_literal: true
class IncomingMessagePrototype
attr_accessor :to
attr_accessor :from
attr_accessor :route_id
attr_accessor :subject
attr_accessor :plain_body
attr_accessor :attachments
def initialize(server, ip, source_type, attributes)
@server = server
@ip = ip
@source_type = source_type
@attachments = []
attributes.each do |key, value|
instance_variable_set("@#{key}", value)
end
end
def from_address
@from.gsub(/.*</, "").gsub(/>.*/, "").strip
end
def route
@route ||= if @to.present?
uname, domain = @to.split("@", 2)
uname, _tag = uname.split("+", 2)
@server.routes.includes(:domain).where(domains: { name: domain }, name: uname).first
end
end
# rubocop:disable Lint/DuplicateMethods
def attachments
(@attachments || []).map do |attachment|
{
name: attachment[:name],
content_type: attachment[:content_type] || "application/octet-stream",
data: attachment[:base64] ? Base64.decode64(attachment[:data]) : attachment[:data]
}
end
end
# rubocop:enable Lint/DuplicateMethods
def create_messages
if valid?
messages = route.create_messages do |message|
message.rcpt_to = @to
message.mail_from = from_address
message.raw_message = raw_message
end
{ route.description => { id: messages.first.id, token: messages.first.token } }
else
false
end
end
def valid?
validate
errors.empty?
end
def errors
@errors || []
end
def validate
@errors = []
if route.nil?
@errors << "NoRoutesFound"
end
if from.empty?
@errors << "FromAddressMissing"
end
if subject.blank?
@errors << "SubjectMissing"
end
@errors
end
def raw_message
@raw_message ||= begin
mail = Mail.new
mail.to = @to
mail.from = @from
mail.subject = @subject
mail.text_part = @plain_body
mail.message_id = "<#{SecureRandom.uuid}@#{Postal::Config.dns.return_path_domain}>"
attachments.each do |attachment|
mail.attachments[attachment[:name]] = {
mime_type: attachment[:content_type],
content: attachment[:data]
}
end
mail.header["Received"] = ReceivedHeader.generate(@server, @source_type, @ip, :http)
mail.to_s
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/additional_route_endpoint.rb | app/models/additional_route_endpoint.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: additional_route_endpoints
#
# id :integer not null, primary key
# route_id :integer
# endpoint_type :string(255)
# endpoint_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class AdditionalRouteEndpoint < ApplicationRecord
belongs_to :route
belongs_to :endpoint, polymorphic: true
validate :validate_endpoint_belongs_to_server
validate :validate_wildcard
validate :validate_uniqueness
def self.find_by_endpoint(endpoint)
class_name, id = endpoint.split("#", 2)
unless Route::ENDPOINT_TYPES.include?(class_name)
raise Postal::Error, "Invalid endpoint class name '#{class_name}'"
end
return unless uuid = class_name.constantize.find_by_uuid(id)
where(endpoint_type: class_name, endpoint_id: uuid).first
end
def _endpoint
"#{endpoint_type}##{endpoint.uuid}"
end
def _endpoint=(value)
if value && value =~ /\#/
class_name, id = value.split("#", 2)
unless Route::ENDPOINT_TYPES.include?(class_name)
raise Postal::Error, "Invalid endpoint class name '#{class_name}'"
end
self.endpoint = class_name.constantize.find_by_uuid(id)
else
self.endpoint = nil
end
end
private
def validate_endpoint_belongs_to_server
return unless endpoint && endpoint&.server != route.server
errors.add :endpoint, :invalid
end
def validate_uniqueness
return unless endpoint == route.endpoint
errors.add :base, "You can only add an endpoint to a route once"
end
def validate_wildcard
return unless route.wildcard?
return unless endpoint_type == "SMTPEndpoint" || endpoint_type == "AddressEndpoint"
errors.add :base, "SMTP or address endpoints are not permitted on wildcard routes"
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/route.rb | app/models/route.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: routes
#
# id :integer not null, primary key
# uuid :string(255)
# server_id :integer
# domain_id :integer
# endpoint_id :integer
# endpoint_type :string(255)
# name :string(255)
# spam_mode :string(255)
# created_at :datetime
# updated_at :datetime
# token :string(255)
# mode :string(255)
#
# Indexes
#
# index_routes_on_token (token)
#
class Route < ApplicationRecord
MODES = %w[Endpoint Accept Hold Bounce Reject].freeze
SPAM_MODES = %w[Mark Quarantine Fail].freeze
ENDPOINT_TYPES = %w[SMTPEndpoint HTTPEndpoint AddressEndpoint].freeze
include HasUUID
belongs_to :server
belongs_to :domain, optional: true
belongs_to :endpoint, polymorphic: true, optional: true
has_many :additional_route_endpoints, dependent: :destroy
validates :name, presence: true, format: /\A(([a-z0-9\-.]*)|(\*)|(__returnpath__))\z/
validates :spam_mode, inclusion: { in: SPAM_MODES }
validates :endpoint, presence: { if: proc { mode == "Endpoint" } }
validates :domain_id, presence: { unless: :return_path? }
validate :validate_route_is_routed
validate :validate_domain_belongs_to_server
validate :validate_endpoint_belongs_to_server
validate :validate_name_uniqueness
validate :validate_return_path_route_endpoints
validate :validate_no_additional_routes_on_non_endpoint_route
after_save :save_additional_route_endpoints
random_string :token, type: :chars, length: 8, unique: true
def return_path?
name == "__returnpath__"
end
def description
if return_path?
"Return Path"
else
"#{name}@#{domain.name}"
end
end
def _endpoint
if mode == "Endpoint"
@endpoint ||= endpoint ? "#{endpoint.class}##{endpoint.uuid}" : nil
else
@endpoint ||= mode
end
end
def _endpoint=(value)
if value.blank?
self.endpoint = nil
self.mode = nil
elsif value =~ /\#/
class_name, id = value.split("#", 2)
unless ENDPOINT_TYPES.include?(class_name)
raise Postal::Error, "Invalid endpoint class name '#{class_name}'"
end
self.endpoint = class_name.constantize.find_by_uuid(id)
self.mode = "Endpoint"
else
self.endpoint = nil
self.mode = value
end
end
def forward_address
@forward_address ||= "#{token}@#{Postal::Config.dns.route_domain}"
end
def wildcard?
name == "*"
end
def additional_route_endpoints_array
@additional_route_endpoints_array ||= additional_route_endpoints.map(&:_endpoint)
end
def additional_route_endpoints_array=(array)
@additional_route_endpoints_array = array.reject(&:blank?)
end
def save_additional_route_endpoints
return unless @additional_route_endpoints_array
seen = []
@additional_route_endpoints_array.each do |item|
if existing = additional_route_endpoints.find_by_endpoint(item)
seen << existing.id
else
route = additional_route_endpoints.build(_endpoint: item)
if route.save
seen << route.id
else
route.errors.each do |_, message|
errors.add :base, message
end
raise ActiveRecord::RecordInvalid
end
end
end
additional_route_endpoints.where.not(id: seen).destroy_all
end
#
# This message will create a suitable number of message objects for messages that
# are destined for this route. It receives a block which can set the message content
# but most information is specified already.
#
# Returns an array of created messages.
#
def create_messages(&block)
messages = []
message = build_message
if mode == "Endpoint" && server.message_db.schema_version >= 18
message.endpoint_type = endpoint_type
message.endpoint_id = endpoint_id
end
block.call(message)
message.save
messages << message
# Also create any messages for additional endpoints that might exist
if mode == "Endpoint" && server.message_db.schema_version >= 18
additional_route_endpoints.each do |endpoint|
next unless endpoint.endpoint
message = build_message
message.endpoint_id = endpoint.endpoint_id
message.endpoint_type = endpoint.endpoint_type
block.call(message)
message.save
messages << message
end
end
messages
end
def build_message
message = server.message_db.new_message
message.scope = "incoming"
message.rcpt_to = description
message.domain_id = domain&.id
message.route_id = id
message
end
private
def validate_route_is_routed
return unless mode.nil?
errors.add :endpoint, "must be chosen"
end
def validate_domain_belongs_to_server
if domain && ![server, server.organization].include?(domain.owner)
errors.add :domain, :invalid
end
return unless domain && !domain.verified?
errors.add :domain, "has not been verified yet"
end
def validate_endpoint_belongs_to_server
return unless endpoint && endpoint&.server != server
errors.add :endpoint, :invalid
end
def validate_name_uniqueness
return if server.nil?
if domain
if route = Route.includes(:domain).where(domains: { name: domain.name }, name: name).where.not(id: id).first
errors.add :name, "is configured on the #{route.server.full_permalink} mail server"
end
elsif Route.where(name: "__returnpath__").where.not(id: id).exists?
errors.add :base, "A return path route already exists for this server"
end
end
def validate_return_path_route_endpoints
return unless return_path?
return unless mode != "Endpoint" || endpoint_type != "HTTPEndpoint"
errors.add :base, "Return path routes must point to an HTTP endpoint"
end
def validate_no_additional_routes_on_non_endpoint_route
return unless mode != "Endpoint" && !additional_route_endpoints_array.empty?
errors.add :base, "Additional routes are not permitted unless the primary route is an actual endpoint"
end
class << self
def find_by_name_and_domain(name, domain)
route = Route.includes(:domain).where(name: name, domains: { name: domain }).first
if route.nil?
route = Route.includes(:domain).where(name: "*", domains: { name: domain }).first
end
route
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/credential.rb | app/models/credential.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: credentials
#
# id :integer not null, primary key
# server_id :integer
# key :string(255)
# type :string(255)
# name :string(255)
# options :text(65535)
# last_used_at :datetime
# created_at :datetime
# updated_at :datetime
# hold :boolean default(FALSE)
# uuid :string(255)
#
class Credential < ApplicationRecord
include HasUUID
belongs_to :server
TYPES = %w[SMTP API SMTP-IP].freeze
validates :key, presence: true, uniqueness: { case_sensitive: false }
validates :type, inclusion: { in: TYPES }
validates :name, presence: true
validate :validate_key_cannot_be_changed
validate :validate_key_for_smtp_ip
serialize :options, type: Hash
before_validation :generate_key
def generate_key
return if type == "SMTP-IP"
return if persisted?
self.key = SecureRandom.alphanumeric(24)
end
def to_param
uuid
end
def use
update_column(:last_used_at, Time.now)
end
def usage_type
if last_used_at.nil?
"Unused"
elsif last_used_at < 1.year.ago
"Inactive"
elsif last_used_at < 6.months.ago
"Dormant"
elsif last_used_at < 1.month.ago
"Quiet"
else
"Active"
end
end
def to_smtp_plain
Base64.encode64("\0XX\0#{key}").strip
end
def ipaddr
return unless type == "SMTP-IP"
@ipaddr ||= IPAddr.new(key)
rescue IPAddr::InvalidAddressError
nil
end
private
def validate_key_cannot_be_changed
return if new_record?
return unless key_changed?
return if type == "SMTP-IP"
errors.add :key, "cannot be changed"
end
def validate_key_for_smtp_ip
return unless type == "SMTP-IP"
IPAddr.new(key.to_s)
rescue IPAddr::InvalidAddressError
errors.add :key, "must be a valid IPv4 or IPv6 address"
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/application_record.rb | app/models/application_record.rb | # frozen_string_literal: true
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
self.inheritance_column = "sti_type"
nilify_blanks
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/ip_address.rb | app/models/ip_address.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: ip_addresses
#
# id :integer not null, primary key
# ip_pool_id :integer
# ipv4 :string(255)
# ipv6 :string(255)
# created_at :datetime
# updated_at :datetime
# hostname :string(255)
# priority :integer
#
class IPAddress < ApplicationRecord
belongs_to :ip_pool
validates :ipv4, presence: true, uniqueness: true
validates :hostname, presence: true
validates :ipv6, uniqueness: { allow_blank: true }
validates :priority, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 100, only_integer: true }
scope :order_by_priority, -> { order(priority: :desc) }
before_validation :set_default_priority
private
def set_default_priority
return if priority.present?
self.priority = 100
end
class << self
def select_by_priority
order(Arel.sql("RAND() * priority DESC")).first
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/organization.rb | app/models/organization.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: organizations
#
# id :integer not null, primary key
# uuid :string(255)
# name :string(255)
# permalink :string(255)
# time_zone :string(255)
# created_at :datetime
# updated_at :datetime
# ip_pool_id :integer
# owner_id :integer
# deleted_at :datetime
# suspended_at :datetime
# suspension_reason :string(255)
#
# Indexes
#
# index_organizations_on_permalink (permalink)
# index_organizations_on_uuid (uuid)
#
class Organization < ApplicationRecord
RESERVED_PERMALINKS = %w[new edit remove delete destroy admin mail org server].freeze
INITIAL_QUOTA = 10
INITIAL_SUPER_QUOTA = 10_000
include HasUUID
include HasSoftDestroy
validates :name, presence: true
validates :permalink, presence: true, format: { with: /\A[a-z0-9-]*\z/ }, uniqueness: { case_sensitive: false }, exclusion: { in: RESERVED_PERMALINKS }
validates :time_zone, presence: true
default_value :time_zone, -> { "UTC" }
default_value :permalink, -> { Organization.find_unique_permalink(name) if name }
belongs_to :owner, class_name: "User"
has_many :organization_users, dependent: :destroy
has_many :users, through: :organization_users, source_type: "User"
has_many :user_invites, through: :organization_users, source_type: "UserInvite", source: :user
has_many :servers, dependent: :destroy
has_many :domains, as: :owner, dependent: :destroy
has_many :organization_ip_pools, dependent: :destroy
has_many :ip_pools, through: :organization_ip_pools
has_many :ip_pool_rules, dependent: :destroy, as: :owner
after_create do
if IPPool.default
ip_pools << IPPool.default
end
end
def status
if suspended?
"Suspended"
else
"Active"
end
end
def to_param
permalink
end
def suspended?
suspended_at.present?
end
def user_assignment(user)
@user_assignments ||= {}
@user_assignments[user.id] ||= organization_users.where(user: user).first
end
def make_owner(new_owner)
user_assignment(new_owner).update(admin: true, all_servers: true)
update(owner: new_owner)
end
# This is an array of addresses that should receive notifications for this organization
def notification_addresses
users.map(&:email_tag)
end
def self.find_unique_permalink(name)
loop.each_with_index do |_, i|
i += 1
proposal = name.parameterize
proposal += "-#{i}" if i > 1
unless where(permalink: proposal).exists?
return proposal
end
end
end
def self.[](id)
if id.is_a?(String)
where(permalink: id).first
else
where(id: id.to_i).first
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/webhook_request.rb | app/models/webhook_request.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: webhook_requests
#
# id :integer not null, primary key
# attempts :integer default(0)
# error :text(65535)
# event :string(255)
# locked_at :datetime
# locked_by :string(255)
# payload :text(65535)
# retry_after :datetime
# url :string(255)
# uuid :string(255)
# created_at :datetime
# server_id :integer
# webhook_id :integer
#
# Indexes
#
# index_webhook_requests_on_locked_by (locked_by)
#
class WebhookRequest < ApplicationRecord
include HasUUID
include HasLocking
belongs_to :server
belongs_to :webhook, optional: true
validates :url, presence: true
validates :event, presence: true
serialize :payload, type: Hash
class << self
def trigger(server, event, payload = {})
unless server.is_a?(Server)
server = Server.find(server.to_i)
end
webhooks = server.webhooks.enabled.includes(:webhook_events).references(:webhook_events).where("webhooks.all_events = ? OR webhook_events.event = ?", true, event)
webhooks.each do |webhook|
server.webhook_requests.create!(event: event, payload: payload, webhook: webhook, url: webhook.url)
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/user_invite.rb | app/models/user_invite.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: user_invites
#
# id :integer not null, primary key
# uuid :string(255)
# email_address :string(255)
# expires_at :datetime
# created_at :datetime
# updated_at :datetime
#
# Indexes
#
# index_user_invites_on_uuid (uuid)
#
class UserInvite < ApplicationRecord
include HasUUID
validates :email_address, presence: true, uniqueness: { case_sensitive: false }, format: { with: /@/, allow_blank: true }
has_many :organization_users, dependent: :destroy, as: :user
has_many :organizations, through: :organization_users
default_value :expires_at, -> { 7.days.from_now }
scope :active, -> { where("expires_at > ?", Time.now) }
def md5_for_gravatar
@md5_for_gravatar ||= Digest::MD5.hexdigest(email_address.to_s.downcase)
end
def avatar_url
@avatar_url ||= email_address ? "https://secure.gravatar.com/avatar/#{md5_for_gravatar}?rating=PG&size=120&d=mm" : nil
end
def name
email_address
end
def accept(user)
transaction do
organization_users.each do |ou|
ou.update(user: user) || ou.destroy
end
organization_users.reload
destroy
end
end
def reject
destroy
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/smtp_endpoint.rb | app/models/smtp_endpoint.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: smtp_endpoints
#
# id :integer not null, primary key
# server_id :integer
# uuid :string(255)
# name :string(255)
# hostname :string(255)
# ssl_mode :string(255)
# port :integer
# error :text(65535)
# disabled_until :datetime
# last_used_at :datetime
# created_at :datetime
# updated_at :datetime
#
class SMTPEndpoint < ApplicationRecord
include HasUUID
belongs_to :server
has_many :routes, as: :endpoint
has_many :additional_route_endpoints, dependent: :destroy, as: :endpoint
SSL_MODES = %w[None Auto STARTTLS TLS].freeze
before_destroy :update_routes
validates :name, presence: true
validates :hostname, presence: true, format: /\A[a-z0-9.-]*\z/
validates :ssl_mode, inclusion: { in: SSL_MODES }
validates :port, numericality: { only_integer: true, allow_blank: true }
def description
"#{name} (#{hostname})"
end
def mark_as_used
update_column(:last_used_at, Time.now)
end
def update_routes
routes.each { |r| r.update(endpoint: nil, mode: "Reject") }
end
def to_smtp_client_server
SMTPClient::Server.new(hostname, port: port || 25, ssl_mode: ssl_mode)
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/webhook_event.rb | app/models/webhook_event.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: webhook_events
#
# id :integer not null, primary key
# webhook_id :integer
# event :string(255)
# created_at :datetime
#
# Indexes
#
# index_webhook_events_on_webhook_id (webhook_id)
#
class WebhookEvent < ApplicationRecord
EVENTS = %w[
MessageSent
MessageDelayed
MessageDeliveryFailed
MessageHeld
MessageBounced
MessageLinkClicked
MessageLoaded
DomainDNSError
].freeze
belongs_to :webhook
validates :event, presence: true
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/scheduled_task.rb | app/models/scheduled_task.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: scheduled_tasks
#
# id :bigint not null, primary key
# name :string(255)
# next_run_after :datetime
#
# Indexes
#
# index_scheduled_tasks_on_name (name) UNIQUE
#
class ScheduledTask < ApplicationRecord
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/server.rb | app/models/server.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: servers
#
# id :integer not null, primary key
# allow_sender :boolean default(FALSE)
# deleted_at :datetime
# domains_not_to_click_track :text(65535)
# log_smtp_data :boolean default(FALSE)
# message_retention_days :integer
# mode :string(255)
# name :string(255)
# outbound_spam_threshold :decimal(8, 2)
# permalink :string(255)
# postmaster_address :string(255)
# privacy_mode :boolean default(FALSE)
# raw_message_retention_days :integer
# raw_message_retention_size :integer
# send_limit :integer
# send_limit_approaching_at :datetime
# send_limit_approaching_notified_at :datetime
# send_limit_exceeded_at :datetime
# send_limit_exceeded_notified_at :datetime
# spam_failure_threshold :decimal(8, 2)
# spam_threshold :decimal(8, 2)
# suspended_at :datetime
# suspension_reason :string(255)
# token :string(255)
# uuid :string(255)
# created_at :datetime
# updated_at :datetime
# ip_pool_id :integer
# organization_id :integer
#
# Indexes
#
# index_servers_on_organization_id (organization_id)
# index_servers_on_permalink (permalink)
# index_servers_on_token (token)
# index_servers_on_uuid (uuid)
#
class Server < ApplicationRecord
RESERVED_PERMALINKS = %w[new all search stats edit manage delete destroy remove].freeze
MODES = %w[Live Development].freeze
include HasUUID
include HasSoftDestroy
attr_accessor :provision_database
belongs_to :organization
belongs_to :ip_pool, optional: true
has_many :domains, dependent: :destroy, as: :owner
has_many :credentials, dependent: :destroy
has_many :smtp_endpoints, dependent: :destroy
has_many :http_endpoints, dependent: :destroy
has_many :address_endpoints, dependent: :destroy
has_many :routes, dependent: :destroy
has_many :queued_messages, dependent: :delete_all
has_many :webhooks, dependent: :destroy
has_many :webhook_requests, dependent: :destroy
has_many :track_domains, dependent: :destroy
has_many :ip_pool_rules, dependent: :destroy, as: :owner
random_string :token, type: :chars, length: 6, unique: true, upper_letters_only: true
default_value :permalink, -> { name ? name.parameterize : nil }
default_value :raw_message_retention_days, -> { 30 }
default_value :raw_message_retention_size, -> { 2048 }
default_value :message_retention_days, -> { 60 }
default_value :spam_threshold, -> { Postal::Config.postal.default_spam_threshold }
default_value :spam_failure_threshold, -> { Postal::Config.postal.default_spam_failure_threshold }
validates :name, presence: true, uniqueness: { scope: :organization_id, case_sensitive: false }
validates :mode, inclusion: { in: MODES }
validates :permalink, presence: true, uniqueness: { scope: :organization_id, case_sensitive: false }, format: { with: /\A[a-z0-9-]*\z/ }, exclusion: { in: RESERVED_PERMALINKS }
validate :validate_ip_pool_belongs_to_organization
before_validation(on: :create) do
self.token = token.downcase if token
end
after_create do
unless provision_database == false
message_db.provisioner.provision
end
end
after_commit(on: :destroy) do
unless provision_database == false
message_db.provisioner.drop
end
end
def status
if suspended?
"Suspended"
else
mode
end
end
def full_permalink
"#{organization.permalink}/#{permalink}"
end
def suspended?
suspended_at.present? || organization.suspended?
end
def actual_suspension_reason
return unless suspended?
if suspended_at.nil?
organization.suspension_reason
else
suspension_reason
end
end
def to_param
permalink
end
def message_db
@message_db ||= Postal::MessageDB::Database.new(organization_id, id)
end
delegate :message, to: :message_db
def message_rate
@message_rate ||= message_db.live_stats.total(60, types: [:incoming, :outgoing]) / 60.0
end
def held_messages
@held_messages ||= message_db.messages(where: { held: true }, count: true)
end
def throughput_stats
@throughput_stats ||= begin
incoming = message_db.live_stats.total(60, types: [:incoming])
outgoing = message_db.live_stats.total(60, types: [:outgoing])
outgoing_usage = send_limit ? (outgoing / send_limit.to_f) * 100 : 0
{
incoming: incoming,
outgoing: outgoing,
outgoing_usage: outgoing_usage
}
end
end
def bounce_rate
@bounce_rate ||= begin
time = Time.now.utc
total_outgoing = 0.0
total_bounces = 0.0
message_db.statistics.get(:daily, [:outgoing, :bounces], time, 30).each do |_, stat|
total_outgoing += stat[:outgoing]
total_bounces += stat[:bounces]
end
total_outgoing.zero? ? 0 : (total_bounces / total_outgoing) * 100
end
end
def domain_stats
domains = Domain.where(owner_id: id, owner_type: "Server").to_a
total = 0
unverified = 0
bad_dns = 0
domains.each do |domain|
total += 1
unverified += 1 unless domain.verified?
bad_dns += 1 if domain.verified? && !domain.dns_ok?
end
[total, unverified, bad_dns]
end
def webhook_hash
{
uuid: uuid,
name: name,
permalink: permalink,
organization: organization&.permalink
}
end
def send_volume
@send_volume ||= message_db.live_stats.total(60, types: [:outgoing])
end
def send_limit_approaching?
return false unless send_limit
(send_volume >= send_limit * 0.90)
end
def send_limit_exceeded?
return false unless send_limit
send_volume >= send_limit
end
def send_limit_warning(type)
if organization.notification_addresses.present?
AppMailer.send("server_send_limit_#{type}", self).deliver
end
update_column("send_limit_#{type}_notified_at", Time.now)
WebhookRequest.trigger(self, "SendLimit#{type.to_s.capitalize}", server: webhook_hash, volume: send_volume, limit: send_limit)
end
def queue_size
@queue_size ||= queued_messages.ready.count
end
# Return the domain which can be used to authenticate emails sent from the given e-mail address.
#
# @param address [String] an e-mail address
# @return [Domain, nil] the domain to use for authentication
def authenticated_domain_for_address(address)
return nil if address.blank?
address = Postal::Helpers.strip_name_from_address(address)
uname, domain_name = address.split("@", 2)
return nil unless uname
return nil unless domain_name
# Find a verified domain which directly matches the domain name for the given address.
domain = Domain.verified
.order(owner_type: :desc)
.where("(owner_type = 'Organization' AND owner_id = ?) OR " \
"(owner_type = 'Server' AND owner_id = ?)", organization_id, id)
.where(name: domain_name)
.first
# If there is a matching domain, return it
return domain if domain
# Otherwise, we need to look to see if there is a domain configured which can be used as the authenticated
# domain for any domain. This will look for domains directly within the server and return that.
any_domain = domains.verified.where(use_for_any: true).order(:name).first
return any_domain if any_domain
# Return nil if we can't find anything suitable
nil
end
def find_authenticated_domain_from_headers(headers)
header_to_check = ["from"]
header_to_check << "sender" if allow_sender?
header_to_check.each do |header_name|
if headers[header_name].is_a?(Array)
values = headers[header_name]
else
values = [headers[header_name].to_s]
end
authenticated_domains = values.map { |v| authenticated_domain_for_address(v) }.compact
if authenticated_domains.size == values.size
return authenticated_domains.first
end
end
nil
end
def suspend(reason)
self.suspended_at = Time.now
self.suspension_reason = reason
save!
if organization.notification_addresses.present?
AppMailer.server_suspended(self).deliver
end
true
end
def unsuspend
self.suspended_at = nil
self.suspension_reason = nil
save!
end
def ip_pool_for_message(message)
return unless message.scope == "outgoing"
[self, organization].each do |scope|
rules = scope.ip_pool_rules.order(created_at: :desc)
rules.each do |rule|
if rule.apply_to_message?(message)
return rule.ip_pool
end
end
end
ip_pool
end
private
def validate_ip_pool_belongs_to_organization
return unless ip_pool && ip_pool_id_changed? && !organization.ip_pools.include?(ip_pool)
errors.add :ip_pool_id, "must belong to the organization"
end
class << self
def triggered_send_limit(type)
servers = where("send_limit_#{type}_at IS NOT NULL AND send_limit_#{type}_at > ?", 3.minutes.ago)
servers.where("send_limit_#{type}_notified_at IS NULL OR send_limit_#{type}_notified_at < ?", 1.hour.ago)
end
def send_send_limit_notifications
[:approaching, :exceeded].each_with_object({}) do |type, hash|
hash[type] = 0
servers = triggered_send_limit(type)
next if servers.empty?
servers.each do |server|
hash[type] += 1
server.send_limit_warning(type)
end
end
end
def [](id, extra = nil)
if id.is_a?(String) && id =~ /\A(\w+)\/(\w+)\z/
joins(:organization).where(
organizations: { permalink: ::Regexp.last_match(1) }, permalink: ::Regexp.last_match(2)
).first
else
find_by(id: id.to_i)
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/http_endpoint.rb | app/models/http_endpoint.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: http_endpoints
#
# id :integer not null, primary key
# server_id :integer
# uuid :string(255)
# name :string(255)
# url :string(255)
# encoding :string(255)
# format :string(255)
# strip_replies :boolean default(FALSE)
# error :text(65535)
# disabled_until :datetime
# last_used_at :datetime
# created_at :datetime
# updated_at :datetime
# include_attachments :boolean default(TRUE)
# timeout :integer
#
class HTTPEndpoint < ApplicationRecord
DEFAULT_TIMEOUT = 5
include HasUUID
belongs_to :server
has_many :routes, as: :endpoint
has_many :additional_route_endpoints, dependent: :destroy, as: :endpoint
ENCODINGS = %w[BodyAsJSON FormData].freeze
FORMATS = %w[Hash RawMessage].freeze
before_destroy :update_routes
validates :name, presence: true
validates :url, presence: true
validates :encoding, inclusion: { in: ENCODINGS }
validates :format, inclusion: { in: FORMATS }
validates :timeout, numericality: { greater_than_or_equal_to: 5, less_than_or_equal_to: 60 }
default_value :timeout, -> { DEFAULT_TIMEOUT }
def description
"#{name} (#{url})"
end
def mark_as_used
update_column(:last_used_at, Time.now)
end
def update_routes
routes.each { |r| r.update(endpoint: nil, mode: "Reject") }
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/webhook.rb | app/models/webhook.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: webhooks
#
# id :integer not null, primary key
# server_id :integer
# uuid :string(255)
# name :string(255)
# url :string(255)
# last_used_at :datetime
# all_events :boolean default(FALSE)
# enabled :boolean default(TRUE)
# sign :boolean default(TRUE)
# created_at :datetime
# updated_at :datetime
#
# Indexes
#
# index_webhooks_on_server_id (server_id)
#
class Webhook < ApplicationRecord
include HasUUID
belongs_to :server
has_many :webhook_events, dependent: :destroy
has_many :webhook_requests
validates :name, presence: true
validates :url, presence: true, format: { with: /\Ahttps?:\/\/[a-z0-9\-._?=&\/+:%@]+\z/i, allow_blank: true }
scope :enabled, -> { where(enabled: true) }
after_save :save_events
after_save :destroy_events_when_all_events_enabled
def events
@events ||= webhook_events.map(&:event)
end
def events=(value)
@events = value.map(&:to_s).select(&:present?)
end
private
def save_events
return unless @events
@events.each do |event|
webhook_events.where(event: event).first_or_create!
end
webhook_events.where.not(event: @events).destroy_all
end
def destroy_events_when_all_events_enabled
return unless all_events
webhook_events.destroy_all
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/user.rb | app/models/user.rb | # frozen_string_literal: true
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# admin :boolean default(FALSE)
# email_address :string(255)
# email_verification_token :string(255)
# email_verified_at :datetime
# first_name :string(255)
# last_name :string(255)
# oidc_issuer :string(255)
# oidc_uid :string(255)
# password_digest :string(255)
# password_reset_token :string(255)
# password_reset_token_valid_until :datetime
# time_zone :string(255)
# uuid :string(255)
# created_at :datetime
# updated_at :datetime
#
# Indexes
#
# index_users_on_email_address (email_address)
# index_users_on_uuid (uuid)
#
class User < ApplicationRecord
include HasUUID
include HasAuthentication
validates :first_name, presence: true
validates :last_name, presence: true
validates :email_address, presence: true, uniqueness: { case_sensitive: false }, format: { with: /@/, allow_blank: true }
default_value :time_zone, -> { "UTC" }
has_many :organization_users, dependent: :destroy, as: :user
has_many :organizations, through: :organization_users
def organizations_scope
if admin?
@organizations_scope ||= Organization.present
else
@organizations_scope ||= organizations.present
end
end
def name
"#{first_name} #{last_name}"
end
def password?
password_digest.present?
end
def oidc?
oidc_uid.present?
end
def to_param
uuid
end
def email_tag
"#{name} <#{email_address}>"
end
class << self
# Lookup a user by email address
#
# @param email [String] the email address
#
# @return [User, nil] the user
def [](email)
find_by(email_address: email)
end
# Find a user based on an OIDC authentication hash
#
# @param auth [Hash] the authentication hash
# @param logger [Logger] a logger to log debug information to
#
# @return [User, nil] the user
def find_from_oidc(auth, logger: nil)
config = Postal::Config.oidc
uid = auth[config.uid_field]
oidc_name = auth[config.name_field]
oidc_email_address = auth[config.email_address_field]
logger&.debug "got auth details from issuer: #{auth.inspect}"
# look for an existing user with the same UID and OIDC issuer. If we find one,
# this is the user we'll want to use.
user = where(oidc_uid: uid, oidc_issuer: config.issuer).first
if user
logger&.debug "found user with UID #{uid} for issuer #{config.issuer} (user ID: #{user.id})"
else
logger&.debug "no user with UID #{uid} for issuer #{config.issuer}"
end
# if we don't have an existing user, we will look for users which have no OIDC
# credentials but with a matching e-mail address.
if user.nil? && oidc_email_address.present?
user = where(oidc_uid: nil, email_address: oidc_email_address).first
if user
logger&.debug "found user with e-mail address #{oidc_email_address} (user ID: #{user.id})"
else
logger&.debug "no user with e-mail address #{oidc_email_address}"
end
end
# now, if we still don't have a user, we're not going to create one so we'll just
# return nil (we might auto create users in the future but not right now)
return if user.nil?
# otherwise, let's update our user as appropriate
user.oidc_uid = uid
user.oidc_issuer = config.issuer
user.email_address = oidc_email_address if oidc_email_address.present?
user.first_name, user.last_name = oidc_name.split(/\s+/, 2) if oidc_name.present?
user.password = nil
user.save!
# return the user
user
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/concerns/has_uuid.rb | app/models/concerns/has_uuid.rb | # frozen_string_literal: true
module HasUUID
def self.included(base)
base.class_eval do
random_string :uuid, type: :uuid, unique: true
end
end
def to_param
uuid
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/concerns/has_message.rb | app/models/concerns/has_message.rb | # frozen_string_literal: true
module HasMessage
def self.included(base)
base.extend ClassMethods
end
def message
return @message if instance_variable_defined?("@message")
@message = server.message_db.message(message_id)
rescue Postal::MessageDB::Message::NotFound
@message = nil
end
def message=(message)
@message = message
self.message_id = message&.id
end
module ClassMethods
def include_message
queued_messages = all.to_a
server_ids = queued_messages.map(&:server_id).uniq
if server_ids.empty?
return []
elsif server_ids.size > 1
raise Postal::Error, "'include_message' can only be used on collections of messages from the same server"
end
message_ids = queued_messages.map(&:message_id).uniq
server = queued_messages.first&.server
messages = server.message_db.messages(where: { id: message_ids }).index_by do |message|
message.id
end
queued_messages.each do |queued_message|
if m = messages[queued_message.message_id]
queued_message.message = m
end
end
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/concerns/has_authentication.rb | app/models/concerns/has_authentication.rb | # frozen_string_literal: true
module HasAuthentication
extend ActiveSupport::Concern
included do
has_secure_password validations: false
validates :password, length: { minimum: 8, allow_blank: true }
validates :password, confirmation: { allow_blank: true }
validate :validate_password_presence
before_save :clear_password_reset_token_on_password_change
scope :with_password, -> { where.not(password_digest: nil) }
end
class_methods do
def authenticate(email_address, password)
user = find_by(email_address: email_address)
raise Postal::Errors::AuthenticationError, "InvalidEmailAddress" if user.nil?
raise Postal::Errors::AuthenticationError, "InvalidPassword" unless user.authenticate(password)
user
end
end
def authenticate_with_previous_password_first(unencrypted_password)
if password_digest_changed?
BCrypt::Password.new(password_digest_was).is_password?(unencrypted_password) && self
else
authenticate(unencrypted_password)
end
end
def begin_password_reset(return_to = nil)
if Postal::Config.oidc.enabled? && (oidc_uid.present? || password_digest.blank?)
raise Postal::Error, "User has OIDC enabled, password resets are not supported"
end
self.password_reset_token = SecureRandom.alphanumeric(24)
self.password_reset_token_valid_until = 1.day.from_now
save!
AppMailer.password_reset(self, return_to).deliver
end
private
def clear_password_reset_token_on_password_change
return unless password_digest_changed?
self.password_reset_token = nil
self.password_reset_token_valid_until = nil
end
def validate_password_presence
return if password_digest.present? || Postal::Config.oidc.enabled?
errors.add :password, :blank
end
end
# -*- SkipSchemaAnnotations
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/concerns/has_dns_checks.rb | app/models/concerns/has_dns_checks.rb | # frozen_string_literal: true
require "resolv"
module HasDNSChecks
def dns_ok?
spf_status == "OK" && dkim_status == "OK" && %w[OK Missing].include?(mx_status) && %w[OK Missing].include?(return_path_status)
end
def dns_checked?
spf_status.present?
end
def check_dns(source = :manual)
check_spf_record
check_dkim_record
check_mx_records
check_return_path_record
self.dns_checked_at = Time.now
save!
if source == :auto && !dns_ok? && owner.is_a?(Server)
WebhookRequest.trigger(owner, "DomainDNSError", {
server: owner.webhook_hash,
domain: name,
uuid: uuid,
dns_checked_at: dns_checked_at.to_f,
spf_status: spf_status,
spf_error: spf_error,
dkim_status: dkim_status,
dkim_error: dkim_error,
mx_status: mx_status,
mx_error: mx_error,
return_path_status: return_path_status,
return_path_error: return_path_error
})
end
dns_ok?
end
#
# SPF
#
def check_spf_record
result = resolver.txt(name)
spf_records = result.grep(/\Av=spf1/)
if spf_records.empty?
self.spf_status = "Missing"
self.spf_error = "No SPF record exists for this domain"
else
suitable_spf_records = spf_records.grep(/include:\s*#{Regexp.escape(Postal::Config.dns.spf_include)}/)
if suitable_spf_records.empty?
self.spf_status = "Invalid"
self.spf_error = "An SPF record exists but it doesn't include #{Postal::Config.dns.spf_include}"
false
else
self.spf_status = "OK"
self.spf_error = nil
true
end
end
end
def check_spf_record!
check_spf_record
save!
end
#
# DKIM
#
def check_dkim_record
domain = "#{dkim_record_name}.#{name}"
records = resolver.txt(domain)
if records.empty?
self.dkim_status = "Missing"
self.dkim_error = "No TXT records were returned for #{domain}"
else
sanitised_dkim_record = records.first.strip.ends_with?(";") ? records.first.strip : "#{records.first.strip};"
if records.size > 1
self.dkim_status = "Invalid"
self.dkim_error = "There are #{records.size} records for at #{domain}. There should only be one."
elsif sanitised_dkim_record != dkim_record
self.dkim_status = "Invalid"
self.dkim_error = "The DKIM record at #{domain} does not match the record we have provided. Please check it has been copied correctly."
else
self.dkim_status = "OK"
self.dkim_error = nil
true
end
end
end
def check_dkim_record!
check_dkim_record
save!
end
#
# MX
#
def check_mx_records
records = resolver.mx(name).map(&:last)
if records.empty?
self.mx_status = "Missing"
self.mx_error = "There are no MX records for #{name}"
else
missing_records = Postal::Config.dns.mx_records.dup - records.map { |r| r.to_s.downcase }
if missing_records.empty?
self.mx_status = "OK"
self.mx_error = nil
elsif missing_records.size == Postal::Config.dns.mx_records.size
self.mx_status = "Missing"
self.mx_error = "You have MX records but none of them point to us."
else
self.mx_status = "Invalid"
self.mx_error = "MX #{missing_records.size == 1 ? 'record' : 'records'} for #{missing_records.to_sentence} are missing and are required."
end
end
end
def check_mx_records!
check_mx_records
save!
end
#
# Return Path
#
def check_return_path_record
records = resolver.cname(return_path_domain)
if records.empty?
self.return_path_status = "Missing"
self.return_path_error = "There is no return path record at #{return_path_domain}"
elsif records.size == 1 && records.first == Postal::Config.dns.return_path_domain
self.return_path_status = "OK"
self.return_path_error = nil
else
self.return_path_status = "Invalid"
self.return_path_error = "There is a CNAME record at #{return_path_domain} but it points to #{records.first} which is incorrect. It should point to #{Postal::Config.dns.return_path_domain}."
end
end
def check_return_path_record!
check_return_path_record
save!
end
end
# -*- SkipSchemaAnnotations
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/concerns/has_locking.rb | app/models/concerns/has_locking.rb | # frozen_string_literal: true
# This concern provides functionality for locking items along with additional functionality to handle
# the concept of retrying items after a certain period of time. The following database columns are
# required on the model
#
# * locked_by - A string column to store the name of the process that has locked the item
# * locked_at - A datetime column to store the time the item was locked
# * retry_after - A datetime column to store the time after which the item should be retried
# * attempts - An integer column to store the number of attempts that have been made to process the item
#
# 'ready' means that it's ready to be processed.
module HasLocking
extend ActiveSupport::Concern
included do
scope :unlocked, -> { where(locked_at: nil) }
scope :ready, -> { where("retry_after IS NULL OR retry_after < ?", Time.now) }
end
def ready?
retry_after.nil? || retry_after < Time.now
end
def unlock
self.locked_by = nil
self.locked_at = nil
update_columns(locked_by: nil, locked_at: nil)
end
def locked?
locked_at.present?
end
def retry_later(time = nil)
retry_time = time || calculate_retry_time(attempts, 5.minutes)
self.locked_by = nil
self.locked_at = nil
update_columns(locked_by: nil, locked_at: nil, retry_after: Time.now + retry_time, attempts: attempts + 1)
end
def calculate_retry_time(attempts, initial_period)
(1.3**attempts) * initial_period
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/models/concerns/has_soft_destroy.rb | app/models/concerns/has_soft_destroy.rb | # frozen_string_literal: true
module HasSoftDestroy
def self.included(base)
base.define_callbacks :soft_destroy
base.class_eval do
scope :deleted, -> { where.not(deleted_at: nil) }
scope :present, -> { where(deleted_at: nil) }
end
end
def soft_destroy
run_callbacks :soft_destroy do
self.deleted_at = Time.now
save!
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/lib/reply_separator.rb | app/lib/reply_separator.rb | # frozen_string_literal: true
class ReplySeparator
RULES = [
/^-{2,10} $.*/m,
/^>*\s*----- ?Original Message ?-----.*/m,
/^>*\s*From:[^\r\n]*[\r\n]+Sent:.*/m,
/^>*\s*From:[^\r\n]*[\r\n]+Date:.*/m,
/^>*\s*-----Urspr.ngliche Nachricht----- .*/m,
/^>*\s*Le[^\r\n]{10,200}a .crit ?:\s*$.*/,
/^>*\s*__________________.*/m,
/^>*\s*On.{10,200}wrote:\s*$.*/m,
/^>*\s*Sent from my.*/m,
/^>*\s*=== Please reply above this line ===.*/m,
/(^>.*\n?){10,}/,
].freeze
def self.separate(text)
return "" unless text.is_a?(String)
text = text.gsub("\r", "")
stripped = String.new
RULES.each do |rule|
text.gsub!(rule) do
stripped = ::Regexp.last_match(0).to_s + "\n" + stripped
""
end
end
stripped = stripped.strip
[text.strip, stripped.presence]
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |
postalserver/postal | https://github.com/postalserver/postal/blob/b7e5232e077b3c9b7a999dcb6676fba0ec61458e/app/lib/message_dequeuer.rb | app/lib/message_dequeuer.rb | # frozen_string_literal: true
module MessageDequeuer
class << self
def process(message, logger:)
processor = InitialProcessor.new(message, logger: logger)
processor.process
end
end
end
| ruby | MIT | b7e5232e077b3c9b7a999dcb6676fba0ec61458e | 2026-01-04T15:37:27.414740Z | false |