47c733da221faad86433139a363d78e87bad7ab3
[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
123 info_cng =
124 info
125 |> Pleroma.User.Info.set_keys(pem)
126
127 cng =
128 Ecto.Changeset.change(user)
129 |> Ecto.Changeset.put_embed(:info, info_cng)
130
131 User.update_and_set_cache(cng)
132 end
133 end
134
135 defp get_magic_key(magic_key) do
136 "data:application/magic-public-key," <> magic_key = magic_key
137 {:ok, magic_key}
138 rescue
139 MatchError -> {:error, "Missing magic key data."}
140 end
141
142 defp webfinger_from_xml(doc) do
143 with magic_key <- XML.string_from_xpath(~s{//Link[@rel="magic-public-key"]/@href}, doc),
144 {:ok, magic_key} <- get_magic_key(magic_key),
145 topic <-
146 XML.string_from_xpath(
147 ~s{//Link[@rel="http://schemas.google.com/g/2010#updates-from"]/@href},
148 doc
149 ),
150 subject <- XML.string_from_xpath("//Subject", doc),
151 salmon <- XML.string_from_xpath(~s{//Link[@rel="salmon"]/@href}, doc),
152 subscribe_address <-
153 XML.string_from_xpath(
154 ~s{//Link[@rel="http://ostatus.org/schema/1.0/subscribe"]/@template},
155 doc
156 ),
157 ap_id <-
158 XML.string_from_xpath(
159 ~s{//Link[@rel="self" and @type="application/activity+json"]/@href},
160 doc
161 ) do
162 data = %{
163 "magic_key" => magic_key,
164 "topic" => topic,
165 "subject" => subject,
166 "salmon" => salmon,
167 "subscribe_address" => subscribe_address,
168 "ap_id" => ap_id
169 }
170
171 {:ok, data}
172 else
173 {:error, e} ->
174 {:error, e}
175
176 e ->
177 {:error, e}
178 end
179 end
180
181 defp webfinger_from_json(doc) do
182 data =
183 Enum.reduce(doc["links"], %{"subject" => doc["subject"]}, fn link, data ->
184 case {link["type"], link["rel"]} do
185 {"application/activity+json", "self"} ->
186 Map.put(data, "ap_id", link["href"])
187
188 {"application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"", "self"} ->
189 Map.put(data, "ap_id", link["href"])
190
191 {_, "magic-public-key"} ->
192 "data:application/magic-public-key," <> magic_key = link["href"]
193 Map.put(data, "magic_key", magic_key)
194
195 {"application/atom+xml", "http://schemas.google.com/g/2010#updates-from"} ->
196 Map.put(data, "topic", link["href"])
197
198 {_, "salmon"} ->
199 Map.put(data, "salmon", link["href"])
200
201 {_, "http://ostatus.org/schema/1.0/subscribe"} ->
202 Map.put(data, "subscribe_address", link["template"])
203
204 _ ->
205 Logger.debug("Unhandled type: #{inspect(link["type"])}")
206 data
207 end
208 end)
209
210 {:ok, data}
211 end
212
213 def get_template_from_xml(body) do
214 xpath = "//Link[@rel='lrdd']/@template"
215
216 with doc when doc != :error <- XML.parse_document(body),
217 template when template != nil <- XML.string_from_xpath(xpath, doc) do
218 {:ok, template}
219 end
220 end
221
222 def find_lrdd_template(domain) do
223 with {:ok, %{status: status, body: body}} when status in 200..299 <-
224 @httpoison.get("http://#{domain}/.well-known/host-meta", []) do
225 get_template_from_xml(body)
226 else
227 _ ->
228 with {:ok, %{body: body}} <- @httpoison.get("https://#{domain}/.well-known/host-meta", []) do
229 get_template_from_xml(body)
230 else
231 e -> {:error, "Can't find LRDD template: #{inspect(e)}"}
232 end
233 end
234 end
235
236 def finger(account) do
237 account = String.trim_leading(account, "@")
238
239 domain =
240 with [_name, domain] <- String.split(account, "@") do
241 domain
242 else
243 _e ->
244 URI.parse(account).host
245 end
246
247 address =
248 case find_lrdd_template(domain) do
249 {:ok, template} ->
250 String.replace(template, "{uri}", URI.encode(account))
251
252 _ ->
253 "https://#{domain}/.well-known/webfinger?resource=acct:#{account}"
254 end
255
256 with response <-
257 @httpoison.get(
258 address,
259 Accept: "application/xrd+xml,application/jrd+json"
260 ),
261 {:ok, %{status: status, body: body}} when status in 200..299 <- response do
262 doc = XML.parse_document(body)
263
264 if doc != :error do
265 webfinger_from_xml(doc)
266 else
267 with {:ok, doc} <- Jason.decode(body) do
268 webfinger_from_json(doc)
269 else
270 {:error, e} -> e
271 end
272 end
273 else
274 e ->
275 Logger.debug(fn -> "Couldn't finger #{account}" end)
276 Logger.debug(fn -> inspect(e) end)
277 {:error, e}
278 end
279 end
280 end