@geekmidas/auth 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/dist/{cacheTokenStorage-Ca05vf3T.mjs → cacheTokenStorage-16NE8Cd9.mjs} +3 -3
  2. package/dist/cacheTokenStorage-16NE8Cd9.mjs.map +1 -0
  3. package/dist/{cacheTokenStorage-BzBRJfd-.d.mts → cacheTokenStorage-B7sOoysu.d.cts} +8 -6
  4. package/dist/cacheTokenStorage-B7sOoysu.d.cts.map +1 -0
  5. package/dist/{cacheTokenStorage-CvptztkW.cjs → cacheTokenStorage-CEpMniTi.cjs} +3 -3
  6. package/dist/cacheTokenStorage-CEpMniTi.cjs.map +1 -0
  7. package/dist/{cacheTokenStorage-yNUpDD8W.d.cts → cacheTokenStorage-_tq4Kmhc.d.mts} +8 -6
  8. package/dist/cacheTokenStorage-_tq4Kmhc.d.mts.map +1 -0
  9. package/dist/cacheTokenStorage.cjs +1 -1
  10. package/dist/cacheTokenStorage.d.cts +1 -1
  11. package/dist/cacheTokenStorage.d.mts +1 -1
  12. package/dist/cacheTokenStorage.mjs +1 -1
  13. package/dist/{client-DaiUm0UZ.cjs → client-BPl_mMvb.cjs} +14 -8
  14. package/dist/client-BPl_mMvb.cjs.map +1 -0
  15. package/dist/{client-DjNZS6vZ.mjs → client-eidYNJSH.mjs} +14 -8
  16. package/dist/client-eidYNJSH.mjs.map +1 -0
  17. package/dist/client.cjs +2 -2
  18. package/dist/client.d.cts +1 -1
  19. package/dist/client.d.mts +1 -1
  20. package/dist/client.mjs +2 -2
  21. package/dist/hono/jwt.cjs +1 -1
  22. package/dist/hono/jwt.cjs.map +1 -1
  23. package/dist/hono/jwt.d.cts +2 -1
  24. package/dist/hono/jwt.d.cts.map +1 -0
  25. package/dist/hono/jwt.d.mts +2 -1
  26. package/dist/hono/jwt.d.mts.map +1 -0
  27. package/dist/hono/jwt.mjs +1 -1
  28. package/dist/hono/jwt.mjs.map +1 -1
  29. package/dist/hono/oidc.cjs +1 -1
  30. package/dist/hono/oidc.cjs.map +1 -1
  31. package/dist/hono/oidc.d.cts +3 -2
  32. package/dist/hono/oidc.d.cts.map +1 -0
  33. package/dist/hono/oidc.d.mts +3 -2
  34. package/dist/hono/oidc.d.mts.map +1 -0
  35. package/dist/hono/oidc.mjs +1 -1
  36. package/dist/hono/oidc.mjs.map +1 -1
  37. package/dist/index.cjs +3 -3
  38. package/dist/index.d.cts +2 -2
  39. package/dist/index.d.mts +2 -2
  40. package/dist/index.mjs +3 -3
  41. package/dist/{jwt-DF9kFbmh.d.cts → jwt-3eIuY2dg.d.cts} +2 -1
  42. package/dist/jwt-3eIuY2dg.d.cts.map +1 -0
  43. package/dist/jwt-Bo_eACEi.cjs.map +1 -1
  44. package/dist/{jwt-DH8CJ2xC.d.mts → jwt-BqLlRkw-.d.mts} +2 -1
  45. package/dist/jwt-BqLlRkw-.d.mts.map +1 -0
  46. package/dist/jwt-D88cPJyT.mjs.map +1 -1
  47. package/dist/jwt.d.cts +1 -1
  48. package/dist/jwt.d.mts +1 -1
  49. package/dist/lambda/jwt.cjs +2 -2
  50. package/dist/lambda/jwt.cjs.map +1 -1
  51. package/dist/lambda/jwt.d.cts +2 -1
  52. package/dist/lambda/jwt.d.cts.map +1 -0
  53. package/dist/lambda/jwt.d.mts +2 -1
  54. package/dist/lambda/jwt.d.mts.map +1 -0
  55. package/dist/lambda/jwt.mjs +2 -2
  56. package/dist/lambda/jwt.mjs.map +1 -1
  57. package/dist/lambda/oidc.cjs +2 -2
  58. package/dist/lambda/oidc.cjs.map +1 -1
  59. package/dist/lambda/oidc.d.cts +3 -2
  60. package/dist/lambda/oidc.d.cts.map +1 -0
  61. package/dist/lambda/oidc.d.mts +3 -2
  62. package/dist/lambda/oidc.d.mts.map +1 -0
  63. package/dist/lambda/oidc.mjs +2 -2
  64. package/dist/lambda/oidc.mjs.map +1 -1
  65. package/dist/oidc-C0KyYaAK.cjs.map +1 -1
  66. package/dist/{oidc-CKOGLxjV.d.mts → oidc-ChA17wLB.d.cts} +3 -2
  67. package/dist/oidc-ChA17wLB.d.cts.map +1 -0
  68. package/dist/{oidc-DDLIB5gb.d.cts → oidc-DTRgBBl6.d.mts} +3 -2
  69. package/dist/oidc-DTRgBBl6.d.mts.map +1 -0
  70. package/dist/oidc-KA30gMlx.mjs.map +1 -1
  71. package/dist/oidc.d.cts +2 -2
  72. package/dist/oidc.d.mts +2 -2
  73. package/dist/server.cjs +2 -2
  74. package/dist/server.d.cts +2 -2
  75. package/dist/server.d.mts +2 -2
  76. package/dist/server.mjs +2 -2
  77. package/dist/{tokenManager--Q93eNYr.d.mts → tokenManager-CL3yE06D.d.cts} +2 -1
  78. package/dist/tokenManager-CL3yE06D.d.cts.map +1 -0
  79. package/dist/{tokenManager-BVXxfHRa.mjs → tokenManager-Ci2Tgxp8.mjs} +5 -3
  80. package/dist/tokenManager-Ci2Tgxp8.mjs.map +1 -0
  81. package/dist/{tokenManager-EPmwgai2.cjs → tokenManager-CvEMgxOp.cjs} +5 -3
  82. package/dist/tokenManager-CvEMgxOp.cjs.map +1 -0
  83. package/dist/{tokenManager-H6-lWEah.d.cts → tokenManager-RrwjL0y-.d.mts} +2 -1
  84. package/dist/tokenManager-RrwjL0y-.d.mts.map +1 -0
  85. package/dist/tokenManager.cjs +1 -1
  86. package/dist/tokenManager.d.cts +1 -1
  87. package/dist/tokenManager.d.mts +1 -1
  88. package/dist/tokenManager.mjs +1 -1
  89. package/package.json +3 -3
  90. package/src/__tests__/cacheTokenStorage.spec.ts +148 -148
  91. package/src/__tests__/client.spec.ts +339 -339
  92. package/src/__tests__/hono-jwt.spec.ts +219 -219
  93. package/src/__tests__/hono-oidc.spec.ts +560 -560
  94. package/src/__tests__/jwt.spec.ts +150 -127
  95. package/src/__tests__/lambda-jwt.spec.ts +205 -205
  96. package/src/__tests__/lambda-oidc.spec.ts +580 -579
  97. package/src/__tests__/oidc.spec.ts +365 -365
  98. package/src/__tests__/tokenManager.spec.ts +254 -254
  99. package/src/cacheTokenStorage.ts +32 -32
  100. package/src/client.ts +199 -190
  101. package/src/hono/jwt.ts +111 -111
  102. package/src/hono/oidc.ts +131 -131
  103. package/src/index.ts +2 -2
  104. package/src/jwt.ts +57 -57
  105. package/src/lambda/jwt.ts +170 -170
  106. package/src/lambda/oidc.ts +165 -165
  107. package/src/oidc.ts +121 -121
  108. package/src/server.ts +6 -7
  109. package/src/tokenManager.ts +89 -87
  110. package/tsconfig.json +10 -0
  111. package/dist/cacheTokenStorage-Ca05vf3T.mjs.map +0 -1
  112. package/dist/cacheTokenStorage-CvptztkW.cjs.map +0 -1
  113. package/dist/client-DaiUm0UZ.cjs.map +0 -1
  114. package/dist/client-DjNZS6vZ.mjs.map +0 -1
  115. package/dist/tokenManager-BVXxfHRa.mjs.map +0 -1
  116. package/dist/tokenManager-EPmwgai2.cjs.map +0 -1
