@geekmidas/auth 9.0.2 → 10.0.0-alpha.1

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 (100) hide show
  1. package/dist/{cacheTokenStorage-_tq4Kmhc.d.mts → cacheTokenStorage-DaqxdNxI.d.mts} +1 -1
  2. package/dist/cacheTokenStorage-DaqxdNxI.d.mts.map +1 -0
  3. package/dist/cacheTokenStorage.d.mts +1 -1
  4. package/dist/client.d.mts +1 -1
  5. package/dist/cookies-Bc6gUjb6.cjs +30 -0
  6. package/dist/cookies-Bc6gUjb6.cjs.map +1 -0
  7. package/dist/cookies-C80f8JtE.mjs +24 -0
  8. package/dist/cookies-C80f8JtE.mjs.map +1 -0
  9. package/dist/cookies.cjs +3 -0
  10. package/dist/cookies.d.cts +14 -0
  11. package/dist/cookies.d.cts.map +1 -0
  12. package/dist/cookies.d.mts +14 -0
  13. package/dist/cookies.d.mts.map +1 -0
  14. package/dist/cookies.mjs +3 -0
  15. package/dist/hono/jwt.cjs +4 -7
  16. package/dist/hono/jwt.cjs.map +1 -1
  17. package/dist/hono/jwt.d.cts.map +1 -1
  18. package/dist/hono/jwt.d.mts +1 -1
  19. package/dist/hono/jwt.d.mts.map +1 -1
  20. package/dist/hono/jwt.mjs +5 -7
  21. package/dist/hono/jwt.mjs.map +1 -1
  22. package/dist/hono/oidc.cjs +4 -7
  23. package/dist/hono/oidc.cjs.map +1 -1
  24. package/dist/hono/oidc.d.cts.map +1 -1
  25. package/dist/hono/oidc.d.mts +2 -2
  26. package/dist/hono/oidc.d.mts.map +1 -1
  27. package/dist/hono/oidc.mjs +5 -7
  28. package/dist/hono/oidc.mjs.map +1 -1
  29. package/dist/index.cjs +1 -1
  30. package/dist/index.d.mts +2 -2
  31. package/dist/index.mjs +1 -1
  32. package/dist/{jwt-D88cPJyT.mjs → jwt-bZR2_t8F.mjs} +1 -1
  33. package/dist/{jwt-D88cPJyT.mjs.map → jwt-bZR2_t8F.mjs.map} +1 -1
  34. package/dist/{jwt-Bo_eACEi.cjs → jwt-clq6I6vG.cjs} +1 -1
  35. package/dist/{jwt-Bo_eACEi.cjs.map → jwt-clq6I6vG.cjs.map} +1 -1
  36. package/dist/{jwt-BqLlRkw-.d.mts → jwt-kejix7rd.d.mts} +1 -1
  37. package/dist/{jwt-BqLlRkw-.d.mts.map → jwt-kejix7rd.d.mts.map} +1 -1
  38. package/dist/jwt.cjs +1 -1
  39. package/dist/jwt.d.mts +1 -1
  40. package/dist/jwt.mjs +1 -1
  41. package/dist/lambda/jwt.cjs +4 -5
  42. package/dist/lambda/jwt.cjs.map +1 -1
  43. package/dist/lambda/jwt.d.cts.map +1 -1
  44. package/dist/lambda/jwt.d.mts +1 -1
  45. package/dist/lambda/jwt.d.mts.map +1 -1
  46. package/dist/lambda/jwt.mjs +5 -5
  47. package/dist/lambda/jwt.mjs.map +1 -1
  48. package/dist/lambda/oidc.cjs +4 -5
  49. package/dist/lambda/oidc.cjs.map +1 -1
  50. package/dist/lambda/oidc.d.cts.map +1 -1
  51. package/dist/lambda/oidc.d.mts +2 -2
  52. package/dist/lambda/oidc.d.mts.map +1 -1
  53. package/dist/lambda/oidc.mjs +5 -5
  54. package/dist/lambda/oidc.mjs.map +1 -1
  55. package/dist/{oidc-KA30gMlx.mjs → oidc-BYHREHir.mjs} +1 -1
  56. package/dist/{oidc-KA30gMlx.mjs.map → oidc-BYHREHir.mjs.map} +1 -1
  57. package/dist/{oidc-DTRgBBl6.d.mts → oidc-Ca7GYwmM.d.mts} +2 -2
  58. package/dist/{oidc-DTRgBBl6.d.mts.map → oidc-Ca7GYwmM.d.mts.map} +1 -1
  59. package/dist/{oidc-C0KyYaAK.cjs → oidc-jdMfVyyC.cjs} +1 -1
  60. package/dist/{oidc-C0KyYaAK.cjs.map → oidc-jdMfVyyC.cjs.map} +1 -1
  61. package/dist/oidc.cjs +1 -1
  62. package/dist/oidc.d.mts +2 -2
  63. package/dist/oidc.mjs +1 -1
  64. package/dist/server.cjs +1 -1
  65. package/dist/server.d.mts +2 -2
  66. package/dist/server.mjs +1 -1
  67. package/dist/{tokenManager-Ci2Tgxp8.mjs → tokenManager-BbylTW7F.mjs} +1 -1
  68. package/dist/{tokenManager-Ci2Tgxp8.mjs.map → tokenManager-BbylTW7F.mjs.map} +1 -1
  69. package/dist/{tokenManager-RrwjL0y-.d.mts → tokenManager-CosB7J0i.d.mts} +1 -1
  70. package/dist/{tokenManager-RrwjL0y-.d.mts.map → tokenManager-CosB7J0i.d.mts.map} +1 -1
  71. package/dist/{tokenManager-CvEMgxOp.cjs → tokenManager-PQ-OI_NU.cjs} +1 -1
  72. package/dist/{tokenManager-CvEMgxOp.cjs.map → tokenManager-PQ-OI_NU.cjs.map} +1 -1
  73. package/dist/tokenManager.cjs +1 -1
  74. package/dist/tokenManager.d.mts +1 -1
  75. package/dist/tokenManager.mjs +1 -1
  76. package/package.json +6 -3
  77. package/CHANGELOG.md +0 -60
  78. package/dist/cacheTokenStorage-_tq4Kmhc.d.mts.map +0 -1
  79. package/src/__tests__/cacheTokenStorage.spec.ts +0 -213
  80. package/src/__tests__/client.spec.ts +0 -465
  81. package/src/__tests__/hono-jwt.spec.ts +0 -232
  82. package/src/__tests__/hono-oidc.spec.ts +0 -605
  83. package/src/__tests__/jwt.spec.ts +0 -197
  84. package/src/__tests__/lambda-jwt.spec.ts +0 -278
  85. package/src/__tests__/lambda-oidc.spec.ts +0 -624
  86. package/src/__tests__/oidc.spec.ts +0 -405
  87. package/src/__tests__/tokenManager.spec.ts +0 -259
  88. package/src/cacheTokenStorage.ts +0 -43
  89. package/src/client.ts +0 -220
  90. package/src/hono/jwt.ts +0 -142
  91. package/src/hono/oidc.ts +0 -170
  92. package/src/index.ts +0 -3
  93. package/src/jwt.ts +0 -106
  94. package/src/lambda/jwt.ts +0 -210
  95. package/src/lambda/oidc.ts +0 -203
  96. package/src/oidc.ts +0 -156
  97. package/src/server.ts +0 -8
  98. package/src/tokenManager.ts +0 -106
  99. package/tsconfig.json +0 -10
  100. package/tsdown.config.ts +0 -3
