$state, 'challenge' => $challenge, 'redirectUri' => $redirectUri]; } public static function challengeOf(string $verifier): string { return rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '='); } public static function redeems(array $pending, string $code, string $verifier, string $redirectUri, int $now): bool { $hash = $pending['code'] ?? null; $challenge = $pending['challenge'] ?? null; $expected = $pending['redirectUri'] ?? null; $expires = $pending['expires'] ?? null; return is_string($hash) && is_string($challenge) && is_string($expected) && is_int($expires) && $now < $expires && hash_equals($hash, hash('sha256', $code)) && hash_equals($expected, $redirectUri) && preg_match(self::VERIFIER, $verifier) === 1 && hash_equals($challenge, self::challengeOf($verifier)); } public function grant(string $challenge, string $redirectUri, int $now): string { $code = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '='); update_option(self::OPTION, [ 'code' => hash('sha256', $code), 'challenge' => $challenge, 'redirectUri' => $redirectUri, 'expires' => $now + self::LIFETIME, ], false); return $code; } public function redeem(string $code, string $verifier, string $redirectUri, int $now): bool { $pending = get_option(self::OPTION); return is_array($pending) && self::redeems($pending, $code, $verifier, $redirectUri, $now) && delete_option(self::OPTION); } }