@geekmidas/auth 0.1.0 → 1.0.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 (117) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/{cacheTokenStorage-Ca05vf3T.mjs → cacheTokenStorage-16NE8Cd9.mjs} +3 -3
  3. package/dist/cacheTokenStorage-16NE8Cd9.mjs.map +1 -0
  4. package/dist/{cacheTokenStorage-BzBRJfd-.d.mts → cacheTokenStorage-B7sOoysu.d.cts} +8 -6
  5. package/dist/cacheTokenStorage-B7sOoysu.d.cts.map +1 -0
  6. package/dist/{cacheTokenStorage-CvptztkW.cjs → cacheTokenStorage-CEpMniTi.cjs} +3 -3
  7. package/dist/cacheTokenStorage-CEpMniTi.cjs.map +1 -0
  8. package/dist/{cacheTokenStorage-yNUpDD8W.d.cts → cacheTokenStorage-_tq4Kmhc.d.mts} +8 -6
  9. package/dist/cacheTokenStorage-_tq4Kmhc.d.mts.map +1 -0
  10. package/dist/cacheTokenStorage.cjs +1 -1
  11. package/dist/cacheTokenStorage.d.cts +1 -1
  12. package/dist/cacheTokenStorage.d.mts +1 -1
  13. package/dist/cacheTokenStorage.mjs +1 -1
  14. package/dist/{client-DaiUm0UZ.cjs → client-BPl_mMvb.cjs} +14 -8
  15. package/dist/client-BPl_mMvb.cjs.map +1 -0
  16. package/dist/{client-DjNZS6vZ.mjs → client-eidYNJSH.mjs} +14 -8
  17. package/dist/client-eidYNJSH.mjs.map +1 -0
  18. package/dist/client.cjs +2 -2
  19. package/dist/client.d.cts +1 -1
  20. package/dist/client.d.mts +1 -1
  21. package/dist/client.mjs +2 -2
  22. package/dist/hono/jwt.cjs +1 -1
  23. package/dist/hono/jwt.cjs.map +1 -1
  24. package/dist/hono/jwt.d.cts +2 -1
  25. package/dist/hono/jwt.d.cts.map +1 -0
  26. package/dist/hono/jwt.d.mts +2 -1
  27. package/dist/hono/jwt.d.mts.map +1 -0
  28. package/dist/hono/jwt.mjs +1 -1
  29. package/dist/hono/jwt.mjs.map +1 -1
  30. package/dist/hono/oidc.cjs +1 -1
  31. package/dist/hono/oidc.cjs.map +1 -1
  32. package/dist/hono/oidc.d.cts +3 -2
  33. package/dist/hono/oidc.d.cts.map +1 -0
  34. package/dist/hono/oidc.d.mts +3 -2
  35. package/dist/hono/oidc.d.mts.map +1 -0
  36. package/dist/hono/oidc.mjs +1 -1
  37. package/dist/hono/oidc.mjs.map +1 -1
  38. package/dist/index.cjs +3 -3
  39. package/dist/index.d.cts +2 -2
  40. package/dist/index.d.mts +2 -2
  41. package/dist/index.mjs +3 -3
  42. package/dist/{jwt-DF9kFbmh.d.cts → jwt-3eIuY2dg.d.cts} +2 -1
  43. package/dist/jwt-3eIuY2dg.d.cts.map +1 -0
  44. package/dist/jwt-Bo_eACEi.cjs.map +1 -1
  45. package/dist/{jwt-DH8CJ2xC.d.mts → jwt-BqLlRkw-.d.mts} +2 -1
  46. package/dist/jwt-BqLlRkw-.d.mts.map +1 -0
  47. package/dist/jwt-D88cPJyT.mjs.map +1 -1
  48. package/dist/jwt.d.cts +1 -1
  49. package/dist/jwt.d.mts +1 -1
  50. package/dist/lambda/jwt.cjs +2 -2
  51. package/dist/lambda/jwt.cjs.map +1 -1
  52. package/dist/lambda/jwt.d.cts +2 -1
  53. package/dist/lambda/jwt.d.cts.map +1 -0
  54. package/dist/lambda/jwt.d.mts +2 -1
  55. package/dist/lambda/jwt.d.mts.map +1 -0
  56. package/dist/lambda/jwt.mjs +2 -2
  57. package/dist/lambda/jwt.mjs.map +1 -1
  58. package/dist/lambda/oidc.cjs +2 -2
  59. package/dist/lambda/oidc.cjs.map +1 -1
  60. package/dist/lambda/oidc.d.cts +3 -2
  61. package/dist/lambda/oidc.d.cts.map +1 -0
  62. package/dist/lambda/oidc.d.mts +3 -2
  63. package/dist/lambda/oidc.d.mts.map +1 -0
  64. package/dist/lambda/oidc.mjs +2 -2
  65. package/dist/lambda/oidc.mjs.map +1 -1
  66. package/dist/oidc-C0KyYaAK.cjs.map +1 -1
  67. package/dist/{oidc-CKOGLxjV.d.mts → oidc-ChA17wLB.d.cts} +3 -2
  68. package/dist/oidc-ChA17wLB.d.cts.map +1 -0
  69. package/dist/{oidc-DDLIB5gb.d.cts → oidc-DTRgBBl6.d.mts} +3 -2
  70. package/dist/oidc-DTRgBBl6.d.mts.map +1 -0
  71. package/dist/oidc-KA30gMlx.mjs.map +1 -1
  72. package/dist/oidc.d.cts +2 -2
  73. package/dist/oidc.d.mts +2 -2
  74. package/dist/server.cjs +2 -2
  75. package/dist/server.d.cts +2 -2
  76. package/dist/server.d.mts +2 -2
  77. package/dist/server.mjs +2 -2
  78. package/dist/{tokenManager--Q93eNYr.d.mts → tokenManager-CL3yE06D.d.cts} +2 -1
  79. package/dist/tokenManager-CL3yE06D.d.cts.map +1 -0
  80. package/dist/{tokenManager-BVXxfHRa.mjs → tokenManager-Ci2Tgxp8.mjs} +5 -3
  81. package/dist/tokenManager-Ci2Tgxp8.mjs.map +1 -0
  82. package/dist/{tokenManager-EPmwgai2.cjs → tokenManager-CvEMgxOp.cjs} +5 -3
  83. package/dist/tokenManager-CvEMgxOp.cjs.map +1 -0
  84. package/dist/{tokenManager-H6-lWEah.d.cts → tokenManager-RrwjL0y-.d.mts} +2 -1
  85. package/dist/tokenManager-RrwjL0y-.d.mts.map +1 -0
  86. package/dist/tokenManager.cjs +1 -1
  87. package/dist/tokenManager.d.cts +1 -1
  88. package/dist/tokenManager.d.mts +1 -1
  89. package/dist/tokenManager.mjs +1 -1
  90. package/package.json +3 -3
  91. package/src/__tests__/cacheTokenStorage.spec.ts +148 -148
  92. package/src/__tests__/client.spec.ts +339 -339
  93. package/src/__tests__/hono-jwt.spec.ts +219 -219
  94. package/src/__tests__/hono-oidc.spec.ts +560 -560
  95. package/src/__tests__/jwt.spec.ts +150 -127
  96. package/src/__tests__/lambda-jwt.spec.ts +205 -205
  97. package/src/__tests__/lambda-oidc.spec.ts +580 -579
  98. package/src/__tests__/oidc.spec.ts +365 -365
  99. package/src/__tests__/tokenManager.spec.ts +254 -254
  100. package/src/cacheTokenStorage.ts +32 -32
  101. package/src/client.ts +199 -190
  102. package/src/hono/jwt.ts +111 -111
  103. package/src/hono/oidc.ts +131 -131
  104. package/src/index.ts +2 -2
  105. package/src/jwt.ts +57 -57
  106. package/src/lambda/jwt.ts +170 -170
  107. package/src/lambda/oidc.ts +165 -165
  108. package/src/oidc.ts +121 -121
  109. package/src/server.ts +6 -7
  110. package/src/tokenManager.ts +89 -87
  111. package/tsconfig.json +10 -0
  112. package/dist/cacheTokenStorage-Ca05vf3T.mjs.map +0 -1
  113. package/dist/cacheTokenStorage-CvptztkW.cjs.map +0 -1
  114. package/dist/client-DaiUm0UZ.cjs.map +0 -1
  115. package/dist/client-DjNZS6vZ.mjs.map +0 -1
  116. package/dist/tokenManager-BVXxfHRa.mjs.map +0 -1
  117. package/dist/tokenManager-EPmwgai2.cjs.map +0 -1
