ReviewOS

also looking at this

mail-os/mail

feat: mailbox recovery addresses and password reset by email

#13
Merged chris wants to merge feat/mailbox-recovery into main
21 files +1503 -10
packages/webmail/functions/recovery.tsadded+48-0
Changes to packages/webmail/functions/recovery.ts
@@ -0,0 +1,48 @@
1/**
2 * Password reset and recovery address helpers shared by the reset page and
3 * the settings dialog. Pure functions, so they are tested without a browser.
4 */
5
6/** A reset token is 32 bytes as 64 lowercase hex characters. */
7const TOKEN = /^[0-9a-f]{64}$/
8
9/**
10 * The token from a reset link's fragment (`#token=<hex>`). The link carries
11 * it in the fragment so it never reaches a server log; anything that is not a
12 * well-formed token reads as none.
13 */
14export function tokenFromHash(hash: string): string {
15 const params = new URLSearchParams(hash.replace(/^#/, ''))
16 const token = (params.get('token') || '').trim().toLowerCase()
17 return TOKEN.test(token) ? token : ''
18}
19
20export const MIN_PASSWORD_LENGTH = 12
21
22/** Why a new password cannot be submitted, or '' when it can. */
23export function newPasswordProblem(password: string, confirmation: string): string {
24 if (password.length < MIN_PASSWORD_LENGTH) return `Use at least ${MIN_PASSWORD_LENGTH} characters.`
25 if (password.length > 1024) return 'Use at most 1024 characters.'
26 if (password !== confirmation) return 'The new passwords do not match.'
27 return ''
28}
29
30/**
31 * Why a recovery address cannot be saved for `mailbox`, or '' when it can.
32 * An empty address is allowed: it removes the recovery address. The server
33 * applies the same rules; this only answers sooner.
34 */
35export function recoveryAddressProblem(mailbox: string, address: string): string {
36 const value = address.trim()
37 if (!value) return ''
38 if (!/^[^\s@,;:"<>\\/]+@[^\s@,;:"<>\\/]+\.[^\s@,;:"<>\\/]+$/.test(value)) return 'Enter a valid email address.'
39 if (value.toLowerCase() === mailbox.trim().toLowerCase()) return 'Use an address outside this mailbox.'
40 return ''
41}
42
43/** The message for a failed reset request, by HTTP status. */
44export function resetErrorMessage(status: number, fallback = 'Something went wrong. Please try again.'): string {
45 if (status === 429) return 'Too many attempts. Please wait a few minutes.'
46 if (status === 400) return 'This reset link is invalid, already used or expired. Ask for a new one.'
47 return fallback
48}