2024-07-15 03:59:51 +00:00
|
|
|
import { fail, error, type Actions } from '@sveltejs/kit';
|
2024-06-08 22:09:21 +00:00
|
|
|
import { and, eq } from 'drizzle-orm';
|
|
|
|
|
import { Argon2id } from 'oslo/password';
|
|
|
|
|
import { decodeHex } from 'oslo/encoding';
|
|
|
|
|
import { TOTPController } from 'oslo/otp';
|
|
|
|
|
import { zod } from 'sveltekit-superforms/adapters';
|
|
|
|
|
import { setError, superValidate } from 'sveltekit-superforms/server';
|
|
|
|
|
import { redirect } from 'sveltekit-flash-message/server';
|
|
|
|
|
import { RateLimiter } from 'sveltekit-rate-limiter/server';
|
|
|
|
|
import db from '../../../db';
|
|
|
|
|
import { lucia } from '$lib/server/auth';
|
2024-07-15 03:59:51 +00:00
|
|
|
import { recoveryCodeSchema, totpSchema } from '$lib/validations/auth';
|
2024-07-11 22:53:56 +00:00
|
|
|
import { users, twoFactor, recoveryCodes } from '$db/schema';
|
2024-07-19 02:51:34 +00:00
|
|
|
import type {PageServerLoad, RequestEvent} from './$types';
|
2024-06-12 02:12:12 +00:00
|
|
|
import { notSignedInMessage } from '$lib/flashMessages';
|
2024-07-12 22:37:05 +00:00
|
|
|
import env from '../../../env';
|
2024-06-08 22:09:21 +00:00
|
|
|
|
|
|
|
|
export const load: PageServerLoad = async (event) => {
|
2024-07-13 00:44:45 +00:00
|
|
|
const { cookies, locals } = event;
|
|
|
|
|
const { user, session } = locals;
|
2024-06-12 02:12:12 +00:00
|
|
|
|
|
|
|
|
if (!user || !session) {
|
|
|
|
|
redirect(302, '/login', notSignedInMessage, event);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (user && session) {
|
2024-06-08 22:09:21 +00:00
|
|
|
const dbUser = await db.query.users.findFirst({
|
|
|
|
|
where: eq(users.username, user.username),
|
|
|
|
|
});
|
|
|
|
|
|
2024-07-11 22:53:56 +00:00
|
|
|
const twoFactorDetails = await db.query.twoFactor.findFirst({
|
|
|
|
|
where: eq(twoFactor.userId, dbUser!.id!),
|
|
|
|
|
});
|
|
|
|
|
|
2024-07-13 00:44:45 +00:00
|
|
|
if (!twoFactorDetails || !twoFactorDetails.enabled) {
|
2024-07-15 03:59:51 +00:00
|
|
|
const message = {
|
|
|
|
|
type: 'error',
|
|
|
|
|
message: 'Two factor authentication is not enabled',
|
|
|
|
|
} as const;
|
2024-07-13 00:44:45 +00:00
|
|
|
redirect(302, '/login', message, event);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let twoFactorInitiatedTime = twoFactorDetails.initiatedTime;
|
|
|
|
|
if (twoFactorInitiatedTime === null) {
|
|
|
|
|
console.log('twoFactorInitiatedTime is null');
|
|
|
|
|
twoFactorInitiatedTime = new Date();
|
|
|
|
|
console.log('twoFactorInitiatedTime', twoFactorInitiatedTime);
|
|
|
|
|
await db
|
|
|
|
|
.update(twoFactor)
|
|
|
|
|
.set({ initiatedTime: twoFactorInitiatedTime })
|
|
|
|
|
.where(eq(twoFactor.userId, dbUser!.id!));
|
|
|
|
|
}
|
|
|
|
|
|
2024-07-08 16:09:41 +00:00
|
|
|
// Check if two factor started less than TWO_FACTOR_TIMEOUT
|
2024-07-15 02:43:20 +00:00
|
|
|
const totpElapsed = totpTimeElapsed(twoFactorInitiatedTime);
|
|
|
|
|
if (totpElapsed) {
|
2024-07-15 03:59:51 +00:00
|
|
|
console.log(
|
|
|
|
|
'Time elapsed was more than TWO_FACTOR_TIMEOUT',
|
|
|
|
|
totpElapsed,
|
|
|
|
|
env.TWO_FACTOR_TIMEOUT,
|
|
|
|
|
);
|
2024-07-13 00:44:45 +00:00
|
|
|
await lucia.invalidateSession(session!.id!);
|
|
|
|
|
const sessionCookie = lucia.createBlankSessionCookie();
|
|
|
|
|
cookies.set(sessionCookie.name, sessionCookie.value, {
|
|
|
|
|
path: '.',
|
|
|
|
|
...sessionCookie.attributes,
|
|
|
|
|
});
|
2024-07-08 16:09:41 +00:00
|
|
|
const message = { type: 'error', message: 'Two factor authentication has expired' } as const;
|
|
|
|
|
redirect(302, '/login', message, event);
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-08 22:09:21 +00:00
|
|
|
const isTwoFactorAuthenticated = session?.isTwoFactorAuthenticated;
|
|
|
|
|
|
2024-06-09 00:25:01 +00:00
|
|
|
console.log('session', session);
|
|
|
|
|
console.log('isTwoFactorAuthenticated', isTwoFactorAuthenticated);
|
|
|
|
|
|
2024-07-15 03:59:51 +00:00
|
|
|
if (isTwoFactorAuthenticated && twoFactorDetails?.enabled && twoFactorDetails?.secret !== '') {
|
2024-06-08 22:09:21 +00:00
|
|
|
const message = { type: 'success', message: 'You are already signed in' } as const;
|
|
|
|
|
throw redirect('/', message, event);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
2024-07-15 03:59:51 +00:00
|
|
|
totpForm: await superValidate(event, zod(totpSchema)),
|
|
|
|
|
recoveryCodeForm: await superValidate(event, zod(recoveryCodeSchema)),
|
2024-06-08 22:09:21 +00:00
|
|
|
};
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const limiter = new RateLimiter({
|
|
|
|
|
// A rate is defined by [number, unit]
|
|
|
|
|
IPUA: [5, 'm'],
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
export const actions: Actions = {
|
2024-07-19 02:51:34 +00:00
|
|
|
validateTotp: async (event) => {
|
2024-07-13 00:44:45 +00:00
|
|
|
const { cookies, locals } = event;
|
2024-06-08 22:09:21 +00:00
|
|
|
const session = locals.session;
|
|
|
|
|
const user = locals.user;
|
|
|
|
|
|
2024-07-19 02:51:34 +00:00
|
|
|
if (await limiter.isLimited(event)) {
|
|
|
|
|
throw error(429);
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-08 22:09:21 +00:00
|
|
|
if (!user || !session) {
|
|
|
|
|
throw fail(401);
|
|
|
|
|
}
|
|
|
|
|
|
2024-07-19 02:51:34 +00:00
|
|
|
const { dbUser, twoFactorDetails } = await validateUserData(event, locals);
|
2024-06-08 22:09:21 +00:00
|
|
|
|
2024-07-19 02:51:34 +00:00
|
|
|
const totpForm = await superValidate(event, zod(totpSchema));
|
|
|
|
|
|
|
|
|
|
if (!totpForm.valid) {
|
|
|
|
|
totpForm.data.totpToken = '';
|
|
|
|
|
return fail(400, { totpForm });
|
2024-06-08 22:09:21 +00:00
|
|
|
}
|
|
|
|
|
|
2024-07-19 02:51:34 +00:00
|
|
|
let sessionCookie;
|
|
|
|
|
const totpToken = totpForm?.data?.totpToken;
|
|
|
|
|
|
|
|
|
|
const twoFactorSecretPopulated =
|
|
|
|
|
twoFactorDetails.secret !== '' && twoFactorDetails.secret !== null;
|
|
|
|
|
if (twoFactorDetails.enabled && !twoFactorSecretPopulated && !totpToken) {
|
|
|
|
|
return fail(400, { totpForm });
|
|
|
|
|
} else if (twoFactorSecretPopulated && totpToken) {
|
|
|
|
|
// Check if two factor started less than TWO_FACTOR_TIMEOUT
|
|
|
|
|
const totpElapsed = totpTimeElapsed(twoFactorDetails.initiatedTime ?? new Date());
|
|
|
|
|
if (totpElapsed) {
|
|
|
|
|
await lucia.invalidateSession(session!.id!);
|
|
|
|
|
const sessionCookie = lucia.createBlankSessionCookie();
|
|
|
|
|
cookies.set(sessionCookie.name, sessionCookie.value, {
|
|
|
|
|
path: '.',
|
|
|
|
|
...sessionCookie.attributes,
|
|
|
|
|
});
|
|
|
|
|
const message = {
|
|
|
|
|
type: 'error',
|
|
|
|
|
message: 'Two factor authentication has expired',
|
|
|
|
|
} as const;
|
|
|
|
|
redirect(302, '/login', message, event);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
console.log('totpToken', totpToken);
|
|
|
|
|
const validOTP = await new TOTPController().verify(
|
|
|
|
|
totpToken,
|
|
|
|
|
decodeHex(twoFactorDetails.secret ?? ''),
|
|
|
|
|
);
|
|
|
|
|
console.log('validOTP', validOTP);
|
|
|
|
|
|
|
|
|
|
if (!validOTP) {
|
|
|
|
|
console.log('invalid TOTP code');
|
|
|
|
|
totpForm.data.totpToken = '';
|
|
|
|
|
return setError(totpForm, 'totpToken', 'Invalid code.');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
console.log('ip', locals.ip);
|
|
|
|
|
console.log('country', locals.country);
|
|
|
|
|
await lucia.invalidateSession(session.id);
|
|
|
|
|
const newSession = await lucia.createSession(dbUser.id, {
|
|
|
|
|
ip_country: locals.country,
|
|
|
|
|
ip_address: locals.ip,
|
|
|
|
|
twoFactorAuthEnabled: true,
|
|
|
|
|
isTwoFactorAuthenticated: true,
|
2024-07-15 02:43:20 +00:00
|
|
|
});
|
2024-07-19 02:51:34 +00:00
|
|
|
console.log('logging in session', newSession);
|
|
|
|
|
sessionCookie = lucia.createSessionCookie(newSession.id);
|
|
|
|
|
console.log('logging in session cookie', sessionCookie);
|
|
|
|
|
|
|
|
|
|
console.log('setting session cookie', sessionCookie);
|
|
|
|
|
event.cookies.set(sessionCookie.name, sessionCookie.value, {
|
|
|
|
|
path: '.',
|
|
|
|
|
...sessionCookie.attributes,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
totpForm.data.totpToken = '';
|
|
|
|
|
const message = { type: 'success', message: 'Signed In!' } as const;
|
|
|
|
|
redirect(302, '/', message, event);
|
|
|
|
|
},
|
|
|
|
|
validateRecoveryCode: async (event) => {
|
|
|
|
|
const { cookies, locals } = event;
|
|
|
|
|
const session = locals.session;
|
|
|
|
|
const user = locals.user;
|
2024-07-15 02:43:20 +00:00
|
|
|
|
2024-07-19 02:51:34 +00:00
|
|
|
if (await limiter.isLimited(event)) {
|
|
|
|
|
throw error(429);
|
2024-07-15 02:43:20 +00:00
|
|
|
}
|
2024-06-08 22:09:21 +00:00
|
|
|
|
2024-07-19 02:51:34 +00:00
|
|
|
if (!user || !session) {
|
|
|
|
|
throw fail(401);
|
2024-06-08 22:09:21 +00:00
|
|
|
}
|
|
|
|
|
|
2024-07-19 02:51:34 +00:00
|
|
|
const { dbUser, twoFactorDetails } = await validateUserData(event, locals);
|
2024-06-08 22:09:21 +00:00
|
|
|
|
2024-07-19 02:51:34 +00:00
|
|
|
const recoveryCodeForm = await superValidate(event, zod(recoveryCodeSchema));
|
|
|
|
|
if (!recoveryCodeForm.valid) {
|
2024-06-08 22:09:21 +00:00
|
|
|
return fail(400, {
|
2024-07-19 02:51:34 +00:00
|
|
|
form: recoveryCodeForm,
|
2024-06-08 22:09:21 +00:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let sessionCookie;
|
2024-07-19 02:51:34 +00:00
|
|
|
const recoveryCode = recoveryCodeForm?.data?.recoveryCode;
|
2024-06-08 22:09:21 +00:00
|
|
|
|
2024-07-19 02:51:34 +00:00
|
|
|
const twoFactorSecretPopulated =
|
2024-07-15 02:43:20 +00:00
|
|
|
twoFactorDetails.secret !== '' && twoFactorDetails.secret !== null;
|
2024-07-19 02:51:34 +00:00
|
|
|
if (twoFactorDetails.enabled && !twoFactorSecretPopulated && !recoveryCode) {
|
|
|
|
|
return fail(400, { recoveryCodeForm });
|
|
|
|
|
} else if (twoFactorSecretPopulated && recoveryCode) {
|
|
|
|
|
// Check if two factor started less than TWO_FACTOR_TIMEOUT
|
|
|
|
|
const totpElapsed = totpTimeElapsed(twoFactorDetails.initiatedTime ?? new Date());
|
|
|
|
|
if (totpElapsed) {
|
|
|
|
|
await lucia.invalidateSession(session!.id!);
|
|
|
|
|
const sessionCookie = lucia.createBlankSessionCookie();
|
|
|
|
|
cookies.set(sessionCookie.name, sessionCookie.value, {
|
|
|
|
|
path: '.',
|
|
|
|
|
...sessionCookie.attributes,
|
2024-06-08 22:09:21 +00:00
|
|
|
});
|
2024-07-19 02:51:34 +00:00
|
|
|
const message = {
|
|
|
|
|
type: 'error',
|
|
|
|
|
message: 'Two factor authentication has expired',
|
|
|
|
|
} as const;
|
|
|
|
|
redirect(302, '/login', message, event);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
console.log('recoveryCode', recoveryCode);
|
|
|
|
|
|
|
|
|
|
console.log('Check for recovery codes');
|
|
|
|
|
const usedRecoveryCode = await checkRecoveryCode(recoveryCode, dbUser.id);
|
|
|
|
|
if (!usedRecoveryCode) {
|
|
|
|
|
console.log('invalid recovery code');
|
|
|
|
|
recoveryCodeForm.data.recoveryCode = '';
|
|
|
|
|
return setError(recoveryCodeForm, 'recoveryCode', 'Invalid code.');
|
2024-06-08 22:09:21 +00:00
|
|
|
}
|
|
|
|
|
}
|
2024-07-19 02:51:34 +00:00
|
|
|
console.log('ip', locals.ip);
|
|
|
|
|
console.log('country', locals.country);
|
|
|
|
|
await lucia.invalidateSession(session.id);
|
|
|
|
|
const newSession = await lucia.createSession(dbUser.id, {
|
|
|
|
|
ip_country: locals.country,
|
|
|
|
|
ip_address: locals.ip,
|
|
|
|
|
twoFactorAuthEnabled: true,
|
|
|
|
|
isTwoFactorAuthenticated: true,
|
|
|
|
|
});
|
|
|
|
|
console.log('logging in session', newSession);
|
|
|
|
|
sessionCookie = lucia.createSessionCookie(newSession.id);
|
|
|
|
|
console.log('logging in session cookie', sessionCookie);
|
2024-06-08 22:09:21 +00:00
|
|
|
|
|
|
|
|
console.log('setting session cookie', sessionCookie);
|
|
|
|
|
event.cookies.set(sessionCookie.name, sessionCookie.value, {
|
|
|
|
|
path: '.',
|
|
|
|
|
...sessionCookie.attributes,
|
|
|
|
|
});
|
|
|
|
|
|
2024-07-19 02:51:34 +00:00
|
|
|
recoveryCodeForm.data.recoveryCode = '';
|
2024-06-08 22:09:21 +00:00
|
|
|
const message = { type: 'success', message: 'Signed In!' } as const;
|
|
|
|
|
redirect(302, '/', message, event);
|
2024-07-19 02:51:34 +00:00
|
|
|
}
|
2024-06-08 22:09:21 +00:00
|
|
|
};
|
|
|
|
|
|
2024-07-19 02:51:34 +00:00
|
|
|
async function validateUserData(event: RequestEvent, locals: App.Locals) {
|
|
|
|
|
const { user, session } = locals;
|
|
|
|
|
|
|
|
|
|
if (!user || !session) {
|
|
|
|
|
throw fail(401);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const dbUser = await db.query.users.findFirst({
|
|
|
|
|
where: eq(users.username, user.username),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!dbUser) {
|
|
|
|
|
throw fail(401);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const isTwoFactorAuthenticated = session?.isTwoFactorAuthenticated;
|
|
|
|
|
const twoFactorDetails = await db.query.twoFactor.findFirst({
|
|
|
|
|
where: eq(twoFactor.userId, dbUser!.id!),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!twoFactorDetails) {
|
|
|
|
|
const message = {type: 'error', message: 'Unable to process request'} as const;
|
|
|
|
|
throw redirect(302, '/login', message, event);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (isTwoFactorAuthenticated && twoFactorDetails.enabled && twoFactorDetails.secret !== '') {
|
|
|
|
|
const message = {type: 'success', message: 'You are already signed in'} as const;
|
|
|
|
|
throw redirect('/', message, event);
|
|
|
|
|
}
|
|
|
|
|
return { dbUser, twoFactorDetails };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2024-07-15 02:43:20 +00:00
|
|
|
function totpTimeElapsed(initiatedTime: Date) {
|
|
|
|
|
if (initiatedTime === null || initiatedTime === undefined) {
|
|
|
|
|
return true;
|
2024-07-13 00:44:45 +00:00
|
|
|
}
|
2024-07-15 02:43:20 +00:00
|
|
|
|
|
|
|
|
const timeElapsed = Date.now() - initiatedTime.getTime();
|
2024-07-13 00:44:45 +00:00
|
|
|
console.log('Time elapsed', timeElapsed);
|
|
|
|
|
if (timeElapsed > env.TWO_FACTOR_TIMEOUT) {
|
2024-07-15 02:43:20 +00:00
|
|
|
console.log(
|
|
|
|
|
'Time elapsed was more than TWO_FACTOR_TIMEOUT',
|
|
|
|
|
timeElapsed,
|
|
|
|
|
env.TWO_FACTOR_TIMEOUT,
|
|
|
|
|
);
|
|
|
|
|
return true;
|
2024-07-13 00:44:45 +00:00
|
|
|
}
|
2024-07-15 02:43:20 +00:00
|
|
|
return false;
|
2024-07-13 00:44:45 +00:00
|
|
|
}
|
|
|
|
|
|
2024-06-08 22:09:21 +00:00
|
|
|
async function checkRecoveryCode(recoveryCode: string, userId: string) {
|
2024-06-09 00:25:01 +00:00
|
|
|
const userRecoveryCodes = await db.query.recoveryCodes.findMany({
|
2024-06-18 00:37:47 +00:00
|
|
|
where: and(eq(recoveryCodes.used, false), eq(recoveryCodes.userId, userId)),
|
2024-06-08 22:09:21 +00:00
|
|
|
});
|
|
|
|
|
for (const code of userRecoveryCodes) {
|
|
|
|
|
const validRecoveryCode = await new Argon2id().verify(code.code, recoveryCode);
|
|
|
|
|
if (validRecoveryCode) {
|
|
|
|
|
await db
|
2024-06-18 00:37:47 +00:00
|
|
|
.update(recoveryCodes)
|
2024-06-08 22:09:21 +00:00
|
|
|
.set({
|
|
|
|
|
used: true,
|
|
|
|
|
})
|
2024-06-18 00:37:47 +00:00
|
|
|
.where(eq(recoveryCodes.id, code.id));
|
2024-06-08 22:09:21 +00:00
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return false;
|
|
|
|
|
}
|