Rename search.ex to database_search.ex and add search/2
[akkoma] / lib / pleroma / web / web_finger.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.WebFinger do
6 alias Pleroma.HTTP
7 alias Pleroma.User
8 alias Pleroma.Web.Endpoint
9 alias Pleroma.Web.Federator.Publisher
10 alias Pleroma.Web.XML
11 alias Pleroma.XmlBuilder
12 require Jason
13 require Logger
14
15 def host_meta do
16 base_url = Endpoint.url()
17
18 {
19 :XRD,
20 %{xmlns: "http://docs.oasis-open.org/ns/xri/xrd-1.0"},
21 {
22 :Link,
23 %{
24 rel: "lrdd",
25 type: "application/xrd+xml",
26 template: "#{base_url}/.well-known/webfinger?resource={uri}"
27 }
28 }
29 }
30 |> XmlBuilder.to_doc()
31 end
32
33 def webfinger(resource, fmt) when fmt in ["XML", "JSON"] do
34 host = Pleroma.Web.Endpoint.host()
35 regex = ~r/(acct:)?(?<username>[a-z0-9A-Z_\.-]+)@#{host}/
36
37 with %{"username" => username} <- Regex.named_captures(regex, resource),
38 %User{} = user <- User.get_cached_by_nickname(username) do
39 {:ok, represent_user(user, fmt)}
40 else
41 _e ->
42 with %User{} = user <- User.get_cached_by_ap_id(resource) do
43 {:ok, represent_user(user, fmt)}
44 else
45 _e ->
46 {:error, "Couldn't find user"}
47 end
48 end
49 end
50
51 defp gather_links(%User{} = user) do
52 [
53 %{
54 "rel" => "http://webfinger.net/rel/profile-page",
55 "type" => "text/html",
56 "href" => user.ap_id
57 }
58 ] ++ Publisher.gather_webfinger_links(user)
59 end
60
61 defp gather_aliases(%User{} = user) do
62 [user.ap_id | user.also_known_as]
63 end
64
65 def represent_user(user, "JSON") do
66 {:ok, user} = User.ensure_keys_present(user)
67
68 %{
69 "subject" => "acct:#{user.nickname}@#{Pleroma.Web.Endpoint.host()}",
70 "aliases" => gather_aliases(user),
71 "links" => gather_links(user)
72 }
73 end
74
75 def represent_user(user, "XML") do
76 {:ok, user} = User.ensure_keys_present(user)
77
78 aliases =
79 user
80 |> gather_aliases()
81 |> Enum.map(&{:Alias, &1})
82
83 links =
84 gather_links(user)
85 |> Enum.map(fn link -> {:Link, link} end)
86
87 {
88 :XRD,
89 %{xmlns: "http://docs.oasis-open.org/ns/xri/xrd-1.0"},
90 [
91 {:Subject, "acct:#{user.nickname}@#{Pleroma.Web.Endpoint.host()}"}
92 ] ++ aliases ++ links
93 }
94 |> XmlBuilder.to_doc()
95 end
96
97 defp webfinger_from_xml(body) do
98 with {:ok, doc} <- XML.parse_document(body) do
99 subject = XML.string_from_xpath("//Subject", doc)
100
101 subscribe_address =
102 ~s{//Link[@rel="http://ostatus.org/schema/1.0/subscribe"]/@template}
103 |> XML.string_from_xpath(doc)
104
105 ap_id =
106 ~s{//Link[@rel="self" and @type="application/activity+json"]/@href}
107 |> XML.string_from_xpath(doc)
108
109 data = %{
110 "subject" => subject,
111 "subscribe_address" => subscribe_address,
112 "ap_id" => ap_id
113 }
114
115 {:ok, data}
116 end
117 end
118
119 defp webfinger_from_json(body) do
120 with {:ok, doc} <- Jason.decode(body) do
121 data =
122 Enum.reduce(doc["links"], %{"subject" => doc["subject"]}, fn link, data ->
123 case {link["type"], link["rel"]} do
124 {"application/activity+json", "self"} ->
125 Map.put(data, "ap_id", link["href"])
126
127 {"application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"", "self"} ->
128 Map.put(data, "ap_id", link["href"])
129
130 {nil, "http://ostatus.org/schema/1.0/subscribe"} ->
131 Map.put(data, "subscribe_address", link["template"])
132
133 _ ->
134 Logger.debug("Unhandled type: #{inspect(link["type"])}")
135 data
136 end
137 end)
138
139 {:ok, data}
140 end
141 end
142
143 def get_template_from_xml(body) do
144 xpath = "//Link[@rel='lrdd']/@template"
145
146 with {:ok, doc} <- XML.parse_document(body),
147 template when template != nil <- XML.string_from_xpath(xpath, doc) do
148 {:ok, template}
149 end
150 end
151
152 def find_lrdd_template(domain) do
153 with {:ok, %{status: status, body: body}} when status in 200..299 <-
154 HTTP.get("http://#{domain}/.well-known/host-meta") do
155 get_template_from_xml(body)
156 else
157 _ ->
158 with {:ok, %{body: body, status: status}} when status in 200..299 <-
159 HTTP.get("https://#{domain}/.well-known/host-meta") do
160 get_template_from_xml(body)
161 else
162 e -> {:error, "Can't find LRDD template: #{inspect(e)}"}
163 end
164 end
165 end
166
167 defp get_address_from_domain(domain, encoded_account) when is_binary(domain) do
168 case find_lrdd_template(domain) do
169 {:ok, template} ->
170 String.replace(template, "{uri}", encoded_account)
171
172 _ ->
173 "https://#{domain}/.well-known/webfinger?resource=#{encoded_account}"
174 end
175 end
176
177 defp get_address_from_domain(_, _), do: nil
178
179 @spec finger(String.t()) :: {:ok, map()} | {:error, any()}
180 def finger(account) do
181 account = String.trim_leading(account, "@")
182
183 domain =
184 with [_name, domain] <- String.split(account, "@") do
185 domain
186 else
187 _e ->
188 URI.parse(account).host
189 end
190
191 encoded_account = URI.encode("acct:#{account}")
192
193 with address when is_binary(address) <- get_address_from_domain(domain, encoded_account),
194 response <-
195 HTTP.get(
196 address,
197 [{"accept", "application/xrd+xml,application/jrd+json"}]
198 ),
199 {:ok, %{status: status, body: body, headers: headers}} when status in 200..299 <-
200 response do
201 case List.keyfind(headers, "content-type", 0) do
202 {_, content_type} ->
203 case Plug.Conn.Utils.media_type(content_type) do
204 {:ok, "application", subtype, _} when subtype in ~w(xrd+xml xml) ->
205 webfinger_from_xml(body)
206
207 {:ok, "application", subtype, _} when subtype in ~w(jrd+json json) ->
208 webfinger_from_json(body)
209
210 _ ->
211 {:error, {:content_type, content_type}}
212 end
213
214 _ ->
215 {:error, {:content_type, nil}}
216 end
217 else
218 e ->
219 Logger.debug(fn -> "Couldn't finger #{account}" end)
220 Logger.debug(fn -> inspect(e) end)
221 {:error, e}
222 end
223 end
224 end