package/src/client.ts CHANGED
@@ -1,211 +1,220 @@
1
1
  export interface TokenStorage {
2
- getAccessToken(): Promise<string | null> | string | null;
3
- setAccessToken(token: string, ttl?: number): Promise<void> | void;
4
- getRefreshToken(): Promise<string | null> | string | null;
5
- setRefreshToken(token: string, ttl?: number): Promise<void> | void;
6
- clearTokens(): Promise<void> | void;
2
+ getAccessToken(): Promise<string | null> | string | null;
3
+ setAccessToken(token: string, ttl?: number): Promise<void> | void;
4
+ getRefreshToken(): Promise<string | null> | string | null;
5
+ setRefreshToken(token: string, ttl?: number): Promise<void> | void;
6
+ clearTokens(): Promise<void> | void;
7
7
  }
8
8
 
9
9
  export class LocalStorageTokenStorage implements TokenStorage {
10
- private accessTokenKey: string;
11
- private refreshTokenKey: string;
12
-
13
- constructor(
14
- accessTokenKey: string = 'access_token',
15
- refreshTokenKey: string = 'refresh_token',
16
- ) {
17
- this.accessTokenKey = accessTokenKey;
18
- this.refreshTokenKey = refreshTokenKey;
19
- }
20
-
21
- getAccessToken(): string | null {
22
- if (typeof window === 'undefined') return null;
23
- return localStorage.getItem(this.accessTokenKey);
24
- }
25
-
26
- setAccessToken(token: string, ttl?: number): void {
27
- if (typeof window === 'undefined') return;
28
- localStorage.setItem(this.accessTokenKey, token);
29
- }
30
-
31
- getRefreshToken(): string | null {
32
- if (typeof window === 'undefined') return null;
33
- return localStorage.getItem(this.refreshTokenKey);
34
- }
35
-
36
- setRefreshToken(token: string, ttl?: number): void {
37
- if (typeof window === 'undefined') return;
38
- localStorage.setItem(this.refreshTokenKey, token);
39
- }
40
-
41
- clearTokens(): void {
42
- if (typeof window === 'undefined') return;
43
- localStorage.removeItem(this.accessTokenKey);
44
- localStorage.removeItem(this.refreshTokenKey);
45
- }
10
+ private accessTokenKey: string;
11
+ private refreshTokenKey: string;
12
+
13
+ constructor(
14
+ accessTokenKey: string = 'access_token',
15
+ refreshTokenKey: string = 'refresh_token',
16
+ ) {
17
+ this.accessTokenKey = accessTokenKey;
18
+ this.refreshTokenKey = refreshTokenKey;
19
+ }
20
+
21
+ getAccessToken(): string | null {
22
+ if (typeof window === 'undefined') return null;
23
+ return localStorage.getItem(this.accessTokenKey);
24
+ }
25
+
26
+ setAccessToken(token: string, _ttl?: number): void {
27
+ if (typeof window === 'undefined') return;
28
+ localStorage.setItem(this.accessTokenKey, token);
29
+ }
30
+
31
+ getRefreshToken(): string | null {
32
+ if (typeof window === 'undefined') return null;
33
+ return localStorage.getItem(this.refreshTokenKey);
34
+ }
35
+
36
+ setRefreshToken(token: string, _ttl?: number): void {
37
+ if (typeof window === 'undefined') return;
38
+ localStorage.setItem(this.refreshTokenKey, token);
39
+ }
40
+
41
+ clearTokens(): void {
42
+ if (typeof window === 'undefined') return;
43
+ localStorage.removeItem(this.accessTokenKey);
44
+ localStorage.removeItem(this.refreshTokenKey);
45
+ }
46
46
  }
