1 | <?php |
2 | |
3 | namespace Taproot\IndieAuth; |
4 | |
5 | use Exception; |
6 | use Psr\Http\Message\ServerRequestInterface; |
7 | use Psr\Log\LoggerAwareInterface; |
8 | use Psr\Log\LoggerInterface; |
9 | |
10 | |
11 | function generateRandomString(int $numBytes): string { |
12 | if (function_exists('random_bytes')) { |
13 | $bytes = random_bytes($numBytes); |
14 | |
15 | |
16 | } elseif (function_exists('openssl_random_pseudo_bytes')){ |
17 | $bytes = openssl_random_pseudo_bytes($numBytes); |
18 | } else { |
19 | $bytes = ''; |
20 | for($i=0, $bytes=''; $i < $numBytes; $i++) { |
21 | $bytes .= chr(mt_rand(0, 255)); |
22 | } |
23 | |
24 | } |
25 | return bin2hex($bytes); |
26 | } |
27 | |
28 | function generateRandomPrintableAsciiString(int $length): string { |
29 | $chars = []; |
30 | while (count($chars) < $length) { |
31 | |
32 | $chars[] = chr(random_int(0x21, 0x7E)); |
33 | } |
34 | return join('', $chars); |
35 | } |
36 | |
37 | function generatePKCECodeChallenge(string $plaintext): string { |
38 | return base64_urlencode(hash('sha256', $plaintext, true)); |
39 | } |
40 | |
41 | function base64_urlencode(string $string): string { |
42 | return rtrim(strtr(base64_encode($string), '+/', '-_'), '='); |
43 | } |
44 | |
45 | function hashAuthorizationRequestParameters(ServerRequestInterface $request, string $secret, ?string $algo=null, ?array $hashedParameters=null, bool $requirePkce=true): ?string { |
46 | $queryParams = $request->getQueryParams(); |
47 | |
48 | if (is_null($hashedParameters)) { |
49 | $hashedParameters = ($requirePkce or isset($queryParams['code_challenge'])) ? ['client_id', 'redirect_uri', 'code_challenge', 'code_challenge_method'] : ['client_id', 'redirect_uri']; |
50 | } |
51 | |
52 | $algo = $algo ?? 'sha256'; |
53 | |
54 | $data = ''; |
55 | foreach ($hashedParameters as $key) { |
56 | if (!isset($queryParams[$key])) { |
57 | return null; |
58 | } |
59 | $data .= $queryParams[$key]; |
60 | } |
61 | return hash_hmac($algo, $data, $secret); |
62 | } |
63 | |
64 | function isIndieAuthAuthorizationCodeRedeemingRequest(ServerRequestInterface $request): bool { |
65 | return strtolower($request->getMethod()) == 'post' |
66 | && array_key_exists('grant_type', $request->getParsedBody() ?? []) |
67 | && $request->getParsedBody()['grant_type'] == 'authorization_code'; |
68 | } |
69 | |
70 | function isIndieAuthAuthorizationRequest(ServerRequestInterface $request, array $permittedMethods=['get']): bool { |
71 | return in_array(strtolower($request->getMethod()), array_map('strtolower', $permittedMethods)) |
72 | && array_key_exists('response_type', $request->getQueryParams()) |
73 | && $request->getQueryParams()['response_type'] == 'code'; |
74 | } |
75 | |
76 | function isAuthorizationApprovalRequest(ServerRequestInterface $request): bool { |
77 | return strtolower($request->getMethod()) == 'post' |
78 | && array_key_exists('taproot_indieauth_action', $request->getParsedBody() ?? []) |
79 | && $request->getParsedBody()[Server::APPROVE_ACTION_KEY] == Server::APPROVE_ACTION_VALUE; |
80 | } |
81 | |
82 | function buildQueryString(array $parameters): string { |
83 | $qs = []; |
84 | foreach ($parameters as $k => $v) { |
85 | $qs[] = urlencode($k) . '=' . urlencode($v); |
86 | } |
87 | return join('&', $qs); |
88 | } |
89 | |
90 | function urlComponentsMatch(string $url1, string $url2, ?array $components=null): bool { |
91 | $validComponents = [PHP_URL_HOST, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_PORT, PHP_URL_USER, PHP_URL_QUERY, PHP_URL_SCHEME, PHP_URL_FRAGMENT]; |
92 | $components = $components ?? $validComponents; |
93 | |
94 | foreach ($components as $cmp) { |
95 | if (!in_array($cmp, $validComponents)) { |
96 | throw new Exception("Invalid parse_url() component passed: $cmp"); |
97 | } |
98 | |
99 | if (parse_url($url1, $cmp) !== parse_url($url2, $cmp)) { |
100 | return false; |
101 | } |
102 | } |
103 | |
104 | return true; |
105 | } |
106 | |
107 | |
108 | |
109 | |
110 | |
111 | |
112 | |
113 | |
114 | function appendQueryParams(string $uri, array $queryParams): string { |
115 | if (empty($queryParams)) { |
116 | return $uri; |
117 | } |
118 | |
119 | $queryString = buildQueryString($queryParams); |
120 | $separator = parse_url($uri, \PHP_URL_QUERY) ? '&' : '?'; |
121 | $uri = rtrim($uri, '?&'); |
122 | return "{$uri}{$separator}{$queryString}"; |
123 | } |
124 | |
125 | |
126 | |
127 | |
128 | |
129 | |
130 | |
131 | |
132 | |
133 | |
134 | function trySetLogger($target, LoggerInterface $logger) { |
135 | if ($target instanceof LoggerAwareInterface) { |
136 | $target->setLogger($logger); |
137 | } |
138 | return $target; |
139 | } |
140 | |
141 | function renderTemplate(string $template, array $context=[]) { |
142 | $render = function ($__template, $__templateData) { |
143 | $render = function ($template, $data){ |
144 | return renderTemplate($template, $data); |
145 | }; |
146 | ob_start(); |
147 | extract($__templateData); |
148 | unset($__templateData); |
149 | include $__template; |
150 | return ob_get_clean(); |
151 | }; |
152 | return $render($template, $context); |
153 | } |
154 | |
155 | |
156 | |
157 | |
158 | |
159 | |
160 | |
161 | |
162 | |
163 | |
164 | |
165 | |
166 | function isClientIdentifier(string $client_id): bool { |
167 | return ($url_components = parse_url($client_id)) && |
168 | in_array($url_components['scheme'] ?? '', ['http', 'https']) && |
169 | 0 < strlen($url_components['path'] ?? '') && |
170 | false === strpos($url_components['path'], '/./') && |
171 | false === strpos($url_components['path'], '/../') && |
172 | false === isset($url_components['fragment']) && |
173 | false === isset($url_components['user']) && |
174 | false === isset($url_components['pass']) && |
175 | ( |
176 | false === filter_var($url_components['host'], FILTER_VALIDATE_IP) || |
177 | ($url_components['host'] ?? null) == '127.0.0.1' || |
178 | ($url_components['host'] ?? null) == '[::1]' |
179 | ) |
180 | ; |
181 | } |
182 | |
183 | |
184 | |
185 | |
186 | |
187 | |
188 | |
189 | |
190 | function isProfileUrl(string $profile_url): bool { |
191 | return ($url_components = parse_url($profile_url)) && |
192 | in_array($url_components['scheme'] ?? '', ['http', 'https']) && |
193 | 0 < strlen($url_components['path'] ?? '') && |
194 | false === strpos($url_components['path'], '/./') && |
195 | false === strpos($url_components['path'], '/../') && |
196 | false === isset($url_components['fragment']) && |
197 | false === isset($url_components['user']) && |
198 | false === isset($url_components['pass']) && |
199 | false === isset($url_components['port']) && |
200 | false === filter_var($url_components['host'], FILTER_VALIDATE_IP) |
201 | ; |
202 | } |
203 | |
204 | |
205 | |
206 | |
207 | |
208 | |
209 | function isValidState(string $state): bool { |
210 | return false !== filter_var($state, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^[\x20-\x7E]*$/']]); |
211 | } |
212 | |
213 | |
214 | |
215 | |
216 | |
217 | |
218 | function isValidCodeChallenge(string $challenge): bool { |
219 | return false !== filter_var($challenge, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^[A-Za-z0-9_-]+$/']]); |
220 | } |
221 | |
222 | |
223 | |
224 | |
225 | |
226 | function isValidScope(string $scope): bool { |
227 | return false !== filter_var($scope, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^([\x21\x23-\x5B\x5D-\x7E]+( [\x21\x23-\x5B\x5D-\x7E]+)*)?$/']]); |
228 | } |