Support reaching user@sub.domain.tld at user@domain.tld (#134)
[akkoma] / lib / pleroma / web / web_finger.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.WebFinger do
6 alias Pleroma.HTTP
7 alias Pleroma.User
8 alias Pleroma.Web.Endpoint
9 alias Pleroma.Web.Federator.Publisher
10 alias Pleroma.Web.XML
11 alias Pleroma.XmlBuilder
12 require Jason
13 require Logger
14
15 def host_meta do
16 base_url = Endpoint.url()
17
18 {
19 :XRD,
20 %{xmlns: "http://docs.oasis-open.org/ns/xri/xrd-1.0"},
21 {
22 :Link,
23 %{
24 rel: "lrdd",
25 type: "application/xrd+xml",
26 template: "#{base_url}/.well-known/webfinger?resource={uri}"
27 }
28 }
29 }
30 |> XmlBuilder.to_doc()
31 end
32
33 def webfinger(resource, fmt) when fmt in ["XML", "JSON"] do
34 host = Pleroma.Web.Endpoint.host()
35
36 regex =
37 if webfinger_domain = Pleroma.Config.get([__MODULE__, :domain]) do
38 ~r/(acct:)?(?<username>[a-z0-9A-Z_\.-]+)@(#{host}|#{webfinger_domain})/
39 else
40 ~r/(acct:)?(?<username>[a-z0-9A-Z_\.-]+)@#{host}/
41 end
42
43 with %{"username" => username} <- Regex.named_captures(regex, resource),
44 %User{} = user <- User.get_cached_by_nickname(username) do
45 {:ok, represent_user(user, fmt)}
46 else
47 _e ->
48 with %User{} = user <- User.get_cached_by_ap_id(resource) do
49 {:ok, represent_user(user, fmt)}
50 else
51 _e ->
52 {:error, "Couldn't find user"}
53 end
54 end
55 end
56
57 defp gather_links(%User{} = user) do
58 [
59 %{
60 "rel" => "http://webfinger.net/rel/profile-page",
61 "type" => "text/html",
62 "href" => user.ap_id
63 }
64 ] ++ Publisher.gather_webfinger_links(user)
65 end
66
67 defp gather_aliases(%User{} = user) do
68 [user.ap_id | user.also_known_as]
69 end
70
71 def represent_user(user, "JSON") do
72 {:ok, user} = User.ensure_keys_present(user)
73
74 %{
75 "subject" => "acct:#{user.nickname}@#{domain()}",
76 "aliases" => gather_aliases(user),
77 "links" => gather_links(user)
78 }
79 end
80
81 def represent_user(user, "XML") do
82 {:ok, user} = User.ensure_keys_present(user)
83
84 aliases =
85 user
86 |> gather_aliases()
87 |> Enum.map(&{:Alias, &1})
88
89 links =
90 gather_links(user)
91 |> Enum.map(fn link -> {:Link, link} end)
92
93 {
94 :XRD,
95 %{xmlns: "http://docs.oasis-open.org/ns/xri/xrd-1.0"},
96 [
97 {:Subject, "acct:#{user.nickname}@#{domain()}"}
98 ] ++ aliases ++ links
99 }
100 |> XmlBuilder.to_doc()
101 end
102
103 defp domain do
104 Pleroma.Config.get([__MODULE__, :domain]) || Pleroma.Web.Endpoint.host()
105 end
106
107 defp webfinger_from_xml(body) do
108 with {:ok, doc} <- XML.parse_document(body) do
109 subject = XML.string_from_xpath("//Subject", doc)
110
111 subscribe_address =
112 ~s{//Link[@rel="http://ostatus.org/schema/1.0/subscribe"]/@template}
113 |> XML.string_from_xpath(doc)
114
115 ap_id =
116 ~s{//Link[@rel="self" and @type="application/activity+json"]/@href}
117 |> XML.string_from_xpath(doc)
118
119 data = %{
120 "subject" => subject,
121 "subscribe_address" => subscribe_address,
122 "ap_id" => ap_id
123 }
124
125 {:ok, data}
126 end
127 end
128
129 defp webfinger_from_json(body) do
130 with {:ok, doc} <- Jason.decode(body) do
131 data =
132 Enum.reduce(doc["links"], %{"subject" => doc["subject"]}, fn link, data ->
133 case {link["type"], link["rel"]} do
134 {"application/activity+json", "self"} ->
135 Map.put(data, "ap_id", link["href"])
136
137 {"application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"", "self"} ->
138 Map.put(data, "ap_id", link["href"])
139
140 {nil, "http://ostatus.org/schema/1.0/subscribe"} ->
141 Map.put(data, "subscribe_address", link["template"])
142
143 _ ->
144 Logger.debug("Unhandled type: #{inspect(link["type"])}")
145 data
146 end
147 end)
148
149 {:ok, data}
150 end
151 end
152
153 def get_template_from_xml(body) do
154 xpath = "//Link[@rel='lrdd']/@template"
155
156 with {:ok, doc} <- XML.parse_document(body),
157 template when template != nil <- XML.string_from_xpath(xpath, doc) do
158 {:ok, template}
159 end
160 end
161
162 def find_lrdd_template(domain) do
163 # WebFinger is restricted to HTTPS - https://tools.ietf.org/html/rfc7033#section-9.1
164 meta_url = "https://#{domain}/.well-known/host-meta"
165
166 with {:ok, %{status: status, body: body}} when status in 200..299 <- HTTP.get(meta_url) do
167 get_template_from_xml(body)
168 else
169 error ->
170 Logger.warn("Can't find LRDD template in #{inspect(meta_url)}: #{inspect(error)}")
171 {:error, :lrdd_not_found}
172 end
173 end
174
175 defp get_address_from_domain(domain, encoded_account) when is_binary(domain) do
176 case find_lrdd_template(domain) do
177 {:ok, template} ->
178 String.replace(template, "{uri}", encoded_account)
179
180 _ ->
181 "https://#{domain}/.well-known/webfinger?resource=#{encoded_account}"
182 end
183 end
184
185 defp get_address_from_domain(_, _), do: {:error, :webfinger_no_domain}
186
187 @spec finger(String.t()) :: {:ok, map()} | {:error, any()}
188 def finger(account) do
189 account = String.trim_leading(account, "@")
190
191 domain =
192 with [_name, domain] <- String.split(account, "@") do
193 domain
194 else
195 _e ->
196 URI.parse(account).host
197 end
198
199 encoded_account = URI.encode("acct:#{account}")
200
201 with address when is_binary(address) <- get_address_from_domain(domain, encoded_account),
202 {:ok, %{status: status, body: body, headers: headers}} when status in 200..299 <-
203 HTTP.get(
204 address,
205 [{"accept", "application/xrd+xml,application/jrd+json"}]
206 ) do
207 case List.keyfind(headers, "content-type", 0) do
208 {_, content_type} ->
209 case Plug.Conn.Utils.media_type(content_type) do
210 {:ok, "application", subtype, _} when subtype in ~w(xrd+xml xml) ->
211 webfinger_from_xml(body)
212
213 {:ok, "application", subtype, _} when subtype in ~w(jrd+json json) ->
214 webfinger_from_json(body)
215
216 _ ->
217 {:error, {:content_type, content_type}}
218 end
219
220 _ ->
221 {:error, {:content_type, nil}}
222 end
223 else
224 error ->
225 Logger.debug("Couldn't finger #{account}: #{inspect(error)}")
226 error
227 end
228 end
229 end