47
47
 
48
48
  export class MemoryTokenStorage implements TokenStorage {
49
- private accessToken: string | null = null;
50
- private refreshToken: string | null = null;
49
+ private accessToken: string | null = null;
50
+ private refreshToken: string | null = null;
51
51
 
52
- getAccessToken(): string | null {
53
- return this.accessToken;
54
- }
52
+ getAccessToken(): string | null {
53
+ return this.accessToken;
54
+ }
55
55
 
56
- setAccessToken(token: string, ttl?: number): void {
57
- this.accessToken = token;
58
- }
56
+ setAccessToken(token: string, _ttl?: number): void {
57
+ this.accessToken = token;
58
+ }
59
59
 
60
- getRefreshToken(): string | null {
61
- return this.refreshToken;
62
- }
60
+ getRefreshToken(): string | null {
61
+ return this.refreshToken;
62
+ }
63
63
 
64
- setRefreshToken(token: string, ttl?: number): void {
65
- this.refreshToken = token;
66
- }
64
+ setRefreshToken(token: string, _ttl?: number): void {
65
+ this.refreshToken = token;
66
+ }
67
67
 
68
- clearTokens(): void {
69
- this.accessToken = null;
70
- this.refreshToken = null;
71
- }
68
+ clearTokens(): void {
69
+ this.accessToken = null;
70
+ this.refreshToken = null;
71
+ }
72
72
  }
