@@ -52,8 +52,19 @@ export interface JWTOption<
52
52
name ?: Name
53
53
/**
54
54
* JWT Secret
55
+ * Only `secret` or both `privateKey`, `publicKey` must be set
55
56
*/
56
- secret : string | Uint8Array | KeyLike
57
+ secret ?: string | Uint8Array | KeyLike
58
+ /**
59
+ * JWT Private Key
60
+ * Only `secret` or both `privateKey`, `publicKey` must be set
61
+ */
62
+ privateKey ?: Uint8Array | KeyLike
63
+ /**
64
+ * JWT Public Key
65
+ * Only `secret` or both `privateKey`, `publicKey` must be set
66
+ */
67
+ publicKey ?: Uint8Array | KeyLike
57
68
/**
58
69
* Type strict validation for JWT payload
59
70
*/
@@ -80,6 +91,8 @@ export const jwt = <
80
91
> ( {
81
92
name = 'jwt' as Name ,
82
93
secret,
94
+ publicKey,
95
+ privateKey,
83
96
// Start JWT Header
84
97
alg = 'HS256' ,
85
98
crit,
@@ -91,11 +104,29 @@ export const jwt = <
91
104
...payload
92
105
} : // End JWT Payload
93
106
JWTOption < Name , Schema > ) => {
94
- if ( ! secret ) throw new Error ( "Secret can't be empty" )
95
-
96
107
const key =
97
108
typeof secret === 'string' ? new TextEncoder ( ) . encode ( secret ) : secret
98
109
110
+ let asymmetric = false
111
+
112
+ if ( secret && ( privateKey || publicKey ) ) {
113
+ throw new Error ( "When using asymmetric algorithm, only `privateKey` and `publicKey` is accepted" )
114
+ }
115
+
116
+ if ( privateKey && ! publicKey ) {
117
+ throw new Error ( "When using asymmetric algorithm, both `privateKey` and `publicKey` must be set. Public key is missing" )
118
+ }
119
+
120
+ if ( publicKey && ! privateKey ) {
121
+ throw new Error ( "When using asymmetric algorithm, both `privateKey` and `publicKey` must be set. Private key is missing" )
122
+ }
123
+
124
+ if ( privateKey && privateKey ) {
125
+ asymmetric = true
126
+ } else if ( ! secret ) {
127
+ throw new Error ( "Secret can't be empty" )
128
+ }
129
+
99
130
const validator = schema
100
131
? getSchemaValidator (
101
132
t . Intersect ( [
@@ -146,7 +177,7 @@ JWTOption<Name, Schema>) => {
146
177
if ( nbf ) jwt = jwt . setNotBefore ( nbf )
147
178
if ( exp ) jwt = jwt . setExpirationTime ( exp )
148
179
149
- return jwt . sign ( key )
180
+ return jwt . sign ( asymmetric ? privateKey ! : key ! )
150
181
} ,
151
182
verify : async (
152
183
jwt ?: string
@@ -158,7 +189,7 @@ JWTOption<Name, Schema>) => {
158
189
if ( ! jwt ) return false
159
190
160
191
try {
161
- const data : any = ( await jwtVerify ( jwt , key ) ) . payload
192
+ const data : any = ( await jwtVerify ( jwt , asymmetric ? publicKey ! : key ! ) ) . payload
162
193
163
194
if ( validator && ! validator ! . Check ( data ) )
164
195
throw new ValidationError ( 'JWT' , validator , data )
0 commit comments