574 lines
19 KiB
TypeScript
574 lines
19 KiB
TypeScript
import { PoolClient } from "pg";
|
|
import { config } from "./config";
|
|
import { pool } from "./db";
|
|
import { sendMail } from "./mailer";
|
|
import {
|
|
addDays,
|
|
addHours,
|
|
hashPassword,
|
|
isAdminEmail,
|
|
normalizeEmail,
|
|
randomToken,
|
|
sha256Hex,
|
|
timingSafeEqualHex,
|
|
verifyPassword,
|
|
} from "./security";
|
|
import { anonymizeEmail, securityLog } from "./securityLog";
|
|
|
|
export interface AuthUser {
|
|
id: string;
|
|
email: string;
|
|
emailVerifiedAt: string | null;
|
|
profileUsername: string | null;
|
|
isFutureRacesPublic: boolean;
|
|
isCompletedRacesPublic: boolean;
|
|
isAdmin: boolean;
|
|
}
|
|
|
|
interface UserRow {
|
|
id: string;
|
|
email: string;
|
|
password_hash: string;
|
|
email_verified_at: Date | string | null;
|
|
profile_username: string | null;
|
|
is_future_races_public: boolean;
|
|
is_completed_races_public: boolean;
|
|
}
|
|
|
|
interface SessionRow {
|
|
id: string;
|
|
user_id: string;
|
|
token_hash: string;
|
|
csrf_token_hash: string;
|
|
expires_at: Date | string;
|
|
email: string;
|
|
email_verified_at: Date | string | null;
|
|
profile_username: string | null;
|
|
is_future_races_public: boolean;
|
|
is_completed_races_public: boolean;
|
|
}
|
|
|
|
interface SessionListRow {
|
|
id: string;
|
|
created_at: Date | string;
|
|
last_seen_at: Date | string;
|
|
expires_at: Date | string;
|
|
current: boolean;
|
|
}
|
|
|
|
export interface ActiveSession {
|
|
id: string;
|
|
createdAt: string;
|
|
lastSeenAt: string;
|
|
expiresAt: string;
|
|
current: boolean;
|
|
}
|
|
|
|
function toIso(value: Date | string | null): string | null {
|
|
if (!value) {
|
|
return null;
|
|
}
|
|
return value instanceof Date ? value.toISOString() : String(value);
|
|
}
|
|
|
|
function userFromRow(row: UserRow): AuthUser {
|
|
return {
|
|
id: row.id,
|
|
email: row.email,
|
|
emailVerifiedAt: toIso(row.email_verified_at),
|
|
profileUsername: row.profile_username,
|
|
isFutureRacesPublic: row.is_future_races_public,
|
|
isCompletedRacesPublic: row.is_completed_races_public,
|
|
isAdmin: isAdminEmail(row.email),
|
|
};
|
|
}
|
|
|
|
function appUrl(path: string, token: string): string {
|
|
const url = new URL(path, config.appBaseUrl);
|
|
url.searchParams.set("token", token);
|
|
return url.toString();
|
|
}
|
|
|
|
function isUniqueViolation(error: unknown): boolean {
|
|
return typeof error === "object" && error !== null && (error as { code?: unknown }).code === "23505";
|
|
}
|
|
|
|
export async function findUserByEmail(email: string): Promise<UserRow | null> {
|
|
const normalized = normalizeEmail(email);
|
|
const { rows } = await pool.query<UserRow>(
|
|
`SELECT id, email, password_hash, email_verified_at, profile_username,
|
|
is_future_races_public, is_completed_races_public
|
|
FROM users WHERE LOWER(BTRIM(email)) = $1`,
|
|
[normalized],
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function createVerificationToken(client: PoolClient, userId: string): Promise<string> {
|
|
await client.query(
|
|
"UPDATE email_verification_tokens SET used_at = NOW() WHERE user_id = $1 AND used_at IS NULL",
|
|
[userId],
|
|
);
|
|
const token = randomToken(32);
|
|
await client.query(
|
|
`INSERT INTO email_verification_tokens (user_id, token_hash, expires_at)
|
|
VALUES ($1, $2, $3)`,
|
|
[userId, sha256Hex(token), addHours(new Date(), 24)],
|
|
);
|
|
return token;
|
|
}
|
|
|
|
export async function createResetToken(client: PoolClient, userId: string): Promise<string> {
|
|
await client.query(
|
|
"UPDATE password_reset_tokens SET used_at = NOW() WHERE user_id = $1 AND used_at IS NULL",
|
|
[userId],
|
|
);
|
|
const token = randomToken(32);
|
|
await client.query(
|
|
`INSERT INTO password_reset_tokens (user_id, token_hash, expires_at)
|
|
VALUES ($1, $2, $3)`,
|
|
[userId, sha256Hex(token), addHours(new Date(), 1)],
|
|
);
|
|
return token;
|
|
}
|
|
|
|
export async function sendVerificationEmail(email: string, token: string): Promise<void> {
|
|
await sendMail(
|
|
email,
|
|
"Подтвердите email в Calendar Run",
|
|
`Откройте ссылку для подтверждения email: ${appUrl("/verify-email", token)}`,
|
|
);
|
|
}
|
|
|
|
export async function sendResetEmail(email: string, token: string): Promise<void> {
|
|
await sendMail(
|
|
email,
|
|
"Сброс пароля Calendar Run",
|
|
`Откройте ссылку для сброса пароля: ${appUrl("/reset-password", token)}`,
|
|
);
|
|
}
|
|
|
|
export async function registerUser(email: string, password: string): Promise<void> {
|
|
const normalized = normalizeEmail(email);
|
|
const passwordHash = await hashPassword(password);
|
|
const client = await pool.connect();
|
|
try {
|
|
await client.query("BEGIN");
|
|
let rows: UserRow[];
|
|
try {
|
|
({ rows } = await client.query<UserRow>(
|
|
`INSERT INTO users (email, password_hash)
|
|
VALUES ($1, $2)
|
|
RETURNING id, email, password_hash, email_verified_at, profile_username,
|
|
is_future_races_public, is_completed_races_public`,
|
|
[normalized, passwordHash],
|
|
));
|
|
} catch (error) {
|
|
if (isUniqueViolation(error)) {
|
|
await client.query("ROLLBACK");
|
|
securityLog("register.existing", { emailHash: anonymizeEmail(normalized) });
|
|
return;
|
|
}
|
|
throw error;
|
|
}
|
|
const user = rows[0];
|
|
if (user) {
|
|
const token = await createVerificationToken(client, user.id);
|
|
await client.query("COMMIT");
|
|
await sendVerificationEmail(user.email, token);
|
|
securityLog("register.created", { emailHash: anonymizeEmail(normalized) });
|
|
return;
|
|
}
|
|
await client.query("COMMIT");
|
|
securityLog("register.existing", { emailHash: anonymizeEmail(normalized) });
|
|
} catch (error) {
|
|
await client.query("ROLLBACK");
|
|
throw error;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
export async function createSession(userId: string): Promise<{ sessionToken: string; csrfToken: string; user: AuthUser }> {
|
|
const sessionToken = randomToken(32);
|
|
const csrfToken = randomToken(32);
|
|
const expiresAt = addDays(new Date(), config.session.ttlDays);
|
|
const client = await pool.connect();
|
|
let row: SessionRow;
|
|
try {
|
|
await client.query("BEGIN");
|
|
await client.query("UPDATE users SET last_login_at = NOW() WHERE id = $1", [userId]);
|
|
const { rows } = await client.query<SessionRow>(
|
|
`INSERT INTO sessions (user_id, token_hash, csrf_token_hash, expires_at)
|
|
VALUES ($1, $2, $3, $4)
|
|
RETURNING id, user_id, token_hash, csrf_token_hash, expires_at,
|
|
(SELECT email FROM users WHERE id = $1) AS email,
|
|
(SELECT email_verified_at FROM users WHERE id = $1) AS email_verified_at,
|
|
(SELECT profile_username FROM users WHERE id = $1) AS profile_username,
|
|
(SELECT is_future_races_public FROM users WHERE id = $1) AS is_future_races_public,
|
|
(SELECT is_completed_races_public FROM users WHERE id = $1) AS is_completed_races_public`,
|
|
[userId, sha256Hex(sessionToken), sha256Hex(csrfToken), expiresAt],
|
|
);
|
|
row = rows[0];
|
|
await client.query("COMMIT");
|
|
} catch (error) {
|
|
await client.query("ROLLBACK");
|
|
throw error;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
securityLog("session.issued", { userId });
|
|
return {
|
|
sessionToken,
|
|
csrfToken,
|
|
user: {
|
|
id: row.user_id,
|
|
email: row.email,
|
|
emailVerifiedAt: toIso(row.email_verified_at),
|
|
profileUsername: row.profile_username,
|
|
isFutureRacesPublic: row.is_future_races_public,
|
|
isCompletedRacesPublic: row.is_completed_races_public,
|
|
isAdmin: isAdminEmail(row.email),
|
|
},
|
|
};
|
|
}
|
|
|
|
export async function loginUser(email: string, password: string): Promise<{ ok: false } | { ok: true; sessionToken: string; csrfToken: string; user: AuthUser }> {
|
|
const normalized = normalizeEmail(email);
|
|
const user = await findUserByEmail(normalized);
|
|
const passwordOk = await verifyPassword(user?.password_hash ?? null, password);
|
|
if (!user || !passwordOk || !user.email_verified_at) {
|
|
securityLog("login.failed", { emailHash: anonymizeEmail(normalized) });
|
|
return { ok: false };
|
|
}
|
|
const session = await createSession(user.id);
|
|
securityLog("login.succeeded", { userId: user.id });
|
|
return { ok: true, ...session };
|
|
}
|
|
|
|
export async function revokeSession(sessionToken: string): Promise<void> {
|
|
await pool.query("UPDATE sessions SET revoked_at = NOW() WHERE token_hash = $1", [sha256Hex(sessionToken)]);
|
|
securityLog("session.revoked");
|
|
}
|
|
|
|
export async function listActiveSessions(userId: string, sessionToken: string): Promise<ActiveSession[]> {
|
|
const { rows } = await pool.query<SessionListRow>(
|
|
`SELECT id, created_at, last_seen_at, expires_at, token_hash = $2 AS current
|
|
FROM sessions
|
|
WHERE user_id = $1 AND revoked_at IS NULL AND expires_at > NOW()
|
|
ORDER BY created_at DESC`,
|
|
[userId, sha256Hex(sessionToken)],
|
|
);
|
|
return rows.map((row) => ({
|
|
id: row.id,
|
|
createdAt: toIso(row.created_at)!,
|
|
lastSeenAt: toIso(row.last_seen_at)!,
|
|
expiresAt: toIso(row.expires_at)!,
|
|
current: row.current,
|
|
}));
|
|
}
|
|
|
|
export async function revokeSessionById(userId: string, sessionId: string, sessionToken: string): Promise<{ revoked: boolean; current: boolean }> {
|
|
const { rows } = await pool.query<{ current: boolean }>(
|
|
`UPDATE sessions
|
|
SET revoked_at = NOW()
|
|
WHERE id = $1 AND user_id = $2 AND revoked_at IS NULL AND expires_at > NOW()
|
|
RETURNING token_hash = $3 AS current`,
|
|
[sessionId, userId, sha256Hex(sessionToken)],
|
|
);
|
|
const row = rows[0];
|
|
if (!row) {
|
|
return { revoked: false, current: false };
|
|
}
|
|
securityLog("session.revoked", { userId });
|
|
return { revoked: true, current: row.current };
|
|
}
|
|
|
|
export async function revokeOtherSessions(userId: string, sessionToken: string): Promise<void> {
|
|
await pool.query(
|
|
`UPDATE sessions
|
|
SET revoked_at = NOW()
|
|
WHERE user_id = $1 AND token_hash <> $2 AND revoked_at IS NULL AND expires_at > NOW()`,
|
|
[userId, sha256Hex(sessionToken)],
|
|
);
|
|
securityLog("session.others_revoked", { userId });
|
|
}
|
|
|
|
export async function changePassword(
|
|
userId: string,
|
|
sessionToken: string,
|
|
currentPassword: string,
|
|
newPassword: string,
|
|
): Promise<boolean> {
|
|
const newPasswordHash = await hashPassword(newPassword);
|
|
const client = await pool.connect();
|
|
try {
|
|
await client.query("BEGIN");
|
|
const { rows } = await client.query<{ password_hash: string }>(
|
|
"SELECT password_hash FROM users WHERE id = $1 FOR UPDATE",
|
|
[userId],
|
|
);
|
|
const user = rows[0];
|
|
if (!user || !(await verifyPassword(user.password_hash, currentPassword))) {
|
|
await client.query("ROLLBACK");
|
|
return false;
|
|
}
|
|
await client.query("UPDATE users SET password_hash = $2, updated_at = NOW() WHERE id = $1", [userId, newPasswordHash]);
|
|
await client.query(
|
|
"UPDATE sessions SET revoked_at = NOW() WHERE user_id = $1 AND token_hash <> $2 AND revoked_at IS NULL",
|
|
[userId, sha256Hex(sessionToken)],
|
|
);
|
|
await client.query("COMMIT");
|
|
securityLog("password.changed", { userId });
|
|
return true;
|
|
} catch (error) {
|
|
await client.query("ROLLBACK");
|
|
throw error;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
export async function rotateCsrf(sessionToken: string): Promise<string | null> {
|
|
const csrfToken = randomToken(32);
|
|
const { rowCount } = await pool.query(
|
|
`UPDATE sessions
|
|
SET csrf_token_hash = $2, last_seen_at = NOW()
|
|
WHERE token_hash = $1 AND revoked_at IS NULL AND expires_at > NOW()`,
|
|
[sha256Hex(sessionToken), sha256Hex(csrfToken)],
|
|
);
|
|
return rowCount && rowCount > 0 ? csrfToken : null;
|
|
}
|
|
|
|
export async function getSession(sessionToken: string): Promise<{ user: AuthUser; csrfTokenHash: string } | null> {
|
|
const tokenHash = sha256Hex(sessionToken);
|
|
const { rows } = await pool.query<SessionRow>(
|
|
`SELECT s.id, s.user_id, s.token_hash, s.csrf_token_hash, s.expires_at, u.email, u.email_verified_at,
|
|
u.profile_username, u.is_future_races_public, u.is_completed_races_public
|
|
FROM sessions s
|
|
JOIN users u ON u.id = s.user_id
|
|
WHERE s.token_hash = $1 AND s.revoked_at IS NULL AND s.expires_at > NOW()`,
|
|
[tokenHash],
|
|
);
|
|
const row = rows[0];
|
|
if (!row) {
|
|
return null;
|
|
}
|
|
await pool.query("UPDATE sessions SET last_seen_at = NOW(), expires_at = $2 WHERE id = $1", [
|
|
row.id,
|
|
addDays(new Date(), config.session.ttlDays),
|
|
]);
|
|
return {
|
|
user: {
|
|
id: row.user_id,
|
|
email: row.email,
|
|
emailVerifiedAt: toIso(row.email_verified_at),
|
|
profileUsername: row.profile_username,
|
|
isFutureRacesPublic: row.is_future_races_public,
|
|
isCompletedRacesPublic: row.is_completed_races_public,
|
|
isAdmin: isAdminEmail(row.email),
|
|
},
|
|
csrfTokenHash: row.csrf_token_hash,
|
|
};
|
|
}
|
|
|
|
export async function updateProfile(
|
|
userId: string,
|
|
profile: {
|
|
profileUsername?: string | null;
|
|
isFutureRacesPublic?: boolean;
|
|
isCompletedRacesPublic?: boolean;
|
|
},
|
|
): Promise<void> {
|
|
await pool.query(
|
|
`UPDATE users SET
|
|
profile_username = CASE WHEN $2 THEN $3 ELSE profile_username END,
|
|
is_future_races_public = CASE WHEN $4 THEN $5 ELSE is_future_races_public END,
|
|
is_completed_races_public = CASE WHEN $6 THEN $7 ELSE is_completed_races_public END,
|
|
updated_at = NOW()
|
|
WHERE id = $1`,
|
|
[
|
|
userId,
|
|
profile.profileUsername !== undefined,
|
|
profile.profileUsername,
|
|
profile.isFutureRacesPublic !== undefined,
|
|
profile.isFutureRacesPublic,
|
|
profile.isCompletedRacesPublic !== undefined,
|
|
profile.isCompletedRacesPublic,
|
|
],
|
|
);
|
|
}
|
|
|
|
export function csrfMatches(hash: string, token: string): boolean {
|
|
return timingSafeEqualHex(hash, sha256Hex(token));
|
|
}
|
|
|
|
export async function verifyEmailToken(token: string): Promise<boolean> {
|
|
const tokenHash = sha256Hex(token);
|
|
const client = await pool.connect();
|
|
try {
|
|
await client.query("BEGIN");
|
|
const { rows } = await client.query<{ id: string; user_id: string; token_hash: string }>(
|
|
`SELECT id, user_id, token_hash
|
|
FROM email_verification_tokens
|
|
WHERE token_hash = $1 AND used_at IS NULL AND expires_at > NOW()
|
|
FOR UPDATE`,
|
|
[tokenHash],
|
|
);
|
|
const row = rows.find((candidate) => timingSafeEqualHex(candidate.token_hash, tokenHash));
|
|
if (!row) {
|
|
await client.query("ROLLBACK");
|
|
return false;
|
|
}
|
|
const consumed = await client.query(
|
|
"UPDATE email_verification_tokens SET used_at = NOW() WHERE id = $1 AND used_at IS NULL RETURNING id",
|
|
[row.id],
|
|
);
|
|
if (consumed.rowCount === 0) {
|
|
await client.query("ROLLBACK");
|
|
return false;
|
|
}
|
|
await client.query(
|
|
"UPDATE email_verification_tokens SET used_at = NOW() WHERE user_id = $1 AND id <> $2 AND used_at IS NULL",
|
|
[row.user_id, row.id],
|
|
);
|
|
await client.query("UPDATE users SET email_verified_at = COALESCE(email_verified_at, NOW()), updated_at = NOW() WHERE id = $1", [row.user_id]);
|
|
await client.query("SELECT pg_advisory_xact_lock(706365)");
|
|
const claimed = await client.query("SELECT value FROM app_settings WHERE key = 'orphan_races_claimed_by_user_id' FOR UPDATE");
|
|
if (claimed.rows.length === 0) {
|
|
await client.query("UPDATE races SET owner_user_id = $1, updated_at = NOW() WHERE owner_user_id IS NULL", [row.user_id]);
|
|
await client.query(
|
|
`INSERT INTO app_settings (key, value)
|
|
VALUES ('orphan_races_claimed_by_user_id', $1)`,
|
|
[row.user_id],
|
|
);
|
|
}
|
|
await client.query("COMMIT");
|
|
securityLog("email.verified", { userId: row.user_id });
|
|
return true;
|
|
} catch (error) {
|
|
await client.query("ROLLBACK");
|
|
throw error;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
export async function requestPasswordReset(email: string): Promise<void> {
|
|
const normalized = normalizeEmail(email);
|
|
const client = await pool.connect();
|
|
try {
|
|
await client.query("BEGIN");
|
|
const { rows } = await client.query<UserRow>(
|
|
`SELECT id, email, password_hash, email_verified_at, profile_username,
|
|
is_future_races_public, is_completed_races_public
|
|
FROM users WHERE LOWER(BTRIM(email)) = $1 FOR UPDATE`,
|
|
[normalized],
|
|
);
|
|
const user = rows[0];
|
|
if (!user) {
|
|
await client.query("COMMIT");
|
|
securityLog("password_reset.requested_missing", { emailHash: anonymizeEmail(normalized) });
|
|
return;
|
|
}
|
|
const token = await createResetToken(client, user.id);
|
|
await client.query("COMMIT");
|
|
await sendResetEmail(user.email, token);
|
|
securityLog("password_reset.requested", { userId: user.id });
|
|
} catch (error) {
|
|
await client.query("ROLLBACK");
|
|
throw error;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
export async function resetPassword(token: string, password: string): Promise<boolean> {
|
|
const tokenHash = sha256Hex(token);
|
|
const passwordHash = await hashPassword(password);
|
|
const client = await pool.connect();
|
|
try {
|
|
await client.query("BEGIN");
|
|
const { rows } = await client.query<{ id: string; user_id: string; token_hash: string }>(
|
|
`SELECT id, user_id, token_hash
|
|
FROM password_reset_tokens
|
|
WHERE token_hash = $1 AND used_at IS NULL AND expires_at > NOW()
|
|
FOR UPDATE`,
|
|
[tokenHash],
|
|
);
|
|
const row = rows.find((candidate) => timingSafeEqualHex(candidate.token_hash, tokenHash));
|
|
if (!row) {
|
|
await client.query("ROLLBACK");
|
|
return false;
|
|
}
|
|
const consumed = await client.query(
|
|
"UPDATE password_reset_tokens SET used_at = NOW() WHERE id = $1 AND used_at IS NULL RETURNING id",
|
|
[row.id],
|
|
);
|
|
if (consumed.rowCount === 0) {
|
|
await client.query("ROLLBACK");
|
|
return false;
|
|
}
|
|
await client.query(
|
|
"UPDATE password_reset_tokens SET used_at = NOW() WHERE user_id = $1 AND id <> $2 AND used_at IS NULL",
|
|
[row.user_id, row.id],
|
|
);
|
|
await client.query("UPDATE users SET password_hash = $2, updated_at = NOW() WHERE id = $1", [row.user_id, passwordHash]);
|
|
await client.query("UPDATE sessions SET revoked_at = NOW() WHERE user_id = $1 AND revoked_at IS NULL", [row.user_id]);
|
|
await client.query("COMMIT");
|
|
securityLog("password_reset.completed", { userId: row.user_id });
|
|
return true;
|
|
} catch (error) {
|
|
await client.query("ROLLBACK");
|
|
throw error;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
export async function resendVerification(email: string): Promise<void> {
|
|
const normalized = normalizeEmail(email);
|
|
const client = await pool.connect();
|
|
try {
|
|
await client.query("BEGIN");
|
|
const { rows } = await client.query<UserRow>(
|
|
`SELECT id, email, password_hash, email_verified_at, profile_username,
|
|
is_future_races_public, is_completed_races_public
|
|
FROM users WHERE LOWER(BTRIM(email)) = $1 FOR UPDATE`,
|
|
[normalized],
|
|
);
|
|
const user = rows[0];
|
|
if (!user || user.email_verified_at) {
|
|
await client.query("COMMIT");
|
|
return;
|
|
}
|
|
const token = await createVerificationToken(client, user.id);
|
|
await client.query("COMMIT");
|
|
await sendVerificationEmail(user.email, token);
|
|
} catch (error) {
|
|
await client.query("ROLLBACK");
|
|
throw error;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
export async function cleanupExpiredAuthRows(): Promise<void> {
|
|
await pool.query("DELETE FROM sessions WHERE expires_at <= NOW() OR revoked_at < NOW() - INTERVAL '30 days'");
|
|
await pool.query("DELETE FROM email_verification_tokens WHERE expires_at <= NOW() OR used_at IS NOT NULL");
|
|
await pool.query("DELETE FROM password_reset_tokens WHERE expires_at <= NOW() OR used_at IS NOT NULL");
|
|
}
|
|
|
|
export function startAuthCleanupSchedule(intervalHours = config.authCleanupIntervalHours): NodeJS.Timeout {
|
|
const runCleanup = () => {
|
|
void cleanupExpiredAuthRows().catch((error) => {
|
|
console.error("[auth-cleanup] Failed:", error);
|
|
});
|
|
};
|
|
runCleanup();
|
|
const safeHours = Number.isFinite(intervalHours) && intervalHours > 0 ? intervalHours : 24;
|
|
const timer = setInterval(runCleanup, safeHours * 60 * 60 * 1000);
|
|
timer.unref?.();
|
|
return timer;
|
|
}
|