2024-07-13 00:44:45 +00:00
|
|
|
import { fail, error, type Actions, type Cookies, type RequestEvent } 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';
|
|
|
|
|
import { totpSchema } from '$lib/validations/auth';
|
2024-07-11 22:53:56 +00:00
|
|
|
import { users, twoFactor, recoveryCodes } from '$db/schema';
|
2024-06-08 22:09:21 +00:00
|
|
|
import type { PageServerLoad } 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) {
|
|
|
|
|
const message = { type: 'error', message: 'Two factor authentication is not enabled' } as const;
|
|
|
|
|
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-13 00:44:45 +00:00
|
|
|
console.log('Time elapsed was more than TWO_FACTOR_TIMEOUT', timeElapsed, env.TWO_FACTOR_TIMEOUT);
|
|
|
|
|
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-06-12 02:12:12 +00:00
|
|
|
if (
|
|
|
|
|
isTwoFactorAuthenticated &&
|
2024-07-11 22:53:56 +00:00
|
|
|
twoFactorDetails?.enabled &&
|
|
|
|
|
twoFactorDetails?.secret !== ''
|
2024-06-12 02:12:12 +00:00
|
|
|
) {
|
2024-06-08 22:09:21 +00:00
|
|
|
const message = { type: 'success', message: 'You are already signed in' } as const;
|
|
|
|
|
throw redirect('/', message, event);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const form = await superValidate(event, zod(totpSchema));
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
form,
|
|
|
|
|
};
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const limiter = new RateLimiter({
|
|
|
|
|
// A rate is defined by [number, unit]
|
|
|
|
|
IPUA: [5, 'm'],
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
export const actions: Actions = {
|
|
|
|
|
default: async (event) => {
|
|
|
|
|
if (await limiter.isLimited(event)) {
|
|
|
|
|
throw error(429);
|
|
|
|
|
}
|
|
|
|
|
|
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;
|
|
|
|
|
|
|
|
|
|
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;
|
2024-07-11 22:53:56 +00:00
|
|
|
const twoFactorDetails = await db.query.twoFactor.findFirst({
|
|
|
|
|
where: eq(twoFactor.userId, dbUser!.id!),
|
2024-07-15 02:43:20 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!twoFactorDetails) {
|
|
|
|
|
const message = { type: 'error', message: 'Unable to process request' } as const;
|
|
|
|
|
throw redirect(302, '/login', message, event);
|
|
|
|
|
}
|
2024-06-08 22:09:21 +00:00
|
|
|
|
2024-06-12 02:12:12 +00:00
|
|
|
if (
|
|
|
|
|
isTwoFactorAuthenticated &&
|
2024-07-15 02:43:20 +00:00
|
|
|
twoFactorDetails.enabled &&
|
|
|
|
|
twoFactorDetails.secret !== ''
|
2024-06-12 02:12:12 +00:00
|
|
|
) {
|
2024-06-08 22:09:21 +00:00
|
|
|
const message = { type: 'success', message: 'You are already signed in' } as const;
|
|
|
|
|
throw redirect('/', message, event);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const form = await superValidate(event, zod(totpSchema));
|
|
|
|
|
|
|
|
|
|
if (!form.valid) {
|
|
|
|
|
form.data.totpToken = '';
|
|
|
|
|
return fail(400, {
|
|
|
|
|
form,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let sessionCookie;
|
|
|
|
|
try {
|
|
|
|
|
const totpToken = form?.data?.totpToken;
|
|
|
|
|
|
2024-06-18 00:37:47 +00:00
|
|
|
const twoFactorSecretPopulated =
|
2024-07-15 02:43:20 +00:00
|
|
|
twoFactorDetails.secret !== '' && twoFactorDetails.secret !== null;
|
|
|
|
|
if (twoFactorDetails.enabled && !twoFactorSecretPopulated && !totpToken) {
|
2024-06-08 22:09:21 +00:00
|
|
|
return fail(400, {
|
|
|
|
|
form,
|
|
|
|
|
});
|
2024-06-18 00:37:47 +00:00
|
|
|
} else if (twoFactorSecretPopulated && totpToken) {
|
2024-07-13 00:44:45 +00:00
|
|
|
// Check if two factor started less than TWO_FACTOR_TIMEOUT
|
2024-07-15 02:43:20 +00:00
|
|
|
const totpElapsed = totpTimeElapsed(twoFactorDetails.initiatedTime);
|
|
|
|
|
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);
|
|
|
|
|
}
|
2024-07-13 00:44:45 +00:00
|
|
|
|
2024-06-12 02:12:12 +00:00
|
|
|
console.log('totpToken', totpToken);
|
2024-06-08 22:09:21 +00:00
|
|
|
const validOTP = await new TOTPController().verify(
|
2024-06-09 00:25:01 +00:00
|
|
|
totpToken,
|
2024-07-15 02:43:20 +00:00
|
|
|
decodeHex(twoFactorDetails.secret ?? ''),
|
2024-06-08 22:09:21 +00:00
|
|
|
);
|
|
|
|
|
console.log('validOTP', validOTP);
|
|
|
|
|
|
|
|
|
|
if (!validOTP) {
|
|
|
|
|
console.log('invalid TOTP code check for recovery codes');
|
|
|
|
|
const usedRecoveryCode = await checkRecoveryCode(totpToken, dbUser.id);
|
|
|
|
|
if (!usedRecoveryCode) {
|
|
|
|
|
console.log('invalid TOTP code');
|
|
|
|
|
return setError(form, '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,
|
2024-06-12 02:12:12 +00:00
|
|
|
twoFactorAuthEnabled: true,
|
2024-06-08 22:09:21 +00:00
|
|
|
isTwoFactorAuthenticated: true,
|
|
|
|
|
});
|
|
|
|
|
console.log('logging in session', newSession);
|
|
|
|
|
sessionCookie = lucia.createSessionCookie(newSession.id);
|
|
|
|
|
console.log('logging in session cookie', sessionCookie);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
// TODO: need to return error message to the client
|
|
|
|
|
console.error(e);
|
|
|
|
|
return setError(form, 'totpToken', 'Error verifying TOTP code.');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
console.log('setting session cookie', sessionCookie);
|
|
|
|
|
event.cookies.set(sessionCookie.name, sessionCookie.value, {
|
|
|
|
|
path: '.',
|
|
|
|
|
...sessionCookie.attributes,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
form.data.totpToken = '';
|
|
|
|
|
const message = { type: 'success', message: 'Signed In!' } as const;
|
|
|
|
|
redirect(302, '/', message, event);
|
|
|
|
|
},
|
|
|
|
|
};
|
|
|
|
|
|
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;
|
|
|
|
|
}
|