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