@@ -1,605 +1,605 @@
1
1
  import { Hono } from 'hono';
2
2
  import * as jose from 'jose';
3
- import { http, HttpResponse } from 'msw';
3
+ import { HttpResponse, http } from 'msw';
4
4
  import { setupServer } from 'msw/node';
5
5
  import {
6
- afterAll,
7
- afterEach,
8
- beforeAll,
9
- describe,
10
- expect,
11
- it,
12
- vi,
6
+ afterAll,
7
+ afterEach,
8
+ beforeAll,
9
+ describe,
10
+ expect,
11
+ it,
12
+ vi,
13
13
  } from 'vitest';
14
14
  import type { OidcClaims, OidcUserInfo } from '../hono/oidc';
15
15
  import { OidcMiddleware } from '../hono/oidc';
16
16
 
17
17
  // Define context variable types for Hono
18
18
  type AppVariables = {
19
- oidcClaims: OidcClaims;
20
- oidcToken: string;
21
- oidcUserInfo: OidcUserInfo;
22
- user: OidcClaims;
19
+ oidcClaims: OidcClaims;
20
+ oidcToken: string;
21
+ oidcUserInfo: OidcUserInfo;
22
+ user: OidcClaims;
23
23
  };
24
24
 
25
25
  // Mock discovery document
26
26
  const mockDiscovery = {
27
- issuer: 'https://auth.example.com',
28
- authorization_endpoint: 'https://auth.example.com/authorize',
29
- token_endpoint: 'https://auth.example.com/token',
30
- userinfo_endpoint: 'https://auth.example.com/userinfo',
31
- jwks_uri: 'https://auth.example.com/.well-known/jwks.json',
32
- scopes_supported: ['openid', 'profile', 'email'],
33
- response_types_supported: ['code', 'token'],
34
- claims_supported: ['sub', 'name', 'email'],
27
+ issuer: 'https://auth.example.com',
28
+ authorization_endpoint: 'https://auth.example.com/authorize',
29
+ token_endpoint: 'https://auth.example.com/token',
30
+ userinfo_endpoint: 'https://auth.example.com/userinfo',
31
+ jwks_uri: 'https://auth.example.com/.well-known/jwks.json',
32
+ scopes_supported: ['openid', 'profile', 'email'],
33
+ response_types_supported: ['code', 'token'],
34
+ claims_supported: ['sub', 'name', 'email'],
35
35
  };
36
36
 
37
37
  // Mock user info
38
38
  const mockUserInfo = {
39
- sub: 'user-123',
40
- name: 'Test User',
41
- email: 'test@example.com',
42
- email_verified: true,
39
+ sub: 'user-123',
40
+ name: 'Test User',
41
+ email: 'test@example.com',
42
+ email_verified: true,
43
43
  };
44
44
 
45
45
  // Generate test keys and tokens - stored in object for mock access
46
46
  const testKeys: {
47
- privateKey: jose.KeyLike | null;
48
- publicKey: jose.KeyLike | null;
47
+ privateKey: jose.KeyLike | null;
48
+ publicKey: jose.KeyLike | null;
49
49
  } = {
50
- privateKey: null,
51
- publicKey: null,
50
+ privateKey: null,
51
+ publicKey: null,
52
52
  };
53
53
  let jwks: jose.JSONWebKeySet;
