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