• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

daycry / auth / 44317717916

18 Nov 2026 01:49PM UTC coverage: 82.894% (+4.4%) from 78.462%
44317717916

Pull #79

github

web-flow
Merge 7c781daeb into 55dbf61d2
Pull Request #79: feat: security fixes, extension points and auth completion

1214 of 1370 new or added lines in 67 files covered. (88.61%)

12 existing lines in 5 files now uncovered.

6663 of 8038 relevant lines covered (82.89%)

97.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

89.23
/src/Models/JwtTokenRepository.php
1
<?php
2

3
declare(strict_types=1);
4

5
/**
6
 * This file is part of Daycry Auth.
7
 *
8
 * (c) Daycry <daycry9@proton.me>
9
 *
10
 * For the full copyright and license information, please view
11
 * the LICENSE file that was distributed with this source code.
12
 */
13

14
namespace Daycry\Auth\Models;
15

16
use CodeIgniter\I18n\Time;
17
use Daycry\Auth\Entities\UserIdentity;
18
use Daycry\Auth\Enums\IdentityType;
19
use Daycry\Auth\Exceptions\DatabaseException;
20
use Daycry\Auth\Interfaces\JwtTokenRepositoryInterface;
21
use Daycry\Auth\Services\AuditLogger;
22
use Throwable;
23

24
/**
25
 * Repository for JWT refresh token operations.
26
 *
27
 * Encapsulates JWT refresh token CRUD from UserIdentityModel.
28
 */