54
54
 
55
55
  async function setupKeys() {
56
- const keyPair = await jose.generateKeyPair('RS256');
57
- testKeys.privateKey = keyPair.privateKey;
58
- testKeys.publicKey = keyPair.publicKey;
59
- const publicJwk = await jose.exportJWK(keyPair.publicKey);
60
- jwks = {
61
- keys: [{ ...publicJwk, kid: 'test-key-id', use: 'sig', alg: 'RS256' }],
62
- };
56
+ const keyPair = await jose.generateKeyPair('RS256');
57
+ testKeys.privateKey = keyPair.privateKey;
58
+ testKeys.publicKey = keyPair.publicKey;
59
+ const publicJwk = await jose.exportJWK(keyPair.publicKey);
60
+ jwks = {
61
+ keys: [{ ...publicJwk, kid: 'test-key-id', use: 'sig', alg: 'RS256' }],
62
+ };
63
63
  }
64
64
 
65
65
  // Mock createRemoteJWKSet to return test keys directly.
66
66
  // MSW intercepts jose's fetch in standalone scripts but fails in vitest for unknown reasons.
67
67
  // TODO: Investigate vitest/MSW/jose interaction and remove this mock if possible.
68
68
  vi.mock('jose', async (importOriginal) => {
69
- const actual = await importOriginal<typeof jose>();
70
- return {
71
- ...actual,
72
- createRemoteJWKSet: () => {
73
- return async (protectedHeader: jose.JWSHeaderParameters) => {
74
- if (protectedHeader.kid === 'test-key-id' && testKeys.publicKey) {
75
- return testKeys.publicKey;
76
- }
77
- throw new Error(`Unknown key ID: ${protectedHeader.kid}`);
78
- };
79
- },
80
- };
69
+ const actual = await importOriginal<typeof jose>();
70
+ return {
71
+ ...actual,
72
+ createRemoteJWKSet: () => {
73
+ return async (protectedHeader: jose.JWSHeaderParameters) => {
74
+ if (protectedHeader.kid === 'test-key-id' && testKeys.publicKey) {
75
+ return testKeys.publicKey;
76
+ }
77
+ throw new Error(`Unknown key ID: ${protectedHeader.kid}`);
78
+ };
79
+ },
80
+ };
81
81
  });
82
82
 
83
83
  async function createTestToken(
84
- claims: Record<string, unknown> = {},
85
- options: { expiresIn?: string } = {},
84
+ claims: Record<string, unknown> = {},
85
+ options: { expiresIn?: string } = {},
86
86
  ) {
87
- if (!testKeys.privateKey) {
88
- throw new Error('Keys not initialized');
89
- }
90
- return await new jose.SignJWT({ sub: 'user-123', ...claims })
91
- .setProtectedHeader({ alg: 'RS256', kid: 'test-key-id' })
92
- .setIssuedAt()
93
- .setIssuer('https://auth.example.com')
94
- .setAudience('my-api')
95
- .setExpirationTime(options.expiresIn ?? '1h')
96
- .sign(testKeys.privateKey);
87
+ if (!testKeys.privateKey) {
88
+ throw new Error('Keys not initialized');
89
+ }
90
+ return await new jose.SignJWT({ sub: 'user-123', ...claims })
91
+ .setProtectedHeader({ alg: 'RS256', kid: 'test-key-id' })
92
+ .setIssuedAt()
93
+ .setIssuer('https://auth.example.com')
94
+ .setAudience('my-api')
95
+ .setExpirationTime(options.expiresIn ?? '1h')
96
+ .sign(testKeys.privateKey);
97
97
  }
98
98
 
99
99
  // MSW server setup
100
100
  const server = setupServer(
101
- http.get('https://auth.example.com/.well-known/openid-configuration', () => {
102
- return HttpResponse.json(mockDiscovery);
103
- }),
104
- http.get('https://auth.example.com/.well-known/jwks.json', () => {
105
- return HttpResponse.json(jwks);
106
- }),
107
- http.get('https://auth.example.com/userinfo', () => {
108
- return HttpResponse.json(mockUserInfo);
109
- }),
101
+ http.get('https://auth.example.com/.well-known/openid-configuration', () => {
102
+ return HttpResponse.json(mockDiscovery);
103
+ }),
104
+ http.get('https://auth.example.com/.well-known/jwks.json', () => {
105
+ return HttpResponse.json(jwks);
106
+ }),
107
+ http.get('https://auth.example.com/userinfo', () => {
108
+ return HttpResponse.json(mockUserInfo);
109
+ }),
110
110
  );
111
111
 
