@@ -2,10 +2,9 @@ import { Router, Request } from "express"
22import { promises as fs } from "fs"
33import { RateLimiter as Limiter } from "limiter"
44import * as path from "path"
5- import safeCompare from "safe-compare"
65import { rootPath } from "../constants"
76import { authenticated , getCookieDomain , redirect , replaceTemplates } from "../http"
8- import { hash , humanPath } from "../util"
7+ import { getPasswordMethod , handlePasswordValidation , humanPath , sanitizeString } from "../util"
98
109export enum Cookie {
1110 Key = "key" ,
@@ -49,9 +48,9 @@ const limiter = new RateLimiter()
4948
5049export const router = Router ( )
5150
52- router . use ( ( req , res , next ) => {
51+ router . use ( async ( req , res , next ) => {
5352 const to = ( typeof req . query . to === "string" && req . query . to ) || "/"
54- if ( authenticated ( req ) ) {
53+ if ( await authenticated ( req ) ) {
5554 return redirect ( req , res , to , { to : undefined } )
5655 }
5756 next ( )
@@ -62,24 +61,31 @@ router.get("/", async (req, res) => {
6261} )
6362
6463router . post ( "/" , async ( req , res ) => {
64+ const password = sanitizeString ( req . body . password )
65+ const hashedPasswordFromArgs = req . args [ "hashed-password" ]
66+
6567 try {
6668 // Check to see if they exceeded their login attempts
6769 if ( ! limiter . canTry ( ) ) {
6870 throw new Error ( "Login rate limited!" )
6971 }
7072
71- if ( ! req . body . password ) {
73+ if ( ! password ) {
7274 throw new Error ( "Missing password" )
7375 }
7476
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 ) {
8086 // The hash does not add any actual security but we do it for
8187 // 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 , {
8389 domain : getCookieDomain ( req . headers . host || "" , req . args [ "proxy-domain" ] ) ,
8490 path : req . body . base || "/" ,
8591 sameSite : "lax" ,
0 commit comments