73
73
 
74
74
  export interface TokenClientOptions {
75
- storage?: TokenStorage;
76
- refreshEndpoint?: string;
77
- onTokenRefresh?: (tokens: {
78
- accessToken: string;
79
- refreshToken?: string;
80
- }) => void;
81
- onTokenExpired?: () => void;
75
+ storage?: TokenStorage;
76
+ refreshEndpoint?: string;
77
+ onTokenRefresh?: (tokens: {
78
+ accessToken: string;
79
+ refreshToken?: string;
80
+ }) => void;
81
+ onTokenExpired?: () => void;
82
82
  }
83
83
 
84
84
  export class TokenClient {
85
- private storage: TokenStorage;
86
- private refreshEndpoint?: string;
87
- private onTokenRefresh?: (tokens: {
88
- accessToken: string;
89
- refreshToken?: string;
90
- }) => void;
91
- private onTokenExpired?: () => void;
92
-
93
- constructor(options: TokenClientOptions = {}) {
94
- this.storage = options.storage || new LocalStorageTokenStorage();
95
- this.refreshEndpoint = options.refreshEndpoint;
96
- this.onTokenRefresh = options.onTokenRefresh;
97
- this.onTokenExpired = options.onTokenExpired;
98
- }
99
-
100
- async getAccessToken(): Promise<string | null> {
101
- return await this.storage.getAccessToken();
102
- }
103
-
104
- async getRefreshToken(): Promise<string | null> {
105
- return await this.storage.getRefreshToken();
106
- }
107
-
108
- async setTokens(
109
- accessToken: string,
110
- refreshToken?: string,
111
- accessTtl?: number,
112
- refreshTtl?: number,
113
- ): Promise<void> {
114
- await this.storage.setAccessToken(accessToken, accessTtl);
115
- if (refreshToken) {
116
- await this.storage.setRefreshToken(refreshToken, refreshTtl);
117
- }
118
- }
119
-
120
- async clearTokens(): Promise<void> {
121
- await this.storage.clearTokens();
122
- }
123
-
124
- isTokenExpired(token: string): boolean {
125
- try {
126
- const payload = JSON.parse(atob(token.split('.')[1]));
127
- const now = Math.floor(Date.now() / 1000);
128
- return payload.exp < now;
129
- } catch {
130
- return true;
131
- }
132
- }
133
-
134
- getTokenExpiration(token: string): Date | null {
135
- try {
136
- const payload = JSON.parse(atob(token.split('.')[1]));
137
- return new Date(payload.exp * 1000);
138
- } catch {
139
- return null;
140
- }
141
- }
142
-
143
- async refreshTokens(): Promise<boolean> {
144
- const refreshToken = await this.getRefreshToken();
145
-
146
- if (!refreshToken || !this.refreshEndpoint) {
147
- return false;
148
- }
149
-
150
- try {
151
- const response = await fetch(this.refreshEndpoint, {
152
- method: 'POST',
153
- headers: {
154
- 'Content-Type': 'application/json',
155
- },
156
- body: JSON.stringify({ refreshToken }),
157
- });
158
-
159
- if (!response.ok) {
160
- throw new Error('Failed to refresh token');
161
- }
162
-
163
- const data = await response.json();
164
- const { accessToken, refreshToken: newRefreshToken } = data;
165
-
166
- await this.setTokens(accessToken, newRefreshToken);
167
-
168
- if (this.onTokenRefresh) {
169
- this.onTokenRefresh({ accessToken, refreshToken: newRefreshToken });
170
- }
171
-
172
- return true;
173
- } catch (error) {
174
- await this.clearTokens();
175
- if (this.onTokenExpired) {
176
- this.onTokenExpired();
177
- }
178
- return false;
179
- }
180
- }
181
-
182
- async getValidAccessToken(): Promise<string | null> {
183
- const accessToken = await this.getAccessToken();
184
-
185
- if (!accessToken) {
186
- return null;
187
- }
188
-
189
- if (this.isTokenExpired(accessToken)) {
190
- const refreshed = await this.refreshTokens();
191
- if (!refreshed) {
192
- return null;
193
- }
194
- return await this.getAccessToken();
195
- }
196
-
197
- return accessToken;
198
- }
199
-
200
- async createAuthHeaders(): Promise<Record<string, string>> {
201
- const token = await this.getAccessToken();
202
- return token ? { Authorization: `Bearer ${token}` } : {};
203
- }
204
-
205
- async createValidAuthHeaders(): Promise<Record<string, string>> {
206
- const token = await this.getValidAccessToken();
207
- return token ? { Authorization: `Bearer ${token}` } : {};
208
- }
85
+ private storage: TokenStorage;
86
+ private refreshEndpoint?: string;
87
+ private onTokenRefresh?: (tokens: {
88
+ accessToken: string;
89
+ refreshToken?: string;
90
+ }) => void;
91
+ private onTokenExpired?: () => void;
92
+
93
+ constructor(options: TokenClientOptions = {}) {
94
+ this.storage = options.storage || new LocalStorageTokenStorage();
95
+ this.refreshEndpoint = options.refreshEndpoint;
96
+ this.onTokenRefresh = options.onTokenRefresh;
97
+ this.onTokenExpired = options.onTokenExpired;
98
+ }
99
+
100
+ async getAccessToken(): Promise<string | null> {
101
+ return await this.storage.getAccessToken();
102
+ }
103
+
104
+ async getRefreshToken(): Promise<string | null> {
105
+ return await this.storage.getRefreshToken();
106
+ }
107
+
108
+ async setTokens(
109
+ accessToken: string,
110
+ refreshToken?: string,
111
+ accessTtl?: number,
112
+ refreshTtl?: number,
113
+ ): Promise<void> {
114
+ await this.storage.setAccessToken(accessToken, accessTtl);
115
+ if (refreshToken) {
116
+ await this.storage.setRefreshToken(refreshToken, refreshTtl);
117
+ }
118
+ }
119
+
120
+ async clearTokens(): Promise<void> {
121
+ await this.storage.clearTokens();
122
+ }
123
+
124
+ isTokenExpired(token: string): boolean {
125
+ try {
126
+ const parts = token.split('.');
127
+ const payloadPart = parts[1];
128
+ if (!payloadPart) return true;
129
+ const payload = JSON.parse(atob(payloadPart));
130
+ const now = Math.floor(Date.now() / 1000);
131
+ return payload.exp < now;
132
+ } catch {
133
+ return true;
134
+ }
135
+ }
136
+
137
+ getTokenExpiration(token: string): Date | null {
138
+ try {
139
+ const parts = token.split('.');
140
+ const payloadPart = parts[1];
141
+ if (!payloadPart) return null;
142
+ const payload = JSON.parse(atob(payloadPart));
143
+ return new Date(payload.exp * 1000);
144
+ } catch {
145
+ return null;
146
+ }
147
+ }
148
+
149
+ async refreshTokens(): Promise<boolean> {
150
+ const refreshToken = await this.getRefreshToken();
151
+
152
+ if (!refreshToken || !this.refreshEndpoint) {
153
+ return false;
154
+ }
155
+
156
+ try {
157
+ const response = await fetch(this.refreshEndpoint, {
158
+ method: 'POST',
159
+ headers: {
160
+ 'Content-Type': 'application/json',
161
+ },
162
+ body: JSON.stringify({ refreshToken }),
163
+ });
164
+
165
+ if (!response.ok) {
166
+ throw new Error('Failed to refresh token');
167
+ }
168
+
169
+ const data = (await response.json()) as {
170
+ accessToken: string;
171
+ refreshToken: string;
172
+ };
173
+ const { accessToken, refreshToken: newRefreshToken } = data;
174
+
175
+ await this.setTokens(accessToken, newRefreshToken);
176
+
177
+ if (this.onTokenRefresh) {
178
+ this.onTokenRefresh({ accessToken, refreshToken: newRefreshToken });
179
+ }
180
+
181
+ return true;
182
+ } catch (_error) {
183
+ await this.clearTokens();
184
+ if (this.onTokenExpired) {
185
+ this.onTokenExpired();
186
+ }
187
+ return false;
188
+ }
189
+ }
190
+
191
+ async getValidAccessToken(): Promise<string | null> {
192
+ const accessToken = await this.getAccessToken();
193
+
194
+ if (!accessToken) {
195
+ return null;
196
+ }
197
+
198
+ if (this.isTokenExpired(accessToken)) {
199
+ const refreshed = await this.refreshTokens();
200
+ if (!refreshed) {
201
+ return null;
202
+ }
203
+ return await this.getAccessToken();
204
+ }
205
+
206
+ return accessToken;
207
+ }
208
+
209
+ async createAuthHeaders(): Promise<Record<string, string>> {
210
+ const token = await this.getAccessToken();
211
+ return token ? { Authorization: `Bearer ${token}` } : {};
212
+ }
213
+
214
+ async createValidAuthHeaders(): Promise<Record<string, string>> {
215
+ const token = await this.getValidAccessToken();
216
+ return token ? { Authorization: `Bearer ${token}` } : {};
217
+ }
209
218
  }
