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 | && in_array($request->getQueryParams()['response_type'], ['code', 'id']); |
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 | if (!is_null($v)) { |
86 | $qs[] = urlencode($k) . '=' . urlencode($v); |
87 | } |
88 | } |
89 | return join('&', $qs); |
90 | } |
91 | |
92 | function urlComponentsMatch(string $url1, string $url2, ?array $components=null): bool { |
93 | $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]; |
94 | $components = $components ?? $validComponents; |
95 | |
96 | foreach ($components as $cmp) { |
97 | if (!in_array($cmp, $validComponents)) { |
98 | throw new Exception("Invalid parse_url() component passed: $cmp"); |
99 | } |
100 | |
101 | if (parse_url($url1, $cmp) !== parse_url($url2, $cmp)) { |
102 | return false; |
103 | } |
104 | } |
105 | |
106 | return true; |
107 | } |
108 | |
109 | |
110 | |
111 | |
112 | |
113 | |
114 | |
115 | |
116 | function appendQueryParams(string $uri, array $queryParams): string { |
117 | if (empty($queryParams)) { |
118 | return $uri; |
119 | } |
120 | |
121 | $queryString = buildQueryString($queryParams); |
122 | $separator = parse_url($uri, \PHP_URL_QUERY) ? '&' : '?'; |
123 | $uri = rtrim($uri, '?&'); |
124 | return "{$uri}{$separator}{$queryString}"; |
125 | } |
126 | |
127 | |
128 | |
129 | |
130 | |
131 | |
132 | |
133 | |
134 | |
135 | |
136 | function trySetLogger($target, LoggerInterface $logger) { |
137 | if ($target instanceof LoggerAwareInterface) { |
138 | $target->setLogger($logger); |
139 | } |
140 | return $target; |
141 | } |
142 | |
143 | function renderTemplate(string $template, array $context=[]) { |
144 | $render = function ($__template, $__templateData) { |
145 | $render = function ($template, $data) { |
146 | return renderTemplate($template, $data); |
147 | }; |
148 | ob_start(); |
149 | extract($__templateData); |
150 | unset($__templateData); |
151 | include $__template; |
152 | return ob_get_clean(); |
153 | }; |
154 | return $render($template, $context); |
155 | } |
156 | |
157 | |
158 | |
159 | |
160 | |
161 | |
162 | |
163 | |
164 | |
165 | |
166 | |
167 | |
168 | function isClientIdentifier(string $client_id): bool { |
169 | return ($url_components = parse_url($client_id)) && |
170 | in_array($url_components['scheme'] ?? '', ['http', 'https']) && |
171 | 0 < strlen($url_components['path'] ?? '') && |
172 | false === strpos($url_components['path'], '/./') && |
173 | false === strpos($url_components['path'], '/../') && |
174 | false === isset($url_components['fragment']) && |
175 | false === isset($url_components['user']) && |
176 | false === isset($url_components['pass']) && |
177 | ( |
178 | false === filter_var($url_components['host'], FILTER_VALIDATE_IP) || |
179 | ($url_components['host'] ?? null) == '127.0.0.1' || |
180 | ($url_components['host'] ?? null) == '[::1]' |
181 | ) |
182 | ; |
183 | } |
184 | |
185 | |
186 | |
187 | |
188 | |
189 | |
190 | |
191 | |
192 | function isProfileUrl(string $profile_url): bool { |
193 | return ($url_components = parse_url($profile_url)) && |
194 | in_array($url_components['scheme'] ?? '', ['http', 'https']) && |
195 | 0 < strlen($url_components['path'] ?? '') && |
196 | false === strpos($url_components['path'], '/./') && |
197 | false === strpos($url_components['path'], '/../') && |
198 | false === isset($url_components['fragment']) && |
199 | false === isset($url_components['user']) && |
200 | false === isset($url_components['pass']) && |
201 | false === isset($url_components['port']) && |
202 | false === filter_var($url_components['host'], FILTER_VALIDATE_IP) |
203 | ; |
204 | } |
205 | |
206 | |
207 | |
208 | |
209 | |
210 | |
211 | function isValidState(string $state): bool { |
212 | return false !== filter_var($state, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^[\x20-\x7E]*$/']]); |
213 | } |
214 | |
215 | |
216 | |
217 | |
218 | |
219 | |
220 | function isValidCodeChallenge(string $challenge): bool { |
221 | return false !== filter_var($challenge, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^[A-Za-z0-9_\-.~]+$/']]); |
222 | } |
223 | |
224 | |
225 | |
226 | |
227 | |
228 | function isValidScope(string $scope): bool { |
229 | return false !== filter_var($scope, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^([\x21\x23-\x5B\x5D-\x7E]+( [\x21\x23-\x5B\x5D-\x7E]+)*)?$/']]); |
230 | } |