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