Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
23 / 23 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| OidcPkceGenerator | |
100.00% |
23 / 23 |
|
100.00% |
2 / 2 |
8 | |
100.00% |
1 / 1 |
| generateVerifier | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
4 | |||
| generateChallenge | |
100.00% |
12 / 12 |
|
100.00% |
1 / 1 |
4 | |||
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * OIDC PKCE helper. |
| 5 | * |
| 6 | * This Source Code Form is subject to the terms of the Mozilla Public License, |
| 7 | * v. 2.0. If a copy of the MPL was not distributed with this file, You can |
| 8 | * obtain one at https://mozilla.org/MPL/2.0/. |
| 9 | * |
| 10 | * @package phpMyFAQ |
| 11 | * @author Thorsten Rinne <thorsten@phpmyfaq.de> |
| 12 | * @copyright 2026 phpMyFAQ Team |
| 13 | * @license https://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0 |
| 14 | * @link https://www.phpmyfaq.de |
| 15 | * @since 2026-04-18 |
| 16 | */ |
| 17 | |
| 18 | declare(strict_types=1); |
| 19 | |
| 20 | namespace phpMyFAQ\Auth\Oidc; |
| 21 | |
| 22 | use InvalidArgumentException; |
| 23 | |
| 24 | final class OidcPkceGenerator |
| 25 | { |
| 26 | public function generateVerifier(int $length = 128): string |
| 27 | { |
| 28 | if ($length < 43 || $length > 128) { |
| 29 | throw new InvalidArgumentException(sprintf( |
| 30 | 'PKCE verifier length must be between 43 and 128, got %d', |
| 31 | $length, |
| 32 | )); |
| 33 | } |
| 34 | |
| 35 | $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-._~'; |
| 36 | $charLength = strlen($chars) - 1; |
| 37 | $verifier = ''; |
| 38 | |
| 39 | for ($index = 0; $index < $length; ++$index) { |
| 40 | $verifier .= $chars[random_int(0, $charLength)]; |
| 41 | } |
| 42 | |
| 43 | return $verifier; |
| 44 | } |
| 45 | |
| 46 | public function generateChallenge(string $verifier): string |
| 47 | { |
| 48 | $len = strlen($verifier); |
| 49 | if ($len < 43 || $len > 128) { |
| 50 | throw new InvalidArgumentException(sprintf( |
| 51 | 'PKCE verifier length must be between 43 and 128, got %d', |
| 52 | $len, |
| 53 | )); |
| 54 | } |
| 55 | |
| 56 | if (preg_match('/[^0-9a-zA-Z\-._~]/', $verifier) === 1) { |
| 57 | throw new InvalidArgumentException('PKCE verifier contains invalid characters'); |
| 58 | } |
| 59 | |
| 60 | return rtrim( |
| 61 | strtr(base64_encode(hash(algo: 'sha256', data: $verifier, binary: true)), from: '+/', to: '-_'), |
| 62 | characters: '=', |
| 63 | ); |
| 64 | } |
| 65 | } |