Password reset by email
CI / check (push) Canceled after 0s

"Forgot your password?" on web and mobile sends a one-time link (1 hour)
to the account's email; the website's reset page sets the new password,
signs out every other session and signs in. The request responds the same
whether or not the email has an account, and the email goes out in the
background so timing doesn't reveal it either. Only a hash of the link
token is stored. Sends through SMTP_* settings; without them, emails are
logged (and captured in tests).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MzFywujuH9TiuXbr9vjoX8
This commit is contained in:
2026-10-06 01:05:30 -04:00
co-authored by Claude Opus 5.5
parent 2b02aa8e89
commit 1f0cdb68f5
21 changed files with 1811 additions and 5 deletions
+15
View File
@@ -238,6 +238,21 @@ export const featuredSongs = pgTable('featured_songs', {
.default(sql`now()`),
});
/** One-time password reset links. Only a hash of the token is stored. */
export const passwordResets = pgTable(
'password_resets',
{
id: text('id').primaryKey(),
userId: uuid('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
usedAt: timestamp('used_at', { withTimezone: true }),
createdAt: createdAt(),
},
(t) => [index('password_resets_user_idx').on(t.userId)],
);
const bytea = customType<{ data: Buffer }>({ dataType: () => 'bytea' });
/** Profile pictures, already resized and re-encoded (WebP, metadata stripped). */
+7
View File
@@ -37,6 +37,12 @@ const schema = z.object({
* dev or self-hosting: in a hosted deployment it lets users make the server
* request internal addresses (SSRF).
*/
/** Outgoing email (password resets). Without SMTP_HOST, emails are only logged. */
SMTP_HOST: optional,
SMTP_PORT: z.coerce.number().default(465),
SMTP_USER: optional,
SMTP_PASSWORD: optional,
MAIL_FROM: z.string().default('musicshare <app@musicshare.binarygnome.com>'),
ALLOW_PRIVATE_SERVER_URLS: z
.string()
.default('false')
@@ -47,3 +53,4 @@ export const env = schema.parse(process.env);
export const spotifyConfigured = Boolean(env.SPOTIFY_CLIENT_ID && env.SPOTIFY_CLIENT_SECRET);
export const appleMusicConfigured = Boolean(env.APPLE_TEAM_ID && env.APPLE_MUSICKIT_KEY_ID && env.APPLE_MUSICKIT_PRIVATE_KEY);
export const mailConfigured = Boolean(env.SMTP_HOST);
+44
View File
@@ -0,0 +1,44 @@
import nodemailer, { type Transporter } from 'nodemailer';
import { env, mailConfigured } from '../env';
export interface Mail {
to: string;
subject: string;
text: string;
html: string;
}
/** Messages "sent" while SMTP isn't configured (tests, local dev). */
export const outbox: Mail[] = [];
let transport: Transporter | null = null;
export async function sendMail(mail: Mail): Promise<void> {
if (!mailConfigured) {
outbox.push(mail);
if (env.NODE_ENV !== 'test') console.info(`[mail] SMTP not configured; would send to ${mail.to}: ${mail.subject}\n${mail.text}`);
return;
}
transport ??= nodemailer.createTransport({
host: env.SMTP_HOST,
port: env.SMTP_PORT,
secure: env.SMTP_PORT === 465, // 465 is TLS from the start; 587 upgrades with STARTTLS
auth: env.SMTP_USER ? { user: env.SMTP_USER, pass: env.SMTP_PASSWORD } : undefined,
});
await transport.sendMail({ from: env.MAIL_FROM, ...mail });
}
const escape = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
/** A plain, readable email: a few lines of text and one button. */
export function simpleEmail({ lines, button, footer }: { lines: string[]; button: { label: string; url: string }; footer: string }) {
const text = [...lines, '', `${button.label}: ${button.url}`, '', footer].join('\n');
const html = `<!doctype html><html><body style="margin:0;background:#0b0820;font-family:-apple-system,Segoe UI,Roboto,sans-serif;color:#ecebff">
<div style="max-width:480px;margin:0 auto;padding:32px 24px">
<div style="font-size:22px;font-weight:700;margin-bottom:20px">musicshare</div>
${lines.map((l) => `<p style="font-size:15px;line-height:1.5;margin:0 0 12px">${escape(l)}</p>`).join('\n')}
<p style="margin:24px 0"><a href="${escape(button.url)}" style="display:inline-block;background:linear-gradient(90deg,#7b2ff7,#2f8cff);background-color:#5b4cf0;color:#fff;text-decoration:none;font-weight:600;padding:12px 22px;border-radius:999px">${escape(button.label)}</a></p>
<p style="font-size:13px;line-height:1.5;color:#9a97c0;margin:0">${escape(footer)}</p>
</div></body></html>`;
return { text, html };
}
+64 -2
View File
@@ -1,13 +1,17 @@
import { hash, verify } from '@node-rs/argon2';
import { count, eq, or, sql } from 'drizzle-orm';
import { and, count, eq, gt, isNull, or, sql } from 'drizzle-orm';
import type { FastifyInstance } from 'fastify';
import { loginSchema, registerSchema } from '@musicshare/shared';
import { forgotPasswordSchema, loginSchema, registerSchema, resetPasswordSchema } from '@musicshare/shared';
import { db, schema } from '../db';
import { env } from '../env';
import { SESSION_COOKIE, createSession } from '../lib/auth';
import { randomToken, sha256 } from '../lib/crypto';
import { HttpError } from '../lib/http';
import { sendMail, simpleEmail } from '../lib/mail';
import { toMeDTO } from './me';
const authRateLimit = { config: { rateLimit: { max: 10, timeWindow: '1 minute' } } };
const RESET_MINUTES = 60;
export async function authRoutes(app: FastifyInstance) {
app.post('/auth/register', authRateLimit, async (req, reply) => {
@@ -47,6 +51,64 @@ export async function authRoutes(app: FastifyInstance) {
return { user: toMeDTO(user), token };
});
/**
* Emails a one-time reset link. Responds the same whether or not the email has
* an account, so it can't be used to find out who's signed up.
*/
app.post('/auth/forgot-password', { config: { rateLimit: { max: 5, timeWindow: '1 hour' } } }, async (req) => {
const { email } = forgotPasswordSchema.parse(req.body);
const [user] = await db.select().from(schema.users).where(eq(schema.users.email, email));
if (!user || user.suspendedAt) return { ok: true };
// One live link at a time: asking again replaces the old one.
await db.delete(schema.passwordResets).where(eq(schema.passwordResets.userId, user.id));
const token = randomToken();
await db.insert(schema.passwordResets).values({
id: sha256(token),
userId: user.id,
expiresAt: new Date(Date.now() + RESET_MINUTES * 60_000),
});
const url = `${env.WEB_URL.replace(/\/$/, '')}/reset-password?token=${encodeURIComponent(token)}`;
const mail = simpleEmail({
lines: [`Hi ${user.displayName ?? user.username},`, 'Someone (hopefully you) asked to reset your musicshare password.'],
button: { label: 'Choose a new password', url },
footer: `This link works once and expires in ${RESET_MINUTES} minutes. If you didn't ask for it, you can ignore this email; your password won't change.`,
});
// Send in the background: waiting on the mail server would make the response
// slower for real accounts, which would also reveal who has one.
sendMail({ to: user.email, subject: 'Reset your musicshare password', ...mail }).catch((err) =>
req.log.error({ err }, 'password reset email failed'),
);
return { ok: true };
});
app.post('/auth/reset-password', authRateLimit, async (req, reply) => {
const input = resetPasswordSchema.parse(req.body);
const passwordHash = await hash(input.password);
const user = await db.transaction(async (tx) => {
const [reset] = await tx
.update(schema.passwordResets)
.set({ usedAt: new Date() })
.where(
and(
eq(schema.passwordResets.id, sha256(input.token)),
isNull(schema.passwordResets.usedAt),
gt(schema.passwordResets.expiresAt, new Date()),
),
)
.returning();
if (!reset) return null;
const [updated] = await tx.update(schema.users).set({ passwordHash }).where(eq(schema.users.id, reset.userId)).returning();
// Sign out everywhere: whoever knew the old password shouldn't stay signed in.
await tx.delete(schema.sessions).where(eq(schema.sessions.userId, reset.userId));
return updated ?? null;
});
if (!user) throw new HttpError(400, 'This reset link has expired or was already used. Ask for a new one.');
if (user.suspendedAt) throw new HttpError(403, 'This account has been suspended');
const token = await createSession(user.id, reply);
return { user: toMeDTO(user), token };
});
app.post('/auth/logout', async (req, reply) => {
if (req.sessionId) await db.delete(schema.sessions).where(eq(schema.sessions.id, req.sessionId));
reply.clearCookie(SESSION_COOKIE, { path: '/' });