Merge remote-tracking branch 'upstream/develop' into aliases
[akkoma] / lib / pleroma / web / web_finger.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 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
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 = Web.base_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 gather_aliases(user)
80 |> Enum.map(fn the_alias -> {:Alias, the_alias} end)
81
82 links =
83 gather_links(user)
84 |> Enum.map(fn link -> {:Link, link} end)
85
86 {
87 :XRD,
88 %{xmlns: "http://docs.oasis-open.org/ns/xri/xrd-1.0"},
89 [
90 {:Subject, "acct:#{user.nickname}@#{Pleroma.Web.Endpoint.host()}"}
91 ] ++ aliases ++ links
92 }
93 |> XmlBuilder.to_doc()
94 end
95
96 defp webfinger_from_xml(doc) do
97 subject = XML.string_from_xpath("//Subject", doc)
98
99 subscribe_address =
100 ~s{//Link[@rel="http://ostatus.org/schema/1.0/subscribe"]/@template}
101 |> XML.string_from_xpath(doc)
102
103 ap_id =
104 ~s{//Link[@rel="self" and @type="application/activity+json"]/@href}
105 |> XML.string_from_xpath(doc)
106
107 data = %{
108 "subject" => subject,
109 "subscribe_address" => subscribe_address,
110 "ap_id" => ap_id
111 }
112
113 {:ok, data}
114 end
115
116 defp webfinger_from_json(doc) do
117 data =
118 Enum.reduce(doc["links"], %{"subject" => doc["subject"]}, fn link, data ->
119 case {link["type"], link["rel"]} do
120 {"application/activity+json", "self"} ->
121 Map.put(data, "ap_id", link["href"])
122
123 {"application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"", "self"} ->
124 Map.put(data, "ap_id", link["href"])
125
126 _ ->
127 Logger.debug("Unhandled type: #{inspect(link["type"])}")
128 data
129 end
130 end)
131
132 {:ok, data}
133 end
134
135 def get_template_from_xml(body) do
136 xpath = "//Link[@rel='lrdd']/@template"
137
138 with doc when doc != :error <- XML.parse_document(body),
139 template when template != nil <- XML.string_from_xpath(xpath, doc) do
140 {:ok, template}
141 end
142 end
143
144 def find_lrdd_template(domain) do
145 with {:ok, %{status: status, body: body}} when status in 200..299 <-
146 HTTP.get("http://#{domain}/.well-known/host-meta") do
147 get_template_from_xml(body)
148 else
149 _ ->
150 with {:ok, %{body: body, status: status}} when status in 200..299 <-
151 HTTP.get("https://#{domain}/.well-known/host-meta") do
152 get_template_from_xml(body)
153 else
154 e -> {:error, "Can't find LRDD template: #{inspect(e)}"}
155 end
156 end
157 end
158
159 defp get_address_from_domain(domain, encoded_account) when is_binary(domain) do
160 case find_lrdd_template(domain) do
161 {:ok, template} ->
162 String.replace(template, "{uri}", encoded_account)
163
164 _ ->
165 "https://#{domain}/.well-known/webfinger?resource=#{encoded_account}"
166 end
167 end
168
169 defp get_address_from_domain(_, _), do: nil
170
171 @spec finger(String.t()) :: {:ok, map()} | {:error, any()}
172 def finger(account) do
173 account = String.trim_leading(account, "@")
174
175 domain =
176 with [_name, domain] <- String.split(account, "@") do
177 domain
178 else
179 _e ->
180 URI.parse(account).host
181 end
182
183 encoded_account = URI.encode("acct:#{account}")
184
185 with address when is_binary(address) <- get_address_from_domain(domain, encoded_account),
186 response <-
187 HTTP.get(
188 address,
189 [{"accept", "application/xrd+xml,application/jrd+json"}]
190 ),
191 {:ok, %{status: status, body: body}} when status in 200..299 <- response do
192 doc = XML.parse_document(body)
193
194 if doc != :error do
195 webfinger_from_xml(doc)
196 else
197 with {:ok, doc} <- Jason.decode(body) do
198 webfinger_from_json(doc)
199 end
200 end
201 else
202 e ->
203 Logger.debug(fn -> "Couldn't finger #{account}" end)
204 Logger.debug(fn -> inspect(e) end)
205 {:error, e}
206 end
207 end
208 end