Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
fix(auth): preserve surrounding spaces in passwords (#207)
Kevin Rose0286e1676997
diff --git a/src/components/auth/login-shell.tsx b/src/components/auth/login-shell.tsxindex a4ca58d..04c27e4 100644--- a/src/components/auth/login-shell.tsx+++ b/src/components/auth/login-shell.tsx@@ -16,8 +16,13 @@ import {describePasswordRefusal,newPasswordLengthError,PASSWORD_TOO_LONG_MESSAGE,+ PASSWORD_TOO_SHORT_MESSAGE,} from "@/lib/password-messages";-import { forgotPasswordSchema, loginSchema } from "@/lib/schemas/auth";+import {+ forgotPasswordSchema,+ loginSchema,+ resetPasswordSchema,+} from "@/lib/schemas/auth";import {Dialog,DialogContent,@@ -639,25 +644,28 @@ function ResetPasswordCard({ resetToken }: { resetToken: string }) {}const formData = new FormData(event.currentTarget);- const trimmedPassword = String(+ const submittedPassword = String(formData.get("reset-password") ?? password,- ).trim();-- const lengthError = newPasswordLengthError(trimmedPassword);+ );+ const validationResult = resetPasswordSchema.safeParse({+ newPassword: submittedPassword,+ });- if (lengthError) {- setError(lengthError);+ if (!validationResult.success) {+ setError(+ newPasswordLengthError(submittedPassword) ?? PASSWORD_TOO_SHORT_MESSAGE,+ );setSuccessMessage(null);return;}- setPassword(trimmedPassword);+ setPassword(validationResult.data.newPassword);setError(null);setSuccessMessage(null);setIsSubmitting(true);const result = await authClient.resetPassword({- newPassword: trimmedPassword,+ newPassword: validationResult.data.newPassword,token: resetToken,});diff --git a/src/components/settings/settings-shell.tsx b/src/components/settings/settings-shell.tsxindex 394ab97..c3f71a9 100644--- a/src/components/settings/settings-shell.tsx+++ b/src/components/settings/settings-shell.tsx@@ -16,6 +16,12 @@ import {} from "@/components/ui/dialog";import { Field, FieldLabel } from "@/components/ui/field";import { Input } from "@/components/ui/input";+import {+ describePasswordRefusal,+ newPasswordLengthError,+ PASSWORD_TOO_SHORT_MESSAGE,+} from "@/lib/password-messages";+import { updatePasswordSchema } from "@/lib/schemas/auth";const CLOSURE_CONFIRMATION_PHRASE = "close my account";const GENERIC_ERROR_MESSAGE = "Something went wrong. Please try again.";@@ -96,14 +102,26 @@ function validateProfileValues(values: ProfileValues): ProfileErrors {}function validatePasswordValues(values: PasswordValues): PasswordErrors {- const errors: PasswordErrors = {};+ const validationResult = updatePasswordSchema.safeParse(values);- if (values.currentPassword.length === 0) {- errors.currentPassword = "Enter your current password";+ if (validationResult.success) {+ return {};}- if (values.newPassword.trim().length < 15) {- errors.newPassword = "Password must be at least 15 characters";+ const errors: PasswordErrors = {};++ for (const issue of validationResult.error.issues) {+ const field = issue.path[0];++ if (field === "currentPassword") {+ errors.currentPassword = "Enter your current password";+ }++ if (field === "newPassword") {+ errors.newPassword =+ newPasswordLengthError(values.newPassword) ??+ PASSWORD_TOO_SHORT_MESSAGE;+ }}return errors;@@ -151,14 +169,6 @@ function isInvalidPasswordMessage(message: string) {return message.toLowerCase().includes("invalid password");}-function isPasswordTooShortMessage(message: string) {- return message.toLowerCase().includes("password too short");-}--function isCompromisedPasswordMessage(message: string) {- return message.toLowerCase().includes("compromised");-}-function isNoOpEmailChangeMessage(message: string) {const normalizedMessage = message.toLowerCase();@@ -402,22 +412,19 @@ export function SettingsShell({if (!response.ok) {const errorMessage = extractApiErrorMessage(payload);+ const newPasswordError =+ describePasswordRefusal({ message: errorMessage }) ?? undefined;+ const invalidCurrentPassword = isInvalidPasswordMessage(errorMessage);setPasswordErrors({- currentPassword: isInvalidPasswordMessage(errorMessage)+ currentPassword: invalidCurrentPassword? "Current password is incorrect": undefined,- newPassword: isPasswordTooShortMessage(errorMessage)- ? "Password must be at least 15 characters"- : isCompromisedPasswordMessage(errorMessage)- ? "Choose a password that hasn't appeared in a breach"- : undefined,+ newPassword: newPasswordError,});setFeedback({message:- isInvalidPasswordMessage(errorMessage) ||- isPasswordTooShortMessage(errorMessage) ||- isCompromisedPasswordMessage(errorMessage)+ invalidCurrentPassword || newPasswordError? "Please correct the highlighted fields.": errorMessage,tone: "error",diff --git a/src/components/signing/signer-verification-screen.tsx b/src/components/signing/signer-verification-screen.tsxindex 9fb1ded..511b05a 100644--- a/src/components/signing/signer-verification-screen.tsx+++ b/src/components/signing/signer-verification-screen.tsx@@ -232,7 +232,9 @@ export function SignerVerificationScreen({<div className="flex flex-col gap-3 sm:flex-row"><ShellButtondisabled={- code.trim().length === 0 ||+ (method === "account"+ ? code.length === 0+ : code.trim().length === 0) ||(method === "account" && email.trim().length === 0)}loading={isChecking}diff --git a/src/lib/password-messages.test.ts b/src/lib/password-messages.test.tsindex 5c3147b..8f48d43 100644--- a/src/lib/password-messages.test.ts+++ b/src/lib/password-messages.test.ts@@ -20,6 +20,11 @@ test("a new password over 128 characters is told the maximum, not the minimum (inewPasswordLengthError("a".repeat(14)),PASSWORD_TOO_SHORT_MESSAGE,);+ assert.equal(newPasswordLengthError(" 12345678901 "), null);+ assert.equal(+ newPasswordLengthError(` ${"a".repeat(127)} `),+ PASSWORD_TOO_LONG_MESSAGE,+ );});test("Better Auth's password refusals get their own messages", () => {diff --git a/src/lib/schemas/auth.test.ts b/src/lib/schemas/auth.test.tsnew file mode 100644index 0000000..7bb128e--- /dev/null+++ b/src/lib/schemas/auth.test.ts@@ -0,0 +1,234 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ loginSchema,+ resetPasswordSchema,+ signUpSchema,+ updatePasswordSchema,+} from "./auth.ts";+import { signingSubmissionSchema } from "./field.ts";+import { signerCheckRequestSchema } from "./signing.ts";++const PADDED_PASSWORD = " amber river morning compass ";++test("loginSchema preserves leading and trailing spaces in passwords while trimming email (issue #207)", () => {+ const parsed = loginSchema.parse({+ email: " [email protected] ",+ password: PADDED_PASSWORD,+ });++ assert.equal(parsed.email, "[email protected]");+ assert.equal(parsed.password, PADDED_PASSWORD);++ assert.equal(+ loginSchema.parse({+ email: "[email protected]",+ password: " leading only",+ }).password,+ " leading only",+ );+ assert.equal(+ loginSchema.parse({+ email: "[email protected]",+ password: "trailing only ",+ }).password,+ "trailing only ",+ );+ assert.equal(+ loginSchema.parse({+ email: "[email protected]",+ password: " ".repeat(15),+ }).password,+ " ".repeat(15),+ );++ // Overlong passwords pass schema parsing so the login form can surface+ // Better Auth's PASSWORD_TOO_LONG message instead of "Enter your password" (#57).+ const overlong = ` ${"a".repeat(127)} `;++ assert.equal(+ loginSchema.parse({ email: "[email protected]", password: overlong })+ .password,+ overlong,+ );++ assert.equal(+ loginSchema.safeParse({ email: "[email protected]", password: "" })+ .success,+ false,+ );+ assert.equal(+ loginSchema.safeParse({ email: "not-an-email", password: PADDED_PASSWORD })+ .success,+ false,+ );+});++test("signUpSchema preserves surrounding spaces and counts them in password length bounds", () => {+ const parsed = signUpSchema.parse({+ email: " [email protected] ",+ fullName: " Jane Smith ",+ password: PADDED_PASSWORD,+ });++ assert.deepEqual(parsed, {+ email: "[email protected]",+ fullName: "Jane Smith",+ password: PADDED_PASSWORD,+ });++ // 15 characters total (11 trimmed): valid because spaces are part of the password.+ const fifteenWithSpaces = " elevenchars ";++ assert.equal(fifteenWithSpaces.length, 15);+ assert.equal(+ signUpSchema.parse({+ email: "[email protected]",+ fullName: "Jane Smith",+ password: fifteenWithSpaces,+ }).password,+ fifteenWithSpaces,+ );++ assert.equal(+ signUpSchema.safeParse({+ email: "[email protected]",+ fullName: "Jane Smith",+ password: " short ",+ }).success,+ false,+ );+ assert.equal(+ signUpSchema.safeParse({+ email: "[email protected]",+ fullName: "Jane Smith",+ password: "",+ }).success,+ false,+ );++ const atLimit = ` ${"a".repeat(126)} `;+ const overLimit = ` ${"a".repeat(127)} `;++ assert.equal(atLimit.length, 128);+ assert.equal(overLimit.length, 129);+ assert.equal(+ signUpSchema.parse({+ email: "[email protected]",+ fullName: "Jane Smith",+ password: atLimit,+ }).password,+ atLimit,+ );+ assert.equal(+ signUpSchema.safeParse({+ email: "[email protected]",+ fullName: "Jane Smith",+ password: overLimit,+ }).success,+ false,+ );+});++test("updatePasswordSchema preserves surrounding spaces in both current and new passwords", () => {+ const newPasswordWithSpaces = " thirteenchars ";++ assert.equal(newPasswordWithSpaces.length, 17);+ const parsed = updatePasswordSchema.parse({+ currentPassword: PADDED_PASSWORD,+ newPassword: newPasswordWithSpaces,+ });++ assert.deepEqual(parsed, {+ currentPassword: PADDED_PASSWORD,+ newPassword: newPasswordWithSpaces,+ });++ assert.equal(+ updatePasswordSchema.safeParse({+ currentPassword: "",+ newPassword: PADDED_PASSWORD,+ }).success,+ false,+ );+ assert.equal(+ updatePasswordSchema.safeParse({+ currentPassword: PADDED_PASSWORD,+ newPassword: " too short ",+ }).success,+ false,+ );+ assert.equal(+ updatePasswordSchema.safeParse({+ currentPassword: PADDED_PASSWORD,+ newPassword: ` ${"a".repeat(127)} `,+ }).success,+ false,+ );+});++test("resetPasswordSchema preserves surrounding spaces and enforces length bounds", () => {+ assert.equal(+ resetPasswordSchema.parse({ newPassword: PADDED_PASSWORD }).newPassword,+ PADDED_PASSWORD,+ );++ const fifteenWithSpaces = " elevenchars ";++ assert.equal(+ resetPasswordSchema.parse({ newPassword: fifteenWithSpaces }).newPassword,+ fifteenWithSpaces,+ );+ assert.equal(+ resetPasswordSchema.safeParse({ newPassword: "" }).success,+ false,+ );+ assert.equal(+ resetPasswordSchema.safeParse({ newPassword: " too short " }).success,+ false,+ );+ assert.equal(+ resetPasswordSchema.safeParse({ newPassword: ` ${"a".repeat(127)} ` })+ .success,+ false,+ );+});++test("Part 11 signing password schemas preserve surrounding spaces verbatim", () => {+ const accountCheck = signerCheckRequestSchema.parse({+ email: " [email protected] ",+ method: "account",+ password: PADDED_PASSWORD,+ });++ assert.deepEqual(accountCheck, {+ email: "[email protected]",+ method: "account",+ password: PADDED_PASSWORD,+ });+ assert.equal(+ signerCheckRequestSchema.safeParse({+ email: "[email protected]",+ method: "account",+ password: "",+ }).success,+ false,+ );++ const submission = signingSubmissionSchema.parse({+ clientTimezoneOffsetMinutes: 0,+ fields: [],+ reauthentication: {+ email: " [email protected] ",+ meaningConfirmed: true,+ password: PADDED_PASSWORD,+ },+ });++ assert.deepEqual(submission.reauthentication, {+ email: "[email protected]",+ meaningConfirmed: true,+ password: PADDED_PASSWORD,+ });+});diff --git a/src/lib/schemas/auth.ts b/src/lib/schemas/auth.tsindex 22d45dc..11d5e86 100644--- a/src/lib/schemas/auth.ts+++ b/src/lib/schemas/auth.ts@@ -1,38 +1,54 @@import { z } from "zod";+import {+ PASSWORD_MAX_LENGTH,+ PASSWORD_MIN_LENGTH,+} from "../password-messages.ts";import {emailSchema,idSchema,nameSchema,- nonEmptyStringSchema,unixTimestampSchema,} from "./common.ts";export const accountClosureConfirmationPhrase = "close my account" as const;+// Passwords are never trimmed: leading and trailing spaces are valid+// characters and must reach Better Auth verbatim on sign-up, sign-in,+// password change and password reset (issue #207).+const existingPasswordSchema = z.string().min(1);+const newPasswordSchema = z+ .string()+ .min(PASSWORD_MIN_LENGTH)+ .max(PASSWORD_MAX_LENGTH);+export const signUpSchema = z.object({fullName: nameSchema,email: emailSchema,- password: z.string().min(15).max(128),+ password: newPasswordSchema,});export const loginSchema = z.object({email: emailSchema,- password: nonEmptyStringSchema,+ password: existingPasswordSchema,});export const forgotPasswordSchema = z.object({email: emailSchema,});+export const resetPasswordSchema = z.object({+ newPassword: newPasswordSchema,+});+export const updateProfileSchema = z.object({fullName: nameSchema,email: emailSchema,});export const updatePasswordSchema = z.object({- currentPassword: nonEmptyStringSchema,- newPassword: z.string().min(15).max(128),+ currentPassword: existingPasswordSchema,+ newPassword: newPasswordSchema,});export const accountClosureRequestSchema = z.object({@@ -53,6 +69,7 @@ export const senderSessionSchema = z.object({export type SignUpInput = z.infer<typeof signUpSchema>;export type LoginInput = z.infer<typeof loginSchema>;export type ForgotPasswordInput = z.infer<typeof forgotPasswordSchema>;+export type ResetPasswordInput = z.infer<typeof resetPasswordSchema>;export type UpdateProfileInput = z.infer<typeof updateProfileSchema>;export type UpdatePasswordInput = z.infer<typeof updatePasswordSchema>;export type AccountClosureRequestInput = z.infer<