feat: add collaborative shopping lists with items and invitations
Some checks failed
CI / Verify (push) Has been cancelled

API: lists, items and invitations modules (list, create, get, update,
set-primary, items create/list, invitation create/accept/list-pending),
BetterAuth session helper, list membership, mailer and Prisma schema plus
migrations.

Web: lists overview, list detail (items) and list management (settings)
views, item and invitation forms/hooks, sign-up and invitation accept pages.

Shared: shopping list DTOs.

Tooling: ignore the generated TanStack Router cache (apps/web/.tanstack).
This commit is contained in:
Jose Selesan
2026-10-16 10:12:11 -03:00
parent 964a3c7217
commit 6aa86a3b68
81 changed files with 3476 additions and 269 deletions

View File

@@ -0,0 +1,42 @@
import { problems } from '@superlist/shared'
import type { Context, MiddlewareHandler } from 'hono'
import { auth } from '@/lib/auth'
import { problemResponse } from '@/lib/problem-details'
import type { AppEnv, SessionUser } from '@/types'
/** Reads the BetterAuth session for the current request, or `null`. */
export async function getSession(c: Context<AppEnv>) {
return auth.api.getSession({ headers: c.req.raw.headers })
}
/**
* Middleware for protected routes: resolves the BetterAuth session, exposes the
* user/session on the context and answers `401` when there is none.
*
* ```ts
* app.get('/', requireSession, (c) => {
* const user = c.get('user')
* ...
* })
* ```
*/
export const requireSession: MiddlewareHandler<AppEnv> = async (c, next) => {
const session = await auth.api.getSession({ headers: c.req.raw.headers })
if (!session) {
return problemResponse(c, problems.unauthorized())
}
const user: SessionUser = {
id: session.user.id,
name: session.user.name,
email: session.user.email,
image: session.user.image,
}
c.set('user', user)
c.set('session', { id: session.session.id, userId: session.user.id })
await next()
}

View File

@@ -1,6 +1,7 @@
import { betterAuth } from 'better-auth'
import { prismaAdapter } from 'better-auth/adapters/prisma'
import { acceptPendingInvitations, ensurePrimaryList } from '@/lib/list-membership'
import { prisma } from '@/lib/prisma'
const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
@@ -15,6 +16,20 @@ export const auth = betterAuth({
trustedOrigins,
emailAndPassword: {
enabled: true,
minPasswordLength: 8,
requireEmailVerification: false,
},
databaseHooks: {
user: {
create: {
// People invited before signing up get their shared lists on creation,
// and everyone ends up with at least one list of their own.
after: async (user) => {
await acceptPendingInvitations(prisma, { userId: user.id, email: user.email })
await ensurePrimaryList(prisma, { userId: user.id })
},
},
},
},
})

View File

@@ -0,0 +1,52 @@
import type { Email } from '@/lib/mailer'
type InvitationEmailInput = {
inviterName: string
listName: string
acceptUrl: string
}
/** Builds the "you have been invited to a list" email (in Spanish). */
export function invitationEmail({
inviterName,
listName,
acceptUrl,
}: InvitationEmailInput): Omit<Email, 'to'> {
const subject = `${inviterName} te invitó a la lista «${listName}»`
const text = [
`${inviterName} te invitó a colaborar en la lista de compras «${listName}» en Superlist.`,
'',
'Abre este enlace para aceptar la invitación:',
acceptUrl,
'',
'Si no tienes cuenta, podrás crear una en el mismo enlace.',
].join('\n')
const html = `<!doctype html>
<html lang="es">
<body style="font-family: ui-sans-serif, system-ui, sans-serif; background:#f4f4f5; padding:32px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:480px; margin:0 auto; background:#ffffff; border-radius:12px; padding:32px;">
<tr><td>
<h1 style="font-size:20px; margin:0 0 16px;">Te invitaron a una lista</h1>
<p style="font-size:15px; line-height:1.5; color:#3f3f46; margin:0 0 8px;">
<strong>${inviterName}</strong> te invitó a colaborar en la lista de compras
<strong>«${listName}»</strong> en Superlist.
</p>
<p style="font-size:15px; line-height:1.5; color:#3f3f46; margin:0 0 24px;">
Si todavía no tienes cuenta, podrás crear una en el mismo enlace.
</p>
<a href="${acceptUrl}" style="display:inline-block; background:#18181b; color:#ffffff; text-decoration:none; padding:12px 20px; border-radius:8px; font-size:15px;">
Aceptar invitación
</a>
<p style="font-size:13px; line-height:1.5; color:#71717a; margin:24px 0 0;">
Si el botón no funciona, copia y pega este enlace en tu navegador:<br />
<a href="${acceptUrl}" style="color:#2563eb;">${acceptUrl}</a>
</p>
</td></tr>
</table>
</body>
</html>`
return { subject, html, text }
}