package/src/lambda/jwt.ts DELETED
@@ -1,210 +0,0 @@
1
- import type {
2
- APIGatewayAuthorizerResult,
3
- APIGatewayRequestAuthorizerEvent,
4
- APIGatewayTokenAuthorizerEvent,
5
- Context as LambdaContext,
6
- PolicyDocument,
7
- } from 'aws-lambda';
8
- import {
9
- type JwtClaims,
10
- type JwtConfig,
11
- JwtVerifier,
12
- type TokenExtractionOptions,
13
- } from '../jwt';
14
-
15
- export {
16
- JwtVerifier,
17
- type JwtClaims,
18
- type JwtConfig,
19
- type TokenExtractionOptions,
20
- };
21
-
22
- function generatePolicy(
23
- principalId: string,
24
- effect: 'Allow' | 'Deny',
25
- resource: string,
26
- context?: Record<string, string | number | boolean>,
27
- ): APIGatewayAuthorizerResult {
28
- const policyDocument: PolicyDocument = {
29
- Version: '2012-10-17',
30
- Statement: [
31
- {
32
- Action: 'execute-api:Invoke',
33
- Effect: effect,
34
- Resource: resource,
35
- },
36
- ],
37
- };
38
-
39
- return {
40
- principalId,
41
- policyDocument,
42
- context,
43
- };
44
- }
45
-
46
- function getWildcardResource(methodArn: string): string {
47
- const parts = methodArn.split('/');
48
- return `${parts[0]}/${parts[1]}/*`;
49
- }
50
-
51
- export interface JwtAuthorizerOptions<TClaims extends JwtClaims = JwtClaims> {
52
- config: JwtConfig;
53
- extraction?: TokenExtractionOptions;
54
- wildcardResource?: boolean;
55
- getPrincipalId?: (claims: TClaims) => string;
56
- getContext?: (
57
- claims: TClaims,
58
- ) => Record<string, string | number | boolean> | undefined;
59
- authorize?: (claims: TClaims) => boolean | Promise<boolean>;
60
- }
61
-
62
- /**
63
- * JWT Lambda Authorizer
64
- *
65
- * @example
66
- * ```typescript
67
- * const authorizer = new JwtAuthorizer({
68
- * config: {
69
- * jwksUri: 'https://auth.example.com/.well-known/jwks.json',
70
- * issuer: 'https://auth.example.com',
71
- * },
72
- * getContext: (claims) => ({ userId: claims.sub! }),
73
- * });
74
- *
75
- * // TOKEN authorizer
76
- * export const tokenHandler = authorizer.tokenHandler();
77
- *
78
- * // REQUEST authorizer
79
- * export const requestHandler = authorizer.requestHandler();
80
- * ```
81
- */
82
- export class JwtAuthorizer<TClaims extends JwtClaims = JwtClaims> {
83
- private readonly verifier: JwtVerifier<TClaims>;
84
- private readonly extraction: TokenExtractionOptions;
85
- private readonly wildcardResource: boolean;
86
- private readonly getPrincipalId: (claims: TClaims) => string;
87
- private readonly getContext?: (
88
- claims: TClaims,
89
- ) => Record<string, string | number | boolean> | undefined;
90
- private readonly authorize?: (claims: TClaims) => boolean | Promise<boolean>;
91
-
92
- constructor(options: JwtAuthorizerOptions<TClaims>) {
93
- this.verifier = new JwtVerifier(options.config);
94
- this.extraction = options.extraction ?? {};
95
- this.wildcardResource = options.wildcardResource ?? true;
96
- this.getPrincipalId = options.getPrincipalId ?? ((c) => c.sub ?? 'unknown');
97
- this.getContext = options.getContext;
98
- this.authorize = options.authorize;
99
- }
100
-
101
- /**
102
- * Returns a TOKEN authorizer handler
103
- */
104
- tokenHandler() {
105
- return async (
106
- event: APIGatewayTokenAuthorizerEvent,
107
- _context: LambdaContext,
108
- ): Promise<APIGatewayAuthorizerResult> => {
109
- const { authorizationToken, methodArn } = event;
110
- const resource = this.wildcardResource
111
- ? getWildcardResource(methodArn)
112
- : methodArn;
113
-
114
- const token = authorizationToken.startsWith('Bearer ')
115
- ? authorizationToken.slice(7)
116
- : authorizationToken;
117
-
118
- try {
119
- const claims = await this.verifier.verify(token);
120
-
121
- if (this.authorize) {
122
- const isAuthorized = await this.authorize(claims);
123
- if (!isAuthorized) {
124
- return generatePolicy('unauthorized', 'Deny', resource);
125
- }
126
- }
127
-
128
- const principalId = this.getPrincipalId(claims);
129
- const context = this.getContext?.(claims);
130
-
131
- return generatePolicy(principalId, 'Allow', resource, context);
132
- } catch {
133
- return generatePolicy('unauthorized', 'Deny', resource);
134
- }
135
- };
136
- }
137
-
138
- /**
139
- * Returns a REQUEST authorizer handler
140
- */
141
- requestHandler() {
142
- const {
143
- headerName = 'authorization',
144
- cookieName,
145
- tokenPrefix = 'Bearer ',
146
- } = this.extraction;
147
-
148
- const extractToken = (
149
- event: APIGatewayRequestAuthorizerEvent,
150
- ): string | null => {
151
- const headers = event.headers ?? {};
152
- const headerKey = Object.keys(headers).find(
153
- (k) => k.toLowerCase() === headerName.toLowerCase(),
154
- );
155
- if (headerKey) {
156
- const headerValue = headers[headerKey];
157
- if (headerValue) {
158
- if (tokenPrefix && headerValue.startsWith(tokenPrefix)) {
159
- return headerValue.slice(tokenPrefix.length);
160
- }
161
- return headerValue;
162
- }
163
- }
164
-
165
- if (cookieName) {
166
- const cookieHeader = headers.cookie ?? headers.Cookie ?? '';
167
- const match = cookieHeader.match(new RegExp(`${cookieName}=([^;]+)`));
168
- if (match?.[1]) {
169
- return match[1];
170
- }
171
- }
172
-
173
- return null;
174
- };
175
-
176
- return async (
177
- event: APIGatewayRequestAuthorizerEvent,
178
- _context: LambdaContext,
179
- ): Promise<APIGatewayAuthorizerResult> => {
180
- const methodArn = event.methodArn;
181
- const resource = this.wildcardResource
182
- ? getWildcardResource(methodArn)
183
- : methodArn;
184
-
185
- const token = extractToken(event);
186
-
187
- if (!token) {
188
- return generatePolicy('unauthorized', 'Deny', resource);
189
- }
190
-
191
- try {
192
- const claims = await this.verifier.verify(token);
193
-
194
- if (this.authorize) {
195
- const isAuthorized = await this.authorize(claims);
196
- if (!isAuthorized) {
197
- return generatePolicy('unauthorized', 'Deny', resource);
198
- }
199
- }
200
-
201
- const principalId = this.getPrincipalId(claims);
202
- const context = this.getContext?.(claims);
203
-
204
- return generatePolicy(principalId, 'Allow', resource, context);
205
- } catch {
206
- return generatePolicy('unauthorized', 'Deny', resource);
207
- }
208
- };
209
- }
210
- }
@@ -1,203 +0,0 @@
1
- import type {
2
- APIGatewayAuthorizerResult,
3
- APIGatewayRequestAuthorizerEvent,
4
- APIGatewayTokenAuthorizerEvent,
5
- Context as LambdaContext,
6
- PolicyDocument,
7
- } from 'aws-lambda';
8
- import {
9
- type OidcClaims,
10
- type OidcConfig,
11
- OidcVerifier,
12
- type TokenExtractionOptions,
13
- } from '../oidc';
14
-
15
- export {
16
- OidcVerifier,
17
- type OidcClaims,
18
- type OidcConfig,
19
- type TokenExtractionOptions,
20
- };
21
-
22
- function generatePolicy(
23
- principalId: string,
24
- effect: 'Allow' | 'Deny',
25
- resource: string,
26
- context?: Record<string, string | number | boolean>,
27
- ): APIGatewayAuthorizerResult {
28
- const policyDocument: PolicyDocument = {
29
- Version: '2012-10-17',
30
- Statement: [
31
- {
32
- Action: 'execute-api:Invoke',
33
- Effect: effect,
34
- Resource: resource,
35
- },
36
- ],
37
- };
38
-
39
- return {
40
- principalId,
41
- policyDocument,
42
- context,
43
- };
44
- }
45
-
46
- function getWildcardResource(methodArn: string): string {
47
- const parts = methodArn.split('/');
48
- return `${parts[0]}/${parts[1]}/*`;
49
- }
50
-
51
- export interface OidcAuthorizerOptions<
52
- TClaims extends OidcClaims = OidcClaims,
53
- > {
54
- config: OidcConfig;
55
- extraction?: TokenExtractionOptions;
56
- wildcardResource?: boolean;
57
- getPrincipalId?: (claims: TClaims) => string;
58
- getContext?: (
59
- claims: TClaims,
60
- ) => Record<string, string | number | boolean> | undefined;
61
- authorize?: (claims: TClaims) => boolean | Promise<boolean>;
62
- }
63
-
64
- /**
65
- * OIDC Lambda Authorizer
66
- *
67
- * @example
68
- * ```typescript
69
- * const authorizer = new OidcAuthorizer({
70
- * config: {
71
- * issuer: 'https://auth.example.com',
72
- * audience: 'my-api',
73
- * },
74
- * getContext: (claims) => ({ userId: claims.sub! }),
75
- * });
76
- *
77
- * export const tokenHandler = authorizer.tokenHandler();
78
- * export const requestHandler = authorizer.requestHandler();
79
- * ```
80
- */
81
- export class OidcAuthorizer<TClaims extends OidcClaims = OidcClaims> {
82
- private readonly verifier: OidcVerifier<TClaims>;
83
- private readonly extraction: TokenExtractionOptions;
84
- private readonly wildcardResource: boolean;
85
- private readonly getPrincipalId: (claims: TClaims) => string;
86
- private readonly getContext?: (
87
- claims: TClaims,
88
- ) => Record<string, string | number | boolean> | undefined;
89
- private readonly authorize?: (claims: TClaims) => boolean | Promise<boolean>;
90
-
91
- constructor(options: OidcAuthorizerOptions<TClaims>) {
92
- this.verifier = new OidcVerifier(options.config);
93
- this.extraction = options.extraction ?? {};
94
- this.wildcardResource = options.wildcardResource ?? true;
95
- this.getPrincipalId = options.getPrincipalId ?? ((c) => c.sub ?? 'unknown');
96
- this.getContext = options.getContext;
97
- this.authorize = options.authorize;
98
- }
99
-
100
- tokenHandler() {
101
- return async (
102
- event: APIGatewayTokenAuthorizerEvent,
103
- _context: LambdaContext,
104
- ): Promise<APIGatewayAuthorizerResult> => {
105
- const { authorizationToken, methodArn } = event;
106
- const resource = this.wildcardResource
107
- ? getWildcardResource(methodArn)
108
- : methodArn;
109
-
110
- const token = authorizationToken.startsWith('Bearer ')
111
- ? authorizationToken.slice(7)
112
- : authorizationToken;
113
-
114
- try {
115
- const claims = await this.verifier.verify(token);
116
-
117
- if (this.authorize) {
118
- const isAuthorized = await this.authorize(claims);
119
- if (!isAuthorized) {
120
- return generatePolicy('unauthorized', 'Deny', resource);
121
- }
122
- }
123
-
124
- const principalId = this.getPrincipalId(claims);
125
- const context = this.getContext?.(claims);
126
-
127
- return generatePolicy(principalId, 'Allow', resource, context);
128
- } catch {
129
- return generatePolicy('unauthorized', 'Deny', resource);
130
- }
131
- };
132
- }
133
-
134
- requestHandler() {
135
- const {
136
- headerName = 'authorization',
137
- cookieName,
138
- tokenPrefix = 'Bearer ',
139
- } = this.extraction;
140
-
141
- const extractToken = (
142
- event: APIGatewayRequestAuthorizerEvent,
143
- ): string | null => {
144
- const headers = event.headers ?? {};
145
- const headerKey = Object.keys(headers).find(
146
- (k) => k.toLowerCase() === headerName.toLowerCase(),
147
- );
148
- if (headerKey) {
149
- const headerValue = headers[headerKey];
150
- if (headerValue) {
151
- if (tokenPrefix && headerValue.startsWith(tokenPrefix)) {
152
- return headerValue.slice(tokenPrefix.length);
153
- }
154
- return headerValue;
155
- }
156
- }
157
-
158
- if (cookieName) {
159
- const cookieHeader = headers.cookie ?? headers.Cookie ?? '';
160
- const match = cookieHeader.match(new RegExp(`${cookieName}=([^;]+)`));
161
- if (match?.[1]) {
162
- return match[1];
163
- }
164
- }
165
-
166
- return null;
167
- };
168
-
169
- return async (
170
- event: APIGatewayRequestAuthorizerEvent,
171
- _context: LambdaContext,
172
- ): Promise<APIGatewayAuthorizerResult> => {
173
- const methodArn = event.methodArn;
174
- const resource = this.wildcardResource
175
- ? getWildcardResource(methodArn)
176
- : methodArn;
177
-
178
- const token = extractToken(event);
179
-
180
- if (!token) {
181
- return generatePolicy('unauthorized', 'Deny', resource);
182
- }
183
-
184
- try {
185
- const claims = await this.verifier.verify(token);
186
-
187
- if (this.authorize) {
188
- const isAuthorized = await this.authorize(claims);
189
- if (!isAuthorized) {
190
- return generatePolicy('unauthorized', 'Deny', resource);
191
- }
192
- }
193
-
194
- const principalId = this.getPrincipalId(claims);
195
- const context = this.getContext?.(claims);
196
-
197
- return generatePolicy(principalId, 'Allow', resource, context);
198
- } catch {
199
- return generatePolicy('unauthorized', 'Deny', resource);
200
- }
201
- };
202
- }
203
- }
package/src/oidc.ts DELETED
@@ -1,156 +0,0 @@
1
- import * as jose from 'jose';
2
- import type { JwtClaims, TokenExtractionOptions } from './jwt';
3
-
4
- export type { TokenExtractionOptions };
5
-
6
- /**
7
- * Standard OIDC claims (extends JWT claims)
8
- */
9
- export interface OidcClaims extends JwtClaims {
10
- nonce?: string;
11
- auth_time?: number;
12
- at_hash?: string;
13
- c_hash?: string;
14
- azp?: string;
15
- }
16
-
17
- /**
18
- * Standard OIDC user info claims
19
- */
20
- export interface OidcUserInfo {
21
- sub: string;
22
- name?: string;
23
- given_name?: string;
24
- family_name?: string;
25
- middle_name?: string;
26
- nickname?: string;
27
- preferred_username?: string;
28
- profile?: string;
29
- picture?: string;
30
- website?: string;
31
- email?: string;
32
- email_verified?: boolean;
33
- gender?: string;
34
- birthdate?: string;
35
- zoneinfo?: string;
36
- locale?: string;
37
- phone_number?: string;
38
- phone_number_verified?: boolean;
39
- address?: {
40
- formatted?: string;
41
- street_address?: string;
42
- locality?: string;
43
- region?: string;
44
- postal_code?: string;
45
- country?: string;
46
- };
47
- updated_at?: number;
48
- }
49
-
50
- /**
51
- * OIDC Discovery document
52
- */
53
- export interface OidcDiscovery {
54
- issuer: string;
55
- authorization_endpoint: string;
56
- token_endpoint: string;
57
- userinfo_endpoint?: string;
58
- jwks_uri: string;
59
- scopes_supported?: string[];
60
- response_types_supported: string[];
61
- claims_supported?: string[];
62
- }
63
-
64
- /**
65
- * Configuration for OIDC verification
66
- */
67
- export interface OidcConfig {
68
- issuer: string;
69
- audience: string | string[];
70
- cacheDiscovery?: boolean;
71
- }
72
-
73
- /**
74
- * OIDC Verifier with auto-discovery and caching
75
- */
76
- export class OidcVerifier<
77
- TClaims extends OidcClaims = OidcClaims,
78
- TUserInfo extends OidcUserInfo = OidcUserInfo,
79
- > {
80
- private discovery: OidcDiscovery | null = null;
81
- private jwks: jose.JWTVerifyGetKey | null = null;
82
- private readonly discoveryUrl: string;
83
-
84
- constructor(private readonly config: OidcConfig) {
85
- this.discoveryUrl = config.issuer.endsWith('/')
86
- ? `${config.issuer}.well-known/openid-configuration`
87
- : `${config.issuer}/.well-known/openid-configuration`;
88
- }
89
-
90
- async getDiscovery(): Promise<OidcDiscovery> {
91
- if (this.discovery && this.config.cacheDiscovery !== false) {
92
- return this.discovery;
93
- }
94
-
95
- const response = await fetch(this.discoveryUrl);
96
- if (!response.ok) {
97
- throw new Error(`Failed to fetch OIDC discovery: ${response.statusText}`);
98
- }
99
-
100
- this.discovery = (await response.json()) as OidcDiscovery;
101
- return this.discovery;
102
- }
103
-
104
- private async getJwks(): Promise<jose.JWTVerifyGetKey> {
105
- if (this.jwks && this.config.cacheDiscovery !== false) {
106
- return this.jwks;
107
- }
108
-
109
- const disc = await this.getDiscovery();
110
- this.jwks = jose.createRemoteJWKSet(new URL(disc.jwks_uri));
111
- return this.jwks;
112
- }
113
-
114
- async verify(token: string): Promise<TClaims> {
115
- const key = await this.getJwks();
116
- const { payload } = await jose.jwtVerify(token, key, {
117
- issuer: this.config.issuer,
118
- audience: this.config.audience,
119
- });
120
- return payload as unknown as TClaims;
121
- }
122
-
123
- async verifyOrNull(token: string): Promise<TClaims | null> {
124
- try {
125
- return await this.verify(token);
126
- } catch {
127
- return null;
128
- }
129
- }
130
-
131
- async fetchUserInfo(token: string): Promise<TUserInfo | null> {
132
- try {
133
- const disc = await this.getDiscovery();
134
- if (!disc.userinfo_endpoint) {
135
- return null;
136
- }
137
-
138
- const response = await fetch(disc.userinfo_endpoint, {
139
- headers: { Authorization: `Bearer ${token}` },
140
- });
141
-
142
- if (!response.ok) {
143
- return null;
144
- }
145
-
146
- return (await response.json()) as TUserInfo;
147
- } catch {
148
- return null;
149
- }
150
- }
151
-
152
- clearCache(): void {
153
- this.discovery = null;
154
- this.jwks = null;
155
- }
156
- }
package/src/server.ts DELETED
@@ -1,8 +0,0 @@
1
- export { CacheTokenStorage } from './cacheTokenStorage.js';
2
- export {
3
- type DecodedToken,
4
- TokenManager,
5
- type TokenManagerOptions,
6
- type TokenPair,
7
- type TokenPayload,
8
- } from './tokenManager.js';
@@ -1,106 +0,0 @@
1
- import jwt from 'jsonwebtoken';
2
- import type ms from 'ms';
3
-
4
- export interface TokenPayload {
5
- userId: string;
6
- email?: string;
7
- [key: string]: any;
8
- }
9
-
10
- export interface TokenPair {
11
- accessToken: string;
12
- refreshToken: string;
13
- }
14
-
15
- export interface TokenManagerOptions {
16
- accessTokenSecret: string;
17
- refreshTokenSecret: string;
18
- accessTokenExpiresIn?: ms.StringValue;
19
- refreshTokenExpiresIn?: ms.StringValue;
20
- }
21
-
22
- export interface DecodedToken extends TokenPayload {
23
- iat: number;
24
- exp: number;
25
- }
26
-
27
- export class TokenManager {
28
- private accessTokenSecret: string;
29
- private refreshTokenSecret: string;
30
- private accessTokenExpiresIn: ms.StringValue;
31
- private refreshTokenExpiresIn: ms.StringValue;
32
-
33
- constructor(options: TokenManagerOptions) {
34
- this.accessTokenSecret = options.accessTokenSecret;
35
- this.refreshTokenSecret = options.refreshTokenSecret;
36
- this.accessTokenExpiresIn = options.accessTokenExpiresIn || '15m';
37
- this.refreshTokenExpiresIn = options.refreshTokenExpiresIn || '7d';
38
- }
39
-
40
- generateTokenPair(payload: TokenPayload): TokenPair {
41
- const accessToken = jwt.sign(payload, this.accessTokenSecret, {
42
- expiresIn: this.accessTokenExpiresIn,
43
- });
44
-
45
- const refreshToken = jwt.sign(payload, this.refreshTokenSecret, {
46
- expiresIn: this.refreshTokenExpiresIn,
47
- });
48
-
49
- return {
50
- accessToken,
51
- refreshToken,
52
- };
53
- }
54
-
55
- verifyAccessToken(token: string): DecodedToken {
56
- try {
57
- return jwt.verify(token, this.accessTokenSecret) as DecodedToken;
58
- } catch (error) {
59
- const message = error instanceof Error ? error.message : String(error);
60
- throw new Error(`Invalid access token: ${message}`);
61
- }
62
- }
63
-
64
- verifyRefreshToken(token: string): DecodedToken {
65
- try {
66
- return jwt.verify(token, this.refreshTokenSecret) as DecodedToken;
67
- } catch (error) {
68
- const message = error instanceof Error ? error.message : String(error);
69
- throw new Error(`Invalid refresh token: ${message}`);
70
- }
71
- }
72
-
73
- refreshAccessToken(refreshToken: string): string {
74
- const decoded = this.verifyRefreshToken(refreshToken);
75
-
76
- // Remove JWT specific fields before creating new token
77
- const { iat, exp, ...payload } = decoded;
78
-
79
- return jwt.sign(payload, this.accessTokenSecret, {
80
- expiresIn: this.accessTokenExpiresIn,
81
- });
82
- }
83
-
84
- decodeToken(token: string): DecodedToken | null {
85
- try {
86
- return jwt.decode(token) as DecodedToken;
87
- } catch {
88
- return null;
89
- }
90
- }
91
-
92
- isTokenExpired(token: string): boolean {
93
- const decoded = this.decodeToken(token);
94
- if (!decoded) return true;
95
-
96
- const now = Math.floor(Date.now() / 1000);
97
- return decoded.exp < now;
98
- }
99
-
100
- getTokenExpiration(token: string): Date | null {
101
- const decoded = this.decodeToken(token);
102
- if (!decoded) return null;
103
-
104
- return new Date(decoded.exp * 1000);
105
- }
106
- }
package/tsconfig.json DELETED
@@ -1,10 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.base.json",
3
- "compilerOptions": {
4
- "outDir": "./dist",
5
- "rootDir": "./src",
6
- "composite": true,
7
- "lib": ["ES2023", "DOM"]
8
- },
9
- "include": ["src/**/*"]
10
- }
package/tsdown.config.ts DELETED
@@ -1,3 +0,0 @@
1
- import { defineConfig } from 'tsdown';
2
-
3
- export default defineConfig({});