A platform for community discussion. Free, open, simple.
DEV: Add experimental illegal content reporting form (#44679)
Alan Guo Xiang Tan5b4523580862
diff --git a/app/assets/stylesheets/common/base/_index.scss b/app/assets/stylesheets/common/base/_index.scssindex df4cab9233a..df4f296dd39 100644--- a/app/assets/stylesheets/common/base/_index.scss+++ b/app/assets/stylesheets/common/base/_index.scss@@ -45,6 +45,7 @@@import "review";@import "reviewables";@import "dsa-classification";+@import "dsa-notice";@import "revise-and-reject-post-reviewable";@import "rtl";@import "search";diff --git a/app/assets/stylesheets/common/base/dsa-notice.scss b/app/assets/stylesheets/common/base/dsa-notice.scssnew file mode 100644index 00000000000..0491d636fd7--- /dev/null+++ b/app/assets/stylesheets/common/base/dsa-notice.scss@@ -0,0 +1,3 @@+.dsa-notice {+ padding-block-end: var(--space-6);+}diff --git a/app/controllers/admin/email_templates_controller.rb b/app/controllers/admin/email_templates_controller.rbindex d356fd20f2c..b0a033f7408 100644--- a/app/controllers/admin/email_templates_controller.rb+++ b/app/controllers/admin/email_templates_controller.rb@@ -14,6 +14,8 @@ class Admin::EmailTemplatesController < Admin::AdminControllercustom_invite_forum_mailercustom_invite_mailerdownload_backup_mailer+ dsa_notice_mailer+ dsa_notice_verificationemail_login_code_mailerinvite_forum_mailerinvite_mailerdiff --git a/app/controllers/dsa_notices_controller.rb b/app/controllers/dsa_notices_controller.rbnew file mode 100644index 00000000000..c06f5b62413--- /dev/null+++ b/app/controllers/dsa_notices_controller.rb@@ -0,0 +1,60 @@+# frozen_string_literal: true++class DsaNoticesController < ApplicationController+ skip_before_action :check_xhr, only: :index+ skip_before_action :redirect_to_login_if_required, :redirect_to_profile_if_required+ before_action :ensure_enabled++ def index+ respond_to { |format| format.html { render "default/empty" } }+ end++ def verify_email+ Dsa::RequestNoticeVerification.call(+ service_params.merge(options: { ip_address: request.remote_ip }),+ ) do+ on_success { |token:| render json: { token: }, status: :accepted }+ on_failed_contract do |contract|+ render_json_error(contract.errors.full_messages, status: 422)+ end+ on_failure { render_json_error(I18n.t("js.generic_error")) }+ end+ end++ def create+ Dsa::SubmitNotice.call(service_params) do+ on_success { |notice:| render json: { reference: notice.reference }, status: :created }+ on_failed_contract do |contract|+ render_json_error(contract.errors.full_messages, status: 422)+ end+ on_model_not_found(:verification) do+ render_json_error(+ I18n.t("dsa_notice.verification_invalid"),+ status: 422,+ type: "verification_required",+ )+ end+ on_failure { render_json_error(I18n.t("js.generic_error")) }+ end+ end++ def verify_code+ Dsa::VerifyNoticeEmail.call(service_params) do+ on_success { render json: success_json }+ on_failed_contract do |contract|+ render_json_error(contract.errors.full_messages, status: 422)+ end+ on_model_not_found(:verification) do |failure|+ raise failure.exception if failure.exception+ render_json_error(I18n.t("dsa_notice.verification_invalid"), status: 422)+ end+ on_failure { render_json_error(I18n.t("js.generic_error")) }+ end+ end++ private++ def ensure_enabled+ raise Discourse::NotFound unless SiteSetting.dsa_reporting_enabled+ end+enddiff --git a/app/jobs/regular/dsa_notice_receipt.rb b/app/jobs/regular/dsa_notice_receipt.rbnew file mode 100644index 00000000000..ca2cb599b6b--- /dev/null+++ b/app/jobs/regular/dsa_notice_receipt.rb@@ -0,0 +1,16 @@+# frozen_string_literal: true++module Jobs+ class DsaNoticeReceipt < ::Jobs::Base+ def execute(args)+ notice = Dsa::Notice.find_by(id: args[:notice_id])+ if !notice || !notice.post || notice.post.deleted_at || notice.email.blank? ||+ notice.receipt_sent?+ return+ end++ sent = Email::Sender.new(DsaNoticeMailer.receipt(notice), :dsa_notice_receipt).send+ notice.mark_receipt_sent! if sent.is_a?(EmailLog) && sent.persisted?+ end+ end+enddiff --git a/app/jobs/regular/dsa_notice_verification.rb b/app/jobs/regular/dsa_notice_verification.rbnew file mode 100644index 00000000000..bab1d079d42--- /dev/null+++ b/app/jobs/regular/dsa_notice_verification.rb@@ -0,0 +1,15 @@+# frozen_string_literal: true++module Jobs+ class DsaNoticeVerification < ::Jobs::Base+ def execute(args)+ submission = Dsa::NoticeVerification.find(args[:token])+ return unless submission&.dig(:code)++ Email::Sender.new(+ DsaNoticeMailer.verification(email: submission[:email], code: submission[:code]),+ :dsa_notice_verification,+ ).send+ end+ end+enddiff --git a/app/mailers/dsa_notice_mailer.rb b/app/mailers/dsa_notice_mailer.rbnew file mode 100644index 00000000000..df0c30748ba--- /dev/null+++ b/app/mailers/dsa_notice_mailer.rb@@ -0,0 +1,35 @@+# frozen_string_literal: true++class DsaNoticeMailer < ActionMailer::Base+ include Email::BuildEmailHelper++ layout "email_template"++ def verification(email:, code:)+ build_email(+ email,+ template: "dsa_notice_verification",+ verification_code: code,+ expires_in_minutes: Dsa::NoticeVerification::VALID_FOR.in_minutes.to_i,+ site_title: SiteSetting.title,+ )+ end++ def receipt(notice)+ html_body =+ I18n.t(+ "dsa_notice_mailer.text_body_template",+ reference: notice.reference,+ summary: notice.summary,+ site_title: ERB::Util.html_escape(SiteSetting.title),+ )+ build_email(+ notice.email,+ template: "dsa_notice_mailer",+ reference: notice.reference,+ summary: notice.summary(plain_text: true),+ site_title: SiteSetting.title,+ html_override: PrettyText.cook(html_body),+ )+ end+enddiff --git a/app/models/dsa/notice.rb b/app/models/dsa/notice.rbnew file mode 100644index 00000000000..185b28b6eec--- /dev/null+++ b/app/models/dsa/notice.rb@@ -0,0 +1,82 @@+# frozen_string_literal: true++module Dsa+ class Notice < ActiveRecord::Base+ self.table_name = "dsa_notices"++ belongs_to :post, -> { with_deleted }, optional: true++ def self.create_with_post!(attributes:, group:)+ transaction do+ notice = create!(attributes)+ notice.post =+ PostCreator.create!(+ Discourse.system_user,+ title: I18n.t("dsa_notice.subject", reference: notice.reference),+ raw: notice.summary,+ archetype: Archetype.private_message,+ target_group_names: group.name,+ skip_validations: true,+ skip_jobs: true,+ )+ notice.save!+ notice+ end+ end++ def reference+ "DSA-#{id}"+ end++ def receipt_sent?+ receipt_sent_at.present?+ end++ def mark_receipt_sent!+ update!(receipt_sent_at: Time.current)+ end++ def summary(plain_text: false)+ reporter_email =+ if plain_text+ else+ "[#{escaped(email)}](mailto:#{ERB::Util.url_encode(email)})"+ end+ I18n.t(+ "dsa_notice.summary",+ reference:,+ content_url: plain_text ? content_url : "<#{content_url}>",+ explanation: plain_text ? explanation : escaped(explanation),+ reporter_email:,+ reporter_name: plain_text ? name : escaped(name),+ )+ end++ private++ def escaped(value)+ ERB::Util.html_escape(+ value.gsub(/[\\`*_{}\[\]()#+.!|~=:\/-]/) { |character| "\\#{character}" },+ ).gsub("@", "@")+ end+ end+end++# == Schema Information+#+# Table name: dsa_notices+#+# id :bigint not null, primary key+# content_url :text not null+# email :string+# explanation :text not null+# name :string+# receipt_sent_at :datetime+# created_at :datetime not null+# post_id :bigint+#+# Indexes+#+# index_dsa_notices_on_post_id (post_id) UNIQUE+#diff --git a/app/models/dsa/notice_verification.rb b/app/models/dsa/notice_verification.rbnew file mode 100644index 00000000000..f4a046a9ee3--- /dev/null+++ b/app/models/dsa/notice_verification.rb@@ -0,0 +1,47 @@+# frozen_string_literal: true++module Dsa+ class NoticeVerification+ VALID_FOR = 30.minutes++ def self.create(email)+ token = SecureRandom.hex(32)+ code = SecureRandom.random_number(1_000_000).to_s.rjust(6, "0")+ Discourse.redis.setex(key(token), VALID_FOR.to_i, { email:, code: }.to_json)+ token+ end++ def self.find(token)+ value = Discourse.redis.get(key(token))+ JSON.parse(value, symbolize_names: true) if value+ end++ def self.verify(token:, email:, code:)+ verification = find(token)+ return unless verification && verification[:code]++ RateLimiter.new(nil, "dsa-notice-verification-attempts-#{token}", 5, VALID_FOR).performed!+ unless verification[:email] == email &&+ ActiveSupport::SecurityUtils.secure_compare(verification[:code], code)+ return+ end++ saved =+ Discourse.redis.set(key(token), { email:, verified: true }.to_json, xx: true, keepttl: true)+ { email: } if saved+ end++ def self.consume(token:, email:)+ verification = find(token)+ return unless verification && verification[:verified] && verification[:email] == email++ value = Discourse.redis.getdel(key(token))+ JSON.parse(value, symbolize_names: true).except(:verified) if value+ end++ def self.key(token)+ "dsa-notice-verification:#{token}"+ end+ private_class_method :key+ end+enddiff --git a/app/services/dsa/request_notice_verification.rb b/app/services/dsa/request_notice_verification.rbnew file mode 100644index 00000000000..f9ed3e09ee8--- /dev/null+++ b/app/services/dsa/request_notice_verification.rb@@ -0,0 +1,54 @@+# frozen_string_literal: true++module Dsa+ class RequestNoticeVerification+ include Service::Base++ options { attribute :ip_address, :string }++ params do+ attribute :email, :string++ before_validation { self.email = email.to_s.strip.downcase }++ validates :email, presence: true, length: { maximum: 254 }+ validate :valid_email++ private++ def valid_email+ return if Email.is_valid?(email) && !email.match?(/[\r\n]/)+ errors.add(:email, I18n.t("dsa_notice.invalid_email"))+ end+ end++ step :rate_limit_notice+ model :token, :create_verification+ step :enqueue_verification++ private++ def rate_limit_notice(params:, options:)+ if options.ip_address.present?+ RateLimiter.new(nil, "dsa-notice-ip-#{options.ip_address}", 5, 1.hour).performed!+ end+ email_key = Digest::SHA256.hexdigest(params.email)+ email_limiter = RateLimiter.new(nil, "dsa-notice-email-#{email_key}", 3, 1.day)+ email_limiter.performed!+ begin+ RateLimiter.new(nil, "dsa-notice-global", 100, 1.hour).performed!+ rescue RateLimiter::LimitExceeded+ email_limiter.rollback!+ raise+ end+ end++ def create_verification(params:)+ Dsa::NoticeVerification.create(params.email)+ end++ def enqueue_verification(token:)+ Jobs.enqueue(:dsa_notice_verification, token:)+ end+ end+enddiff --git a/app/services/dsa/submit_notice.rb b/app/services/dsa/submit_notice.rbnew file mode 100644index 00000000000..995ca3506ff--- /dev/null+++ b/app/services/dsa/submit_notice.rb@@ -0,0 +1,93 @@+# frozen_string_literal: true++module Dsa+ class SubmitNotice+ include Service::Base++ params do+ attribute :notice do+ attribute :content_url, :string+ attribute :explanation, :string+ attribute :name, :string+ attribute :email, :string+ attribute :declaration, :boolean++ before_validation do+ @valid_shape =+ raw_attributes.all? do |field, value|+ if field == "declaration"+ [nil, true, false, "true", "false", "1", "0", 1, 0].include?(value)+ else+ value.nil? || value.is_a?(String)+ end+ end+ self.content_url = content_url.to_s.strip+ self.explanation = explanation.to_s.strip+ self.name = name.to_s.strip+ self.email = email.to_s.strip.downcase+ end++ validates :content_url, presence: true, length: { maximum: 2048 }+ validates :explanation, length: { minimum: 50, maximum: 20_000 }+ validates :declaration, inclusion: { in: [true] }+ validates :name, presence: true, length: { maximum: 200 }+ validates :email, presence: true, length: { maximum: 254 }+ validate :valid_shape+ validate :valid_content_url+ validate :valid_email++ private++ def valid_shape+ errors.add(:base, I18n.t("dsa_notice.invalid_parameters")) unless @valid_shape+ end++ def valid_content_url+ uri = URI.parse(content_url)+ if uri.is_a?(URI::HTTP) && uri.host.present? && uri.userinfo.nil? &&+ !content_url.match?(/[\s<>]/)+ return+ end+ errors.add(:content_url, I18n.t("dsa_notice.invalid_url"))+ rescue URI::InvalidURIError+ errors.add(:content_url, I18n.t("dsa_notice.invalid_url"))+ end++ def valid_email+ return if Email.is_valid?(email) && !email.match?(/[\r\n]/)+ errors.add(:email, I18n.t("dsa_notice.invalid_email"))+ end+ end++ attribute :token, :string++ validates :notice, presence: true+ validates :token, presence: true, length: { is: 64 }+ end++ model :verification+ model :notice, :create_notice+ step :enqueue_group_notifications+ step :enqueue_receipt++ private++ def fetch_verification(params:)+ Dsa::NoticeVerification.consume(token: params.token, email: params.notice.email)+ end++ def create_notice(params:)+ group = Group.find_by(id: SiteSetting.dsa_notice_group)+ group = Group[:admins] if !group || !group.users.exists?+ Dsa::Notice.create_with_post!(attributes: params.notice.to_hash.except(:declaration), group:)+ end++ def enqueue_group_notifications(notice:)+ PostJobsEnqueuer.new(notice.post, notice.post.topic, true).enqueue_jobs+ end++ def enqueue_receipt(notice:)+ Jobs.enqueue(:dsa_notice_receipt, notice_id: notice.id)+ end+ end+enddiff --git a/app/services/dsa/verify_notice_email.rb b/app/services/dsa/verify_notice_email.rbnew file mode 100644index 00000000000..b09c549cb10--- /dev/null+++ b/app/services/dsa/verify_notice_email.rb@@ -0,0 +1,31 @@+# frozen_string_literal: true++module Dsa+ class VerifyNoticeEmail+ include Service::Base++ params do+ attribute :token, :string+ attribute :email, :string+ attribute :verification_code, :string++ before_validation { self.email = email.to_s.strip.downcase }++ validates :token, presence: true, length: { is: 64 }+ validates :email, presence: true, length: { maximum: 254 }+ validates :verification_code, format: { with: /\A[0-9]{6}\z/ }+ end++ model :verification++ private++ def fetch_verification(params:)+ Dsa::NoticeVerification.verify(+ token: params.token,+ email: params.email,+ code: params.verification_code,+ )+ end+ end+enddiff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rbindex be58bda53a5..9c3e2131732 100644--- a/config/initializers/filter_parameter_logging.rb+++ b/config/initializers/filter_parameter_logging.rb@@ -5,6 +5,8 @@# Configure sensitive parameters which will be filtered from the log file.Rails.application.config.filter_parameters += %i[password+ token+ verification_codepop3_polling_passwordapi_keys3_secret_access_keydiff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex fa3befa34cb..b9384aa2842 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -1,5 +1,23 @@en:js:+ dsa_notice:+ title: "Report illegal content"+ content_url: "Exact URL of the content"+ explanation: "Why do you believe this content is illegal?"+ explanation_help: "Describe the facts and why the content may be illegal. You do not need to cite a specific law."+ name: "Full name or organization name"+ email: "Email address"+ declaration_section: "Declaration"+ declaration: "I confirm that I have a bona fide belief that the information and allegations in this notice are accurate and complete."+ submit: "Submit report"+ get_email_code: "Get email code"+ resend_email_code: "Resend code"+ email_verified: "Verified"+ verification_code: "Verification code"+ received: "Report received"+ received_description: "%{site} has received your report for review."+ reference: "Your report reference is <strong>%{reference}</strong>."+ contact_confirmation: "We will email you a receipt and a copy of your report. The reviewing team will email you the outcome."mcp_oauth_client_id_metadata_policy:disabled: "Admin registration only"approved_domains: "CIMD from approved domains"diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex f875b311870..d243a39ebde 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -1,4 +1,31 @@en:+ dsa_notice:+ subject: "[%{reference}] Report of potentially illegal content"+ summary: "**Report reference: %{reference}**\n\n**Email address:** %{reporter_email}\n\n**Full name or organization name:** %{reporter_name}\n\n**Exact URL of the content:** %{content_url}\n\n**Why do you believe this content is illegal?**\n\n%{explanation}"+ verification_invalid: "The email verification code is incorrect or has expired. Check the code or request a new one."+ invalid_parameters: "The report contains invalid values."+ invalid_url: "must be a valid HTTP or HTTPS URL without login credentials"+ invalid_email: "must be a valid email address"+ dsa_notice_verification:+ subject_template: "[%{email_prefix}] Your report verification code"+ text_body_template: |+ Use this code to verify your email for reporting illegal content on %{site_title}:++ ## %{verification_code}++ This code expires in %{expires_in_minutes} minutes. If you didn’t request it, you can safely ignore this email.+ dsa_notice_mailer:+ subject_template: "[%{email_prefix}] Your report of potentially illegal content %{reference}"+ text_body_template: |+ %{site_title} has received your report.++ The reviewing team will email you the outcome. This receipt does not mean that a decision has been made or that the content has been removed.++ %{summary}++ **Declaration:**++ I confirm that I have a bona fide belief that the information and allegations in this notice are accurate and complete.dsa_statements:classification_note: "Classified this moderation decision for DSA reporting.\nCommunity rule: %{ground}\nCategory: %{category}"errors:@@ -2118,6 +2145,7 @@ en:unavailable: "A random username could not be generated. Check the random username word lists in your site settings."site_settings:+ dsa_notice_group: "Group receiving illegal content notices when {{setting:dsa_reporting_enabled}} is enabled. Members can read notices and reporter contact details. Defaults to admins, which also receives notices if the selected group is missing or empty."dsa_community_rules: "Community rules available for DSA classification when {{setting:dsa_reporting_enabled}} is enabled. Each rule needs an exact contractual reference (up to 500 characters) and an explanation (up to 2000 characters). Leave empty to disable classification."allow_bulk_invite: "Allow bulk invites by uploading a CSV file"disabled: "disabled"diff --git a/config/routes.rb b/config/routes.rbindex 1cb2cc9be6c..62d555c8b25 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -683,6 +683,10 @@ Discourse::Application.routes.draw doget "password-reset" => "static#show", :id => "password_reset"get "privacy" => "static#show", :id => "privacy", :as => "privacy"get "tos" => "static#show", :id => "tos", :as => "tos"+ get "dsa/report-illegal-content" => "dsa_notices#index"+ post "dsa/report-illegal-content" => "dsa_notices#create"+ post "dsa/report-illegal-content/verify-email" => "dsa_notices#verify_email"+ post "dsa/report-illegal-content/verify-code" => "dsa_notices#verify_code"get "faq" => "static#show", :id => "faq"%w[guidelines rules conduct].each do |guidelines_alias|get guidelines_alias => "static#show", :id => "guidelines", :as => guidelines_aliasdiff --git a/config/site_settings.yml b/config/site_settings.ymlindex 801820c62b2..7032942c1a7 100644--- a/config/site_settings.yml+++ b/config/site_settings.yml@@ -4900,7 +4900,13 @@ experimental:enable_form_templates:client: truedefault: true+ dsa_notice_group:+ default: "1"+ type: group+ hidden: true+ area: "experimental"dsa_reporting_enabled:+ client: truedefault: falsehidden: truearea: "experimental"diff --git a/db/migrate/20261016063822_create_dsa_notices.rb b/db/migrate/20261016063822_create_dsa_notices.rbnew file mode 100644index 00000000000..ff003f5d903--- /dev/null+++ b/db/migrate/20261016063822_create_dsa_notices.rb@@ -0,0 +1,17 @@+# frozen_string_literal: true++class CreateDsaNotices < ActiveRecord::Migration[8.0]+ def change+ create_table :dsa_notices do |t|+ t.bigint :post_id+ t.text :content_url, null: false+ t.text :explanation, null: false+ t.string :name+ t.string :email+ t.datetime :receipt_sent_at+ t.datetime :created_at, null: false+ end++ add_index :dsa_notices, :post_id, unique: true+ end+enddiff --git a/db/structure.sql b/db/structure.sqlindex 6672cd5cacf..a159b317b9c 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -6095,6 +6095,41 @@ CREATE SEQUENCE public.drafts_id_seqALTER SEQUENCE public.drafts_id_seq OWNED BY public.drafts.id;+--+-- Name: dsa_notices; Type: TABLE; Schema: public; Owner: -+--++CREATE TABLE public.dsa_notices (+ id bigint NOT NULL,+ post_id bigint,+ content_url text NOT NULL,+ explanation text NOT NULL,+ name character varying,+ email character varying,+ receipt_sent_at timestamp(6) without time zone,+ created_at timestamp(6) without time zone NOT NULL+);+++--+-- Name: dsa_notices_id_seq; Type: SEQUENCE; Schema: public; Owner: -+--++CREATE SEQUENCE public.dsa_notices_id_seq+ START WITH 1+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+++--+-- Name: dsa_notices_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -+--++ALTER SEQUENCE public.dsa_notices_id_seq OWNED BY public.dsa_notices.id;++---- Name: dsa_statement_of_records; Type: TABLE; Schema: public; Owner: ---@@ -15114,6 +15149,13 @@ ALTER TABLE ONLY public.draft_sequences ALTER COLUMN id SET DEFAULT nextval('pubALTER TABLE ONLY public.drafts ALTER COLUMN id SET DEFAULT nextval('public.drafts_id_seq'::regclass);+--+-- Name: dsa_notices id; Type: DEFAULT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.dsa_notices ALTER COLUMN id SET DEFAULT nextval('public.dsa_notices_id_seq'::regclass);++---- Name: email_change_requests id; Type: DEFAULT; Schema: public; Owner: ---@@ -17833,6 +17875,14 @@ ALTER TABLE ONLY public.draftsADD CONSTRAINT drafts_pkey PRIMARY KEY (id);+--+-- Name: dsa_notices dsa_notices_pkey; Type: CONSTRAINT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.dsa_notices+ ADD CONSTRAINT dsa_notices_pkey PRIMARY KEY (id);++---- Name: dsa_statement_of_records dsa_statement_of_records_pkey; Type: CONSTRAINT; Schema: public; Owner: ---@@ -22228,6 +22278,13 @@ CREATE UNIQUE INDEX index_draft_sequences_on_user_id_and_draft_key ON public.draCREATE UNIQUE INDEX index_drafts_on_user_id_and_draft_key ON public.drafts USING btree (user_id, draft_key);+--+-- Name: index_dsa_notices_on_post_id; Type: INDEX; Schema: public; Owner: -+--++CREATE UNIQUE INDEX index_dsa_notices_on_post_id ON public.dsa_notices USING btree (post_id);++---- Name: index_dsa_statement_of_records_on_reviewable_id; Type: INDEX; Schema: public; Owner: ---@@ -26111,6 +26168,7 @@ INSERT INTO "schema_migrations" (version) VALUES('20261019105124'),('20261019104439'),('20261018172000'),+('20261016063822'),('20261015175355'),('20261015175340'),('20261015121116'),diff --git a/frontend/discourse/app/components/dsa-notice-form.gjs b/frontend/discourse/app/components/dsa-notice-form.gjsnew file mode 100644index 00000000000..d84612c04b3--- /dev/null+++ b/frontend/discourse/app/components/dsa-notice-form.gjs@@ -0,0 +1,322 @@+import Component from "@glimmer/component";+import { cached, tracked } from "@glimmer/tracking";+import { array, hash } from "@ember/helper";+import { action } from "@ember/object";+import { service } from "@ember/service";+import { trustHTML } from "@ember/template";+import Form from "discourse/components/form";+import FKContainer from "discourse/form-kit/components/fk/container";+import FKErrors from "discourse/form-kit/components/fk/errors";+import { ajax } from "discourse/lib/ajax";+import { extractError, popupAjaxError } from "discourse/lib/ajax-error";+import { emailValid, escapeExpression } from "discourse/lib/utilities";+import { and, not, or } from "discourse/truth-helpers";+import DOtp from "discourse/ui-kit/d-otp";+import dLoadingSpinner from "discourse/ui-kit/helpers/d-loading-spinner";+import dAutoFocus from "discourse/ui-kit/modifiers/d-auto-focus";+import { i18n } from "discourse-i18n";++export default class DsaNoticeForm extends Component {+ @service siteSettings;++ @tracked result;+ @tracked emailVerified = false;+ @tracked requestingCode = false;+ @tracked verificationError;+ @tracked verifyingCode = false;+ @tracked verificationToken;++ #form;++ get emailCodeDisabled() {+ const email = this.#form?.get("email")?.trim();+ return (+ this.emailVerified ||+ this.requestingCode ||+ this.verifyingCode ||+ !email ||+ !emailValid(email)+ );+ }++ get emailCodeLabel() {+ if (this.emailVerified) {+ return "dsa_notice.email_verified";+ }+ return this.verificationToken+ ? "dsa_notice.resend_email_code"+ : "dsa_notice.get_email_code";+ }++ @cached+ get initialData() {+ return {+ content_url: this.args.contentUrl,+ declaration: false,+ };+ }++ @action+ registerForm(form) {+ this.#form = form;+ }++ @action+ codeChanged(value) {+ this.#form.set("verification_code", value);+ this.verificationError = null;+ if (value.length === 6) {+ this.verifyCode(value);+ }+ }++ @action+ emailChanged(value, { set }) {+ set("email", value);+ set("verification_code", "");+ this.emailVerified = false;+ this.verificationError = null;+ this.verificationToken = null;+ }++ @action+ async requestCode() {+ const email = this.#form.get("email")?.trim().toLowerCase();+ if (!email || !emailValid(email)) {+ this.#form.addError("email", {+ title: i18n("dsa_notice.email"),+ message: i18n("user.email.invalid"),+ });+ return;+ }++ this.requestingCode = true;+ try {+ const result = await ajax("/dsa/report-illegal-content/verify-email", {+ type: "POST",+ data: { email },+ });+ if (this.#form.get("email")?.trim().toLowerCase() === email) {+ this.verificationToken = result.token;+ this.verificationError = null;+ this.#form.set("verification_code", "");+ }+ } catch (error) {+ popupAjaxError(error);+ } finally {+ this.requestingCode = false;+ }+ }++ @action+ async submit(data) {+ const notice = { ...data };+ delete notice.verification_code;+ try {+ this.result = await ajax("/dsa/report-illegal-content", {+ type: "POST",+ data: { notice, token: this.verificationToken },+ });+ window.scrollTo(0, 0);+ } catch (error) {+ if (error.jqXHR?.responseJSON?.error_type === "verification_required") {+ this.emailVerified = false;+ this.verificationToken = null;+ this.verificationError = null;+ this.#form.set("verification_code", "");+ }+ popupAjaxError(error);+ }+ }++ @action+ async verifyCode(verification_code) {+ if (this.verifyingCode || this.emailVerified) {+ return;+ }++ this.verifyingCode = true;+ try {+ await ajax("/dsa/report-illegal-content/verify-code", {+ type: "POST",+ data: {+ token: this.verificationToken,+ email: this.#form.get("email")?.trim().toLowerCase(),+ verification_code,+ },+ });+ this.emailVerified = true;+ } catch (error) {+ this.verificationError =+ error.jqXHR?.responseJSON?.errors?.[0] || extractError(error);+ } finally {+ this.verifyingCode = false;+ }+ }++ @action+ validateEmail(name, value, { addError }) {+ if (value && !emailValid(value.trim())) {+ addError(name, {+ title: i18n("dsa_notice.email"),+ message: i18n("user.email.invalid"),+ });+ }+ }++ <template>+ <div class="dsa-notice" ...attributes>+ {{#if this.result}}+ <h1 tabindex="-1" {{dAutoFocus}}>{{i18n "dsa_notice.received"}}</h1>+ <p>{{i18n+ "dsa_notice.received_description"+ site=this.siteSettings.title+ }}</p>+ <p class="dsa-notice__reference">+ {{trustHTML+ (i18n+ "dsa_notice.reference"+ reference=(escapeExpression this.result.reference)+ )+ }}+ </p>+ <p>{{i18n "dsa_notice.contact_confirmation"}}</p>+ {{else}}+ <h1>{{i18n "dsa_notice.title"}}</h1>+ <FKContainer @direction="column" @format="max">+ <Form+ @data={{this.initialData}}+ @onRegisterApi={{this.registerForm}}+ @onSubmit={{this.submit}}+ as |form|+ >+ <form.Section>+ <form.Fieldset+ aria-busy={{or this.requestingCode this.verifyingCode}}+ aria-label={{i18n "dsa_notice.email"}}+ disabled={{or this.requestingCode this.verifyingCode}}+ >+ <form.Field+ @disabled={{or this.emailVerified this.verifyingCode}}+ @format="full"+ @name="email"+ @onSet={{this.emailChanged}}+ @title={{i18n "dsa_notice.email"}}+ @type="input-email"+ @validate={{this.validateEmail}}+ @validation="required"+ as |field|+ >+ <form.Actions>+ <field.Control autocomplete="email" />+ <form.Button+ aria-live="polite"+ class={{if+ this.emailVerified+ "btn-success"+ "btn-default"+ }}+ @action={{this.requestCode}}+ @disabled={{this.emailCodeDisabled}}+ @icon={{if this.emailVerified "check"}}+ @isLoading={{this.requestingCode}}+ @label={{this.emailCodeLabel}}+ />+ </form.Actions>+ </form.Field>+ {{#if (and this.verificationToken (not this.emailVerified))}}+ <form.Field+ class={{if this.verificationError "has-error"}}+ @disabled={{this.verifyingCode}}+ @format="full"+ @name="verification_code"+ @title={{i18n "dsa_notice.verification_code"}}+ @type="custom"+ @validation="required"+ as |field|+ >+ <form.Actions>+ {{#each (array this.verificationToken) key="@identity"}}+ <DOtp+ aria-describedby={{if+ this.verificationError+ field.errorId+ }}+ aria-invalid={{if this.verificationError "true"}}+ id={{field.id}}+ @onChange={{this.codeChanged}}+ />+ {{/each}}+ {{#if this.verifyingCode}}+ <div aria-label={{i18n "loading"}} role="status">+ {{dLoadingSpinner size="small"}}+ </div>+ {{/if}}+ </form.Actions>+ {{#if this.verificationError}}+ <FKErrors+ @error={{hash messages=(array this.verificationError)}}+ @id={{field.errorId}}+ />+ {{/if}}+ </form.Field>+ {{/if}}+ </form.Fieldset>+ <form.Field+ @disabled={{not this.emailVerified}}+ @format="full"+ @name="name"+ @title={{i18n "dsa_notice.name"}}+ @type="input"+ @validation="required:trim|length:1,200"+ as |field|+ >+ <field.Control autocomplete="name" />+ </form.Field>+ <form.Field+ @disabled={{not this.emailVerified}}+ @format="full"+ @name="content_url"+ @title={{i18n "dsa_notice.content_url"}}+ @type="input-url"+ @validation="required|url"+ as |field|+ >+ <field.Control />+ </form.Field>+ <form.Field+ @description={{i18n "dsa_notice.explanation_help"}}+ @disabled={{not this.emailVerified}}+ @format="full"+ @name="explanation"+ @title={{i18n "dsa_notice.explanation"}}+ @type="textarea"+ @validation="required:trim|length:50,20000"+ as |field|+ >+ <field.Control rows="6" />+ </form.Field>+ <form.Field+ @disabled={{not this.emailVerified}}+ @format="full"+ @name="declaration"+ @title={{i18n "dsa_notice.declaration_section"}}+ @type="checkbox"+ @validation="accepted"+ as |field|+ >+ <field.Control @title={{i18n "dsa_notice.declaration"}} />+ </form.Field>+ <form.Actions>+ <form.Submit+ @disabled={{not this.emailVerified}}+ @label="dsa_notice.submit"+ />+ </form.Actions>+ </form.Section>+ </Form>+ </FKContainer>+ {{/if}}+ </div>+ </template>+}diff --git a/frontend/discourse/app/controllers/report-illegal-content.js b/frontend/discourse/app/controllers/report-illegal-content.jsnew file mode 100644index 00000000000..b7d5d7864d0--- /dev/null+++ b/frontend/discourse/app/controllers/report-illegal-content.js@@ -0,0 +1,8 @@+import { tracked } from "@glimmer/tracking";+import Controller from "@ember/controller";++export default class ReportIllegalContentController extends Controller {+ @tracked content_url = "";++ queryParams = ["content_url"];+}diff --git a/frontend/discourse/app/routes/app-route-map.js b/frontend/discourse/app/routes/app-route-map.jsindex 01ccd7b96c3..d7768d19d3d 100644--- a/frontend/discourse/app/routes/app-route-map.js+++ b/frontend/discourse/app/routes/app-route-map.js@@ -8,6 +8,7 @@ export default function () {this.route("exception-unknown", { path: "/404" });this.route("about");+ this.route("report-illegal-content", { path: "/dsa/report-illegal-content" });this.route("post", { path: "/p/:id" });this.route("posts");diff --git a/frontend/discourse/app/routes/report-illegal-content.js b/frontend/discourse/app/routes/report-illegal-content.jsnew file mode 100644index 00000000000..d86bbc1eece--- /dev/null+++ b/frontend/discourse/app/routes/report-illegal-content.js@@ -0,0 +1,17 @@+import { service } from "@ember/service";+import DiscourseRoute from "discourse/routes/discourse";+import { i18n } from "discourse-i18n";++export default class ReportIllegalContentRoute extends DiscourseRoute {+ @service router;++ beforeModel() {+ if (!this.siteSettings.dsa_reporting_enabled) {+ return this.router.replaceWith("exception-unknown");+ }+ }++ titleToken() {+ return i18n("dsa_notice.title", { site: this.siteSettings.title });+ }+}diff --git a/frontend/discourse/app/routes/topic.js b/frontend/discourse/app/routes/topic.jsindex a0340452ee0..4f25ea17cd2 100644--- a/frontend/discourse/app/routes/topic.js+++ b/frontend/discourse/app/routes/topic.js@@ -82,6 +82,15 @@ export default class TopicRoute extends DiscourseRoute {@actionshowFlags(model) {+ if (!this.currentUser && this.siteSettings.dsa_reporting_enabled) {+ this.router.transitionTo("report-illegal-content", {+ queryParams: {+ content_url: window.location.origin + model.urlWithNumber,+ },+ });+ return;+ }+this.modal.show(this.currentUser ? FlagModal : AnonymousFlagModal, {model: {flagTarget: new PostFlag(),diff --git a/frontend/discourse/app/templates/report-illegal-content.gjs b/frontend/discourse/app/templates/report-illegal-content.gjsnew file mode 100644index 00000000000..c6f7f6f60cb--- /dev/null+++ b/frontend/discourse/app/templates/report-illegal-content.gjs@@ -0,0 +1,7 @@+import DsaNoticeForm from "discourse/components/dsa-notice-form";+import hideApplicationSidebar from "discourse/helpers/hide-application-sidebar";++export default <template>+ {{hideApplicationSidebar}}+ <DsaNoticeForm @contentUrl={{@controller.content_url}} />+</template>diff --git a/spec/jobs/dsa_notice_receipt_spec.rb b/spec/jobs/dsa_notice_receipt_spec.rbnew file mode 100644index 00000000000..377a114717d--- /dev/null+++ b/spec/jobs/dsa_notice_receipt_spec.rb@@ -0,0 +1,54 @@+# frozen_string_literal: true++RSpec.describe Jobs::DsaNoticeReceipt do+ describe "#execute" do+ fab!(:admin)+ fab!(:group)++ let(:notice_params) do+ {+ content_url: "https://example.com/post?a=1&b=2",+ explanation:+ "This listing advertises counterfeit goods as authentic and its payment instructions appear intended to deceive buyers.",+ name: "Pat O'Brien",+ email: "[email protected]",+ }+ end++ let(:notice) { Dsa::Notice.create_with_post!(attributes: notice_params, group:) }+ let(:notice_id) { notice.id }+ let(:job) { described_class.new }++ before do+ SiteSetting.disable_emails = "no"+ group.add(admin)+ end++ it "delivers a receipt once and marks it sent" do+ expect do+ job.execute(notice_id:)+ job.execute(notice_id:)+ end.to change { ActionMailer::Base.deliveries.size }.by(1)++ expect(notice.reload).to be_receipt_sent+ end++ it "leaves delivery pending after SMTP failure and can retry" do+ Email::Sender.any_instance.stubs(:send).raises(Net::SMTPServerBusy, "SMTP unavailable")+ expect { job.execute(notice_id:) }.to raise_error(Net::SMTPServerBusy)+ expect(notice.reload).not_to be_receipt_sent+ Email::Sender.any_instance.unstub(:send)+ expect { job.execute(notice_id:) }.to change { ActionMailer::Base.deliveries.size }.by(1)+ end++ it "leaves the receipt pending when delivery is suppressed" do+ SiteSetting.disable_emails = "yes"+ expect { job.execute(notice_id:) }.not_to change { ActionMailer::Base.deliveries.size }+ expect(notice.reload).not_to be_receipt_sent+ end++ it "ignores a missing notice" do+ expect { job.execute(notice_id: -1) }.not_to change { ActionMailer::Base.deliveries.size }+ end+ end+enddiff --git a/spec/jobs/dsa_notice_verification_spec.rb b/spec/jobs/dsa_notice_verification_spec.rbnew file mode 100644index 00000000000..8e2d405d512--- /dev/null+++ b/spec/jobs/dsa_notice_verification_spec.rb@@ -0,0 +1,29 @@+# frozen_string_literal: true++RSpec.describe Jobs::DsaNoticeVerification do+ describe "#execute" do+ let(:email) { "[email protected]" }+ let(:token) { Dsa::NoticeVerification.create(email) }+ let(:job) { described_class.new }++ before { SiteSetting.disable_emails = "no" }++ it "emails the reporter without consuming the verification" do+ expect { job.execute(token:) }.to change { ActionMailer::Base.deliveries.size }.by(1)++ expect(ActionMailer::Base.deliveries.last.to).to eq([email])+ expect(Dsa::NoticeVerification.find(token)).to include(email:)+ end++ it "sends nothing after the email has been verified" do+ code = Dsa::NoticeVerification.find(token)[:code]+ Dsa::NoticeVerification.verify(token:, email:, code:)++ expect { job.execute(token:) }.not_to change { ActionMailer::Base.deliveries.size }+ end++ it "sends nothing when the pending submission is unavailable" do+ expect { job.execute(token: "a" * 64) }.not_to change { ActionMailer::Base.deliveries.size }+ end+ end+enddiff --git a/spec/mailers/dsa_notice_mailer_spec.rb b/spec/mailers/dsa_notice_mailer_spec.rbnew file mode 100644index 00000000000..6e7f2b91674--- /dev/null+++ b/spec/mailers/dsa_notice_mailer_spec.rb@@ -0,0 +1,61 @@+# frozen_string_literal: true++RSpec.describe DsaNoticeMailer do+ describe "#verification" do+ it "emails the verification code and its lifetime" do+ code = "012345"+ message = described_class.verification(email: "[email protected]", code:)++ expect(message.to).to eq(["[email protected]"])+ expect(message.subject).to include("Your report verification code")+ expect(message.body.decoded).to include(+ code,+ "30 minutes",+ "verify your email for reporting illegal content",+ )+ expect(message["X-Discourse-Reply-Key"]).to be_nil+ end+ end++ describe "#receipt" do+ let(:notice) do+ Dsa::Notice.new(+ {+ "id" => 123,+ "content_url" => "https://example.com/post?a=1&b=2",+ "explanation" =>+ "This listing advertises counterfeit goods as authentic and deceives buyers.",+ "name" => "Pat O'Brien",+ "email" => "[email protected]",+ },+ )+ end++ it "addresses the reporter and renders the reference and submitted summary in both formats" do+ message = described_class.receipt(notice)++ expect(message.to).to eq([notice.email])+ expect(message.subject).to include(notice.reference)+ expect(message.text_part.decoded).to include(notice.summary(plain_text: true))+ fragment = Nokogiri::HTML5.fragment(message.html_part.decoded)+ expected_summary = Nokogiri::HTML5.fragment(PrettyText.cook(notice.summary))+ expect(fragment.text).to include(expected_summary.text)+ expect(fragment.css("strong").map(&:text)).to eq(+ [+ "Report reference: #{notice.reference}",+ "Email address:",+ "Full name or organization name:",+ "Exact URL of the content:",+ "Why do you believe this content is illegal?",+ "Declaration:",+ ],+ )+ expect(fragment.text.scan(notice.reference).length).to eq(1)+ expect(message.text_part.decoded.scan(notice.reference).length).to eq(1)+ expect(fragment.at_css('a[href^="https://example.com/"]')["href"]).to eq(+ "https://example.com/post?a=1&b=2",+ )+ expect(message["X-Discourse-Reply-Key"]).to be_nil+ end+ end+enddiff --git a/spec/models/dsa/notice_spec.rb b/spec/models/dsa/notice_spec.rbnew file mode 100644index 00000000000..f06d860541e--- /dev/null+++ b/spec/models/dsa/notice_spec.rb@@ -0,0 +1,101 @@+# frozen_string_literal: true++RSpec.describe Dsa::Notice do+ let(:attributes) do+ {+ content_url: "https://example.com/post?a=1&b=2",+ explanation: "This listing advertises counterfeit goods as authentic and deceives buyers.",+ name: "Pat O'Brien",+ email: "[email protected]",+ }+ end++ describe ".create_with_post!" do+ fab!(:group)++ it "stores the original notice independently of the PM text" do+ attributes[:name] = "Alex\u00a0Morgan"+ attributes[:explanation] += "\nEvidence\u2002copied\u202ffrom\u3000a listing."++ created_notice = described_class.create_with_post!(attributes:, group:)+ saved_notice = described_class.find(created_notice.id)++ expect(saved_notice.post.id).to eq(created_notice.post.id)+ saved_notice.post.update!(raw: "Staff edited this PM.")+ expect(saved_notice.reload.attributes.symbolize_keys.slice(*attributes.keys)).to eq(+ attributes,+ )+ expect(saved_notice.reference).to eq("DSA-#{saved_notice.id}")+ expect(saved_notice.summary(plain_text: true)).to include(+ attributes[:name],+ attributes[:explanation],+ )+ end++ it "rolls back the notice when the PM cannot be stored" do+ PostCreator.stubs(:create!).raises(ActiveRecord::RecordNotSaved)+ notice_count = described_class.count++ expect do described_class.create_with_post!(attributes:, group:) end.to raise_error(+ ActiveRecord::RecordNotSaved,+ )++ expect(described_class.count).to eq(notice_count)+ end+ end++ describe "#mark_receipt_sent!" do+ fab!(:group)++ it "records when the receipt was sent" do+ notice = described_class.create_with_post!(attributes:, group:)++ freeze_time do+ notice.mark_receipt_sent!++ expect(notice.reload.receipt_sent_at).to eq_time(Time.current)+ expect(notice).to be_receipt_sent+ end+ end+ end++ describe "#summary" do+ subject(:notice) { described_class.new(attributes.merge(id: 123)) }++ it "keeps supplied formatting and mentions out of the trusted message structure" do+ attributes[+ :explanation+ ] = "## Forged instructions\n\nForged staff instructions\n=========================\n\n@admins \n<script>alert(1)</script>"++ fragment = Nokogiri::HTML5.fragment(PrettyText.cook(notice.summary))++ expect(fragment.css("img, script, a.mention")).to be_empty+ expect(fragment.css("h1, h2, h3").map(&:text)).not_to include(+ "Forged instructions",+ "Forged staff instructions",+ )+ expect(fragment.text).to include(+ "@admins",+ "Forged instructions",+ "<script>alert(1)</script>",+ )+ end++ it "preserves literal punctuation and exact URL query parameters" do+ attributes[+ :explanation+ ] = "It's a scam. Literal characters: ' \\1 --> <script> are part of the submitted evidence."++ fragment = Nokogiri::HTML5.fragment(PrettyText.cook(notice.summary))++ expect(fragment.text).to include(attributes[:name], attributes[:explanation])+ expect(fragment.at_css('a[href^="https://example.com/"]')["href"]).to eq(+ attributes[:content_url],+ )+ expect(notice.summary(plain_text: true)).to include(+ attributes[:name],+ attributes[:explanation],+ )+ end+ end+enddiff --git a/spec/models/dsa/notice_verification_spec.rb b/spec/models/dsa/notice_verification_spec.rbnew file mode 100644index 00000000000..6fd82e8720a--- /dev/null+++ b/spec/models/dsa/notice_verification_spec.rb@@ -0,0 +1,92 @@+# frozen_string_literal: true++RSpec.describe Dsa::NoticeVerification do+ let(:email) { "[email protected]" }+ let(:token) { described_class.create(email) }+ let(:code) { described_class.find(token)[:code] }++ describe ".create" do+ it "stores a six digit email code for thirty minutes" do+ verification = described_class.find(token)++ expect(token).to match(/\A[0-9a-f]{64}\z/)+ expect(verification[:email]).to eq(email)+ expect(verification[:code]).to match(/\A[0-9]{6}\z/)+ expect(verification.keys).to contain_exactly(:email, :code)+ expect(Discourse.redis.ttl("dsa-notice-verification:#{token}")).to be_within(5.seconds).of(+ 30.minutes.to_i,+ )+ end+ end++ describe ".find" do+ it "returns a pending verification without consuming it" do+ verification = described_class.find(token)++ expect(described_class.find(token)).to eq(verification)+ end++ it "returns no verification for an unknown token" do+ expect(described_class.find("a" * 64)).to be_nil+ end+ end++ describe ".verify" do+ it "marks the email verified without extending its lifetime" do+ verification_code = code++ Discourse.redis.expire("dsa-notice-verification:#{token}", 1200)++ expect(described_class.verify(token:, email:, code: verification_code)).to eq(email:)+ expect(described_class.find(token)).to eq(email:, verified: true)+ expect(Discourse.redis.ttl("dsa-notice-verification:#{token}")).to be_within(5.seconds).of(+ 1200,+ )+ end++ it "keeps a code available after an incorrect attempt" do+ verification_code = code+ wrong_code = verification_code == "123456" ? "654321" : "123456"++ expect(described_class.verify(token:, email:, code: wrong_code)).to be_nil+ expect(described_class.verify(token:, email:, code: verification_code)).to eq(email:)+ end++ it "rejects a code presented for a different email" do+ expect(described_class.verify(token:, email: "[email protected]", code:)).to be_nil+ end++ it "limits a verification to five attempts" do+ RateLimiter.enable+ verification_code = code+ wrong_code = verification_code == "123456" ? "654321" : "123456"+ 5.times { described_class.verify(token:, email:, code: wrong_code) }++ expect do described_class.verify(token:, email:, code: verification_code) end.to raise_error(+ RateLimiter::LimitExceeded,+ )+ end+ end++ describe ".consume" do+ it "accepts a verified email only once" do+ described_class.verify(token:, email:, code:)++ expect(described_class.consume(token:, email:)).to eq(email:)+ expect(described_class.consume(token:, email:)).to be_nil+ expect(described_class.find(token)).to be_nil+ end++ it "rejects an email while its code is still pending" do+ expect(described_class.consume(token:, email:)).to be_nil+ expect(described_class.find(token)).to include(:code)+ end++ it "rejects a verified token presented for another email" do+ described_class.verify(token:, email:, code:)++ expect(described_class.consume(token:, email: "[email protected]")).to be_nil+ expect(described_class.consume(token:, email:)).to eq(email:)+ end+ end+enddiff --git a/spec/requests/dsa_notices_controller_spec.rb b/spec/requests/dsa_notices_controller_spec.rbnew file mode 100644index 00000000000..31269fe6dd0--- /dev/null+++ b/spec/requests/dsa_notices_controller_spec.rb@@ -0,0 +1,192 @@+# frozen_string_literal: true++RSpec.describe DsaNoticesController do+ fab!(:group)++ let(:email) { "[email protected]" }+ let(:notice) do+ {+ content_url: "#{Discourse.base_url}/t/reported-content/123/4",+ explanation:+ "This listing advertises counterfeit goods as authentic and its payment instructions appear intended to deceive buyers.",+ name: "Alex Morgan",+ email:,+ declaration: true,+ }+ end++ before do+ SiteSetting.dsa_reporting_enabled = true+ SiteSetting.dsa_notice_group = group.id.to_s+ end++ describe "#index" do+ it "serves the form without login on a private site" do+ SiteSetting.login_required = true+ get "/dsa/report-illegal-content"+ expect(response.status).to eq(200)+ get "/dsa/report-illegal-content.json"+ expect(response.status).to eq(406)+ end++ it "returns not found when disabled" do+ SiteSetting.dsa_reporting_enabled = false+ get "/dsa/report-illegal-content"+ expect(response.status).to eq(404)+ end+ end++ describe "#verify_email" do+ it "requests a code without requiring report details or login" do+ SiteSetting.login_required = true++ expect do+ post "/dsa/report-illegal-content/verify-email.json", params: { email: }+ end.not_to change(Dsa::Notice, :count)++ expect(response.status).to eq(202)+ expect(response.parsed_body.keys).to contain_exactly("token")+ expect(response.parsed_body["token"]).to match(/\A[0-9a-f]{64}\z/)+ end++ it "returns not found when disabled" do+ SiteSetting.dsa_reporting_enabled = false+ post "/dsa/report-illegal-content/verify-email.json", params: { email: }+ expect(response.status).to eq(404)+ end++ it "returns email validation errors as unprocessable content" do+ post "/dsa/report-illegal-content/verify-email.json", params: { email: "invalid" }++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to be_present+ end++ it "returns too many requests when requesting a code is rate limited" do+ RateLimiter.enable+ 5.times { RateLimiter.new(nil, "dsa-notice-ip-127.0.0.1", 5, 1.hour).performed! }++ post "/dsa/report-illegal-content/verify-email.json", params: { email: }++ expect(response.status).to eq(429)+ end++ it "requires CSRF protection for code requests" do+ ActionController::Base.allow_forgery_protection = true+ post "/dsa/report-illegal-content/verify-email.json", params: { email: }+ expect(response.status).to eq(403)+ ensure+ ActionController::Base.allow_forgery_protection = false+ end+ end++ describe "#verify_code" do+ let(:token) { Dsa::NoticeVerification.create(email) }+ let(:verification_code) { Dsa::NoticeVerification.find(token)[:code] }+ let(:params) { { email:, token:, verification_code: } }++ it "verifies the email without login or creating a report" do+ SiteSetting.login_required = true++ expect do+ post "/dsa/report-illegal-content/verify-code.json", params: params+ end.not_to change(Dsa::Notice, :count)++ expect(response.status).to eq(200)+ end++ it "returns an actionable error for an unavailable verification" do+ post "/dsa/report-illegal-content/verify-code.json",+ params: {+ email:,+ token: "a" * 64,+ verification_code: "123456",+ }++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to eq([I18n.t("dsa_notice.verification_invalid")])+ end++ it "returns too many requests when code verification attempts are exhausted" do+ RateLimiter.enable+ 5.times do+ RateLimiter.new(nil, "dsa-notice-verification-attempts-#{token}", 5, 30.minutes).performed!+ end++ post "/dsa/report-illegal-content/verify-code.json", params: params++ expect(response.status).to eq(429)+ end++ it "returns not found when disabled" do+ SiteSetting.dsa_reporting_enabled = false+ post "/dsa/report-illegal-content/verify-code.json", params: params+ expect(response.status).to eq(404)+ end++ it "requires CSRF protection for verifying codes" do+ ActionController::Base.allow_forgery_protection = true+ post "/dsa/report-illegal-content/verify-code.json", params: params+ expect(response.status).to eq(403)+ ensure+ ActionController::Base.allow_forgery_protection = false+ end+ end++ describe "#create" do+ let(:token) do+ pending_token = Dsa::NoticeVerification.create(email)+ code = Dsa::NoticeVerification.find(pending_token)[:code]+ Dsa::NoticeVerification.verify(token: pending_token, email:, code:)+ pending_token+ end+ let(:params) { { notice:, token: } }++ it "accepts a report with a verified email without login and returns its reference" do+ SiteSetting.login_required = true+ post "/dsa/report-illegal-content.json", params: params++ expect(response.status).to eq(201)+ expect(response.parsed_body["reference"]).to start_with("DSA-")+ end++ it "returns not found when disabled" do+ SiteSetting.dsa_reporting_enabled = false+ post "/dsa/report-illegal-content.json", params: params+ expect(response.status).to eq(404)+ end++ it "returns report validation errors as unprocessable content" do+ params[:notice][:declaration] = false+ post "/dsa/report-illegal-content.json", params: params++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to be_present+ end++ it "returns an actionable error when the email verification is unavailable" do+ post "/dsa/report-illegal-content.json", params: { notice:, token: "a" * 64 }++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to eq([I18n.t("dsa_notice.verification_invalid")])+ expect(response.parsed_body["error_type"]).to eq("verification_required")+ end++ it "returns a generic failure when the notice cannot be saved" do+ exception = ActiveRecord::RecordNotSaved.new("save failed")+ PostCreator.stubs(:create!).raises(exception)+ post "/dsa/report-illegal-content.json", params: params++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to eq([I18n.t("js.generic_error")])+ end++ it "requires CSRF protection for report submission" do+ ActionController::Base.allow_forgery_protection = true+ post "/dsa/report-illegal-content.json", params: params+ expect(response.status).to eq(403)+ ensure+ ActionController::Base.allow_forgery_protection = false+ end+ end+enddiff --git a/spec/services/dsa/request_notice_verification_spec.rb b/spec/services/dsa/request_notice_verification_spec.rbnew file mode 100644index 00000000000..9e2ae20f52a--- /dev/null+++ b/spec/services/dsa/request_notice_verification_spec.rb@@ -0,0 +1,128 @@+# frozen_string_literal: true++RSpec.describe Dsa::RequestNoticeVerification do+ let(:params) { { email: "[email protected]" } }++ describe described_class::Contract, type: :model do+ subject(:contract) { described_class.new(params) }++ it { is_expected.to validate_presence_of(:email) }+ it { is_expected.to validate_length_of(:email).is_at_most(254) }+ it { is_expected.not_to allow_value("invalid").for(:email) }+ it { is_expected.not_to allow_value("[email protected]\r\nBcc: [email protected]").for(:email) }++ it "normalizes the email before requesting its code" do+ params[:email] = " [email protected] "++ expect(contract).to be_valid+ expect(contract.email).to eq("[email protected]")+ end+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ let(:dependencies) { { options: { ip_address: "198.51.100.1" } } }++ context "when the contract is invalid" do+ before { params[:email] = nil }++ it "halts before queuing verification" do+ expect { result }.not_to change { Jobs::DsaNoticeVerification.jobs.size }+ expect(result).to fail_a_contract+ end+ end++ context "when rate limits are enabled" do+ before { RateLimiter.enable }++ it "limits notices by email address" do+ email_key = Digest::SHA256.hexdigest(params[:email])+ 3.times { RateLimiter.new(nil, "dsa-notice-email-#{email_key}", 3, 1.day).performed! }++ expect { result }.to raise_error(RateLimiter::LimitExceeded)+ end++ it "does not charge notice limits for rejected validation attempts" do+ 5.times do+ invalid_result =+ described_class.call(params: params.merge(email: "invalid"), **dependencies)+ expect(invalid_result).to fail_a_contract+ end++ expect(result).to run_successfully+ end++ it "preserves shared notice capacity when an email exceeds its allowance" do+ email_key = Digest::SHA256.hexdigest(params[:email])+ 3.times { RateLimiter.new(nil, "dsa-notice-email-#{email_key}", 3, 1.day).performed! }+ 99.times { RateLimiter.new(nil, "dsa-notice-global", 100, 1.hour).performed! }+ expect { result }.to raise_error(RateLimiter::LimitExceeded)++ other_reporter_params = params.merge(email: "[email protected]")+ remaining_result =+ described_class.call(+ params: other_reporter_params,+ options: {+ ip_address: "198.51.100.2",+ },+ )+ expect(remaining_result).to run_successfully++ expect do+ described_class.call(+ params: other_reporter_params,+ options: {+ ip_address: "198.51.100.3",+ },+ )+ end.to raise_error(RateLimiter::LimitExceeded)+ end++ it "refunds the email allowance when the site notice limit rejects a notice" do+ email_key = Digest::SHA256.hexdigest(params[:email])+ 2.times { RateLimiter.new(nil, "dsa-notice-email-#{email_key}", 3, 1.day).performed! }+ 100.times { RateLimiter.new(nil, "dsa-notice-global", 100, 1.hour).performed! }+ expect { result }.to raise_error(RateLimiter::LimitExceeded)++ freeze_time(61.minutes.from_now) do+ accepted_result = described_class.call(params:, **dependencies)+ expect(accepted_result).to run_successfully++ expect do described_class.call(params:, **dependencies) end.to raise_error(+ RateLimiter::LimitExceeded,+ )+ end+ end++ it "limits new notices globally across different IP addresses" do+ 99.times { RateLimiter.new(nil, "dsa-notice-global", 100, 1.hour).performed! }+ expect(result).to run_successfully++ expect do+ described_class.call(params:, options: { ip_address: "198.51.100.2" })+ end.to raise_error(RateLimiter::LimitExceeded)+ end++ it "limits notices per IP address" do+ 5.times { RateLimiter.new(nil, "dsa-notice-ip-198.51.100.1", 5, 1.hour).performed! }++ expect { result }.to raise_error(RateLimiter::LimitExceeded)+ end+ end++ context "when the notice is valid" do+ it "stores only email verification details and queues its email" do+ expect { result }.not_to change(Dsa::Notice, :count)++ expect(result).to run_successfully+ expect(Dsa::NoticeVerification.find(result.token)).to include(email: params[:email])+ expect(Dsa::NoticeVerification.find(result.token).keys).to contain_exactly(:email, :code)+ expect(Jobs::DsaNoticeVerification.jobs.last["args"].first.except("current_site_id")).to eq(+ "token" => result.token,+ )+ expect(Jobs::DsaNoticeReceipt.jobs).to be_empty+ end+ end+ end+enddiff --git a/spec/services/dsa/submit_notice_spec.rb b/spec/services/dsa/submit_notice_spec.rbnew file mode 100644index 00000000000..28d8a4c535a--- /dev/null+++ b/spec/services/dsa/submit_notice_spec.rb@@ -0,0 +1,178 @@+# frozen_string_literal: true++RSpec.describe Dsa::SubmitNotice do+ let(:notice) do+ {+ content_url: "#{Discourse.base_url}/t/reported/123",+ explanation:+ "This listing advertises counterfeit goods as authentic and its payment instructions appear intended to deceive buyers.",+ name: "Alex Morgan",+ email: "[email protected]",+ declaration: true,+ }+ end++ describe described_class::Contract, type: :model do+ context "with notice fields" do+ subject(:contract) { described_class.new(notice: notice).notice }++ it { is_expected.to validate_presence_of(:content_url) }+ it { is_expected.to validate_length_of(:explanation).is_at_least(50).is_at_most(20_000) }+ it { is_expected.to validate_presence_of(:name) }+ it { is_expected.to validate_length_of(:name).is_at_most(200) }+ it { is_expected.to validate_presence_of(:email) }+ it { is_expected.to validate_length_of(:email).is_at_most(254) }+ it { is_expected.not_to allow_value(false).for(:declaration) }+ it { is_expected.not_to allow_value("javascript:alert(1)").for(:content_url) }++ it do+ is_expected.not_to allow_value("https://user:[email protected]/post").for(:content_url)+ end++ it { is_expected.not_to allow_value("invalid").for(:email) }++ it do+ is_expected.not_to allow_value("[email protected]\r\nBcc: [email protected]").for(:email)+ end++ it "rejects structured values in scalar fields" do+ notice[:explanation] = [notice[:explanation]]++ expect(contract).not_to be_valid+ end++ it "rejects a notice that is not an object" do+ expect(described_class.new(notice: [notice])).not_to be_valid+ end++ it "normalizes contact information" do+ notice[:name] = " Alex Morgan "+ notice[:email] = " [email protected] "++ expect(contract).to be_valid+ expect(contract.name).to eq("Alex Morgan")+ expect(contract.email).to eq("[email protected]")+ end++ it "requires contact information when a client requests anonymity" do+ notice.merge!(anonymous: true, name: nil, email: nil)++ expect(contract).not_to be_valid+ expect(contract.errors.attribute_names).to include(:name, :email)+ end+ end++ context "with verification fields" do+ subject(:contract) { described_class.new(notice:, token: "a" * 64) }++ it { is_expected.to validate_presence_of(:token) }+ it { is_expected.to validate_length_of(:token).is_equal_to(64) }+ end+ end++ describe ".call" do+ subject(:result) { described_class.call(params:) }++ fab!(:admin)+ fab!(:group)++ let(:token) do+ pending_token = Dsa::NoticeVerification.create(notice[:email])+ code = Dsa::NoticeVerification.find(pending_token)[:code]+ Dsa::NoticeVerification.verify(token: pending_token, email: notice[:email], code:)+ pending_token+ end+ let(:params) { { notice:, token: } }++ before do+ SiteSetting.dsa_notice_group = group.id.to_s+ group.add(admin)+ end++ context "when the token is invalid" do+ let(:token) { nil }++ it { is_expected.to fail_a_contract }+ end++ context "when the verification has expired" do+ let(:token) { "a" * 64 }++ it "creates no notice and reports a missing submission" do+ expect { result }.not_to change(Dsa::Notice, :count)+ expect(result).to fail_to_find_a_model(:verification)+ expect(Jobs::DsaNoticeReceipt.jobs).to be_empty+ end+ end++ context "when the email code has not been verified" do+ let(:token) { Dsa::NoticeVerification.create(notice[:email]) }++ it { is_expected.to fail_to_find_a_model(:verification) }+ end++ context "when the verification has already been used" do+ before { described_class.call(params:) }++ it "creates no duplicate notice" do+ expect { result }.not_to change(Dsa::Notice, :count)+ expect(result).to fail_to_find_a_model(:verification)+ end+ end++ context "when the verification belongs to another email" do+ before do+ token+ notice[:email] = "[email protected]"+ end++ it "creates no notice for an unverified reporter" do+ expect { result }.not_to change(Dsa::Notice, :count)+ expect(result).to fail_to_find_a_model(:verification)+ end+ end++ context "when the selected group is empty" do+ before { group.remove(admin) }++ it "addresses the PM to admins" do+ expect(result).to run_successfully+ expect(result.notice.post.topic.allowed_groups).to contain_exactly(Group[:admins])+ end+ end++ context "when the selected group was deleted" do+ before { group.destroy! }++ it "addresses the PM to admins" do+ expect(result).to run_successfully+ expect(result.notice.post.topic.allowed_groups).to contain_exactly(Group[:admins])+ end+ end++ context "when the PM cannot be saved" do+ before { PostCreator.stubs(:create!).raises(ActiveRecord::RecordNotSaved) }++ it "halts before queuing the receipt" do+ expect { result }.not_to change(Topic, :count)+ expect(result).to fail_to_find_a_model(:notice)+ expect(Jobs::DsaNoticeReceipt.jobs).to be_empty+ end+ end++ context "when the notice is accepted" do+ it "creates a private PM addressed to the selected group" do+ expect(result).to run_successfully+ expect(result.notice.post.topic).to be_private_message+ expect(result.notice.post.topic.allowed_groups).to contain_exactly(group)+ expect(result.notice.post.topic.allowed_users).to contain_exactly(Discourse.system_user)+ end++ it "queues the external receipt for the saved notice" do+ expect { result }.to change { Jobs::DsaNoticeReceipt.jobs.size }.by(1)+ expect(result).to run_successfully+ expect(Jobs::DsaNoticeReceipt.jobs.last["args"].first["notice_id"]).to eq(result.notice.id)+ end+ end+ end+enddiff --git a/spec/services/dsa/verify_notice_email_spec.rb b/spec/services/dsa/verify_notice_email_spec.rbnew file mode 100644index 00000000000..c067b091ed1--- /dev/null+++ b/spec/services/dsa/verify_notice_email_spec.rb@@ -0,0 +1,56 @@+# frozen_string_literal: true++RSpec.describe Dsa::VerifyNoticeEmail do+ describe described_class::Contract, type: :model do+ subject(:contract) do+ described_class.new(email: "[email protected]", token: "a" * 64, verification_code: "123456")+ end++ it { is_expected.to validate_presence_of(:email) }+ it { is_expected.to validate_presence_of(:token) }+ it { is_expected.to validate_length_of(:token).is_equal_to(64) }+ it { is_expected.to allow_value("012345").for(:verification_code) }+ it { is_expected.not_to allow_values("12345", "1234567", "12345a").for(:verification_code) }+ it { is_expected.to validate_length_of(:email).is_at_most(254) }++ it "normalizes the email before verification" do+ contract.email = " [email protected] "++ expect(contract).to be_valid+ expect(contract.email).to eq("[email protected]")+ end+ end++ describe ".call" do+ subject(:result) { described_class.call(params:) }++ let(:email) { "[email protected]" }+ let(:token) { Dsa::NoticeVerification.create(email) }+ let(:verification_code) { Dsa::NoticeVerification.find(token)[:code] }+ let(:params) { { email:, token:, verification_code: } }++ context "when the contract is invalid" do+ let(:verification_code) { "12345" }++ it { is_expected.to fail_a_contract }+ end++ context "when the code is incorrect" do+ let(:verification_code) do+ Dsa::NoticeVerification.find(token)[:code] == "123456" ? "654321" : "123456"+ end++ it { is_expected.to fail_to_find_a_model(:verification) }+ end++ context "when the code is correct" do+ it "verifies the email without creating a report" do+ expect { result }.not_to change(Dsa::Notice, :count)++ expect(result).to run_successfully+ expect(result.verification).to eq(email:)+ expect(Dsa::NoticeVerification.find(token)).to eq(email:, verified: true)+ end+ end+ end+enddiff --git a/spec/system/dsa_notice_spec.rb b/spec/system/dsa_notice_spec.rbnew file mode 100644index 00000000000..5adae9dcba8--- /dev/null+++ b/spec/system/dsa_notice_spec.rb@@ -0,0 +1,43 @@+# frozen_string_literal: true++RSpec.describe "Illegal content notices" do+ fab!(:topic)+ fab!(:reported_post) { Fabricate(:post, topic:) }++ let(:explanation) do+ "This listing advertises counterfeit goods as authentic and asks buyers to pay outside the marketplace. The product description and payment instructions appear intended to deceive buyers."+ end++ let(:notice_page) { PageObjects::Pages::DsaNotice.new }+ let(:topic_page) { PageObjects::Pages::Topic.new }++ before do+ SiteSetting.contact_email = "[email protected]"+ SiteSetting.dsa_reporting_enabled = true+ SiteSetting.disable_emails = "no"+ SiteSetting.allow_all_users_to_flag_illegal_content = true+ Jobs.run_immediately!+ end++ it "lets a reporter verify their email and submit an illegal content report" do+ topic_page.visit_topic(topic)+ topic_page.click_post_action_button(reported_post, :flag)+ expect(notice_page).to have_notice_form+ expect(notice_page.form.field("content_url").value).to end_with(reported_post.url)+ expect(page).to have_button("Submit report", disabled: true)++ notice_page.form.field("email").fill_in("[email protected]")+ notice_page.request_email_code+ expect(notice_page.form).to have_field_with_name("verification_code")+ code = ActionMailer::Base.deliveries.last.text_part.decoded[/\b[0-9]{6}\b/]+ notice_page.fill_verification_code(code)+ expect(notice_page).to have_verified_email+ expect(page).to have_field("Email address", disabled: true)++ notice_page.form.field("name").fill_in("Alex Morgan")+ notice_page.form.field("explanation").fill_in(explanation)+ notice_page.form.field("declaration").check+ notice_page.form.submit+ expect(notice_page).to have_confirmation+ end+enddiff --git a/spec/system/page_objects/pages/dsa_notice.rb b/spec/system/page_objects/pages/dsa_notice.rbnew file mode 100644index 00000000000..4681628b4a8--- /dev/null+++ b/spec/system/page_objects/pages/dsa_notice.rb@@ -0,0 +1,33 @@+# frozen_string_literal: true++module PageObjects+ module Pages+ class DsaNotice < Base+ def form+ PageObjects::Components::FormKit.new(".dsa-notice .form-kit")+ end++ def has_notice_form?+ has_css?(".dsa-notice .form-kit")+ end++ def request_email_code+ click_button("Get email code")+ end++ def fill_verification_code(code)+ page.driver.with_playwright_page do |browser_page|+ browser_page.locator(".dsa-notice .d-otp-input").fill(code)+ end+ end++ def has_verified_email?+ has_button?("Verified", disabled: true)+ end++ def has_confirmation?+ has_css?(".dsa-notice h1", text: "Report received")+ end+ end+ end+end