FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
adminforth/adminforth/auth.ts at main · devforth/adminforth · GitHub
devforth
adminforth
Repository navigation
Code
Issues
16
(16)
Pull requests
6
(6)
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
adminforth
/
adminforth
/
auth.ts
Copy path
More file actions
More file actions
Latest commit
History
History
History
276 lines (242 loc) · 9.82 KB
Breadcrumbs
adminforth
/
adminforth
/
auth.ts
Copy path
File metadata and controls
276 lines (242 loc) · 9.82 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import
jwt
from
'jsonwebtoken'
;
import
crypto
from
'crypto'
;
import
AdminForth
from
'./index.js'
;
import
{
AdminUserAuthorizationResult
,
AdminUserAuthorizeFunction
,
AfterSessionCreatedFunction
,
HttpExtra
,
IAdminForthAuth
,
IAdminForthHttpResponse
}
from
'./types/Back.js'
;
import
{
AdminUser
}
from
'./types/Common.js'
;
import
{
listify
}
from
'./modules/utils.js'
;
import
{
afLogger
}
from
'./modules/logger.js'
;
import
{
Address4
,
Address6
}
from
'ip-address'
;
// Returns true for valid IPs which are not globally reachable (private, loopback, link-local, CGNAT, reserved, etc.)
function
isIpPrivate
(
ip
:
string
|
null
)
:
boolean
{
if
(
Address4
.
isValid
(
ip
)
)
{
return
!
new
Address4
(
ip
)
.
isGlobal
(
)
;
}
if
(
Address6
.
isValid
(
ip
)
)
{
return
!
new
Address6
(
ip
)
.
isGlobal
(
)
;
}
return
false
;
}
// Function to generate a password hash using PBKDF2
function
calcPasswordHash
(
password
,
salt
,
iterations
=
100000
,
keyLength
=
64
,
digest
=
'sha512'
)
{
return
new
Promise
(
(
resolve
,
reject
)
=>
{
crypto
.
pbkdf2
(
password
,
salt
,
iterations
,
keyLength
,
digest
,
(
err
,
derivedKey
)
=>
{
if
(
err
)
reject
(
err
)
;
resolve
(
derivedKey
.
toString
(
'hex'
)
)
;
}
)
;
}
)
;
}
// Function to generate a random salt
function
generateSalt
(
length
=
16
)
{
return
crypto
.
randomBytes
(
length
)
.
toString
(
'hex'
)
;
}
function
parseTimeToSeconds
(
time
:
string
)
:
number
{
const
unit
=
time
.
slice
(
-
1
)
;
const
value
=
parseInt
(
time
.
slice
(
0
,
-
1
)
,
10
)
;
switch
(
unit
)
{
case
's'
:
return
value
;
case
'm'
:
return
value
*
60
;
case
'h'
:
return
value
*
60
*
60
;
case
'd'
:
return
value
*
60
*
60
*
24
;
default
:
throw
new
Error
(
`Invalid time unit:
${
unit
}
`
)
;
}
}
class
AdminForthAuth
implements
IAdminForthAuth
{
adminforth
:
AdminForth
;
constructor
(
adminforth
)
{
this
.
adminforth
=
adminforth
;
}
getClientIp
(
headers
:
object
)
{
const
clientIpHeader
=
this
.
adminforth
.
config
.
auth
.
clientIpHeader
;
const
headersLower
=
Object
.
keys
(
headers
)
.
reduce
(
(
acc
,
key
)
=>
{
acc
[
key
.
toLowerCase
(
)
]
=
headers
[
key
]
;
return
acc
;
}
,
{
}
)
;
let
ip
:
string
|
null
=
null
;
if
(
clientIpHeader
)
{
ip
=
headersLower
[
clientIpHeader
.
toLowerCase
(
)
]
;
}
else
{
// first try common headers which can't bee spoofed, in other words
// most common to nginx/traefik/apache
// then fallback to less secure headers
ip
=
headersLower
[
'x-forwarded-for'
]
?.
split
(
','
)
.
shift
(
)
.
trim
(
)
||
headersLower
[
'x-real-ip'
]
||
headersLower
[
'x-client-ip'
]
||
headersLower
[
'x-cluster-client-ip'
]
||
headersLower
[
'forwarded'
]
||
headersLower
[
'remote-addr'
]
||
headersLower
[
'client-ip'
]
||
headersLower
[
'client-address'
]
||
headersLower
[
'client'
]
||
headersLower
[
'x-host'
]
||
null
;
}
if
(
isIpPrivate
(
ip
)
)
{
return
null
;
}
return
ip
;
}
removeAuthCookie
(
response
)
{
const
brandSlug
=
this
.
adminforth
.
config
.
customization
.
brandNameSlug
;
response
.
setHeader
(
'Set-Cookie'
,
`adminforth_
${
brandSlug
}
_jwt=; Path=
${
this
.
adminforth
.
config
.
baseUrl
||
'/'
}
; HttpOnly; SameSite=Strict; Expires=Thu, 01 Jan 1970 00:00:00 GMT`
)
;
}
async
setAuthCookie
(
{
expireInDuration
,
response
,
username
,
pk
,
sessionId
=
crypto
.
randomUUID
(
)
,
extra
}
:
{
expireInDuration
?:
string
,
response
:
any
,
username
:
string
,
pk
:
string
|
null
,
sessionId
?:
string
,
extra
?:
HttpExtra
}
)
:
Promise
<
string
>
{
const
expiresIn
:
string
=
expireInDuration
||
(
process
.
env
.
ADMINFORTH_AUTH_EXPIRESIN
||
'24h'
)
;
// might be h,m,d in string
const
expiresInSec
=
parseTimeToSeconds
(
expiresIn
)
;
const
token
=
this
.
issueJWT
(
{
username
,
pk
,
sessionId
}
,
'auth'
,
expiresInSec
)
;
const
expiresCookieFormat
=
new
Date
(
Date
.
now
(
)
+
expiresInSec
*
1000
)
.
toUTCString
(
)
;
const
brandSlug
=
this
.
adminforth
.
config
.
customization
.
brandNameSlug
;
// cookie is set before hooks are awaited, so callers which don't await still get it set
response
.
setHeader
(
'Set-Cookie'
,
`adminforth_
${
brandSlug
}
_jwt=
${
token
}
; Path=
${
this
.
adminforth
.
config
.
baseUrl
||
'/'
}
; HttpOnly; SameSite=Strict; Expires=
${
expiresCookieFormat
}
`
)
;
const
afterSessionCreated
=
this
.
adminforth
.
config
.
auth
.
afterSessionCreated
as
(
AfterSessionCreatedFunction
[
]
|
undefined
)
;
for
(
const
hook
of
listify
(
afterSessionCreated
)
)
{
await
hook
(
{
pk
,
username
,
sessionId
,
expiresInSeconds
:
expiresInSec
,
adminforth
:
this
.
adminforth
,
extra
}
)
;
}
return
sessionId
;
}
removeCustomCookie
(
{
response
,
name
}
)
{
const
brandSlug
=
this
.
adminforth
.
config
.
customization
.
brandNameSlug
;
response
.
setHeader
(
'Set-Cookie'
,
`adminforth_
${
brandSlug
}
_
${
name
}
=; Path=
${
this
.
adminforth
.
config
.
baseUrl
||
'/'
}
; HttpOnly; SameSite=Strict; Expires=Thu, 01 Jan 1970 00:00:00 GMT`
)
;
}
setCustomCookie
(
{
response
,
payload
}
:
{
response
:
any
,
payload
:
{
name
:
string
,
value
:
string
,
expiry
?:
number
|
undefined
,
expirySeconds
:
number
|
undefined
,
httpOnly
:
boolean
,
sessionBased
?:
boolean
|
undefined
}
}
)
{
const
{
name
,
value
,
expiry
,
httpOnly
,
expirySeconds
,
sessionBased
}
=
payload
;
let
expiryMs
=
24
*
60
*
60
*
1000
;
// default 1 day
if
(
expirySeconds
!==
undefined
)
{
expiryMs
=
expirySeconds
*
1000
;
}
else
if
(
expiry
!==
undefined
)
{
afLogger
.
warn
(
`setCustomCookie: expiry(in ms) is deprecated, use expirySeconds instead (seconds), traceback:
${
new
Error
(
)
.
stack
}
`
)
;
expiryMs
=
expiry
;
}
const
brandSlug
=
this
.
adminforth
.
config
.
customization
.
brandNameSlug
;
response
.
setHeader
(
'Set-Cookie'
,
`adminforth_
${
brandSlug
}
_
${
name
}
=
${
value
}
; Path=
${
this
.
adminforth
.
config
.
baseUrl
||
'/'
}
;
${
httpOnly
?
' HttpOnly;'
:
''
}
SameSite=Strict;
${
sessionBased
?
''
:
`Expires=
${
new
Date
(
Date
.
now
(
)
+
expiryMs
)
.
toUTCString
(
)
}
`
}
`
)
;
}
getCustomCookie
(
{
cookies
,
name
}
:
{
cookies
:
{
key
:
string
,
value
:
string
}
[
]
,
name
:
string
}
)
:
string
|
null
{
const
brandSlug
=
this
.
adminforth
.
config
.
customization
.
brandNameSlug
;
return
cookies
.
find
(
(
cookie
)
=>
cookie
.
key
===
`adminforth_
${
brandSlug
}
_
${
name
}
`
)
?.
value
||
null
;
}
getAuthCookie
(
cookies
:
{
key
:
string
,
value
:
string
}
[
]
)
:
string
|
null
{
const
brandSlug
=
this
.
adminforth
.
config
.
customization
.
brandNameSlug
;
const
jwts
=
cookies
.
filter
(
(
{
key
}
)
=>
key
===
`adminforth_
${
brandSlug
}
_jwt`
)
;
if
(
jwts
.
length
>
1
)
{
afLogger
.
error
(
'Multiple adminforth_jwt cookies provided'
)
;
}
return
jwts
[
0
]
?.
value
||
null
;
}
async
runAdminUserAuthorizeHooks
(
adminUser
:
AdminUser
,
response
:
IAdminForthHttpResponse
,
extra
:
HttpExtra
)
:
Promise
<
{
allowed
:
boolean
,
error
?:
string
}
>
{
const
adminUserAuthorize
=
this
.
adminforth
.
config
.
auth
.
adminUserAuthorize
as
(
AdminUserAuthorizeFunction
[
]
|
undefined
)
;
for
(
const
hook
of
listify
(
adminUserAuthorize
)
)
{
const
resp
=
await
hook
(
{
adminUser
,
response
,
adminforth
:
this
.
adminforth
,
extra
,
}
)
;
if
(
resp
?.
allowed
===
false
||
resp
?.
error
)
{
return
{
allowed
:
resp
?.
allowed
,
error
:
resp
?.
error
}
;
}
}
return
{
allowed
:
true
}
;
}
async
authorizeByCookies
(
{
cookies
,
response
,
extra
}
:
{
cookies
:
{
key
:
string
,
value
:
string
}
[
]
,
response
:
IAdminForthHttpResponse
,
extra
:
HttpExtra
,
}
)
:
Promise
<
AdminUserAuthorizationResult
>
{
const
jwt
=
this
.
getAuthCookie
(
cookies
)
;
if
(
!
jwt
)
{
return
{
status
:
'noToken'
}
;
}
let
adminUser
:
AdminUser
|
null
;
try
{
adminUser
=
await
this
.
verify
(
jwt
,
'auth'
)
as
AdminUser
|
null
;
}
catch
(
error
)
{
return
{
status
:
'verifyFailed'
,
error
}
;
}
if
(
!
adminUser
)
{
return
{
status
:
'invalidToken'
}
;
}
const
{
allowed
,
error
}
=
await
this
.
runAdminUserAuthorizeHooks
(
adminUser
,
response
,
extra
)
;
if
(
!
allowed
)
{
return
{
status
:
'notAllowed'
,
error
}
;
}
return
{
status
:
'ok'
,
adminUser
}
;
}
issueJWT
(
payload
:
Object
,
type
:
string
,
expiresIn
:
string
|
number
=
'24h'
)
:
string
{
// read ADMINFORH_SECRET from environment if not drop error
const
secret
=
process
.
env
.
ADMINFORTH_SECRET
;
if
(
!
secret
)
{
throw
new
Error
(
'ADMINFORTH_SECRET environment not set'
)
;
}
// issue JWT token
return
jwt
.
sign
(
{
...
payload
,
t
:
type
}
,
secret
,
{
expiresIn
}
)
;
}
async
verify
(
jwtToken
:
string
,
mustHaveType
:
string
,
decodeUser
:
boolean
|
undefined
=
true
)
:
Promise
<
Object
>
{
// read ADMINFORH_SECRET from environment if not drop error
const
secret
=
process
.
env
.
ADMINFORTH_SECRET
;
if
(
!
secret
)
{
throw
new
Error
(
'ADMINFORTH_SECRET environment not set'
)
;
}
let
decoded
;
try
{
// verify JWT token
decoded
=
jwt
.
verify
(
jwtToken
,
secret
)
;
}
catch
(
err
)
{
if
(
err
.
name
===
'TokenExpiredError'
)
{
afLogger
.
info
(
`Token expired:
${
err
.
message
}
`
)
;
}
else
if
(
err
.
name
===
'JsonWebTokenError'
)
{
afLogger
.
info
(
`Token error:
${
err
.
message
}
, JWT secret changed?`
)
;
}
else
{
afLogger
.
error
(
`Failed to verify JWT token:
${
err
}
`
)
;
}
return
null
;
}
const
{
pk
,
t
}
=
decoded
;
if
(
t
!==
mustHaveType
)
{
afLogger
.
error
(
`Invalid token type during verification:
${
t
}
, must be
${
mustHaveType
}
`
)
;
return
null
;
}
if
(
decodeUser
!==
false
)
{
const
dbUser
=
await
this
.
adminforth
.
getUserByPk
(
pk
)
;
if
(
!
dbUser
)
{
afLogger
.
error
(
`User with pk
${
pk
}
not found in database`
)
;
// will logout user which was deleted
return
null
;
}
decoded
.
dbUser
=
dbUser
;
}
return
decoded
;
}
static
async
generatePasswordHash
(
password
)
{
const
salt
=
generateSalt
(
)
;
const
hashedPassword
=
await
calcPasswordHash
(
password
,
salt
)
;
return
`
${
salt
}
:
${
hashedPassword
}
`
;
}
static
async
verifyPassword
(
password
,
hashedPassword
)
{
const
[
salt
,
hash
]
=
hashedPassword
.
split
(
':'
)
;
const
newHash
=
await
calcPasswordHash
(
password
,
salt
)
;
return
newHash
===
hash
;
}
}
export
default
AdminForthAuth
;
Back
|
FazBrowse Home
|
New Git URL