210
219
 
211
220
  export { CacheTokenStorage } from './cacheTokenStorage.js';
package/src/hono/jwt.ts CHANGED
@@ -1,55 +1,55 @@
1
1
  import type { Context, MiddlewareHandler, Next } from 'hono';
2
2
  import {
3
- type JwtClaims,
4
- type JwtConfig,
5
- JwtVerifier,
6
- type TokenExtractionOptions,
3
+ type JwtClaims,
4
+ type JwtConfig,
5
+ JwtVerifier,
6
+ type TokenExtractionOptions,
7
7
  } from '../jwt';
8
8
 
9
9
  export {
10
- JwtVerifier,
11
- type JwtClaims,
12
- type JwtConfig,
13
- type TokenExtractionOptions,
10
+ JwtVerifier,
11
+ type JwtClaims,
12
+ type JwtConfig,
13
+ type TokenExtractionOptions,
14
14
  };
15
15
 
16
16
  function extractToken(
17
- c: Context,
18
- options: TokenExtractionOptions = {},
17
+ c: Context,
18
+ options: TokenExtractionOptions = {},
19
19
  ): string | null {
20
- const {
21
- headerName = 'authorization',
22
- cookieName,
23
- tokenPrefix = 'Bearer ',
24
- } = options;
25
-
26
- const headerValue = c.req.header(headerName);
27
- if (headerValue) {
28
- if (tokenPrefix && headerValue.startsWith(tokenPrefix)) {
29
- return headerValue.slice(tokenPrefix.length);
30
- }
31
- return headerValue;
32
- }
33
-
34
- if (cookieName) {
35
- const cookieHeader = c.req.header('cookie');
36
- if (cookieHeader) {
37
- const match = cookieHeader.match(new RegExp(`${cookieName}=([^;]+)`));
38
- if (match) {
39
- return match[1];
40
- }
41
- }
42
- }
43
-
44
- return null;
20
+ const {
21
+ headerName = 'authorization',
22
+ cookieName,
23
+ tokenPrefix = 'Bearer ',
24
+ } = options;
25
+
26
+ const headerValue = c.req.header(headerName);
27
+ if (headerValue) {
28
+ if (tokenPrefix && headerValue.startsWith(tokenPrefix)) {
29
+ return headerValue.slice(tokenPrefix.length);
30
+ }
31
+ return headerValue;
32
+ }
33
+
34
+ if (cookieName) {
35
+ const cookieHeader = c.req.header('cookie');
36
+ if (cookieHeader) {
37
+ const match = cookieHeader.match(new RegExp(`${cookieName}=([^;]+)`));
38
+ if (match?.[1]) {
39
+ return match[1];
40
+ }
41
+ }
42
+ }
43
+
44
+ return null;
45
45
  }
