Merge branch 'feather_mention' into 'develop'
[akkoma] / lib / pleroma / web / web_finger / web_finger.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.WebFinger do
6 @httpoison Application.get_env(:pleroma, :httpoison)
7
8 alias Pleroma.User
9 alias Pleroma.XmlBuilder
10 alias Pleroma.Web
11 alias Pleroma.Web.XML
12 alias Pleroma.Web.Salmon
13 alias Pleroma.Web.OStatus
14 require Jason
15 require Logger
16
17 def host_meta do
18 base_url = Web.base_url()
19
20 {
21 :XRD,
22 %{xmlns: "http://docs.oasis-open.org/ns/xri/xrd-1.0"},
23 {
24 :Link,
25 %{
26 rel: "lrdd",
27 type: "application/xrd+xml",
28 template: "#{base_url}/.well-known/webfinger?resource={uri}"
29 }
30 }
31 }
32 |> XmlBuilder.to_doc()
33 end
34
35 def webfinger(resource, fmt) when fmt in ["XML", "JSON"] do
36 host = Pleroma.Web.Endpoint.host()
37 regex = ~r/(acct:)?(?<username>\w+)@#{host}/
38
39 with %{"username" => username} <- Regex.named_captures(regex, resource),
40 %User{} = user <- User.get_by_nickname(username) do
41 {:ok, represent_user(user, fmt)}
42 else
43 _e ->
44 with %User{} = user <- User.get_cached_by_ap_id(resource) do
45 {:ok, represent_user(user, fmt)}
46 else
47 _e ->
48 {:error, "Couldn't find user"}
49 end
50 end
51 end
52
53 def represent_user(user, "JSON") do
54 {:ok, user} = ensure_keys_present(user)
55 {:ok, _private, public} = Salmon.keys_from_pem(user.info.keys)
56 magic_key = Salmon.encode_key(public)
57
58 %{
59 "subject" => "acct:#{user.nickname}@#{Pleroma.Web.Endpoint.host()}",
60 "aliases" => [user.ap_id],
61 "links" => [
62 %{
63 "rel" => "http://schemas.google.com/g/2010#updates-from",
64 "type" => "application/atom+xml",
65 "href" => OStatus.feed_path(user)
66 },
67 %{
68 "rel" => "http://webfinger.net/rel/profile-page",
69 "type" => "text/html",
70 "href" => user.ap_id
71 },
72 %{"rel" => "salmon", "href" => OStatus.salmon_path(user)},
73 %{
74 "rel" => "magic-public-key",
75 "href" => "data:application/magic-public-key,#{magic_key}"
76 },
77 %{"rel" => "self", "type" => "application/activity+json", "href" => user.ap_id},
78 %{
79 "rel" => "self",
80 "type" => "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"",
81 "href" => user.ap_id
82 },
83 %{
84 "rel" => "http://ostatus.org/schema/1.0/subscribe",
85 "template" => OStatus.remote_follow_path()
86 }
87 ]
88 }
89 end
90
91 def represent_user(user, "XML") do
92 {:ok, user} = ensure_keys_present(user)
93 {:ok, _private, public} = Salmon.keys_from_pem(user.info.keys)
94 magic_key = Salmon.encode_key(public)
95
96 {
97 :XRD,
98 %{xmlns: "http://docs.oasis-open.org/ns/xri/xrd-1.0"},
99 [
100 {:Subject, "acct:#{user.nickname}@#{Pleroma.Web.Endpoint.host()}"},
101 {:Alias, user.ap_id},
102 {:Link,
103 %{
104 rel: "http://schemas.google.com/g/2010#updates-from",
105 type: "application/atom+xml",
106 href: OStatus.feed_path(user)
107 }},
108 {:Link,
109 %{rel: "http://webfinger.net/rel/profile-page", type: "text/html", href: user.ap_id}},
110 {:Link, %{rel: "salmon", href: OStatus.salmon_path(user)}},
111 {:Link,
112 %{rel: "magic-public-key", href: "data:application/magic-public-key,#{magic_key}"}},
113 {:Link, %{rel: "self", type: "application/activity+json", href: user.ap_id}},
114 {:Link,
115 %{rel: "http://ostatus.org/schema/1.0/subscribe", template: OStatus.remote_follow_path()}}
116 ]
117 }
118 |> XmlBuilder.to_doc()
119 end
120
121 # This seems a better fit in Salmon
122 def ensure_keys_present(user) do
123 info = user.info
124
125 if info.keys do
126 {:ok, user}
127 else
128 {:ok, pem} = Salmon.generate_rsa_pem()
129
130 info_cng =
131 info
132 |> Pleroma.User.Info.set_keys(pem)
133
134 cng =
135 Ecto.Changeset.change(user)
136 |> Ecto.Changeset.put_embed(:info, info_cng)
137
138 User.update_and_set_cache(cng)
139 end
140 end
141
142 defp get_magic_key(magic_key) do
143 "data:application/magic-public-key," <> magic_key = magic_key
144 {:ok, magic_key}
145 rescue
146 MatchError -> {:error, "Missing magic key data."}
147 end
148
149 defp webfinger_from_xml(doc) do
150 with magic_key <- XML.string_from_xpath(~s{//Link[@rel="magic-public-key"]/@href}, doc),
151 {:ok, magic_key} <- get_magic_key(magic_key),
152 topic <-
153 XML.string_from_xpath(
154 ~s{//Link[@rel="http://schemas.google.com/g/2010#updates-from"]/@href},
155 doc
156 ),
157 subject <- XML.string_from_xpath("//Subject", doc),
158 salmon <- XML.string_from_xpath(~s{//Link[@rel="salmon"]/@href}, doc),
159 subscribe_address <-
160 XML.string_from_xpath(
161 ~s{//Link[@rel="http://ostatus.org/schema/1.0/subscribe"]/@template},
162 doc
163 ),
164 ap_id <-
165 XML.string_from_xpath(
166 ~s{//Link[@rel="self" and @type="application/activity+json"]/@href},
167 doc
168 ) do
169 data = %{
170 "magic_key" => magic_key,
171 "topic" => topic,
172 "subject" => subject,
173 "salmon" => salmon,
174 "subscribe_address" => subscribe_address,
175 "ap_id" => ap_id
176 }
177
178 {:ok, data}
179 else
180 {:error, e} ->
181 {:error, e}
182
183 e ->
184 {:error, e}
185 end
186 end
187
188 defp webfinger_from_json(doc) do
189 data =
190 Enum.reduce(doc["links"], %{"subject" => doc["subject"]}, fn link, data ->
191 case {link["type"], link["rel"]} do
192 {"application/activity+json", "self"} ->
193 Map.put(data, "ap_id", link["href"])
194
195 {"application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"", "self"} ->
196 Map.put(data, "ap_id", link["href"])
197
198 {_, "magic-public-key"} ->
199 "data:application/magic-public-key," <> magic_key = link["href"]
200 Map.put(data, "magic_key", magic_key)
201
202 {"application/atom+xml", "http://schemas.google.com/g/2010#updates-from"} ->
203 Map.put(data, "topic", link["href"])
204
205 {_, "salmon"} ->
206 Map.put(data, "salmon", link["href"])
207
208 {_, "http://ostatus.org/schema/1.0/subscribe"} ->
209 Map.put(data, "subscribe_address", link["template"])
210
211 _ ->
212 Logger.debug("Unhandled type: #{inspect(link["type"])}")
213 data
214 end
215 end)
216
217 {:ok, data}
218 end
219
220 def get_template_from_xml(body) do
221 xpath = "//Link[@rel='lrdd']/@template"
222
223 with doc when doc != :error <- XML.parse_document(body),
224 template when template != nil <- XML.string_from_xpath(xpath, doc) do
225 {:ok, template}
226 end
227 end
228
229 def find_lrdd_template(domain) do
230 with {:ok, %{status: status, body: body}} when status in 200..299 <-
231 @httpoison.get("http://#{domain}/.well-known/host-meta", []) do
232 get_template_from_xml(body)
233 else
234 _ ->
235 with {:ok, %{body: body}} <- @httpoison.get("https://#{domain}/.well-known/host-meta", []) do
236 get_template_from_xml(body)
237 else
238 e -> {:error, "Can't find LRDD template: #{inspect(e)}"}
239 end
240 end
241 end
242
243 def finger(account) do
244 account = String.trim_leading(account, "@")
245
246 domain =
247 with [_name, domain] <- String.split(account, "@") do
248 domain
249 else
250 _e ->
251 URI.parse(account).host
252 end
253
254 address =
255 case find_lrdd_template(domain) do
256 {:ok, template} ->
257 String.replace(template, "{uri}", URI.encode(account))
258
259 _ ->
260 "https://#{domain}/.well-known/webfinger?resource=acct:#{account}"
261 end
262
263 with response <-
264 @httpoison.get(
265 address,
266 Accept: "application/xrd+xml,application/jrd+json"
267 ),
268 {:ok, %{status: status, body: body}} when status in 200..299 <- response do
269 doc = XML.parse_document(body)
270
271 if doc != :error do
272 webfinger_from_xml(doc)
273 else
274 with {:ok, doc} <- Jason.decode(body) do
275 webfinger_from_json(doc)
276 else
277 {:error, e} -> e
278 end
279 end
280 else
281 e ->
282 Logger.debug(fn -> "Couldn't finger #{account}" end)
283 Logger.debug(fn -> inspect(e) end)
284 {:error, e}
285 end
286 end
287 end