Debian Codegraph @

vendor/spomky-labs/otphp/src/TOTP.php

raw
1 <?php
2
3 declare(strict_types=1);
4
5 namespace OTPHP;
6
7 use function is_int;
8 use OTPHP\Exception\InvalidParameterException;
9 use Psr\Clock\ClockInterface;
10
11 /**
12 * @readonly
13 *
14 * @see \OTPHP\Test\TOTPTest
15 */
16 final class TOTP extends OTP implements TOTPInterface
17 {
18 private readonly ClockInterface $clock;
19
20 public function __construct(string $secret, ?ClockInterface $clock = null)
21 {
22 parent::__construct($secret);
23 if ($clock === null) {
24 trigger_deprecation(
25 'spomky-labs/otphp',
26 '11.3.0',
27 'The parameter "$clock" will become mandatory in 12.0.0. Please set a valid PSR Clock implementation instead of "null".'
28 );
29 $clock = new InternalClock();
30 }
31
32 $this->clock = $clock;
33 }
34
35 public static function create(
36 null|string $secret = null,
37 int $period = self::DEFAULT_PERIOD,
38 string $digest = self::DEFAULT_DIGEST,
39 int $digits = self::DEFAULT_DIGITS,
40 int $epoch = self::DEFAULT_EPOCH,
41 ?ClockInterface $clock = null,
42 ?int $secretSize = null
43 ): self {
44 $totp = $secret !== null
45 ? self::createFromSecret($secret, $clock)
46 : self::generate($clock, $secretSize)
47 ;
48 $totp->setPeriod($period);
49 $totp->setDigest($digest);
50 $totp->setDigits($digits);
51 $totp->setEpoch($epoch);
52
53 return $totp;
54 }
55
56 public static function createFromSecret(string $secret, ?ClockInterface $clock = null): self
57 {
58 $totp = new self($secret, $clock);
59 $totp->setPeriod(self::DEFAULT_PERIOD);
60 $totp->setDigest(self::DEFAULT_DIGEST);
61 $totp->setDigits(self::DEFAULT_DIGITS);
62 $totp->setEpoch(self::DEFAULT_EPOCH);
63
64 return $totp;
65 }
66
67 /**
68 * @param positive-int|null $secretSize
69 */
70 public static function generate(?ClockInterface $clock = null, ?int $secretSize = null): self
71 {
72 return self::createFromSecret(self::generateSecret($secretSize), $clock);
73 }
74
75 public function getPeriod(): int
76 {
77 $value = $this->getParameter('period');
78 (is_int($value) && $value > 0) || throw new InvalidParameterException(
79 'Invalid "period" parameter.',
80 'period',
81 $value
82 );
83
84 return $value;
85 }
86
87 public function getEpoch(): int
88 {
89 $value = $this->getParameter('epoch');
90 (is_int($value) && $value >= 0) || throw new InvalidParameterException(
91 'Invalid "epoch" parameter.',
92 'epoch',
93 $value
94 );
95
96 return $value;
97 }
98
99 public function expiresIn(): int
100 {
101 $period = $this->getPeriod();
102
103 return $period - (($this->clock->now()->getTimestamp() - $this->getEpoch()) % $period);
104 }
105
106 /**
107 * The OTP at the specified input.
108 *
109 * @param 0|positive-int $input
110 */
111 public function at(int $input): string
112 {
113 return $this->generateOTP($this->timecode($input));
114 }
115
116 public function now(): string
117 {
118 $timestamp = $this->clock->now()
119 ->getTimestamp();
120 $timestamp >= 0 || throw new InvalidParameterException(
121 'The timestamp must return a positive integer.',
122 'timestamp',
123 $timestamp
124 );
125
126 return $this->at($timestamp);
127 }
128
129 /**
130 * If no timestamp is provided, the OTP is verified at the actual timestamp. When used, the leeway parameter will
131 * allow time drift. The passed value is in seconds.
132 *
133 * @param 0|positive-int $timestamp
134 * @param null|0|positive-int $leeway
135 */
136 public function verify(string $otp, null|int $timestamp = null, null|int $leeway = null): bool
137 {
138 $timestamp ??= $this->clock->now()
139 ->getTimestamp();
140 $timestamp >= 0 || throw new InvalidParameterException(
141 'Timestamp must be at least 0.',
142 'timestamp',
143 $timestamp
144 );
145
146 if ($leeway === null) {
147 return $this->compareOTP($this->at($timestamp), $otp);
148 }
149
150 $leeway = abs($leeway);
151 $leeway < $this->getPeriod() || throw new InvalidParameterException(
152 'The leeway must be lower than the TOTP period',
153 'leeway',
154 $leeway
155 );
156 $timestampMinusLeeway = $timestamp - $leeway;
157 $timestampMinusLeeway >= 0 || throw new InvalidParameterException(
158 'The timestamp must be greater than or equal to the leeway.',
159 'timestamp',
160 $timestamp
161 );
162
163 return $this->compareOTP($this->at($timestampMinusLeeway), $otp)
164 || $this->compareOTP($this->at($timestamp), $otp)
165 || $this->compareOTP($this->at($timestamp + $leeway), $otp);
166 }
167
168 public function getProvisioningUri(): string
169 {
170 $params = [];
171 if ($this->getPeriod() !== 30) {
172 $params['period'] = $this->getPeriod();
173 }
174
175 if ($this->getEpoch() !== 0) {
176 $params['epoch'] = $this->getEpoch();
177 }
178
179 return $this->generateURI('totp', $params);
180 }
181
182 public function setPeriod(int $period): void
183 {
184 $this->setParameter('period', $period);
185 }
186
187 public function withPeriod(int $period): self
188 {
189 $otp = clone $this;
190 $otp->setParameter('period', $period);
191
192 return $otp;
193 }
194
195 public function setEpoch(int $epoch): void
196 {
197 $this->setParameter('epoch', $epoch);
198 }
199
200 public function withEpoch(int $epoch): self
201 {
202 $otp = clone $this;
203 $otp->setParameter('epoch', $epoch);
204
205 return $otp;
206 }
207
208 /**
209 * @return array<non-empty-string, callable>
210 */
211 protected function getParameterMap(): array
212 {
213 return [
214 ...parent::getParameterMap(),
215 'period' => static function ($value): int {
216 (int) $value > 0 || throw new InvalidParameterException('Period must be at least 1.', 'period', $value);
217
218 return (int) $value;
219 },
220 'epoch' => static function ($value): int {
221 (int) $value >= 0 || throw new InvalidParameterException(
222 'Epoch must be greater than or equal to 0.',
223 'epoch',
224 $value
225 );
226
227 return (int) $value;
228 },
229 ];
230 }
231
232 /**
233 * @param array<non-empty-string, mixed> $options
234 */
235 protected function filterOptions(array &$options): void
236 {
237 parent::filterOptions($options);
238
239 if (isset($options['epoch']) && $options['epoch'] === 0) {
240 unset($options['epoch']);
241 }
242
243 ksort($options);
244 }
245
246 /**
247 * @param 0|positive-int $timestamp
248 *
249 * @return 0|positive-int
250 */
251 private function timecode(int $timestamp): int
252 {
253 $timecode = (int) floor(($timestamp - $this->getEpoch()) / $this->getPeriod());
254 $timecode >= 0 || throw new InvalidParameterException(
255 'Timecode must be at least 0. The timestamp must be greater than or equal to the epoch.',
256 'timecode',
257 $timecode
258 );
259
260 return $timecode;
261 }
262 }