46
46
 
47
47
  export interface JwtMiddlewareOptions<TClaims extends JwtClaims = JwtClaims> {
48
- config: JwtConfig;
49
- extraction?: TokenExtractionOptions;
50
- contextKey?: string;
51
- onError?: (c: Context, error: Error) => Response | Promise<Response>;
52
- transformClaims?: (claims: JwtClaims) => TClaims;
48
+ config: JwtConfig;
49
+ extraction?: TokenExtractionOptions;
50
+ contextKey?: string;
51
+ onError?: (c: Context, error: Error) => Response | Promise<Response>;
52
+ transformClaims?: (claims: JwtClaims) => TClaims;
53
53
  }
54
54
 
55
55
  /**
@@ -68,75 +68,75 @@ export interface JwtMiddlewareOptions<TClaims extends JwtClaims = JwtClaims> {
68
68
  * ```
69
69
  */
70
70
  export class JwtMiddleware<TClaims extends JwtClaims = JwtClaims> {
71
- private readonly verifier: JwtVerifier<TClaims>;
72
- private readonly extraction: TokenExtractionOptions;
73
- private readonly contextKey: string;
74
- private readonly onError?: (
75
- c: Context,
76
- error: Error,
77
- ) => Response | Promise<Response>;
78
- private readonly transformClaims?: (claims: JwtClaims) => TClaims;
79
-
80
- constructor(options: JwtMiddlewareOptions<TClaims>) {
81
- this.verifier = new JwtVerifier(options.config);
82
- this.extraction = options.extraction ?? {};
83
- this.contextKey = options.contextKey ?? 'jwtClaims';
84
- this.onError = options.onError;
85
- this.transformClaims = options.transformClaims;
86
- }
87
-
88
- /**
89
- * Returns middleware that requires valid JWT
90
- */
91
- handler(): MiddlewareHandler {
92
- return async (c: Context, next: Next) => {
93
- const token = extractToken(c, this.extraction);
94
-
95
- if (!token) {
96
- if (this.onError) {
97
- return this.onError(c, new Error('No token provided'));
98
- }
99
- return c.json({ error: 'Unauthorized' }, 401);
100
- }
101
-
102
- try {
103
- const payload = await this.verifier.verify(token);
104
- const claims = this.transformClaims
105
- ? this.transformClaims(payload)
106
- : payload;
107
-
108
- c.set(this.contextKey, claims);
109
- c.set('jwtToken', token);
110
-
111
- await next();
112
- } catch (error) {
113
- if (this.onError) {
114
- return this.onError(c, error as Error);
115
- }
116
- return c.json({ error: 'Invalid token' }, 401);
117
- }
118
- };
119
- }
120
-
121
- /**
122
- * Returns middleware that allows unauthenticated requests
123
- */
124
- optional(): MiddlewareHandler {
125
- return async (c: Context, next: Next) => {
126
- const token = extractToken(c, this.extraction);
127
-
128
- if (token) {
129
- const claims = await this.verifier.verifyOrNull(token);
130
- if (claims) {
131
- const transformed = this.transformClaims
132
- ? this.transformClaims(claims)
133
- : claims;
134
- c.set(this.contextKey, transformed);
135
- c.set('jwtToken', token);
136
- }
137
- }
138
-
139
- await next();
140
- };
141
- }
71
+ private readonly verifier: JwtVerifier<TClaims>;
72
+ private readonly extraction: TokenExtractionOptions;
73
+ private readonly contextKey: string;
74
+ private readonly onError?: (
75
+ c: Context,
76
+ error: Error,
77
+ ) => Response | Promise<Response>;
78
+ private readonly transformClaims?: (claims: JwtClaims) => TClaims;
79
+
80
+ constructor(options: JwtMiddlewareOptions<TClaims>) {
81
+ this.verifier = new JwtVerifier(options.config);
82
+ this.extraction = options.extraction ?? {};
83
+ this.contextKey = options.contextKey ?? 'jwtClaims';
84
+ this.onError = options.onError;
85
+ this.transformClaims = options.transformClaims;
86
+ }
87
+
88
+ /**
89
+ * Returns middleware that requires valid JWT
90
+ */
91
+ handler(): MiddlewareHandler {
92
+ return async (c: Context, next: Next) => {
93
+ const token = extractToken(c, this.extraction);
94
+
95
+ if (!token) {
96
+ if (this.onError) {
97
+ return this.onError(c, new Error('No token provided'));
98
+ }
99
+ return c.json({ error: 'Unauthorized' }, 401);
100
+ }
101
+
102
+ try {
103
+ const payload = await this.verifier.verify(token);
104
+ const claims = this.transformClaims
105
+ ? this.transformClaims(payload)
106
+ : payload;
107
+
108
+ c.set(this.contextKey, claims);
109
+ c.set('jwtToken', token);
110
+
111
+ await next();
112
+ } catch (error) {
113
+ if (this.onError) {
114
+ return this.onError(c, error as Error);
115
+ }
116
+ return c.json({ error: 'Invalid token' }, 401);
117
+ }
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Returns middleware that allows unauthenticated requests
123
+ */
124
+ optional(): MiddlewareHandler {
125
+ return async (c: Context, next: Next) => {
126
+ const token = extractToken(c, this.extraction);
127
+
128
+ if (token) {
129
+ const claims = await this.verifier.verifyOrNull(token);
130
+ if (claims) {
131
+ const transformed = this.transformClaims
132
+ ? this.transformClaims(claims)
133
+ : claims;
134
+ c.set(this.contextKey, transformed);
135
+ c.set('jwtToken', token);
136
+ }
137
+ }
138
+
139
+ await next();
140
+ };
141
+ }
142
142
  }