@@ -2,10 +2,9 @@ import { Router, Request } from "express"
2
2
import { promises as fs } from "fs"
3
3
import { RateLimiter as Limiter } from "limiter"
4
4
import * as path from "path"
5
- import safeCompare from "safe-compare"
6
5
import { rootPath } from "../constants"
7
6
import { authenticated , getCookieDomain , redirect , replaceTemplates } from "../http"
8
- import { hash , humanPath } from "../util"
7
+ import { getPasswordMethod , handlePasswordValidation , humanPath , sanitizeString } from "../util"
9
8
10
9
export enum Cookie {
11
10
Key = "key" ,
@@ -49,9 +48,9 @@ const limiter = new RateLimiter()
49
48
50
49
export const router = Router ( )
51
50
52
- router . use ( ( req , res , next ) => {
51
+ router . use ( async ( req , res , next ) => {
53
52
const to = ( typeof req . query . to === "string" && req . query . to ) || "/"
54
- if ( authenticated ( req ) ) {
53
+ if ( await authenticated ( req ) ) {
55
54
return redirect ( req , res , to , { to : undefined } )
56
55
}
57
56
next ( )
@@ -62,24 +61,31 @@ router.get("/", async (req, res) => {
62
61
} )
63
62
64
63
router . post ( "/" , async ( req , res ) => {
64
+ const password = sanitizeString ( req . body . password )
65
+ const hashedPasswordFromArgs = req . args [ "hashed-password" ]
66
+
65
67
try {
66
68
// Check to see if they exceeded their login attempts
67
69
if ( ! limiter . canTry ( ) ) {
68
70
throw new Error ( "Login rate limited!" )
69
71
}
70
72
71
- if ( ! req . body . password ) {
73
+ if ( ! password ) {
72
74
throw new Error ( "Missing password" )
73
75
}
74
76
75
- if (
76
- req . args [ "hashed-password" ]
77
- ? safeCompare ( hash ( req . body . password ) , req . args [ "hashed-password" ] )
78
- : req . args . password && safeCompare ( req . body . password , req . args . password )
79
- ) {
77
+ const passwordMethod = getPasswordMethod ( hashedPasswordFromArgs )
78
+ const { isPasswordValid, hashedPassword } = await handlePasswordValidation ( {
79
+ passwordMethod,
80
+ hashedPasswordFromArgs,
81
+ passwordFromRequestBody : password ,
82
+ passwordFromArgs : req . args . password ,
83
+ } )
84
+
85
+ if ( isPasswordValid ) {
80
86
// The hash does not add any actual security but we do it for
81
87
// obfuscation purposes (and as a side effect it handles escaping).
82
- res . cookie ( Cookie . Key , hash ( req . body . password ) , {
88
+ res . cookie ( Cookie . Key , hashedPassword , {
83
89
domain : getCookieDomain ( req . headers . host || "" , req . args [ "proxy-domain" ] ) ,
84
90
path : req . body . base || "/" ,
85
91
sameSite : "lax" ,
0 commit comments