112
112
  describe('OidcMiddleware', () => {
113
- beforeAll(async () => {
114
- await setupKeys();
115
- server.listen({ onUnhandledRequest: 'error' });
116
- });
117
-
118
- afterEach(() => {
119
- server.resetHandlers();
120
- });
121
-
122
- afterAll(() => {
123
- server.close();
124
- });
125
-
126
- describe('handler()', () => {
127
- it('should allow request with valid token', async () => {
128
- const middleware = new OidcMiddleware({
129
- config: {
130
- issuer: 'https://auth.example.com',
131
- audience: 'my-api',
132
- },
133
- });
134
-
135
- const app = new Hono<{ Variables: AppVariables }>();
136
- app.use('/*', middleware.handler());
137
- app.get('/protected', (c) => {
138
- const claims = c.get('oidcClaims');
139
- return c.json({ userId: claims.sub });
140
- });
141
-
142
- const token = await createTestToken();
143
- const res = await app.request('/protected', {
144
- headers: {
145
- authorization: `Bearer ${token}`,
146
- },
147
- });
148
-
149
- expect(res.status).toBe(200);
150
- const body = await res.json();
151
- expect(body.userId).toBe('user-123');
152
- });
153
-
154
- it('should return 401 when no token is provided', async () => {
155
- const middleware = new OidcMiddleware({
156
- config: {
157
- issuer: 'https://auth.example.com',
158
- audience: 'my-api',
159
- },
160
- });
161
-
162
- const app = new Hono<{ Variables: AppVariables }>();
163
- app.use('/*', middleware.handler());
164
- app.get('/protected', (c) => c.json({ success: true }));
165
-
166
- const res = await app.request('/protected');
167
-
168
- expect(res.status).toBe(401);
169
- const body = await res.json();
170
- expect(body.error).toBe('Unauthorized');
171
- });
172
-
173
- it('should return 401 for invalid token', async () => {
174
- const middleware = new OidcMiddleware({
175
- config: {
176
- issuer: 'https://auth.example.com',
177
- audience: 'my-api',
178
- },
179
- });
180
-
181
- const app = new Hono<{ Variables: AppVariables }>();
182
- app.use('/*', middleware.handler());
183
- app.get('/protected', (c) => c.json({ success: true }));
184
-
185
- const res = await app.request('/protected', {
186
- headers: {
187
- authorization: 'Bearer invalid-token',
188
- },
189
- });
190
-
191
- expect(res.status).toBe(401);
192
- const body = await res.json();
193
- expect(body.error).toBe('Invalid token');
194
- });
195
-
196
- it('should set token in context', async () => {
197
- const middleware = new OidcMiddleware({
198
- config: {
199
- issuer: 'https://auth.example.com',
200
- audience: 'my-api',
201
- },
202
- });
203
-
204
- const app = new Hono<{ Variables: AppVariables }>();
205
- app.use('/*', middleware.handler());
206
- app.get('/protected', (c) => {
207
- const token = c.get('oidcToken');
208
- return c.json({ hasToken: !!token });
209
- });
210
-
211
- const token = await createTestToken();
212
- const res = await app.request('/protected', {
213
- headers: {
214
- authorization: `Bearer ${token}`,
215
- },
216
- });
217
-
218
- expect(res.status).toBe(200);
219
- const body = await res.json();
220
- expect(body.hasToken).toBe(true);
221
- });
222
-
223
- it('should use custom context key', async () => {
224
- const middleware = new OidcMiddleware({
225
- config: {
226
- issuer: 'https://auth.example.com',
227
- audience: 'my-api',
228
- },
229
- contextKey: 'user',
230
- });
231
-
232
- const app = new Hono<{ Variables: AppVariables }>();
233
- app.use('/*', middleware.handler());
234
- app.get('/protected', (c) => {
235
- const user = c.get('user');
236
- return c.json({ userId: user.sub });
237
- });
238
-
239
- const token = await createTestToken();
240
- const res = await app.request('/protected', {
241
- headers: {
242
- authorization: `Bearer ${token}`,
243
- },
244
- });
245
-
246
- expect(res.status).toBe(200);
247
- const body = await res.json();
248
- expect(body.userId).toBe('user-123');
249
- });
250
-
251
- it('should extract token from cookie', async () => {
252
- const middleware = new OidcMiddleware({
253
- config: {
254
- issuer: 'https://auth.example.com',
255
- audience: 'my-api',
256
- },
257
- extraction: {
258
- cookieName: 'auth_token',
259
- },
260
- });
261
-
262
- const app = new Hono<{ Variables: AppVariables }>();
263
- app.use('/*', middleware.handler());
264
- app.get('/protected', (c) => {
265
- const claims = c.get('oidcClaims');
266
- return c.json({ userId: claims.sub });
267
- });
268
-
269
- const token = await createTestToken();
270
- const res = await app.request('/protected', {
271
- headers: {
272
- cookie: `auth_token=${token}; other=value`,
273
- },
274
- });
275
-
276
- expect(res.status).toBe(200);
277
- const body = await res.json();
278
- expect(body.userId).toBe('user-123');
279
- });
280
-
281
- it('should use custom header name', async () => {
282
- const middleware = new OidcMiddleware({
283
- config: {
284
- issuer: 'https://auth.example.com',
285
- audience: 'my-api',
286
- },
287
- extraction: {
288
- headerName: 'x-auth-token',
289
- tokenPrefix: '',
290
- },
291
- });
292
-
293
- const app = new Hono<{ Variables: AppVariables }>();
294
- app.use('/*', middleware.handler());
295
- app.get('/protected', (c) => {
296
- const claims = c.get('oidcClaims');
297
- return c.json({ userId: claims.sub });
298
- });
299
-
300
- const token = await createTestToken();
301
- const res = await app.request('/protected', {
302
- headers: {
303
- 'x-auth-token': token,
304
- },
305
- });
306
-
307
- expect(res.status).toBe(200);
308
- const body = await res.json();
309
- expect(body.userId).toBe('user-123');
310
- });
311
-
312
- it('should call custom onError handler', async () => {
313
- const middleware = new OidcMiddleware({
314
- config: {
315
- issuer: 'https://auth.example.com',
316
- audience: 'my-api',
317
- },
318
- onError: (c, error) => {
319
- return c.json({ customError: error.message }, 403);
320
- },
321
- });
322
-
323
- const app = new Hono<{ Variables: AppVariables }>();
324
- app.use('/*', middleware.handler());
325
- app.get('/protected', (c) => c.json({ success: true }));
326
-
327
- const res = await app.request('/protected');
328
-
329
- expect(res.status).toBe(403);
330
- const body = await res.json();
331
- expect(body.customError).toBe('No token provided');
332
- });
333
-
334
- it('should call onError for invalid token', async () => {
335
- const middleware = new OidcMiddleware({
336
- config: {
337
- issuer: 'https://auth.example.com',
338
- audience: 'my-api',
339
- },
340
- onError: (c, error) => {
341
- return c.json({ customError: 'Token verification failed' }, 401);
342
- },
343
- });
344
-
345
- const app = new Hono<{ Variables: AppVariables }>();
346
- app.use('/*', middleware.handler());
347
- app.get('/protected', (c) => c.json({ success: true }));
348
-
349
- const res = await app.request('/protected', {
350
- headers: {
351
- authorization: 'Bearer invalid-token',
352
- },
353
- });
354
-
355
- expect(res.status).toBe(401);
356
- const body = await res.json();
357
- expect(body.customError).toBe('Token verification failed');
358
- });
359
-
360
- it('should fetch user info when configured', async () => {
361
- const middleware = new OidcMiddleware({
362
- config: {
363
- issuer: 'https://auth.example.com',
364
- audience: 'my-api',
365
- },
366
- fetchUserInfo: true,
367
- });
368
-
369
- const app = new Hono<{ Variables: AppVariables }>();
370
- app.use('/*', middleware.handler());
371
- app.get('/protected', (c) => {
372
- const userInfo = c.get('oidcUserInfo');
373
- return c.json({ name: userInfo?.name, email: userInfo?.email });
374
- });
375
-
376
- const token = await createTestToken();
377
- const res = await app.request('/protected', {
378
- headers: {
379
- authorization: `Bearer ${token}`,
380
- },
381
- });
382
-
383
- expect(res.status).toBe(200);
384
- const body = await res.json();
385
- expect(body.name).toBe('Test User');
386
- expect(body.email).toBe('test@example.com');
387
- });
388
-
389
- it('should transform claims when configured', async () => {
390
- interface CustomClaims {
391
- sub?: string;
392
- userId: string;
393
- displayName: string;
394
- }
395
-
396
- const middleware = new OidcMiddleware<CustomClaims>({
397
- config: {
398
- issuer: 'https://auth.example.com',
399
- audience: 'my-api',
400
- },
401
- fetchUserInfo: true,
402
- transformClaims: (claims, userInfo) => ({
403
- ...claims,
404
- userId: claims.sub!,
405
- displayName: userInfo?.name ?? 'Unknown',
406
- }),
407
- });
408
-
409
- const app = new Hono<{ Variables: AppVariables }>();
410
- app.use('/*', middleware.handler());
411
- app.get('/protected', (c) => {
412
- const claims = c.get('oidcClaims') as CustomClaims;
413
- return c.json({
414
- userId: claims.userId,
415
- displayName: claims.displayName,
416
- });
417
- });
418
-
419
- const token = await createTestToken();
420
- const res = await app.request('/protected', {
421
- headers: {
422
- authorization: `Bearer ${token}`,
423
- },
424
- });
425
-
426
- expect(res.status).toBe(200);
427
- const body = await res.json();
428
- expect(body.userId).toBe('user-123');
429
- expect(body.displayName).toBe('Test User');
430
- });
431
- });
432
-
433
- describe('optional()', () => {
434
- it('should allow request without token', async () => {
435
- const middleware = new OidcMiddleware({
436
- config: {
437
- issuer: 'https://auth.example.com',
438
- audience: 'my-api',
439
- },
440
- });
441
-
442
- const app = new Hono<{ Variables: AppVariables }>();
443
- app.use('/*', middleware.optional());
444
- app.get('/public', (c) => {
445
- const claims = c.get('oidcClaims');
446
- return c.json({ authenticated: !!claims });
447
- });
448
-
449
- const res = await app.request('/public');
450
-
451
- expect(res.status).toBe(200);
452
- const body = await res.json();
453
- expect(body.authenticated).toBe(false);
454
- });
455
-
456
- it('should set claims when valid token is provided', async () => {
457
- const middleware = new OidcMiddleware({
458
- config: {
459
- issuer: 'https://auth.example.com',
460
- audience: 'my-api',
461
- },
462
- });
463
-
464
- const app = new Hono<{ Variables: AppVariables }>();
465
- app.use('/*', middleware.optional());
466
- app.get('/public', (c) => {
467
- const claims = c.get('oidcClaims');
468
- return c.json({
469
- authenticated: !!claims,
470
- userId: claims?.sub,
471
- });
472
- });
473
-
474
- const token = await createTestToken();
475
- const res = await app.request('/public', {
476
- headers: {
477
- authorization: `Bearer ${token}`,
478
- },
479
- });
480
-
481
- expect(res.status).toBe(200);
482
- const body = await res.json();
483
- expect(body.authenticated).toBe(true);
484
- expect(body.userId).toBe('user-123');
485
- });
486
-
487
- it('should ignore invalid token and continue', async () => {
488
- const middleware = new OidcMiddleware({
489
- config: {
490
- issuer: 'https://auth.example.com',
491
- audience: 'my-api',
492
- },
493
- });
494
-
495
- const app = new Hono<{ Variables: AppVariables }>();
496
- app.use('/*', middleware.optional());
497
- app.get('/public', (c) => {
498
- const claims = c.get('oidcClaims');
499
- return c.json({ authenticated: !!claims });
500
- });
501
-
502
- const res = await app.request('/public', {
503
- headers: {
504
- authorization: 'Bearer invalid-token',
505
- },
506
- });
507
-
508
- expect(res.status).toBe(200);
509
- const body = await res.json();
510
- expect(body.authenticated).toBe(false);
511
- });
512
-
513
- it('should fetch user info when configured', async () => {
514
- const middleware = new OidcMiddleware({
515
- config: {
516
- issuer: 'https://auth.example.com',
517
- audience: 'my-api',
518
- },
519
- fetchUserInfo: true,
520
- });
521
-
522
- const app = new Hono<{ Variables: AppVariables }>();
523
- app.use('/*', middleware.optional());
524
- app.get('/public', (c) => {
525
- const userInfo = c.get('oidcUserInfo');
526
- return c.json({
527
- hasUserInfo: !!userInfo,
528
- name: userInfo?.name,
529
- });
530
- });
531
-
532
- const token = await createTestToken();
533
- const res = await app.request('/public', {
534
- headers: {
535
- authorization: `Bearer ${token}`,
536
- },
537
- });
538
-
539
- expect(res.status).toBe(200);
540
- const body = await res.json();
541
- expect(body.hasUserInfo).toBe(true);
542
- expect(body.name).toBe('Test User');
543
- });
544
-
545
- it('should transform claims when configured', async () => {
546
- const middleware = new OidcMiddleware({
547
- config: {
548
- issuer: 'https://auth.example.com',
549
- audience: 'my-api',
550
- },
551
- transformClaims: (claims) => ({
552
- ...claims,
553
- customField: 'custom-value',
554
- }),
555
- });
556
-
557
- const app = new Hono<{ Variables: AppVariables }>();
558
- app.use('/*', middleware.optional());
559
- app.get('/public', (c) => {
560
- const claims = c.get('oidcClaims');
561
- return c.json({
562
- hasCustomField: !!(claims as any)?.customField,
563
- });
564
- });
565
-
566
- const token = await createTestToken();
567
- const res = await app.request('/public', {
568
- headers: {
569
- authorization: `Bearer ${token}`,
570
- },
571
- });
572
-
573
- expect(res.status).toBe(200);
574
- const body = await res.json();
575
- expect(body.hasCustomField).toBe(true);
576
- });
577
-
578
- it('should set token in context', async () => {
579
- const middleware = new OidcMiddleware({
580
- config: {
581
- issuer: 'https://auth.example.com',
582
- audience: 'my-api',
583
- },
584
- });
585
-
586
- const app = new Hono<{ Variables: AppVariables }>();
587
- app.use('/*', middleware.optional());
588
- app.get('/public', (c) => {
589
- const token = c.get('oidcToken');
590
- return c.json({ hasToken: !!token });
591
- });
592
-
593
- const token = await createTestToken();
594
- const res = await app.request('/public', {
595
- headers: {
596
- authorization: `Bearer ${token}`,
597
- },
598
- });
599
-
600
- expect(res.status).toBe(200);
601
- const body = await res.json();
602
- expect(body.hasToken).toBe(true);
603
- });
604
- });
113
+ beforeAll(async () => {
114
+ await setupKeys();
115
+ server.listen({ onUnhandledRequest: 'error' });
116
+ });
117
+
118
+ afterEach(() => {
119
+ server.resetHandlers();
120
+ });
121
+
122
+ afterAll(() => {
123
+ server.close();
124
+ });
125
+
126
+ describe('handler()', () => {
127
+ it('should allow request with valid token', async () => {
128
+ const middleware = new OidcMiddleware({
129
+ config: {
130
+ issuer: 'https://auth.example.com',
131
+ audience: 'my-api',
132
+ },
133
+ });
134
+
135
+ const app = new Hono<{ Variables: AppVariables }>();
136
+ app.use('/*', middleware.handler());
137
+ app.get('/protected', (c) => {
138
+ const claims = c.get('oidcClaims');
139
+ return c.json({ userId: claims.sub });
140
+ });
141
+
142
+ const token = await createTestToken();
143
+ const res = await app.request('/protected', {
144
+ headers: {
145
+ authorization: `Bearer ${token}`,
146
+ },
147
+ });
148
+
149
+ expect(res.status).toBe(200);
150
+ const body = await res.json();
151
+ expect(body.userId).toBe('user-123');
152
+ });
153
+
154
+ it('should return 401 when no token is provided', async () => {
155
+ const middleware = new OidcMiddleware({
156
+ config: {
157
+ issuer: 'https://auth.example.com',
158
+ audience: 'my-api',
159
+ },
160
+ });
161
+
162
+ const app = new Hono<{ Variables: AppVariables }>();
163
+ app.use('/*', middleware.handler());
164
+ app.get('/protected', (c) => c.json({ success: true }));
165
+
166
+ const res = await app.request('/protected');
167
+
168
+ expect(res.status).toBe(401);
169
+ const body = await res.json();
170
+ expect(body.error).toBe('Unauthorized');
171
+ });
172
+
173
+ it('should return 401 for invalid token', async () => {
174
+ const middleware = new OidcMiddleware({
175
+ config: {
176
+ issuer: 'https://auth.example.com',
177
+ audience: 'my-api',
178
+ },
179
+ });
180
+
181
+ const app = new Hono<{ Variables: AppVariables }>();
182
+ app.use('/*', middleware.handler());
183
+ app.get('/protected', (c) => c.json({ success: true }));
184
+
185
+ const res = await app.request('/protected', {
186
+ headers: {
187
+ authorization: 'Bearer invalid-token',
188
+ },
189
+ });
190
+
191
+ expect(res.status).toBe(401);
192
+ const body = await res.json();
193
+ expect(body.error).toBe('Invalid token');
194
+ });
195
+
196
+ it('should set token in context', async () => {
197
+ const middleware = new OidcMiddleware({
198
+ config: {
199
+ issuer: 'https://auth.example.com',
200
+ audience: 'my-api',
201
+ },
202
+ });
203
+
204
+ const app = new Hono<{ Variables: AppVariables }>();
205
+ app.use('/*', middleware.handler());
206
+ app.get('/protected', (c) => {
207
+ const token = c.get('oidcToken');
208
+ return c.json({ hasToken: !!token });
209
+ });
210
+
211
+ const token = await createTestToken();
212
+ const res = await app.request('/protected', {
213
+ headers: {
214
+ authorization: `Bearer ${token}`,
215
+ },
216
+ });
217
+
218
+ expect(res.status).toBe(200);
219
+ const body = await res.json();
220
+ expect(body.hasToken).toBe(true);
221
+ });
222
+
223
+ it('should use custom context key', async () => {
224
+ const middleware = new OidcMiddleware({
225
+ config: {
226
+ issuer: 'https://auth.example.com',
227
+ audience: 'my-api',
228
+ },
229
+ contextKey: 'user',
230
+ });
231
+
232
+ const app = new Hono<{ Variables: AppVariables }>();
233
+ app.use('/*', middleware.handler());
234
+ app.get('/protected', (c) => {
235
+ const user = c.get('user');
236
+ return c.json({ userId: user.sub });
237
+ });
238
+
239
+ const token = await createTestToken();
240
+ const res = await app.request('/protected', {
241
+ headers: {
242
+ authorization: `Bearer ${token}`,
243
+ },
244
+ });
245
+
246
+ expect(res.status).toBe(200);
247
+ const body = await res.json();
248
+ expect(body.userId).toBe('user-123');
249
+ });
250
+
251
+ it('should extract token from cookie', async () => {
252
+ const middleware = new OidcMiddleware({
253
+ config: {
254
+ issuer: 'https://auth.example.com',
255
+ audience: 'my-api',
256
+ },
257
+ extraction: {
258
+ cookieName: 'auth_token',
259
+ },
260
+ });
261
+
262
+ const app = new Hono<{ Variables: AppVariables }>();
263
+ app.use('/*', middleware.handler());
264
+ app.get('/protected', (c) => {
265
+ const claims = c.get('oidcClaims');
266
+ return c.json({ userId: claims.sub });
267
+ });
268
+
269
+ const token = await createTestToken();
270
+ const res = await app.request('/protected', {
271
+ headers: {
272
+ cookie: `auth_token=${token}; other=value`,
273
+ },
274
+ });
275
+
276
+ expect(res.status).toBe(200);
277
+ const body = await res.json();
278
+ expect(body.userId).toBe('user-123');
279
+ });
280
+
281
+ it('should use custom header name', async () => {
282
+ const middleware = new OidcMiddleware({
283
+ config: {
284
+ issuer: 'https://auth.example.com',
285
+ audience: 'my-api',
286
+ },
287
+ extraction: {
288
+ headerName: 'x-auth-token',
289
+ tokenPrefix: '',
290
+ },
291
+ });
292
+
293
+ const app = new Hono<{ Variables: AppVariables }>();
294
+ app.use('/*', middleware.handler());
295
+ app.get('/protected', (c) => {
296
+ const claims = c.get('oidcClaims');
297
+ return c.json({ userId: claims.sub });
298
+ });
299
+
300
+ const token = await createTestToken();
301
+ const res = await app.request('/protected', {
302
+ headers: {
303
+ 'x-auth-token': token,
304
+ },
305
+ });
306
+
307
+ expect(res.status).toBe(200);
308
+ const body = await res.json();
309
+ expect(body.userId).toBe('user-123');
310
+ });
311
+
312
+ it('should call custom onError handler', async () => {
313
+ const middleware = new OidcMiddleware({
314
+ config: {
315
+ issuer: 'https://auth.example.com',
316
+ audience: 'my-api',
317
+ },
318
+ onError: (c, error) => {
319
+ return c.json({ customError: error.message }, 403);
320
+ },
321
+ });
322
+
323
+ const app = new Hono<{ Variables: AppVariables }>();
324
+ app.use('/*', middleware.handler());
325
+ app.get('/protected', (c) => c.json({ success: true }));
326
+
327
+ const res = await app.request('/protected');
328
+
329
+ expect(res.status).toBe(403);
330
+ const body = await res.json();
331
+ expect(body.customError).toBe('No token provided');
332
+ });
333
+
334
+ it('should call onError for invalid token', async () => {
335
+ const middleware = new OidcMiddleware({
336
+ config: {
337
+ issuer: 'https://auth.example.com',
338
+ audience: 'my-api',
339
+ },
340
+ onError: (c, _error) => {
341
+ return c.json({ customError: 'Token verification failed' }, 401);
342
+ },
343
+ });
344
+
345
+ const app = new Hono<{ Variables: AppVariables }>();
346
+ app.use('/*', middleware.handler());
347
+ app.get('/protected', (c) => c.json({ success: true }));
348
+
349
+ const res = await app.request('/protected', {
350
+ headers: {
351
+ authorization: 'Bearer invalid-token',
352
+ },
353
+ });
354
+
355
+ expect(res.status).toBe(401);
356
+ const body = await res.json();
357
+ expect(body.customError).toBe('Token verification failed');
358
+ });
359
+
360
+ it('should fetch user info when configured', async () => {
361
+ const middleware = new OidcMiddleware({
362
+ config: {
363
+ issuer: 'https://auth.example.com',
364
+ audience: 'my-api',
365
+ },
366
+ fetchUserInfo: true,
367
+ });
368
+
369
+ const app = new Hono<{ Variables: AppVariables }>();
370
+ app.use('/*', middleware.handler());
371
+ app.get('/protected', (c) => {
372
+ const userInfo = c.get('oidcUserInfo');
373
+ return c.json({ name: userInfo?.name, email: userInfo?.email });
374
+ });
375
+
376
+ const token = await createTestToken();
377
+ const res = await app.request('/protected', {
378
+ headers: {
379
+ authorization: `Bearer ${token}`,
380
+ },
381
+ });
382
+
383
+ expect(res.status).toBe(200);
384
+ const body = await res.json();
385
+ expect(body.name).toBe('Test User');
386
+ expect(body.email).toBe('test@example.com');
387
+ });
388
+
389
+ it('should transform claims when configured', async () => {
390
+ interface CustomClaims {
391
+ sub?: string;
392
+ userId: string;
393
+ displayName: string;
394
+ }
395
+
396
+ const middleware = new OidcMiddleware<CustomClaims>({
397
+ config: {
398
+ issuer: 'https://auth.example.com',
399
+ audience: 'my-api',
400
+ },
401
+ fetchUserInfo: true,
402
+ transformClaims: (claims, userInfo) => ({
403
+ ...claims,
404
+ userId: claims.sub!,
405
+ displayName: userInfo?.name ?? 'Unknown',
406
+ }),
407
+ });
408
+
409
+ const app = new Hono<{ Variables: AppVariables }>();
410
+ app.use('/*', middleware.handler());
411
+ app.get('/protected', (c) => {
412
+ const claims = c.get('oidcClaims') as CustomClaims;
413
+ return c.json({
414
+ userId: claims.userId,
415
+ displayName: claims.displayName,
416
+ });
417
+ });
418
+
419
+ const token = await createTestToken();
420
+ const res = await app.request('/protected', {
421
+ headers: {
422
+ authorization: `Bearer ${token}`,
423
+ },
424
+ });
425
+
426
+ expect(res.status).toBe(200);
427
+ const body = await res.json();
428
+ expect(body.userId).toBe('user-123');
429
+ expect(body.displayName).toBe('Test User');
430
+ });
431
+ });
432
+
433
+ describe('optional()', () => {
434
+ it('should allow request without token', async () => {
435
+ const middleware = new OidcMiddleware({
436
+ config: {
437
+ issuer: 'https://auth.example.com',
438
+ audience: 'my-api',
439
+ },
440
+ });
441
+
442
+ const app = new Hono<{ Variables: AppVariables }>();
443
+ app.use('/*', middleware.optional());
444
+ app.get('/public', (c) => {
445
+ const claims = c.get('oidcClaims');
446
+ return c.json({ authenticated: !!claims });
447
+ });
448
+
449
+ const res = await app.request('/public');
450
+
451
+ expect(res.status).toBe(200);
452
+ const body = await res.json();
453
+ expect(body.authenticated).toBe(false);
454
+ });
455
+
456
+ it('should set claims when valid token is provided', async () => {
457
+ const middleware = new OidcMiddleware({
458
+ config: {
459
+ issuer: 'https://auth.example.com',
460
+ audience: 'my-api',
461
+ },
462
+ });
463
+
464
+ const app = new Hono<{ Variables: AppVariables }>();
465
+ app.use('/*', middleware.optional());
466
+ app.get('/public', (c) => {
467
+ const claims = c.get('oidcClaims');
468
+ return c.json({
469
+ authenticated: !!claims,
470
+ userId: claims?.sub,
471
+ });
472
+ });
473
+
474
+ const token = await createTestToken();
475
+ const res = await app.request('/public', {
476
+ headers: {
477
+ authorization: `Bearer ${token}`,
478
+ },
479
+ });
480
+
481
+ expect(res.status).toBe(200);
482
+ const body = await res.json();
483
+ expect(body.authenticated).toBe(true);
484
+ expect(body.userId).toBe('user-123');
485
+ });
486
+
487
+ it('should ignore invalid token and continue', async () => {
488
+ const middleware = new OidcMiddleware({
489
+ config: {
490
+ issuer: 'https://auth.example.com',
491
+ audience: 'my-api',
492
+ },
493
+ });
494
+
495
+ const app = new Hono<{ Variables: AppVariables }>();
496
+ app.use('/*', middleware.optional());
497
+ app.get('/public', (c) => {
498
+ const claims = c.get('oidcClaims');
499
+ return c.json({ authenticated: !!claims });
500
+ });
501
+
502
+ const res = await app.request('/public', {
503
+ headers: {
504
+ authorization: 'Bearer invalid-token',
505
+ },
506
+ });
507
+
508
+ expect(res.status).toBe(200);
509
+ const body = await res.json();
510
+ expect(body.authenticated).toBe(false);
511
+ });
512
+
513
+ it('should fetch user info when configured', async () => {
514
+ const middleware = new OidcMiddleware({
515
+ config: {
516
+ issuer: 'https://auth.example.com',
517
+ audience: 'my-api',
518
+ },
519
+ fetchUserInfo: true,
520
+ });
521
+
522
+ const app = new Hono<{ Variables: AppVariables }>();
523
+ app.use('/*', middleware.optional());
524
+ app.get('/public', (c) => {
525
+ const userInfo = c.get('oidcUserInfo');
526
+ return c.json({
527
+ hasUserInfo: !!userInfo,
528
+ name: userInfo?.name,
529
+ });
530
+ });
531
+
532
+ const token = await createTestToken();
533
+ const res = await app.request('/public', {
534
+ headers: {
535
+ authorization: `Bearer ${token}`,
536
+ },
537
+ });
538
+
539
+ expect(res.status).toBe(200);
540
+ const body = await res.json();
541
+ expect(body.hasUserInfo).toBe(true);
542
+ expect(body.name).toBe('Test User');
543
+ });
544
+
545
+ it('should transform claims when configured', async () => {
546
+ const middleware = new OidcMiddleware({
547
+ config: {
548
+ issuer: 'https://auth.example.com',
549
+ audience: 'my-api',
550
+ },
551
+ transformClaims: (claims) => ({
552
+ ...claims,
553
+ customField: 'custom-value',
554
+ }),
555
+ });
556
+
557
+ const app = new Hono<{ Variables: AppVariables }>();
558
+ app.use('/*', middleware.optional());
559
+ app.get('/public', (c) => {
560
+ const claims = c.get('oidcClaims');
561
+ return c.json({
562
+ hasCustomField: !!(claims as any)?.customField,
563
+ });
564
+ });
565
+
566
+ const token = await createTestToken();
567
+ const res = await app.request('/public', {
568
+ headers: {
569
+ authorization: `Bearer ${token}`,
570
+ },
571
+ });
572
+
573
+ expect(res.status).toBe(200);
574
+ const body = await res.json();
575
+ expect(body.hasCustomField).toBe(true);
576
+ });
577
+
578
+ it('should set token in context', async () => {
579
+ const middleware = new OidcMiddleware({
580
+ config: {
581
+ issuer: 'https://auth.example.com',
582
+ audience: 'my-api',
583
+ },
584
+ });
585
+
586
+ const app = new Hono<{ Variables: AppVariables }>();
587
+ app.use('/*', middleware.optional());
588
+ app.get('/public', (c) => {
589
+ const token = c.get('oidcToken');
590
+ return c.json({ hasToken: !!token });
591
+ });
592
+
593
+ const token = await createTestToken();
594
+ const res = await app.request('/public', {
595
+ headers: {
596
+ authorization: `Bearer ${token}`,
597
+ },
598
+ });
599
+
600
+ expect(res.status).toBe(200);
601
+ const body = await res.json();
602
+ expect(body.hasToken).toBe(true);
603
+ });
604
+ });
605
605
  });