29
class JwtTokenRepository implements JwtTokenRepositoryInterface
30
{
31
    public function __construct(
48 ✔
32
        private readonly UserIdentityModel $identityModel,
33
    ) {
34
    }
48 ✔
35

36
    /**
37
     * Stores a new JWT refresh token for the given user.
38
     *
39
     * @param int    $userId    User primary key
40
     * @param string $rawToken  The raw (unhashed) token to store
41
     * @param string $expiresAt Datetime string 'Y-m-d H:i:s'
42
     */
43
    public function createRefreshToken(int $userId, string $rawToken, string $expiresAt, bool $mfaVerified = false): void
15 ✔
44
    {
45
        $this->storeRefreshToken($userId, $rawToken, $expiresAt, bin2hex(random_bytes(32)), $mfaVerified);
15 ✔
46
    }
47

48
    /**
49
     * Store a hashed token in the same family as its predecessor.
50
     */
51
    private function storeRefreshToken(int $userId, string $rawToken, string $expiresAt, string $family, bool $mfaVerified = false): void
15 ✔
52
    {
53
        $this->identityModel->create([
15 ✔
54
            'user_id'        => $userId,
15 ✔
55
            'type'           => IdentityType::JWT_REFRESH->value,
15 ✔
56
            'secret'         => hash('sha256', $rawToken),
15 ✔
57
            'expires'        => $expiresAt,
15 ✔
58
            'refresh_family' => $family,
15 ✔
59
            'extra'          => json_encode(['mfa_verified' => $mfaVerified], JSON_THROW_ON_ERROR),
15 ✔
60
        ]);
15 ✔
61
    }
62

63
    /**
64
     * Consume and replace in one transaction. A conditional UPDATE grants
65
     * exactly one request the rotation; a replay invalidates the family.
66
     * Replays are looked up even after revocation, until expired rows are purged.
67
     */
68
    public function rotateRefreshToken(int $userId, string $rawToken, string $replacement, string $expiresAt): bool
8 ✔
69
    {
70
        $db  = $this->identityModel->builder()->db();
8 ✔
71
        $now = Time::now()->format('Y-m-d H:i:s');
8 ✔
72
        $db->transBegin();
8 ✔
73

74
        try {
75
            $identity = $this->identityModel->where('user_id', $userId)
8 ✔
76
                ->where('type', IdentityType::JWT_REFRESH->value)
8 ✔
77
                ->where('secret', hash('sha256', $rawToken))->first();
8 ✔
78
            if ($identity === null) {
8 ✔
NEW
79
                $db->transCommit();
×
80

NEW
81
                return false;
×
82
            }
83
            $family = (string) ($identity->refresh_family ?? '');
8 ✔
84
            // Derive legacy family identity without rewriting a token before
85
            // obtaining its rotation claim; concurrent requests derive the same value.
86
            if ($family === '') {
8 ✔
87
                $family = hash('sha256', 'legacy:' . $userId . ':' . $identity->id);
1 ✔
88
            }
89
            $builder = $this->identityModel->builder();
8 ✔
90
            $ok      = $builder->where('id', $identity->id)->where('revoked_at')
8 ✔
91
                ->where('expires >', $now)
8 ✔
92
                ->update(['revoked_at' => $now, 'refresh_family' => $family]);
8 ✔
93
            if ($ok === false) {
8 ✔
NEW
94
                throw new DatabaseException('Refresh-token rotation failed.');
×
95
            }
96
            if ($db->affectedRows() !== 1) {
8 ✔
97
                // Only possession of a known token can trigger family revocation.
98
                if ($identity->revoked_at !== null || (string) $identity->expires > $now) {
5 ✔
99
                    $builder->where('user_id', $userId)->where('type', IdentityType::JWT_REFRESH->value)
5 ✔
100
                        ->where('refresh_family', $family)->update(['revoked_at' => $now]);
5 ✔
101
                    service('auditLogger')->record(AuditLogger::EVENT_REFRESH_TOKEN_REVOKED, $userId, ['reason' => 'reuse', 'family' => $family]);
5 ✔
102
                }
103
                if (! $db->transStatus()) {
5 ✔
NEW
104
                    throw new DatabaseException('Refresh-token family revocation failed.');
×
105
                }
106
                $db->transCommit();
5 ✔
107

108
                return false;
5 ✔
109
            }
110
            $metadata = json_decode((string) $identity->extra, true);
6 ✔
111
            $this->storeRefreshToken($userId, $replacement, $expiresAt, $family, is_array($metadata) && ($metadata['mfa_verified'] ?? false) === true);
6 ✔
112
            if (! $db->transStatus() || ! $db->transCommit()) {
5 ✔
NEW
113
                throw new DatabaseException('Refresh-token rotation could not commit.');
×
114
            }
115

116
            return true;
5 ✔
117
        } catch (Throwable $e) {
1 ✔
118
            $db->transRollback();
1 ✔
119

120
            throw $e;
1 ✔
121
        }
122
    }
123

124
    /**
125
     * Finds a valid (non-expired, non-revoked) JWT refresh token.
126
     *
127
     * @param int    $userId   User primary key
128
     * @param string $rawToken The raw (unhashed) token
129
     */
130
    public function getRefreshToken(int $userId, string $rawToken): ?UserIdentity
9 ✔
131
    {
132
        return $this->identityModel->getJwtRefreshToken($userId, $rawToken);
9 ✔
133
    }
134

135
    /**
136
     * Revokes a JWT refresh token (hard-delete).
137
     *
138
     * @param int $identityId The identity record primary key
139
     */
140
    public function revokeRefreshToken(int $identityId): void
×
141
    {
142
        $this->identityModel->delete($identityId);
×
143
    }
144

145
    /**
146
     * Soft-revokes a JWT refresh token by setting revoked_at.
147
     *
148
     * @param int         $identityId The identity record primary key
149
     * @param int|null    $userId     User id for audit (when known by the caller)
150
     * @param string|null $reason     Optional reason recorded in the audit log
151
     */
152
    public function softRevokeRefreshToken(int $identityId, ?int $userId = null, ?string $reason = null): void
1 ✔
153
    {
154
        $this->identityModel->revokeIdentityById($identityId);
1 ✔
155

156
        $metadata = ['identity_id' => $identityId];
1 ✔
157

158
        if ($reason !== null) {
1 ✔
159
            $metadata['reason'] = $reason;
1 ✔
160
        }
161

162
        service('auditLogger')->record(AuditLogger::EVENT_REFRESH_TOKEN_REVOKED, $userId, $metadata);
1 ✔
163
    }
164

165
    /**
166
     * Soft-revokes every outstanding JWT refresh token of a user, so none of
167
     * them can mint new access tokens (ban, password change).
168
     *
169
     * @param int         $userId User primary key
170
     * @param string|null $reason Optional reason recorded in the audit log
171
     */
172
    public function softRevokeAllRefreshTokens(int $userId, ?string $reason = null): void
35 ✔
173
    {
174
        $this->identityModel->revokeIdentitiesByUserAndType($userId, IdentityType::JWT_REFRESH->value);
35 ✔
175

176
        $metadata = ['scope' => 'all'];
35 ✔
177

178
        if ($reason !== null) {
35 ✔
179
            $metadata['reason'] = $reason;
35 ✔
180
        }
181

182
        service('auditLogger')->record(AuditLogger::EVENT_REFRESH_TOKEN_REVOKED, $userId, $metadata);
35 ✔
183
    }
184
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc