giant massive dep upgrade and dialyxir-found error emporium (#371)
[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 %{
73 "subject" => "acct:#{user.nickname}@#{domain()}",
74 "aliases" => gather_aliases(user),
75 "links" => gather_links(user)
76 }
77 end
78
79 def represent_user(user, "XML") do
80 aliases =
81 user
82 |> gather_aliases()
83 |> Enum.map(&{:Alias, &1})
84
85 links =
86 gather_links(user)
87 |> Enum.map(fn link -> {:Link, link} end)
88
89 {
90 :XRD,
91 %{xmlns: "http://docs.oasis-open.org/ns/xri/xrd-1.0"},
92 [
93 {:Subject, "acct:#{user.nickname}@#{domain()}"}
94 ] ++ aliases ++ links
95 }
96 |> XmlBuilder.to_doc()
97 end
98
99 defp domain do
100 Pleroma.Config.get([__MODULE__, :domain]) || Pleroma.Web.Endpoint.host()
101 end
102
103 @spec webfinger_from_xml(binary()) :: {:ok, map()} | nil
104 defp webfinger_from_xml(body) do
105 with {:ok, doc} <- XML.parse_document(body) do
106 subject = XML.string_from_xpath("//Subject", doc)
107
108 subscribe_address =
109 ~s{//Link[@rel="http://ostatus.org/schema/1.0/subscribe"]/@template}
110 |> XML.string_from_xpath(doc)
111
112 ap_id =
113 ~s{//Link[@rel="self" and @type="application/activity+json"]/@href}
114 |> XML.string_from_xpath(doc)
115
116 data = %{
117 "subject" => subject,
118 "subscribe_address" => subscribe_address,
119 "ap_id" => ap_id
120 }
121
122 {:ok, data}
123 end
124 end
125
126 defp webfinger_from_json(body) do
127 with {:ok, doc} <- Jason.decode(body) do
128 data =
129 Enum.reduce(doc["links"], %{"subject" => doc["subject"]}, fn link, data ->
130 case {link["type"], link["rel"]} do
131 {"application/activity+json", "self"} ->
132 Map.put(data, "ap_id", link["href"])
133
134 {"application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"", "self"} ->
135 Map.put(data, "ap_id", link["href"])
136
137 {nil, "http://ostatus.org/schema/1.0/subscribe"} ->
138 Map.put(data, "subscribe_address", link["template"])
139
140 _ ->
141 Logger.debug("Unhandled type: #{inspect(link["type"])}")
142 data
143 end
144 end)
145
146 {:ok, data}
147 end
148 end
149
150 def get_template_from_xml(body) do
151 xpath = "//Link[@rel='lrdd']/@template"
152
153 with {:ok, doc} <- XML.parse_document(body),
154 template when template != nil <- XML.string_from_xpath(xpath, doc) do
155 {:ok, template}
156 end
157 end
158
159 def find_lrdd_template(domain) do
160 # WebFinger is restricted to HTTPS - https://tools.ietf.org/html/rfc7033#section-9.1
161 meta_url = "https://#{domain}/.well-known/host-meta"
162
163 with {:ok, %{status: status, body: body}} when status in 200..299 <- HTTP.get(meta_url) do
164 get_template_from_xml(body)
165 else
166 error ->
167 Logger.warn("Can't find LRDD template in #{inspect(meta_url)}: #{inspect(error)}")
168 {:error, :lrdd_not_found}
169 end
170 end
171
172 defp get_address_from_domain(domain, encoded_account) when is_binary(domain) do
173 case find_lrdd_template(domain) do
174 {:ok, template} ->
175 String.replace(template, "{uri}", encoded_account)
176
177 _ ->
178 "https://#{domain}/.well-known/webfinger?resource=#{encoded_account}"
179 end
180 end
181
182 defp get_address_from_domain(_, _), do: {:error, :webfinger_no_domain}
183
184 @spec finger(String.t()) :: {:ok, map()} | {:error, any()}
185 def finger(account) do
186 account = String.trim_leading(account, "@")
187
188 domain =
189 with [_name, domain] <- String.split(account, "@") do
190 domain
191 else
192 _e ->
193 URI.parse(account).host
194 end
195
196 encoded_account = URI.encode("acct:#{account}")
197
198 with address when is_binary(address) <- get_address_from_domain(domain, encoded_account),
199 {:ok, %{status: status, body: body, headers: headers}} when status in 200..299 <-
200 HTTP.get(
201 address,
202 [{"accept", "application/xrd+xml,application/jrd+json"}]
203 ) do
204 case List.keyfind(headers, "content-type", 0) do
205 {_, content_type} ->
206 case Plug.Conn.Utils.media_type(content_type) do
207 {:ok, "application", subtype, _} when subtype in ~w(xrd+xml xml) ->
208 webfinger_from_xml(body)
209
210 {:ok, "application", subtype, _} when subtype in ~w(jrd+json json) ->
211 webfinger_from_json(body)
212
213 _ ->
214 {:error, {:content_type, content_type}}
215 end
216
217 _ ->
218 {:error, {:content_type, nil}}
219 end
220 else
221 error ->
222 Logger.debug("Couldn't finger #{account}: #{inspect(error)}")
223 error
224 end
225 end
226 end