b955bc43f9ca7c625661fdcba7bd62f4e76f1444
[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 %{"rel" => "self", "type" => "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"", "href" => user.ap_id},
90 %{
91 "rel" => "http://ostatus.org/schema/1.0/subscribe",
92 "template" => OStatus.remote_follow_path()
93 }
94 ]
95 }
96 end
97
98 def represent_user(user, "XML") do
99 {:ok, user} = ensure_keys_present(user)
100 {:ok, _private, public} = Salmon.keys_from_pem(user.info["keys"])
101 magic_key = Salmon.encode_key(public)
102
103 {
104 :XRD,
105 %{xmlns: "http://docs.oasis-open.org/ns/xri/xrd-1.0"},
106 [
107 {:Subject, "acct:#{user.nickname}@#{Pleroma.Web.Endpoint.host()}"},
108 {:Alias, user.ap_id},
109 {:Link,
110 %{
111 rel: "http://schemas.google.com/g/2010#updates-from",
112 type: "application/atom+xml",
113 href: OStatus.feed_path(user)
114 }},
115 {:Link,
116 %{rel: "http://webfinger.net/rel/profile-page", type: "text/html", href: user.ap_id}},
117 {:Link, %{rel: "salmon", href: OStatus.salmon_path(user)}},
118 {:Link,
119 %{rel: "magic-public-key", href: "data:application/magic-public-key,#{magic_key}"}},
120 {:Link, %{rel: "self", type: "application/activity+json", href: user.ap_id}},
121 {:Link, %{rel: "self", type: "application/ld+json; profile=&quot;https://www.w3.org/ns/activitystreams&quot;", href: user.ap_id}},
122 {:Link,
123 %{rel: "http://ostatus.org/schema/1.0/subscribe", template: OStatus.remote_follow_path()}}
124 ]
125 }
126 |> XmlBuilder.to_doc()
127 end
128
129 # This seems a better fit in Salmon
130 def ensure_keys_present(user) do
131 info = user.info || %{}
132
133 if info["keys"] do
134 {:ok, user}
135 else
136 {:ok, pem} = Salmon.generate_rsa_pem()
137 info = Map.put(info, "keys", pem)
138
139 Ecto.Changeset.change(user, info: info)
140 |> User.update_and_set_cache()
141 end
142 end
143
144 defp webfinger_from_xml(doc) do
145 magic_key = XML.string_from_xpath(~s{//Link[@rel="magic-public-key"]/@href}, doc)
146 "data:application/magic-public-key," <> magic_key = magic_key
147
148 topic =
149 XML.string_from_xpath(
150 ~s{//Link[@rel="http://schemas.google.com/g/2010#updates-from"]/@href},
151 doc
152 )
153
154 subject = XML.string_from_xpath("//Subject", doc)
155 salmon = XML.string_from_xpath(~s{//Link[@rel="salmon"]/@href}, doc)
156
157 subscribe_address =
158 XML.string_from_xpath(
159 ~s{//Link[@rel="http://ostatus.org/schema/1.0/subscribe"]/@template},
160 doc
161 )
162
163 ap_id =
164 XML.string_from_xpath(
165 ~s{//Link[@rel="self" and @type="application/activity+json"]/@href},
166 doc
167 )
168
169 if ap_id == nil do
170 ap_id =
171 XML.string_from_xpath(
172 ~s{//Link[@rel="self" and @type="application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\""]/@href},
173 doc
174 )
175 end
176
177 data = %{
178 "magic_key" => magic_key,
179 "topic" => topic,
180 "subject" => subject,
181 "salmon" => salmon,
182 "subscribe_address" => subscribe_address,
183 "ap_id" => ap_id
184 }
185
186 {:ok, data}
187 end
188
189 defp webfinger_from_json(doc) do
190 data =
191 Enum.reduce(doc["links"], %{"subject" => doc["subject"]}, fn link, data ->
192 case {link["type"], link["rel"]} do
193 {"application/activity+json", "self"} ->
194 Map.put(data, "ap_id", link["href"])
195
196 {"application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"", "self"} ->
197 Map.put(data, "ap_id", link["href"])
198
199 {_, "magic-public-key"} ->
200 "data:application/magic-public-key," <> magic_key = link["href"]
201 Map.put(data, "magic_key", magic_key)
202
203 {"application/atom+xml", "http://schemas.google.com/g/2010#updates-from"} ->
204 Map.put(data, "topic", link["href"])
205
206 {_, "salmon"} ->
207 Map.put(data, "salmon", link["href"])
208
209 {_, "http://ostatus.org/schema/1.0/subscribe"} ->
210 Map.put(data, "subscribe_address", link["template"])
211
212 _ ->
213 Logger.debug("Unhandled type: #{inspect(link["type"])}")
214 data
215 end
216 end)
217
218 {:ok, data}
219 end
220
221 def get_template_from_xml(body) do
222 xpath = "//Link[@rel='lrdd' and @type='application/xrd+xml']/@template"
223
224 with doc when doc != :error <- XML.parse_document(body),
225 template when template != nil <- XML.string_from_xpath(xpath, doc) do
226 {:ok, template}
227 end
228 end
229
230 def find_lrdd_template(domain) do
231 with {:ok, %{status_code: status_code, body: body}} when status_code in 200..299 <-
232 @httpoison.get("http://#{domain}/.well-known/host-meta", [], follow_redirect: true) do
233 get_template_from_xml(body)
234 else
235 _ ->
236 with {:ok, %{body: body}} <- @httpoison.get("https://#{domain}/.well-known/host-meta", []) do
237 get_template_from_xml(body)
238 else
239 e -> {:error, "Can't find LRDD template: #{inspect(e)}"}
240 end
241 end
242 end
243
244 def finger(account) do
245 account = String.trim_leading(account, "@")
246
247 domain =
248 with [_name, domain] <- String.split(account, "@") do
249 domain
250 else
251 _e ->
252 URI.parse(account).host
253 end
254
255 address =
256 case find_lrdd_template(domain) do
257 {:ok, template} ->
258 String.replace(template, "{uri}", URI.encode(account))
259
260 _ ->
261 "http://#{domain}/.well-known/webfinger?resource=acct:#{account}"
262 end
263
264 with response <-
265 @httpoison.get(
266 address,
267 [Accept: "application/xrd+xml,application/jrd+json"],
268 follow_redirect: true
269 ),
270 {:ok, %{status_code: status_code, body: body}} when status_code in 200..299 <- response do
271 doc = XML.parse_document(body)
272
273 if doc != :error do
274 webfinger_from_xml(doc)
275 else
276 {:ok, doc} = Jason.decode(body)
277 webfinger_from_json(doc)
278 end
279 else
280 e ->
281 Logger.debug(fn -> "Couldn't finger #{account}" end)
282 Logger.debug(fn -> inspect(e) end)
283 {:error, e}
284 end
285 end
286 end