2024-06-19 10:37:10 +02:00
|
|
|
import 'npm:iterator-polyfill'
|
|
|
|
// Polyfill AsyncIterator
|
|
|
|
|
2024-06-20 13:17:12 +02:00
|
|
|
import { FreshContext } from '$fresh/server.ts'
|
2024-07-01 13:11:20 +02:00
|
|
|
import { db } from ':src/db/mod.ts'
|
|
|
|
import { SessionHandlers, SessionStore } from ':src/session/mod.ts'
|
|
|
|
import { respondApi } from ':src/utils.ts'
|
2024-07-15 22:41:18 +02:00
|
|
|
import { Contact, type Mail, send } from '@cohabit/mailer'
|
|
|
|
import { magicLinkTemplate } from '@cohabit/mailer/templates'
|
2024-07-16 15:29:30 +02:00
|
|
|
import { User } from '@cohabit/resources-manager/models'
|
2024-07-01 13:11:20 +02:00
|
|
|
import { sleep } from '@jotsr/delayed'
|
2024-06-19 10:37:10 +02:00
|
|
|
|
|
|
|
type MagicLinkInfos = {
|
|
|
|
remoteId: string
|
|
|
|
email: string
|
|
|
|
timestamp: number
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function getUserByMail(email: string): Promise<User | undefined> {
|
2024-07-16 15:29:30 +02:00
|
|
|
const [user] = await db.resource.user
|
2024-06-19 10:37:10 +02:00
|
|
|
.list((user) => user.mail === email)
|
|
|
|
.take(1)
|
|
|
|
.toArray()
|
|
|
|
|
|
|
|
return user
|
|
|
|
}
|
|
|
|
|
2024-06-20 13:17:12 +02:00
|
|
|
export const handler: SessionHandlers = {
|
2024-06-19 10:37:10 +02:00
|
|
|
async POST(request, ctx) {
|
|
|
|
const { email } = await request.json() as { email: string }
|
|
|
|
|
|
|
|
// check email before continue
|
|
|
|
if (!/\S+@\S+\.\S+/.test(email)) {
|
|
|
|
return respondApi('error', new SyntaxError('empty or invalid email'), 400)
|
|
|
|
}
|
|
|
|
|
|
|
|
const user = await getUserByMail(email)
|
|
|
|
|
|
|
|
// generate magic link
|
|
|
|
const token = crypto.randomUUID()
|
|
|
|
const endpoint =
|
2024-06-20 14:52:16 +02:00
|
|
|
`${ctx.url.origin}/api/magiclink?token=${token}&session=${ctx.state.session.uuid}&redirect=/profil`
|
2024-06-19 10:37:10 +02:00
|
|
|
|
|
|
|
// save token to session
|
2024-06-20 13:17:12 +02:00
|
|
|
ctx.state.session.flash<MagicLinkInfos>(`MAGIC_LINK__${token}`, {
|
2024-06-19 10:37:10 +02:00
|
|
|
email,
|
2024-06-20 13:59:49 +02:00
|
|
|
remoteId: remoteId(request, ctx),
|
2024-06-19 10:37:10 +02:00
|
|
|
timestamp: Date.now(),
|
|
|
|
})
|
|
|
|
|
|
|
|
// send mail to user
|
|
|
|
try {
|
|
|
|
if (user) {
|
2024-06-22 16:02:12 +02:00
|
|
|
// Get user ip through proxy else from tcp connection
|
|
|
|
const ip = request.headers.get('X-FORWARDED-FOR') ??
|
|
|
|
ctx.remoteAddr.hostname
|
2024-06-19 10:37:10 +02:00
|
|
|
const device = request.headers.get('Sec-Ch-Ua-Platform') ?? undefined
|
|
|
|
|
|
|
|
await sendMagicLink(user, { device, ip, endpoint })
|
|
|
|
} else {
|
|
|
|
//! perform wait to prevent time attacks
|
|
|
|
await sleep(Math.random() * 5_000 + 2_000) //between 2s and 7s
|
|
|
|
}
|
|
|
|
return respondApi('success')
|
|
|
|
} catch (error) {
|
|
|
|
console.error('MAGIC_LINK_SENDING', error)
|
|
|
|
return respondApi(
|
|
|
|
'error',
|
|
|
|
new Error(`unable to send mail to ${email}`),
|
|
|
|
500,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
},
|
2024-06-20 13:59:49 +02:00
|
|
|
async GET(request, ctx) {
|
2024-06-19 10:37:10 +02:00
|
|
|
const token = ctx.url.searchParams.get('token')
|
|
|
|
const redirect = ctx.url.searchParams.get('redirect')
|
2024-06-20 14:52:16 +02:00
|
|
|
const sessionId = ctx.url.searchParams.get('session')
|
2024-06-19 10:37:10 +02:00
|
|
|
|
2024-06-20 14:52:16 +02:00
|
|
|
// no token or sessionId
|
|
|
|
if (token === null || sessionId === null) {
|
|
|
|
return respondApi('error', 'no token or session provided', 400)
|
2024-06-19 10:37:10 +02:00
|
|
|
}
|
2024-06-20 14:52:16 +02:00
|
|
|
|
|
|
|
// set session if 3rd party cookies was blocked
|
|
|
|
ctx.state.session = ctx.state.session ?? SessionStore.getSession(sessionId)
|
|
|
|
|
|
|
|
// no session available
|
|
|
|
if (ctx.state.session === null) {
|
|
|
|
return respondApi('error', 'no session datas', 401)
|
|
|
|
}
|
|
|
|
|
2024-06-19 10:37:10 +02:00
|
|
|
// wrong or timeout token
|
2024-06-20 13:17:12 +02:00
|
|
|
const entry = ctx.state.session.get<MagicLinkInfos>(`MAGIC_LINK__${token}`)
|
2024-06-19 10:37:10 +02:00
|
|
|
|
|
|
|
const lifespan = Date.now() - 10 * 60 * 1_000 // ten minutes
|
|
|
|
|
|
|
|
if (entry === undefined || entry.timestamp < lifespan) {
|
|
|
|
return respondApi('error', 'wrong token or timeout exceeded', 401)
|
|
|
|
}
|
|
|
|
|
|
|
|
// check remote id (same user/machine that has query the token)
|
2024-06-20 13:59:49 +02:00
|
|
|
if (entry.remoteId === remoteId(request, ctx)) {
|
2024-06-19 10:37:10 +02:00
|
|
|
const user = await getUserByMail(entry.email)
|
2024-06-20 13:17:12 +02:00
|
|
|
ctx.state.session.set('user', user)
|
2024-06-19 10:37:10 +02:00
|
|
|
|
|
|
|
if (redirect) {
|
2024-06-20 14:45:14 +02:00
|
|
|
return Response.redirect(new URL(redirect, ctx.url.origin))
|
2024-06-19 10:37:10 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return respondApi('success', user)
|
|
|
|
}
|
|
|
|
|
|
|
|
return respondApi(
|
|
|
|
'error',
|
|
|
|
new Error(
|
|
|
|
'invalid id, use the same device/ip to query token and verify token',
|
|
|
|
),
|
|
|
|
401,
|
|
|
|
)
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
function remoteId(
|
2024-06-20 13:59:49 +02:00
|
|
|
{ headers }: { headers: Headers },
|
2024-06-19 10:37:10 +02:00
|
|
|
{ remoteAddr }: { remoteAddr: FreshContext['remoteAddr'] },
|
|
|
|
): string {
|
2024-06-20 13:59:49 +02:00
|
|
|
const forwardedAddress = headers.get('X-FORWARDED-FOR')
|
|
|
|
const forwardedProto = headers.get('X-FORWARDED-PROTO')
|
|
|
|
|
|
|
|
if (forwardedAddress && forwardedProto) {
|
|
|
|
return `${forwardedProto}://${forwardedAddress}`
|
|
|
|
}
|
|
|
|
|
2024-06-19 10:37:10 +02:00
|
|
|
return `(${remoteAddr.transport}):${remoteAddr.hostname}:${remoteAddr.port}`
|
|
|
|
}
|
|
|
|
|
|
|
|
async function sendMagicLink(
|
|
|
|
{ firstname, lastname, mail }: User,
|
|
|
|
{ device, ip, endpoint }: { device?: string; ip?: string; endpoint: string },
|
|
|
|
): Promise<void> {
|
|
|
|
const message: Mail = {
|
|
|
|
from: Contact.expand('contact'),
|
|
|
|
to: [Contact.fromString(`${firstname} ${lastname} <${mail}>`)],
|
|
|
|
subject: 'Lien de connection pour FabLab Coh@bit',
|
|
|
|
body: magicLinkTemplate.builder({
|
|
|
|
device,
|
|
|
|
ip,
|
|
|
|
endpoint,
|
|
|
|
})!,
|
|
|
|
options: {
|
|
|
|
cc: [],
|
|
|
|
cci: [],
|
|
|
|
attachments: [],
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
await send(message)
|
|
|
|
}
|