Spaces:
Runtime error
Runtime error
Andrew commited on
Commit ·
6900c11
1
Parent(s): d6e0230
Remove username/password login, keep only HuggingFace OAuth
Browse filesFiles changed (7)
5 unmodified lines67891011121314153 unmodified lines1920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823835 unmodified linesimport Modal from "$lib/components/Modal.svelte";import { cookiesAreEnabled } from "$lib/utils/cookiesAreEnabled";import Logo from "./icons/Logo.svelte";import CarbonCopy from "~icons/carbon/copy";import CarbonCheckmark from "~icons/carbon/checkmark";import CarbonView from "~icons/carbon/view";import CarbonViewOff from "~icons/carbon/view-off";import { usePublicConfig } from "$lib/utils/PublicConfig.svelte";const publicConfig = usePublicConfig();3 unmodified lines}let { onclose }: Props = $props();let showPasswordForm = $state(false);let isRegistering = $state(false);let isRecovering = $state(false);let passwordErrorMessage = $state("");let passwordSuccessMessage = $state("");let isSubmitting = $state(false);let recoveryKey = $state("");let recoveryKeyCopied = $state(false);let passwordVisible = $state(false);let passwordInput = $state("");let usernameInput = $state("");async function handlePasswordSubmit(event: SubmitEvent) {event.preventDefault();if (isSubmitting) return;if (!cookiesAreEnabled()) {window.open(window.location.href, "_blank");return;}isSubmitting = true;passwordErrorMessage = "";passwordSuccessMessage = "";const formData = new FormData(event.target as HTMLFormElement);const body = Object.fromEntries(formData.entries());try {if (isRecovering) {const response = await fetch(`${base}/login/recover`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify(body),});if (response.ok) {const data = await response.json();if (data.newRecoveryKey) {isRecovering = false;recoveryKey = data.newRecoveryKey;passwordSuccessMessage = "Password reset successfully. Please save your NEW recovery key.";} else {isRecovering = false;isRegistering = false;passwordSuccessMessage = "Password reset successfully. Please sign in.";}} else {const result = await response.json();passwordErrorMessage = result.message || "Recovery failed";}} else if (isRegistering) {const response = await fetch(`${base}/login/register`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify(body),});if (response.ok) {const data = await response.json();recoveryKey = data.recoveryKey;} else {const result = await response.json();passwordErrorMessage = result.message || "Registration failed";}} else {const response = await fetch(`${base}/login/password`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify(body),});if (response.ok) {window.location.href = `${base}/`;} else {const result = await response.json();passwordErrorMessage = result.message || "Invalid username or password";}}} catch (e) {console.error(e);passwordErrorMessage = "An error occurred. Please try again.";} finally {isSubmitting = false;}}function handleCopyRecoveryKey() {navigator.clipboard.writeText(recoveryKey);recoveryKeyCopied = true;}function handleCloseRecoveryModal() {if (passwordSuccessMessage && passwordSuccessMessage.includes("NEW recovery key")) {recoveryKey = "";recoveryKeyCopied = false;isRecovering = false;isRegistering = false;passwordSuccessMessage = "Password updated successfully. Please sign in with your new password.";} else {window.location.href = `${base}/`;}}</script><Modal onclose={() => onclose?.()} width="!max-w-[400px] !m-4"><divclass="from-primary-500/40 via-primary-500/10 to-primary-500/0 flex w-full flex-col items-center gap-6 bg-gradient-to-b px-5 pb-8 pt-9 text-center"><h2 class="flex items-center text-2xl font-semibold text-gray-800"><Logo classNames="mr-1" />{publicConfig.PUBLIC_APP_NAME}</h2>{#if recoveryKey}<div class="flex w-full flex-col items-center gap-4"><h3 class="text-xl font-semibold text-gray-800">{#if passwordSuccessMessage && passwordSuccessMessage.includes("NEW recovery key")}Password Updated!{:else}Account Created!{/if}</h3><p class="text-sm text-gray-600 text-balance">{#if passwordSuccessMessage && passwordSuccessMessage.includes("NEW recovery key")}Your password has been updated.<br/><br/>Your old recovery key has been invalidated. <strong>Save this NEW key safely.</strong> It is now the ONLY way to recover your account.{:else}Save this Recovery Key safely. <strong>It is the ONLY way to recover your account</strong> if you forget your password.{/if}</p><div class="flex w-full items-center gap-2 rounded-md border border-gray-200 bg-gray-50 p-2"><code class="flex-1 break-all font-mono text-sm text-gray-800">{recoveryKey}</code><buttononclick={handleCopyRecoveryKey}class="flex h-8 w-8 flex-none items-center justify-center rounded-md text-gray-500 hover:bg-gray-200 hover:text-black transition-colors"title="Copy Recovery Key">{#if recoveryKeyCopied}<CarbonCheckmark class="text-green-600" />{:else}<CarbonCopy />{/if}</button></div><buttononclick={handleCloseRecoveryModal}disabled={!recoveryKeyCopied}class="mt-2 w-full rounded-full bg-black px-5 py-2 text-lg font-semibold text-gray-100 transition-colors hover:bg-gray-900 disabled:cursor-not-allowed disabled:opacity-50">I have saved my key</button></div>{:else}<div class="flex w-full flex-col items-center gap-3">{#if page.data.loginRequired}<ahref="{base}/login"class="flex w-full flex-wrap items-center justify-center whitespace-nowrap rounded-full bg-black px-5 py-2 text-center text-lg font-semibold text-gray-100 transition-colors hover:bg-gray-900">Sign in with<span class="flex items-center"> <LogoHuggingFaceBorderless classNames="text-xl mr-1" /> Hugging Face</span></a>{#if !showPasswordForm}<buttontype="button"onclick={() => {showPasswordForm = true;isRegistering = false;isRecovering = false;passwordInput = "";passwordErrorMessage = "";passwordSuccessMessage = "";}}class="flex w-full items-center justify-center whitespace-nowrap rounded-full border-2 border-black bg-white px-5 py-2 text-lg font-semibold text-gray-800 transition-colors hover:bg-gray-100">Sign in with username/password</button>{/if}{#if showPasswordForm}<formonsubmit={handlePasswordSubmit}class="flex w-full flex-col gap-2 rounded-xl border border-gray-200 bg-white/80 p-3 text-left shadow-sm"><div class="mb-2 text-center"><h3 class="text-lg font-semibold">{#if isRecovering}Reset Password{:else if isRegistering}Create Account{:else}Sign In{/if}</h3></div><label class="text-sm font-medium text-gray-700">Username<inputtype="text"name="username"autocomplete="username"requiredbind:value={usernameInput}class="mt-1 w-full rounded-md border border-gray-300 px-3 py-2 text-base text-gray-900 focus:border-black focus:outline-none focus:ring-2 focus:ring-black/50"/></label>{#if isRecovering}<label class="text-sm font-medium text-gray-700">Recovery Key<inputtype="text"name="recoveryKey"autocomplete="off"requiredclass="mt-1 w-full rounded-md border border-gray-300 px-3 py-2 text-base text-gray-900 focus:border-black focus:outline-none focus:ring-2 focus:ring-black/50"/></label><label class="text-sm font-medium text-gray-700">New Password<div class="relative mt-1"><inputtype={passwordVisible ? "text" : "password"}name="newPassword"autocomplete="new-password"requiredminlength="8"bind:value={passwordInput}class="w-full rounded-md border border-gray-300 pl-3 pr-20 py-2 text-base text-gray-900 focus:border-black focus:outline-none focus:ring-2 focus:ring-black/50"/><div class="absolute right-2 top-1/2 -translate-y-1/2 flex items-center gap-1"><buttontype="button"class="p-1 text-gray-500 hover:text-black"onclick={() => (passwordVisible = !passwordVisible)}title={passwordVisible ? "Hide password" : "Show password"}>{#if passwordVisible}<CarbonViewOff />{:else}<CarbonView />{/if}</button></div></div></label>{:else}{#if isRegistering}<label class="text-sm font-medium text-gray-700">Email (Optional)<inputtype="email"name="email"autocomplete="email"class="mt-1 w-full rounded-md border border-gray-300 px-3 py-2 text-base text-gray-900 focus:border-black focus:outline-none focus:ring-2 focus:ring-black/50"/></label>{/if}<label class="text-sm font-medium text-gray-700">Password<div class="relative mt-1"><inputtype={passwordVisible ? "text" : "password"}name="password"autocomplete={isRegistering ? "new-password" : "current-password"}requiredminlength="8"bind:value={passwordInput}class="w-full rounded-md border border-gray-300 pl-3 pr-20 py-2 text-base text-gray-900 focus:border-black focus:outline-none focus:ring-2 focus:ring-black/50"/><div class="absolute right-2 top-1/2 -translate-y-1/2 flex items-center gap-1"><buttontype="button"class="p-1 text-gray-500 hover:text-black"onclick={() => (passwordVisible = !passwordVisible)}title={passwordVisible ? "Hide password" : "Show password"}>{#if passwordVisible}<CarbonViewOff />{:else}<CarbonView />{/if}</button></div></div></label>{/if}{#if passwordErrorMessage}<p class="text-sm text-red-600">{passwordErrorMessage}</p>{/if}{#if passwordSuccessMessage}<p class="text-sm text-green-600">{passwordSuccessMessage}</p>{/if}<buttontype="submit"disabled={isSubmitting}class="mt-1 flex w-full items-center justify-center whitespace-nowrap rounded-full bg-black px-4 py-2 text-lg font-semibold text-gray-100 transition-colors hover:bg-gray-900 disabled:cursor-not-allowed disabled:bg-gray-500">{#if isSubmitting}Submitting...{:else}{#if isRecovering}Reset Password{:else if isRegistering}Create Account{:else}Sign In{/if}{/if}</button>{#if !isRecovering && !isRegistering}<div class="mt-1 text-center"><button type="button" onclick={() => { isRecovering = true; isRegistering = false; passwordInput = ""; passwordErrorMessage = ""; passwordSuccessMessage = ""; }} class="text-sm text-gray-500 hover:underline">Forgot Password?</button></div>{/if}<div class="mt-2 text-center text-sm text-gray-600">{#if isRecovering}Remember it? <button type="button" onclick={() => { isRecovering = false; passwordInput = ""; passwordErrorMessage = ""; passwordSuccessMessage = ""; }} class="font-semibold underline">Sign in</button>{:else if isRegistering}Already have an account? <button type="button" onclick={() => { isRegistering = false; passwordInput = ""; passwordErrorMessage = ""; passwordSuccessMessage = ""; }} class="font-semibold underline">Sign in</button>{:else}Don't have an account? <button type="button" onclick={() => { isRegistering = true; passwordInput = ""; passwordErrorMessage = ""; passwordSuccessMessage = ""; }} class="font-semibold underline">Create one</button>{/if}</div></form>{/if}{:else}<buttonclass="flex w-full items-center justify-center whitespace-nowrap rounded-full border-2 border-black bg-black px-5 py-2 text-lg font-semibold text-gray-100 transition-colors hover:bg-gray-900"onclick={(e) => {if (!cookiesAreEnabled()) {e.preventDefault();window.open(window.location.href, "_blank");}onclose?.();}}>Start chatting</button>{/if}</div>{/if}</div></Modal>5 unmodified lines678910113 unmodified lines1516171819202122232425262728293031323334353637383940414243444546474849505152535455565 unmodified linesimport Modal from "$lib/components/Modal.svelte";import { cookiesAreEnabled } from "$lib/utils/cookiesAreEnabled";import Logo from "./icons/Logo.svelte";import { usePublicConfig } from "$lib/utils/PublicConfig.svelte";const publicConfig = usePublicConfig();3 unmodified lines}let { onclose }: Props = $props();</script><Modal onclose={() => onclose?.()} width="!max-w-[400px] !m-4"><divclass="from-primary-500/40 via-primary-500/10 to-primary-500/0 flex w-full flex-col items-center gap-6 bg-gradient-to-b px-5 pb-8 pt-9 text-center"><h2 class="flex items-center text-2xl font-semibold text-gray-800 dark:text-gray-200"><Logo classNames="mr-1" />{publicConfig.PUBLIC_APP_NAME}</h2><div class="flex w-full flex-col items-center gap-3">{#if page.data.loginRequired}<ahref="{base}/login"class="flex w-full flex-wrap items-center justify-center whitespace-nowrap rounded-full bg-black px-5 py-2 text-center text-lg font-semibold text-gray-100 transition-colors hover:bg-gray-900 dark:bg-white dark:text-black dark:hover:bg-gray-200">Sign in with<span class="flex items-center"> <LogoHuggingFaceBorderless classNames="text-xl mr-1" /> Hugging Face</span></a>{:else}<buttonclass="flex w-full items-center justify-center whitespace-nowrap rounded-full border-2 border-black bg-black px-5 py-2 text-lg font-semibold text-gray-100 transition-colors hover:bg-gray-900 dark:bg-white dark:text-black dark:hover:bg-gray-200"onclick={(e) => {if (!cookiesAreEnabled()) {e.preventDefault();window.open(window.location.href, "_blank");}onclose?.();}}>Start chatting</button>{/if}</div></div></Modal>
123456789101112131415161718192021222324252627282930313233import { scrypt, randomBytes, timingSafeEqual } from "node:crypto";import { promisify } from "util";
const scryptAsync = promisify(scrypt);
/** * Hashes a password using scrypt with a random salt. * Returns the salt and hash combined as a string. */export async function hashPassword(password: string): Promise<string> { const salt = randomBytes(16).toString("hex"); const derivedKey = (await scryptAsync(password, salt, 64)) as Buffer; return `${salt}:${derivedKey.toString("hex")}`;}
/** * Verifies a password against a stored hash (salt:hash). */export async function verifyPassword(password: string, storedHash: string): Promise<boolean> { const [salt, key] = storedHash.split(":"); if (!salt || !key) return false;
const keyBuffer = Buffer.from(key, "hex"); const derivedKey = (await scryptAsync(password, salt, 64)) as Buffer; return timingSafeEqual(keyBuffer, derivedKey);}
/** * Generates a secure random recovery key. */export function generateRecoveryKey(): string { return `rk-${randomBytes(24).toString("hex")}`;}123456710 unmodified lines181920212223242526import type { ObjectId } from "mongodb";import type { Timestamps } from "./Timestamps";export type AuthProvider = "huggingface" | "password" | "oidc";export interface User extends Timestamps {_id: ObjectId;10 unmodified lines// Legacy field for backward compatibility (maps to authId when authProvider is "huggingface")hfUserId?: string;passwordHash?: string;recoveryKeyHash?: string;isAdmin?: boolean;isEarlyAccess?: boolean;}123456710 unmodified lines181920212223import type { ObjectId } from "mongodb";import type { Timestamps } from "./Timestamps";export type AuthProvider = "huggingface" | "oidc";export interface User extends Timestamps {_id: ObjectId;10 unmodified lines// Legacy field for backward compatibility (maps to authId when authProvider is "huggingface")hfUserId?: string;isAdmin?: boolean;isEarlyAccess?: boolean;}
18 unmodified lines192021222324252663 unmodified lines909192939495969739 unmodified lines13713813914014114214314418 unmodified linesavatarUrl?: string;isAdmin?: boolean;isEarlyAccess?: boolean;passwordHash?: string;recoveryKeyHash?: string;}export async function updateUserSession(params: {63 unmodified linesisAdmin: userData.isAdmin,isEarlyAccess: userData.isEarlyAccess,...(userData.authProvider === "huggingface" ? { hfUserId: userData.authId } : {}),...(userData.passwordHash ? { passwordHash: userData.passwordHash } : {}),...(userData.recoveryKeyHash ? { recoveryKeyHash: userData.recoveryKeyHash } : {}),};if (existingUser) {39 unmodified linesauthId: userData.authId,email: userData.email,...(userData.authProvider === "huggingface" ? { hfUserId: userData.authId } : {}),...(userData.passwordHash ? { passwordHash: userData.passwordHash } : {}),...(userData.recoveryKeyHash ? { recoveryKeyHash: userData.recoveryKeyHash } : {}),});userId = insertedId;18 unmodified lines19202122232463 unmodified lines88899091929339 unmodified lines13313413513613713818 unmodified linesavatarUrl?: string;isAdmin?: boolean;isEarlyAccess?: boolean;}export async function updateUserSession(params: {63 unmodified linesisAdmin: userData.isAdmin,isEarlyAccess: userData.isEarlyAccess,...(userData.authProvider === "huggingface" ? { hfUserId: userData.authId } : {}),};if (existingUser) {39 unmodified linesauthId: userData.authId,email: userData.email,...(userData.authProvider === "huggingface" ? { hfUserId: userData.authId } : {}),});userId = insertedId;
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273import { json } from "@sveltejs/kit";import { z } from "zod";import { updateUserSession } from "../callback/userSession";import { collections } from "$lib/server/database";import { verifyPassword } from "$lib/server/passwords";
function escapeRegExp(string: string) { return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");}
export async function POST({ request, locals, cookies, getClientAddress }) { let body: Record<string, unknown> = {}; const contentType = request.headers.get("content-type") ?? "";
if (contentType.includes("application/json")) { body = await request.json(); } else { const formData = await request.formData(); body = Object.fromEntries(formData.entries()); }
const { username, password } = z .object({ username: z.string().min(1), password: z.string().min(1), }) .parse(body);
const identifier = username.trim();
// Find user by username or email const user = await collections.users.findOne({ $or: [ { username: { $regex: new RegExp(`^${escapeRegExp(identifier)}$`, "i") } }, { email: { $regex: new RegExp(`^${escapeRegExp(identifier)}$`, "i") } }, ], });
if (!user || !user.passwordHash) { return json({ message: "Invalid username or password" }, { status: 401 }); }
let isValid = false; try { isValid = await verifyPassword(password, user.passwordHash); } catch (e) { console.error("Error verifying password:", e); return json({ message: "Invalid username or password" }, { status: 401 }); }
if (!isValid) { return json({ message: "Invalid username or password" }, { status: 401 }); }
await updateUserSession({ userData: { authProvider: "password", authId: user.username || user.email || identifier, // Use username as authId if available username: user.username, name: user.name, email: user.email, avatarUrl: user.avatarUrl, isAdmin: user.isAdmin, isEarlyAccess: user.isEarlyAccess, }, locals, cookies, userAgent: request.headers.get("user-agent") ?? undefined, ip: getClientAddress(), });
return json({ message: "Success" });}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455import { json } from "@sveltejs/kit";import { z } from "zod";import { collections } from "$lib/server/database";import { verifyPassword, hashPassword, generateRecoveryKey } from "$lib/server/passwords";
function escapeRegExp(string: string) { return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");}
export async function POST({ request }) { const body = await request.json(); const { username, recoveryKey, newPassword } = z .object({ username: z.string().min(1).trim(), recoveryKey: z.string().min(1), newPassword: z.string().min(8), }) .parse(body);
const user = await collections.users.findOne({ username: { $regex: new RegExp(`^${escapeRegExp(username)}$`, "i") }, });
if (!user || !user.recoveryKeyHash) { return json({ message: "Invalid username or recovery key" }, { status: 401 }); }
let isValid = false; try { isValid = await verifyPassword(recoveryKey, user.recoveryKeyHash); } catch (e) { console.error("Error verifying recovery key:", e); return json({ message: "Invalid username or recovery key" }, { status: 401 }); }
if (!isValid) { return json({ message: "Invalid username or recovery key" }, { status: 401 }); }
const passwordHash = await hashPassword(newPassword);
// Rotate the recovery key after successful use const newRecoveryKey = generateRecoveryKey(); const newRecoveryKeyHash = await hashPassword(newRecoveryKey);
await collections.users.updateOne( { _id: user._id }, { $set: { passwordHash, recoveryKeyHash: newRecoveryKeyHash, updatedAt: new Date() } } );
return json({ message: "Password updated successfully. A new recovery key has been generated.", newRecoveryKey, });}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758import { json } from "@sveltejs/kit";import { z } from "zod";import { collections } from "$lib/server/database";import { hashPassword, generateRecoveryKey } from "$lib/server/passwords";import { updateUserSession } from "../callback/userSession";
function escapeRegExp(string: string) { return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");}
export async function POST({ request, locals, cookies, getClientAddress }) { const body = await request.json();
const { username, password, email } = z .object({ username: z.string().min(1).trim(), password: z.string().min(8), email: z .union([z.string().email(), z.literal("")]) .optional() .transform((e) => (e === "" ? undefined : e)), }) .parse(body);
// Check if user already exists const existingUser = await collections.users.findOne({ $or: [ { username: { $regex: new RegExp(`^${escapeRegExp(username)}$`, "i") } }, ...(email ? [{ email: { $regex: new RegExp(`^${escapeRegExp(email)}$`, "i") } }] : []), ], });
if (existingUser) { return json({ message: "User already exists" }, { status: 409 }); }
const recoveryKey = generateRecoveryKey(); const passwordHash = await hashPassword(password); const recoveryKeyHash = await hashPassword(recoveryKey); // Hash recovery key same way as password
await updateUserSession({ userData: { authProvider: "password", authId: username, username, name: username, email, passwordHash, recoveryKeyHash, }, locals, cookies, userAgent: request.headers.get("user-agent") ?? undefined, ip: getClientAddress(), });
return json({ recoveryKey });}src/lib/components/LoginModal.svelte+24-351
src/lib/server/passwords.tsDeleted-33
src/lib/types/User.ts+1-4
src/routes/login/callback/userSession.ts-6
src/routes/login/password/+server.tsDeleted-73
src/routes/login/recover/+server.tsDeleted-55
src/routes/login/register/+server.tsDeleted-58