Skip to content

Commit 0edd8a2

Browse files
committed
fix: token+apiKey 共存時のリフレッシュブロックを修正、プロアクティブリフレッシュを追加
canRefresh() が apiKey の存在で常に false を返し、token (JWT) で認証 しているにも関わらずリフレッシュが一切発動しなかった問題を修正。 apiKey-only(token なし)の場合のみリフレッシュを無効化するように変更。 併せて、リクエスト前に JWT の exp を確認し期限切れ/期限間近なら 事前にリフレッシュするプロアクティブ方式を追加。
1 parent 36f97e9 commit 0edd8a2

3 files changed

Lines changed: 383 additions & 2 deletions

File tree

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@
77

88
## [Unreleased]
99

10+
### 2026-04-05
11+
- **Fix**: token と apiKey が config に共存する場合、`canRefresh()` が apiKey の存在でリフレッシュをブロックし、JWT 期限切れ後にセッションが復旧不能になる問題を修正
12+
- **Feat**: リクエスト前に JWT の `exp` を確認し、期限切れ/期限間近なら事前にリフレッシュするプロアクティブ・トークンリフレッシュを追加
13+
1014
## [0.10.0] - 2026-04-03
1115

1216
### 2026-04-03

src/client.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { ClientOptions, ClientResponse, NgsiError } from "./types.js";
22
import { clientCredentialsGrant } from "./oauth.js";
3+
import { getTokenStatus } from "./token.js";
34

45
export class DryRunSignal extends Error {
56
constructor() {
@@ -163,7 +164,19 @@ export class GdbClient {
163164
}
164165

165166
private canRefresh(): boolean {
166-
return (!!this.refreshToken || (!!this.clientId && !!this.clientSecret)) && !this.apiKey;
167+
if (!this.refreshToken && !(this.clientId && this.clientSecret)) return false;
168+
// When authenticating solely via apiKey (no token), token refresh is unnecessary
169+
if (!this.token && this.apiKey) return false;
170+
return true;
171+
}
172+
173+
/** Proactively refresh the token before making a request if it is expired or about to expire. */
174+
private async proactiveRefresh(): Promise<void> {
175+
if (!this.token || !this.canRefresh()) return;
176+
const status = getTokenStatus(this.token);
177+
if (status.isExpired || status.isExpiringSoon) {
178+
await this.performTokenRefresh();
179+
}
167180
}
168181

169182
/** Check whether an error indicates an authentication/token problem that may be resolved by refreshing. */
@@ -341,6 +354,7 @@ export class GdbClient {
341354
headers?: Record<string, string>;
342355
},
343356
): Promise<ClientResponse<T>> {
357+
await this.proactiveRefresh();
344358
try {
345359
return await this.executeRequest<T>(method, path, options);
346360
} catch (err) {
@@ -404,6 +418,7 @@ export class GdbClient {
404418
skipTenantHeader?: boolean;
405419
},
406420
): Promise<ClientResponse<T>> {
421+
await this.proactiveRefresh();
407422
try {
408423
return await this.executeRawRequest<T>(method, path, options);
409424
} catch (err) {

0 commit comments

Comments
 (0)