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
+10
View File
@@ -0,0 +1,10 @@
CREATE TABLE "password_resets" (
"id" text PRIMARY KEY NOT NULL,
"user_id" uuid NOT NULL,
"expires_at" timestamp with time zone NOT NULL,
"used_at" timestamp with time zone,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "password_resets" ADD CONSTRAINT "password_resets_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "password_resets_user_idx" ON "password_resets" USING btree ("user_id");
File diff suppressed because it is too large Load Diff
+7
View File
@@ -78,6 +78,13 @@
"when": 1791257078479,
"tag": "0010_avatars",
"breakpoints": true
},
{
"idx": 11,
"version": "7",
"when": 1791262411052,
"tag": "0011_password_resets",
"breakpoints": true
}
]
}
+2
View File
@@ -31,6 +31,7 @@
"drizzle-orm": "^0.45.3",
"fastify": "^5.12.5",
"ioredis": "^6.0.0",
"nodemailer": "^10.0.15",
"postgres": "^3.4.9",
"sharp": "^0.35.5",
"undici": "^6.29.0",
@@ -38,6 +39,7 @@
},
"devDependencies": {
"@types/node": "^26.6.4",
"@types/nodemailer": "^8.0.2",
"@types/ws": "^8.18.2",
"concurrently": "^10.0.5",
"drizzle-kit": "^0.31.11",
+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: '/' });
+1 -1
View File
@@ -17,7 +17,7 @@ function assertTestTargets() {
export async function resetState() {
assertTestTargets();
await sql`truncate users, tracks, track_links, sessions, follows, connections, now_playing, featured_songs, listens, devices, blocks, reports, avatars restart identity cascade`;
await sql`truncate users, tracks, track_links, sessions, follows, connections, now_playing, featured_songs, listens, devices, blocks, reports, avatars, password_resets restart identity cascade`;
await redis.flushdb();
}
+84
View File
@@ -0,0 +1,84 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { outbox } from '../src/lib/mail';
import { bearer, createUser, useTestApp } from './helpers';
const app = useTestApp();
beforeEach(() => {
outbox.length = 0;
});
/** The email is sent in the background; give it a moment. */
async function nextMail() {
for (let i = 0; i < 50 && outbox.length === 0; i++) await new Promise((r) => setTimeout(r, 10));
return outbox.at(-1);
}
const tokenFrom = (text: string) => new URL(text.match(/http\S+/)![0]).searchParams.get('token')!;
async function requestReset(email: string) {
return app().inject({ method: 'POST', url: '/auth/forgot-password', payload: { email } });
}
describe('password reset', () => {
it('emails a link that sets a new password, signs out other sessions and signs in', async () => {
const { token: oldSession } = await createUser(app(), 'alice');
expect((await requestReset(' ALICE@example.com ')).json()).toEqual({ ok: true });
const mail = await nextMail();
expect(mail).toMatchObject({ to: 'alice@example.com', subject: 'Reset your musicshare password' });
expect(mail!.text).toContain('http://web.test/reset-password?token=');
expect(mail!.html).toContain('Choose a new password');
const res = await app().inject({
method: 'POST',
url: '/auth/reset-password',
payload: { token: tokenFrom(mail!.text), password: 'brand-new-pass' },
});
expect(res.statusCode).toBe(200);
expect(res.json().user.username).toBe('alice');
expect((await app().inject({ url: '/me', headers: bearer(oldSession) })).statusCode).toBe(401);
const login = await app().inject({
method: 'POST',
url: '/auth/login',
payload: { email: 'alice@example.com', password: 'brand-new-pass' },
});
expect(login.statusCode).toBe(200);
});
it("doesn't reveal whether an email has an account", async () => {
const res = await requestReset('nobody@example.com');
expect(res.json()).toEqual({ ok: true });
await new Promise((r) => setTimeout(r, 100));
expect(outbox).toHaveLength(0);
});
it('links work once, and a new request replaces the old link', async () => {
await createUser(app(), 'alice');
await requestReset('alice@example.com');
const first = tokenFrom((await nextMail())!.text);
outbox.length = 0;
await requestReset('alice@example.com');
const second = tokenFrom((await nextMail())!.text);
const reset = (token: string) =>
app().inject({ method: 'POST', url: '/auth/reset-password', payload: { token, password: 'another-pass-1' } });
expect((await reset(first)).statusCode).toBe(400);
expect((await reset(second)).statusCode).toBe(200);
const again = await reset(second);
expect(again.statusCode).toBe(400);
expect(again.json().error).toMatch(/expired or was already used/);
});
it('rejects short passwords', async () => {
await createUser(app(), 'alice');
await requestReset('alice@example.com');
const res = await app().inject({
method: 'POST',
url: '/auth/reset-password',
payload: { token: tokenFrom((await nextMail())!.text), password: 'short' },
});
expect(res.statusCode).toBe(400);
expect(res.json().error).toMatch(/at least 8/);
});
});
+2
View File
@@ -22,6 +22,8 @@ const testEnv = {
SPOTIFY_CLIENT_ID: 'test-spotify-id',
SPOTIFY_CLIENT_SECRET: 'test-spotify-secret',
ODESLI_API_KEY: '',
// Never send real email from tests (apps/api/.env may hold real SMTP settings).
SMTP_HOST: '',
APPLE_TEAM_ID: 'TEAMID1234',
APPLE_MUSICKIT_KEY_ID: 'KEYID12345',
APPLE_MUSICKIT_PRIVATE_KEY: appleKey.privateKey.export({ type: 'pkcs8', format: 'pem' }).toString().replace(/\n/g, '\\n'),