View File

@@ -0,0 +1,58 @@
import type { Database } from '@/lib/prisma'
/**
* Grants membership for every `pending`, non-expired invitation that matches the
* email and marks those invitations as accepted.
*
* Called right after a BetterAuth user is created, so people who are invited
* before signing up see the shared lists as soon as they register.
*
* @returns how many invitations were accepted
*/
export async function acceptPendingInvitations(
db: Database,
{ userId, email }: { userId: string; email: string },
): Promise<number> {
const pending = await db.shoppingListInvitation.findMany({
where: { email, status: 'pending', expiresAt: { gt: new Date() } },
})
for (const invitation of pending) {
await db.$transaction([
db.shoppingListMember.upsert({
where: { listId_userId: { listId: invitation.listId, userId } },
update: {},
create: { listId: invitation.listId, userId, role: 'collaborator' },
}),
db.shoppingListInvitation.update({
where: { id: invitation.id },
data: { status: 'accepted', acceptedAt: new Date() },
}),
])
}
return pending.length
}
/**
* Guarantees the user has at least one list: when they belong to none, creates a
* "Lista principal" owned by them and marks it as their primary list. Called
* right after a BetterAuth user is created (after pending invitations are
* accepted) so every account has a starting point.
*/
export async function ensurePrimaryList(
db: Database,
{ userId }: { userId: string },
): Promise<void> {
const memberships = await db.shoppingListMember.count({ where: { userId } })
if (memberships > 0) return
await db.shoppingList.create({
data: {
name: 'Lista principal',
ownerId: userId,
members: { create: { userId, role: 'owner', isPrimary: true } },
},
})
}

View File

@@ -0,0 +1,46 @@
import { Resend } from 'resend'
import { logger } from '@/lib/logger'
/** Minimal email payload the API sends. */
export type Email = {
to: string
subject: string
html: string
text: string
}
const apiKey = process.env.RESEND_API_KEY
const from = process.env.MAIL_FROM ?? 'Superlist <onboarding@resend.dev>'
let client: Resend | null = null
function getClient(): Resend | null {
if (!apiKey) return null
client ??= new Resend(apiKey)
return client
}
/**
* Sends an email through Resend. Without `RESEND_API_KEY` (local development)
* it logs the message with Pino instead of sending it, so invitation links are
* still discoverable in the terminal.
*/
export async function sendEmail(email: Email): Promise<void> {
const resend = getClient()
if (!resend) {
logger.info(
{ to: email.to, subject: email.subject, text: email.text },
'email not sent (RESEND_API_KEY is not set) — logging payload instead',
)
return
}
const { error } = await resend.emails.send({ from, ...email })
if (error) {
throw new Error(`Resend failed to send the email: ${error.message}`)
}
}

View File

@@ -0,0 +1,13 @@
const configured = process.env.WEB_APP_URL?.trim()
const corsOrigin = (process.env.CORS_ORIGIN ?? 'http://localhost:7153')
.split(',')
.map((origin) => origin.trim())
.filter(Boolean)[0]
/** Public URL of the web app, used to build links inside emails. */
export const webAppUrl = configured || corsOrigin || 'http://localhost:7153'
/** Deep link the invited user opens to accept an invitation. */
export function invitationUrl(token: string): string {
return `${webAppUrl}/invitations/${token}`
}