Compare commits

...

2 Commits

Author SHA1 Message Date
Jose Selesan
1964d3e08b feat: add dictation 2026-10-29 10:29:57 -03:00
Jose Selesan
2117188bf9 feat(auth): recover a password with a code sent by email
Enable BetterAuth's emailOTP plugin for password resets: a 6-digit code,
valid for 10 minutes with 3 attempts, stored hashed in `verifications`
(no migration). The code goes out through the existing Resend mailer with
a new Spanish template, and other sessions are revoked after the reset.

The web app gets a two-step /forgot-password route (request the code,
then set the new password) linked from sign-in. Unknown emails get the
same responses as known ones so the form doesn't reveal accounts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 10:13:15 -03:00
18 changed files with 958 additions and 188 deletions

17
.claude/launch.json Normal file
View File

@@ -0,0 +1,17 @@
{
"version": "0.0.1",
"configurations": [
{
"name": "web",
"runtimeExecutable": "bun",
"runtimeArgs": ["run", "dev", "--filter=@superlist/web"],
"port": 7153
},
{
"name": "api",
"runtimeExecutable": "bun",
"runtimeArgs": ["run", "dev", "--filter=@superlist/api"],
"port": 4100
}
]
}

View File

@@ -13,7 +13,7 @@ BETTER_AUTH_URL="http://localhost:4100"
NODE_ENV="development"
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
# LOG_LEVEL="info"
# Resend API key used to send invitation emails. Without it, emails are logged instead.
# Resend API key used to send invitation and password reset emails. Without it, emails are logged instead.
# RESEND_API_KEY="re_xxxxxxxx"
# From address for outgoing email (must be a verified Resend sender)
# MAIL_FROM="Superlist <invitaciones@superlist.app>"

View File

@@ -6,7 +6,7 @@ Scaffold is in place and verified: Turborepo monorepo with `apps/api`, `apps/web
Biome as the only JS/TS tool and the text Bun lockfile committed. It is deployed with Docker Compose on
Dokploy (`docker-compose.yml`); there is no hosted CI.
Not done yet: product features are just starting (sign-up, shopping lists, list items and invitations exist;
Not done yet: product features are just starting (sign-up, password recovery with an emailed OTP, shopping lists, list items and invitations exist;
there is no Google login and no email verification; the `voice` module splits dictated text with Gemma 4
through the Gemini API). The `health` module is the reference example.
@@ -203,7 +203,10 @@ export class CreateAlert {
→ `requestId` → request logger → BetterAuth → modules.
- **Auth**: BetterAuth is configured in `apps/api/src/lib/auth.ts` (Prisma adapter, `baseURL` from
`BETTER_AUTH_URL`, `secret` from `BETTER_AUTH_SECRET`, `trustedOrigins` from `CORS_ORIGIN`,
email+password enabled) and owns every route under `/api/auth/*`.
email+password enabled) and owns every route under `/api/auth/*`. Password recovery uses the `emailOTP`
plugin (6-digit code, 10 minutes, hashed in `verifications`): the web `/forgot-password` route calls
`emailOtp.requestPasswordReset` / `emailOtp.resetPassword`, and the code is sent with `sendEmail`
(`lib/mailer.ts`, template in `lib/emails/password-reset.ts`). Without `RESEND_API_KEY` the code is logged.
- **Prisma 7**: the generator is `prisma-client` and writes to `apps/api/src/generated/prisma` (gitignored), so
import it as `@/generated/prisma/client` — never `@prisma/client` directly. The client uses the
`@prisma/adapter-pg` adapter with `DATABASE_URL` and is exported as `prisma` (plus the `Database` type) from
@@ -241,7 +244,7 @@ apps/web/src/
- **Routing: TanStack Router with file-based routes.** Add a file under `src/routes` and the route tree is
regenerated (`bun run routes:generate`, also run by `dev`, `build` and `typecheck`; the Vite plugin watches
the directory in dev). Never edit `routeTree.gen.ts`; `tsr.config.json` holds the generator config.
- `(auth)/sign-in.tsx` — public routes.
- `(auth)/sign-in.tsx`, `sign-up.tsx`, `forgot-password.tsx` — public routes.
- `_authenticated/route.tsx` — pathless layout for signed-in pages; it guards on the BetterAuth session
(`authClient.useSession()`) and redirects to `/sign-in` when there is none. Add authenticated pages inside
`_authenticated/`.

View File

@@ -6,7 +6,7 @@ BETTER_AUTH_URL="http://localhost:4100"
NODE_ENV="development"
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
# LOG_LEVEL="info"
# Resend API key used to send invitation emails. Without it, emails are logged instead.
# Resend API key used to send invitation and password reset emails. Without it, emails are logged instead.
# RESEND_API_KEY="re_xxxxxxxx"
# From address for outgoing email (must be a verified Resend sender)
# MAIL_FROM="Superlist <invitaciones@superlist.app>"

View File

@@ -1,7 +1,11 @@
import { betterAuth } from 'better-auth'
import { prismaAdapter } from 'better-auth/adapters/prisma'
import { emailOTP } from 'better-auth/plugins'
import { passwordResetEmail } from '@/lib/emails/password-reset'
import { acceptPendingInvitations, ensurePrimaryList } from '@/lib/list-membership'
import { logger } from '@/lib/logger'
import { sendEmail } from '@/lib/mailer'
import { prisma } from '@/lib/prisma'
const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
@@ -9,6 +13,8 @@ const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
.map((origin) => origin.trim())
.filter(Boolean)
const OTP_EXPIRES_IN_SECONDS = 10 * 60
export const auth = betterAuth({
database: prismaAdapter(prisma, { provider: 'postgresql' }),
baseURL: process.env.BETTER_AUTH_URL,
@@ -27,7 +33,31 @@ export const auth = betterAuth({
enabled: true,
minPasswordLength: 8,
requireEmailVerification: false,
revokeSessionsOnPasswordReset: true,
},
plugins: [
// Password recovery: a 6-digit code sent by email, checked by
// /api/auth/email-otp/reset-password. Codes live (hashed) in `verifications`.
emailOTP({
otpLength: 6,
expiresIn: OTP_EXPIRES_IN_SECONDS,
allowedAttempts: 3,
storeOTP: 'hashed',
disableSignUp: true,
sendVerificationOTP: async ({ email, otp, type }) => {
if (type !== 'forget-password') return
// Not awaited on purpose: answering at the same speed whether or not the
// email exists avoids leaking which addresses have an account.
void sendEmail({
to: email,
...passwordResetEmail({ otp, expiresInMinutes: OTP_EXPIRES_IN_SECONDS / 60 }),
}).catch((error: unknown) => {
logger.error({ err: error, to: email }, 'failed to send the password reset email')
})
},
}),
],
databaseHooks: {
user: {
create: {

View File

@@ -0,0 +1,47 @@
import type { Email } from '@/lib/mailer'
type PasswordResetEmailInput = {
otp: string
expiresInMinutes: number
}
/** Builds the "your password reset code" email (in Spanish). */
export function passwordResetEmail({
otp,
expiresInMinutes,
}: PasswordResetEmailInput): Omit<Email, 'to'> {
const subject = `Tu código para restablecer la contraseña: ${otp}`
const text = [
'Recibimos una solicitud para restablecer la contraseña de tu cuenta de Superlist.',
'',
`Tu código es: ${otp}`,
'',
`Vence en ${expiresInMinutes} minutos.`,
'Si no lo pediste, ignora este correo: tu contraseña no cambiará.',
].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;">Restablece tu contraseña</h1>
<p style="font-size:15px; line-height:1.5; color:#3f3f46; margin:0 0 24px;">
Recibimos una solicitud para restablecer la contraseña de tu cuenta de Superlist.
Usa este código para elegir una nueva:
</p>
<p style="font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size:32px; font-weight:700; letter-spacing:8px; text-align:center; background:#f4f4f5; border-radius:8px; padding:16px; margin:0 0 24px; color:#18181b;">
${otp}
</p>
<p style="font-size:13px; line-height:1.5; color:#71717a; margin:0;">
El código vence en ${expiresInMinutes} minutos. Si no lo pediste, ignora este correo:
tu contraseña no cambiará.
</p>
</td></tr>
</table>
</body>
</html>`
return { subject, html, text }
}

View File

@@ -1,12 +1,10 @@
import { zodResolver } from '@hookform/resolvers/zod'
import type { ListItem } from '@superlist/shared'
import { Loader2Icon, MicIcon, PlusIcon } from 'lucide-react'
import { type ClipboardEvent, useEffect, useRef, useState } from 'react'
import { type ClipboardEvent, useEffect, useState } from 'react'
import { useForm, useWatch } from 'react-hook-form'
import { toast } from 'sonner'
import { z } from 'zod'
import { ItemInputPreview, type PreviewItem } from '@/components/items/item-input-preview'
import { ItemInputPreview } from '@/components/items/item-input-preview'
import { Field, FieldError } from '@/components/ui/field'
import {
InputGroup,
@@ -14,19 +12,10 @@ import {
InputGroupButton,
InputGroupInput,
} from '@/components/ui/input-group'
import { itemLimitError, readItems, useAddItems } from '@/hooks/use-add-items'
import { useDictation } from '@/hooks/use-dictation'
import {
isOptimisticItem,
useCreateItem,
useItems,
useRemoveItems,
useUpdateItem,
} from '@/hooks/use-items'
import { useKeyboardDictation } from '@/hooks/use-keyboard-dictation'
import { useVoiceSplit } from '@/hooks/use-voice-split'
import { ApiError } from '@/lib/api-client'
import { findDuplicate, mergeBatch, mergeInto } from '@/lib/natural-input/merge'
import { isPlainItem, literalItem, parseItemInput } from '@/lib/natural-input/parse-item'
import { isPlainItem } from '@/lib/natural-input/parse-item'
import { cn } from '@/lib/utils'
// The input may hold several items ("leche, pan y 2 pascualinas" or a pasted list);
@@ -44,9 +33,6 @@ type CreateItemFormProps = {
autoFocus?: boolean
}
/** How long the "Deshacer" of a dictation stays on screen. */
const DICTATION_UNDO_MS = 8000
/** The input carries this id so it can be focused from outside the form (e.g. by the nav). */
const NEW_ITEM_INPUT_ID = 'new-item-input'
@@ -69,23 +55,6 @@ export function refocusNewItemInput(): void {
document.getElementById(NEW_ITEM_INPUT_ID)?.focus()
}
/** Why a read item cannot be sent as is, mirroring the API limits, or `null`. */
function itemLimitError(item: PreviewItem): string | null {
if (item.name.length > 120) return `«${item.name.slice(0, 20)}…»: máximo 120 caracteres`
if ((item.quantity?.length ?? 0) > 40) return `«${item.name}»: la cantidad es demasiado larga`
if ((item.notes?.length ?? 0) > 280) return `«${item.name}»: la nota es demasiado larga`
return null
}
/** What adding a batch of items did, so a dictation can be undone. */
type AddedItems = {
/** Ids of the items created (failed ones are left out). */
created: Promise<string[]>
/** The previous quantity/notes of the pending items that were added to. */
merged: { itemId: string; quantity: string | null; notes: string | null }[]
}
/**
* Input to add items to a list. Submits with Enter or the "+" button. The text is read
* as natural language ("400 de jamon", "Queso crema. Solo Tregar", "leche, pan y
@@ -96,11 +65,6 @@ type AddedItems = {
* AI) and each one goes through this same flow. "Deshacer" removes the whole dictation.
*/
export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProps) {
const createItem = useCreateItem(listId)
const updateItem = useUpdateItem(listId)
const removeItems = useRemoveItems(listId)
const voiceSplit = useVoiceSplit()
const { data: items } = useItems(listId)
// The text the user asked to add as typed; editing it brings the reading back.
const [literalText, setLiteralText] = useState<string | null>(null)
@@ -111,22 +75,31 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
const text = useWatch({ control: form.control, name: 'entry' })
const literal = literalText !== null && literalText === text
// Placeholders have no server id yet, so they cannot be added to.
const existing = (items ?? []).filter((item) => !isOptimisticItem(item))
// A dictation finishes after a request: by then the list may have changed.
const existingRef = useRef(existing)
existingRef.current = existing
const dictation = useDictation({ onTranscript: (transcript) => void addDictation(transcript) })
const restoreText = (source: string, message: string) => {
const current = form.getValues('entry').trim()
form.setValue('entry', current ? `${current}; ${source}` : source)
form.setError('entry', { message })
}
// A failed item comes back to the input, and so does a dictation that breaks the limits.
const { existing, addItems, addDictation, processing } = useAddItems(listId, {
onItemFailed: restoreText,
onDictationRejected: (transcript, message) => {
form.setValue('entry', transcript)
form.setError('entry', { message })
},
})
const dictation = useDictation({ onTranscript: (transcript) => onTranscript(transcript) })
// The keyboard's own microphone (the only one in the installed iOS app) just writes
// text: once it has been quiet for a few seconds, that text is added as a dictation.
const keyboardDictation = useKeyboardDictation({
onIdle: () => {
const dictated = form.getValues('entry').trim()
if (dictated && !dictation.listening && !voiceSplit.isPending) void addDictation(dictated)
if (dictated && !dictation.listening && !processing) onTranscript(dictated)
},
})
const processing = voiceSplit.isPending
const dictating = dictation.listening || processing
// The partial transcript is shown in the input while the user talks.
@@ -140,64 +113,6 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
text.trim() !== '' &&
(literal || !isPlainItem(preview, text) || preview.some((item) => item.duplicate))
const restoreText = (source: string, message: string) => {
const current = form.getValues('entry').trim()
form.setValue('entry', current ? `${current}; ${source}` : source)
form.setError('entry', { message })
}
/** Adds the items, or adds to the pending ones they repeat. A failed one comes back to the input. */
const addItems = (toAdd: PreviewItem[]): AddedItems => {
const created: Promise<string | null>[] = []
const merged: AddedItems['merged'] = []
for (const item of toAdd) {
if (item.duplicate) {
const patch = mergeInto(item.duplicate, item)
if (patch.quantity !== undefined || patch.notes !== undefined) {
updateItem.mutate({ itemId: item.duplicate.id, ...patch })
merged.push({
itemId: item.duplicate.id,
quantity: item.duplicate.quantity,
notes: item.duplicate.notes,
})
}
toast(
patch.quantity
? `Se sumó a «${item.duplicate.name}» (${patch.quantity})`
: `«${item.duplicate.name}» ya está en la lista`,
)
continue
}
created.push(
createItem
.mutateAsync({
name: item.name,
quantity: item.quantity ?? undefined,
notes: item.notes ?? undefined,
})
.then(
(createdItem) => createdItem.id,
(error) => {
restoreText(
item.source,
error instanceof ApiError
? (error.problem.detail ?? error.problem.title)
: 'No pudimos añadir el artículo.',
)
return null
},
),
)
}
return {
created: Promise.all(created).then((ids) => ids.filter((id): id is string => id !== null)),
merged,
}
}
// The input clears at once (items are added optimistically) so several items can be
// typed in a row; if a request fails its text comes back with the error.
const onSubmit = form.handleSubmit((values) => {
@@ -217,48 +132,12 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
addItems(toAdd)
})
/**
* The API splits the transcript into one string per item and each one is read by the
* usual parser. If the request fails, the whole transcript is added as a single item.
*/
const addDictation = async (transcript: string) => {
/** A dictation clears the input and goes through `addDictation`. */
const onTranscript = (transcript: string) => {
keyboardDictation.cancel()
form.reset()
setLiteralText(null)
let toAdd: PreviewItem[]
try {
const { items: spoken } = await voiceSplit.mutateAsync({ text: transcript })
toAdd = readItems(spoken.join('; '), false, existingRef.current)
} catch {
toAdd = readItems(transcript, true, existingRef.current)
}
if (toAdd.length === 0) return
const limitError = toAdd.map(itemLimitError).find(Boolean)
if (limitError) {
form.setValue('entry', transcript)
form.setError('entry', { message: limitError })
return
}
const { created, merged } = addItems(toAdd)
const createdIds = await created
const count = createdIds.length + merged.length
if (count === 0) return
toast(`Se ${count === 1 ? 'agregó 1 producto' : `agregaron ${count} productos`}`, {
// Longer than a plain toast: the user has to check what was understood first.
duration: DICTATION_UNDO_MS,
action: {
label: 'Deshacer',
onClick: () => {
void removeItems(createdIds)
for (const previous of merged) updateItem.mutate(previous)
},
},
})
void addDictation(transcript)
}
// An <input> drops line breaks, so a pasted list keeps one item per line as "; ".
@@ -376,12 +255,3 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
</form>
)
}
/** The items `text` adds, each with the pending item it repeats, if any. */
function readItems(text: string, literal: boolean, existing: ListItem[]): PreviewItem[] {
if (!text.trim()) return []
const items = literal ? [literalItem(text)] : mergeBatch(parseItemInput(text))
return items.map((item) => ({ ...item, duplicate: findDuplicate(existing, item.name) }))
}

View File

@@ -0,0 +1,88 @@
import { Loader2Icon, MicIcon, SquareIcon } from 'lucide-react'
import { useState } from 'react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { useAddItems } from '@/hooks/use-add-items'
import { DICTATION_MESSAGES, useMicrophoneDictation } from '@/hooks/use-microphone-dictation'
type DictateItemsButtonProps = {
listId: string
}
/**
* "Dictar ítems" for an empty list: listens until the user stops it and adds what was
* said through the same flow as the input's microphone (split by the API, undoable).
*/
export function DictateItemsButton({ listId }: DictateItemsButtonProps) {
const [message, setMessage] = useState<string | null>(null)
const { addDictation, processing } = useAddItems(listId, {
onItemFailed: (source, detail) => toast.error(`No pudimos añadir «${source}»: ${detail}`),
onDictationRejected: (_, detail) => setMessage(detail),
})
const dictation = useMicrophoneDictation({
onPhrases: async (phrases) => {
const understood = await addDictation(phrases.join('\n'))
if (understood === 0) setMessage(DICTATION_MESSAGES.empty)
},
onError: setMessage,
})
const listening = dictation.status === 'listening'
const busy = dictation.status === 'requesting' || processing
const label = processing
? 'Procesando el dictado'
: dictation.status === 'requesting'
? 'Pidiendo acceso al micrófono'
: listening
? 'Detener dictado'
: 'Dictar ítems'
return (
<div className="flex flex-col items-center gap-2">
<Button
type="button"
variant={listening ? 'default' : 'secondary'}
aria-label={label}
aria-pressed={listening}
disabled={busy}
className="relative rounded-full"
onClick={() => {
setMessage(null)
if (listening) dictation.stop()
else dictation.start()
}}
>
{busy ? (
<Loader2Icon className="animate-spin" />
) : listening ? (
<SquareIcon className="fill-current" />
) : (
<MicIcon />
)}
{listening ? 'Detener dictado' : 'Dictar ítems'}
</Button>
<div aria-live="polite" className="flex flex-col items-center gap-1 text-sm">
{listening && (
<p className="text-primary flex items-center gap-2 font-medium">
<span className="relative flex size-2.5" aria-hidden="true">
<span className="bg-primary absolute inline-flex size-full rounded-full opacity-75 motion-safe:animate-ping" />
<span className="bg-primary relative inline-flex size-2.5 rounded-full" />
</span>
Micrófono activo, te escuchamos
</p>
)}
{listening && dictation.heard && (
<p className="text-muted-foreground max-w-xs">{dictation.heard}</p>
)}
{listening && !dictation.heard && (
<p className="text-muted-foreground">Di «nuevo ítem» o haz una pausa entre artículos.</p>
)}
{message && !listening && <p className="text-destructive max-w-xs">{message}</p>}
</div>
</div>
)
}

View File

@@ -18,6 +18,7 @@ import { ApiError } from '@/lib/api-client'
import { splitItems } from '@/lib/items'
import { BoughtItemList } from './bought-item-list'
import { DictateItemsButton } from './dictate-items-button'
import { ItemRow } from './item-row'
import { ItemSheet } from './item-sheet'
import { MoveItemDialog } from './move-item-dialog'
@@ -101,6 +102,7 @@ export function ItemList({ listId }: ItemListProps) {
Usa el campo de arriba para añadir tu primer artículo.
</p>
</div>
<DictateItemsButton listId={listId} />
</CardContent>
</Card>
)

View File

@@ -0,0 +1,171 @@
import type { ListItem } from '@superlist/shared'
import { useRef } from 'react'
import { toast } from 'sonner'
import type { PreviewItem } from '@/components/items/item-input-preview'
import {
isOptimisticItem,
useCreateItem,
useItems,
useRemoveItems,
useUpdateItem,
} from '@/hooks/use-items'
import { useVoiceSplit } from '@/hooks/use-voice-split'
import { ApiError } from '@/lib/api-client'
import { findDuplicate, mergeBatch, mergeInto } from '@/lib/natural-input/merge'
import { literalItem, parseItemInput } from '@/lib/natural-input/parse-item'
/** How long the "Deshacer" of a dictation stays on screen. */
const DICTATION_UNDO_MS = 8000
/** Why a read item cannot be sent as is, mirroring the API limits, or `null`. */
export function itemLimitError(item: PreviewItem): string | null {
if (item.name.length > 120) return `«${item.name.slice(0, 20)}…»: máximo 120 caracteres`
if ((item.quantity?.length ?? 0) > 40) return `«${item.name}»: la cantidad es demasiado larga`
if ((item.notes?.length ?? 0) > 280) return `«${item.name}»: la nota es demasiado larga`
return null
}
/** The items `text` adds, each with the pending item it repeats, if any. */
export function readItems(text: string, literal: boolean, existing: ListItem[]): PreviewItem[] {
if (!text.trim()) return []
const items = literal ? [literalItem(text)] : mergeBatch(parseItemInput(text))
return items.map((item) => ({ ...item, duplicate: findDuplicate(existing, item.name) }))
}
/** What adding a batch of items did, so a dictation can be undone. */
type AddedItems = {
/** Ids of the items created (failed ones are left out). */
created: Promise<string[]>
/** The previous quantity/notes of the pending items that were added to. */
merged: { itemId: string; quantity: string | null; notes: string | null }[]
}
type UseAddItemsOptions = {
/** An item could not be created: `source` is the text it was read from. */
onItemFailed: (source: string, message: string) => void
/** A dictation was not added because an item breaks the API limits. */
onDictationRejected: (transcript: string, message: string) => void
}
/**
* Adds items to a list the way the "add an item" input does: an item already pending is
* added to instead of repeated, and a dictation is split into items by the API (with AI)
* and can be undone as a whole.
*/
export function useAddItems(
listId: string,
{ onItemFailed, onDictationRejected }: UseAddItemsOptions,
) {
const createItem = useCreateItem(listId)
const updateItem = useUpdateItem(listId)
const removeItems = useRemoveItems(listId)
const voiceSplit = useVoiceSplit()
const { data: items } = useItems(listId)
// Placeholders have no server id yet, so they cannot be added to.
const existing = (items ?? []).filter((item) => !isOptimisticItem(item))
// A dictation finishes after a request: by then the list may have changed.
const existingRef = useRef(existing)
existingRef.current = existing
/** Adds the items, or adds to the pending ones they repeat. */
const addItems = (toAdd: PreviewItem[]): AddedItems => {
const created: Promise<string | null>[] = []
const merged: AddedItems['merged'] = []
for (const item of toAdd) {
if (item.duplicate) {
const patch = mergeInto(item.duplicate, item)
if (patch.quantity !== undefined || patch.notes !== undefined) {
updateItem.mutate({ itemId: item.duplicate.id, ...patch })
merged.push({
itemId: item.duplicate.id,
quantity: item.duplicate.quantity,
notes: item.duplicate.notes,
})
}
toast(
patch.quantity
? `Se sumó a «${item.duplicate.name}» (${patch.quantity})`
: `«${item.duplicate.name}» ya está en la lista`,
)
continue
}
created.push(
createItem
.mutateAsync({
name: item.name,
quantity: item.quantity ?? undefined,
notes: item.notes ?? undefined,
})
.then(
(createdItem) => createdItem.id,
(error) => {
onItemFailed(
item.source,
error instanceof ApiError
? (error.problem.detail ?? error.problem.title)
: 'No pudimos añadir el artículo.',
)
return null
},
),
)
}
return {
created: Promise.all(created).then((ids) => ids.filter((id): id is string => id !== null)),
merged,
}
}
/**
* The API splits the transcript into one string per item and each one is read by the
* usual parser. If the request fails, the transcript is read as typed text when it is
* already split into lines, and added as a single item otherwise.
*
* @returns how many items were understood (0 when the dictation had none).
*/
const addDictation = async (transcript: string): Promise<number> => {
let toAdd: PreviewItem[]
try {
const { items: spoken } = await voiceSplit.mutateAsync({ text: transcript })
toAdd = readItems(spoken.join('; '), false, existingRef.current)
} catch {
toAdd = readItems(transcript, !/[;\n]/.test(transcript), existingRef.current)
}
if (toAdd.length === 0) return 0
const limitError = toAdd.map(itemLimitError).find(Boolean)
if (limitError) {
onDictationRejected(transcript, limitError)
return toAdd.length
}
const { created, merged } = addItems(toAdd)
const createdIds = await created
const count = createdIds.length + merged.length
if (count === 0) return toAdd.length
toast(`Se ${count === 1 ? 'agregó 1 producto' : `agregaron ${count} productos`}`, {
// Longer than a plain toast: the user has to check what was understood first.
duration: DICTATION_UNDO_MS,
action: {
label: 'Deshacer',
onClick: () => {
void removeItems(createdIds)
for (const previous of merged) updateItem.mutate(previous)
},
},
})
return toAdd.length
}
return { existing, addItems, addDictation, processing: voiceSplit.isPending }
}

View File

@@ -1,22 +1,10 @@
import { useCallback, useEffect, useRef, useState } from 'react'
/** The slice of the Web Speech API this hook uses (TypeScript's DOM lib does not ship it). */
type SpeechRecognitionResultLike = { isFinal: boolean; 0: { transcript: string } }
type SpeechRecognitionLike = {
lang: string
interimResults: boolean
continuous: boolean
maxAlternatives: number
onresult: ((event: { results: ArrayLike<SpeechRecognitionResultLike> }) => void) | null
onerror: ((event: { error: string }) => void) | null
onend: (() => void) | null
start: () => void
stop: () => void
abort: () => void
}
type SpeechRecognitionConstructor = new () => SpeechRecognitionLike
import {
getSpeechRecognition as getBrowserSpeechRecognition,
isIosStandalone,
type SpeechRecognitionConstructor,
} from '@/lib/speech-recognition'
/** Errors that only mean "nothing was said" or "we stopped it": not worth telling. */
const IGNORED_ERRORS = new Set(['no-speech', 'aborted'])
@@ -34,17 +22,9 @@ const ERROR_MESSAGES: Record<string, string> = {
* unsupported (the keyboard's own dictation still works).
*/
function getSpeechRecognition(): SpeechRecognitionConstructor | null {
if (typeof window === 'undefined') return null
if (typeof window === 'undefined' || isIosStandalone()) return null
const iosStandalone = (navigator as Navigator & { standalone?: boolean }).standalone === true
if (iosStandalone) return null
const speechWindow = window as Window & {
SpeechRecognition?: SpeechRecognitionConstructor
webkitSpeechRecognition?: SpeechRecognitionConstructor
}
return speechWindow.SpeechRecognition ?? speechWindow.webkitSpeechRecognition ?? null
return getBrowserSpeechRecognition()
}
type UseDictationOptions = {

View File

@@ -0,0 +1,154 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { splitDictation } from '@/lib/natural-input/dictation'
import { getSpeechRecognition, type SpeechRecognitionLike } from '@/lib/speech-recognition'
export const DICTATION_MESSAGES = {
denied: 'No tenemos permiso para usar el micrófono. Habilítalo en los ajustes del navegador.',
unavailable: 'No encontramos un micrófono disponible.',
unsupported:
'Este navegador no permite dictar. Puedes usar el micrófono del teclado en el campo de arriba.',
empty: 'No escuchamos ningún artículo. Inténtalo de nuevo.',
failed: 'Ocurrió un error al reconocer la voz. Inténtalo de nuevo.',
} as const
/** Recognition errors with a message of their own; any other one is `failed`. */
const RECOGNITION_ERRORS: Record<string, string | null> = {
'not-allowed': DICTATION_MESSAGES.denied,
'service-not-allowed': DICTATION_MESSAGES.unsupported,
'audio-capture': DICTATION_MESSAGES.unavailable,
// Silence just ends with no phrases; a stop of ours is not an error.
'no-speech': null,
aborted: null,
}
/** What `getUserMedia` rejects with, as one of the messages. */
function microphoneError(error: unknown): string {
const name = error instanceof DOMException ? error.name : ''
if (name === 'NotAllowedError' || name === 'SecurityError') return DICTATION_MESSAGES.denied
return DICTATION_MESSAGES.unavailable
}
type DictationStatus = 'idle' | 'requesting' | 'listening'
type UseMicrophoneDictationOptions = {
/** The phrases dictated, one per item said, when the dictation ends with some. */
onPhrases: (phrases: string[]) => void
/** Why the dictation did not deliver anything, in Spanish. */
onError: (message: string) => void
}
/**
* Dictation of several items in a row with the Web Speech API (`webkitSpeechRecognition`
* in Safari), in Argentine Spanish. `start()` must run inside a click handler: it asks
* for the microphone right there, then listens until the user calls `stop()` or the
* browser ends the recognition. Pauses, line breaks and "nuevo ítem" separate phrases
* (`splitDictation`).
*
* The microphone stream is only used to ask for the permission: its tracks are stopped
* as soon as it arrives (even after an unmount), before the recognition opens its own
* capture. Unmounting aborts the recognition.
*/
export function useMicrophoneDictation({ onPhrases, onError }: UseMicrophoneDictationOptions) {
const [status, setStatus] = useState<DictationStatus>('idle')
// What has been heard so far, shown while listening.
const [heard, setHeard] = useState('')
const callbacksRef = useRef({ onPhrases, onError })
// Ends the dictation in progress: `true` delivers what was heard, `false` drops it.
const endRef = useRef<((deliver: boolean) => void) | null>(null)
useEffect(() => {
callbacksRef.current = { onPhrases, onError }
})
useEffect(() => () => endRef.current?.(false), [])
const start = useCallback(() => {
if (endRef.current) return
const SpeechRecognition = getSpeechRecognition()
if (!SpeechRecognition) {
callbacksRef.current.onError(DICTATION_MESSAGES.unsupported)
return
}
let recognition: SpeechRecognitionLike | null = null
let segments: string[] = []
let failure: string | null = null
let done = false
const end = (deliver: boolean) => {
if (done) return
done = true
endRef.current = null
// Aborting afterwards only fires an ignored `aborted` and an `onend` that finds it done.
recognition?.abort()
setStatus('idle')
setHeard('')
// Stopped while the permission was being asked: there is nothing to tell.
if (!deliver || (!recognition && !failure)) return
const phrases = splitDictation(segments)
if (failure) callbacksRef.current.onError(failure)
else if (phrases.length === 0) callbacksRef.current.onError(DICTATION_MESSAGES.empty)
else callbacksRef.current.onPhrases(phrases)
}
const listen = () => {
recognition = new SpeechRecognition()
recognition.lang = 'es-AR'
recognition.interimResults = true
recognition.continuous = true
recognition.maxAlternatives = 1
// Each result is a stretch of speech between pauses; the last one may still change.
recognition.onresult = (event) => {
segments = Array.from(event.results, (result) => result[0].transcript)
setHeard(splitDictation(segments).join(' · '))
}
recognition.onerror = (event) => {
const message = RECOGNITION_ERRORS[event.error]
if (message === null) return
failure = message ?? DICTATION_MESSAGES.failed
}
recognition.onend = () => end(true)
try {
recognition.start()
setStatus('listening')
} catch {
failure = DICTATION_MESSAGES.failed
end(true)
}
}
endRef.current = end
setStatus('requesting')
// Without `getUserMedia` (e.g. outside HTTPS) the recognition asks for the microphone itself.
if (!navigator.mediaDevices?.getUserMedia) {
listen()
return
}
// Called right in the click, before any `await`, so Safari treats it as the user's.
navigator.mediaDevices.getUserMedia({ audio: true }).then(
(stream) => {
for (const track of stream.getTracks()) track.stop()
if (!done) listen()
},
(error: unknown) => {
failure = microphoneError(error)
end(true)
},
)
}, [])
/** Stops listening; what was heard so far is delivered. */
const stop = useCallback(() => endRef.current?.(true), [])
return { status, heard, start, stop }
}

View File

@@ -1,3 +1,4 @@
import { emailOTPClient } from 'better-auth/client/plugins'
import { createAuthClient } from 'better-auth/react'
/**
@@ -7,6 +8,7 @@ import { createAuthClient } from 'better-auth/react'
*/
export const authClient = createAuthClient({
baseURL: import.meta.env.VITE_API_URL || window.location.origin,
plugins: [emailOTPClient()],
})
export const { signIn, signUp, signOut, useSession } = authClient
export const { signIn, signUp, signOut, useSession, emailOtp } = authClient

View File

@@ -0,0 +1,37 @@
import { describe, expect, it } from 'vitest'
import { splitDictation } from './dictation'
describe('splitDictation', () => {
it('splits on "nuevo ítem" and its variants', () => {
expect(
splitDictation([
'leche descremada nuevo ítem pan Nuevo item 2 kilos de papa, otro artículo yerba',
]),
).toEqual(['leche descremada', 'pan', '2 kilos de papa', 'yerba'])
})
it('takes every segment and line as a separate phrase', () => {
expect(splitDictation(['Leche.', ' pan\nqueso rallado '])).toEqual([
'Leche',
'pan',
'queso rallado',
])
})
it('collapses spaces and drops empty phrases', () => {
expect(splitDictation([' dulce de leche ', '', 'nuevo ítem', '...'])).toEqual([
'dulce de leche',
])
})
it('keeps a repeated phrase once, ignoring case and accents', () => {
expect(splitDictation(['jamón', 'Jamon nuevo ítem pan', 'pan'])).toEqual(['jamón', 'pan'])
})
it('does not split words that only contain the keywords', () => {
expect(splitDictation(['productos nuevos de limpieza'])).toEqual([
'productos nuevos de limpieza',
])
})
})

View File

@@ -0,0 +1,35 @@
import { normalizeWord } from './text'
/**
* What the user says to start another item: "nuevo ítem", "otro artículo", "nuevo
* producto". The punctuation the recognizer puts around it goes with it.
*/
const NEXT_ITEM =
/[\s,.;:]*(?<!\p{L})(?:nuevo|otro)\s+(?:[íi]tem|art[íi]culo|producto)(?!\p{L})[\s,.;:]*/giu
/** Punctuation the recognizer adds around a phrase ("Leche."), not part of the item. */
const EDGE_PUNCTUATION = /^[\s,.;:]+|[\s,.;:]+$/g
/**
* The phrases of a dictation, one per item said: each segment (a pause or a line break,
* as the recognizer delivers them) is also split on "nuevo ítem". Spaces are collapsed,
* empty phrases dropped and a phrase repeated in the same dictation kept once (ignoring
* case and accents); the words themselves are left as heard.
*/
export function splitDictation(segments: string[]): string[] {
const phrases: string[] = []
const seen = new Set<string>()
for (const segment of segments) {
for (const part of segment.split(/\r?\n/).flatMap((line) => line.split(NEXT_ITEM))) {
const phrase = part.replace(/\s+/g, ' ').replace(EDGE_PUNCTUATION, '')
const key = normalizeWord(phrase)
if (!phrase || seen.has(key)) continue
seen.add(key)
phrases.push(phrase)
}
}
return phrases
}

View File

@@ -0,0 +1,34 @@
/** The slice of the Web Speech API the app uses (TypeScript's DOM lib does not ship it). */
export type SpeechRecognitionResultLike = { isFinal: boolean; 0: { transcript: string } }
export type SpeechRecognitionLike = {
lang: string
interimResults: boolean
continuous: boolean
maxAlternatives: number
onresult: ((event: { results: ArrayLike<SpeechRecognitionResultLike> }) => void) | null
onerror: ((event: { error: string }) => void) | null
onend: (() => void) | null
start: () => void
stop: () => void
abort: () => void
}
export type SpeechRecognitionConstructor = new () => SpeechRecognitionLike
/** `SpeechRecognition`, or Safari's `webkitSpeechRecognition`, or `null` when there is none. */
export function getSpeechRecognition(): SpeechRecognitionConstructor | null {
if (typeof window === 'undefined') return null
const speechWindow = window as Window & {
SpeechRecognition?: SpeechRecognitionConstructor
webkitSpeechRecognition?: SpeechRecognitionConstructor
}
return speechWindow.SpeechRecognition ?? speechWindow.webkitSpeechRecognition ?? null
}
/** Whether the page runs as an app installed on the iOS home screen. */
export function isIosStandalone(): boolean {
return (navigator as Navigator & { standalone?: boolean }).standalone === true
}

View File

@@ -0,0 +1,288 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import { z } from 'zod'
import { AppBrand } from '@/components/app-logo'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { emailOtp } from '@/lib/auth-client'
type ForgotPasswordSearch = { redirect?: string; email?: string }
export const Route = createFileRoute('/(auth)/forgot-password')({
validateSearch: (search: Record<string, unknown>): ForgotPasswordSearch => ({
redirect: typeof search.redirect === 'string' ? search.redirect : undefined,
email: typeof search.email === 'string' ? search.email : undefined,
}),
component: ForgotPasswordPage,
})
const requestSchema = z.object({
email: z.email('Introduce un correo electrónico válido'),
})
const resetSchema = z
.object({
otp: z.string().regex(/^\d{6}$/, 'El código tiene 6 dígitos'),
password: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'),
confirmPassword: z.string(),
})
.refine((values) => values.password === values.confirmPassword, {
message: 'Las contraseñas no coinciden',
path: ['confirmPassword'],
})
// BetterAuth answers in English; an unknown email reads like a wrong code so the
// form doesn't reveal which addresses have an account.
const resetErrorMessages: Record<string, string> = {
INVALID_OTP: 'El código no es correcto.',
USER_NOT_FOUND: 'El código no es correcto.',
OTP_EXPIRED: 'El código venció. Pide uno nuevo.',
TOO_MANY_ATTEMPTS: 'Demasiados intentos fallidos. Pide un código nuevo.',
}
type RequestValues = z.infer<typeof requestSchema>
type ResetValues = z.infer<typeof resetSchema>
function ForgotPasswordPage() {
const { redirect, email: initialEmail } = Route.useSearch()
const [email, setEmail] = useState<string | null>(null)
return (
<div className="flex min-h-svh flex-col items-center justify-center gap-6 p-6">
<AppBrand />
<Card className="w-full max-w-sm">
{email ? (
<ResetPasswordStep
email={email}
redirect={redirect}
onChangeEmail={() => setEmail(null)}
/>
) : (
<RequestCodeStep
defaultEmail={initialEmail ?? ''}
redirect={redirect}
onSent={setEmail}
/>
)}
</Card>
</div>
)
}
type RequestCodeStepProps = {
defaultEmail: string
redirect?: string
onSent: (email: string) => void
}
function RequestCodeStep({ defaultEmail, redirect, onSent }: RequestCodeStepProps) {
const [error, setError] = useState<string | null>(null)
const form = useForm<RequestValues>({
resolver: zodResolver(requestSchema),
defaultValues: { email: defaultEmail },
})
const onSubmit = form.handleSubmit(async ({ email }) => {
setError(null)
const { error: requestError } = await emailOtp.requestPasswordReset({ email })
if (requestError) {
setError(requestError.message ?? 'No pudimos enviar el código')
return
}
onSent(email)
})
return (
<>
<CardHeader>
<CardTitle>Recuperar contraseña</CardTitle>
<CardDescription>Te enviaremos un código por correo para elegir una nueva.</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={onSubmit} className="flex flex-col gap-6">
{error && (
<Alert variant="destructive">
<AlertTitle>No pudimos enviar el código</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<FieldGroup>
<Field data-invalid={!!form.formState.errors.email}>
<FieldLabel htmlFor="email">Correo electrónico</FieldLabel>
<Input
id="email"
type="email"
autoComplete="email"
placeholder="ada@ejemplo.com"
{...form.register('email')}
/>
<FieldError errors={[form.formState.errors.email]} />
</Field>
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? 'Enviando…' : 'Enviar código'}
</Button>
</FieldGroup>
<BackToSignIn redirect={redirect} />
</form>
</CardContent>
</>
)
}
type ResetPasswordStepProps = {
email: string
redirect?: string
onChangeEmail: () => void
}
function ResetPasswordStep({ email, redirect, onChangeEmail }: ResetPasswordStepProps) {
const navigate = useNavigate()
const [error, setError] = useState<string | null>(null)
const [resending, setResending] = useState(false)
const form = useForm<ResetValues>({
resolver: zodResolver(resetSchema),
defaultValues: { otp: '', password: '', confirmPassword: '' },
})
const onSubmit = form.handleSubmit(async ({ otp, password }) => {
setError(null)
const { error: resetError } = await emailOtp.resetPassword({ email, otp, password })
if (resetError) {
setError(
(resetError.code && resetErrorMessages[resetError.code]) ??
resetError.message ??
'No pudimos cambiar tu contraseña',
)
return
}
toast.success('Contraseña actualizada. Ya puedes iniciar sesión.')
await navigate({ to: '/sign-in', search: redirect ? { redirect } : {} })
})
const resend = async () => {
setResending(true)
const { error: requestError } = await emailOtp.requestPasswordReset({ email })
setResending(false)
if (requestError) {
toast.error(requestError.message ?? 'No pudimos reenviar el código')
return
}
toast.success('Te enviamos un código nuevo')
}
return (
<>
<CardHeader>
<CardTitle>Elige una nueva contraseña</CardTitle>
<CardDescription>
Si existe una cuenta con <span className="text-foreground font-medium">{email}</span>, te
enviamos un código de 6 dígitos. Vence en 10 minutos.
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={onSubmit} className="flex flex-col gap-6">
{error && (
<Alert variant="destructive">
<AlertTitle>No pudimos cambiar tu contraseña</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<FieldGroup>
<Field data-invalid={!!form.formState.errors.otp}>
<FieldLabel htmlFor="otp">Código</FieldLabel>
<Input
id="otp"
inputMode="numeric"
autoComplete="one-time-code"
maxLength={6}
placeholder="123456"
className="font-mono tracking-widest"
{...form.register('otp')}
/>
<FieldError errors={[form.formState.errors.otp]} />
</Field>
<Field data-invalid={!!form.formState.errors.password}>
<FieldLabel htmlFor="password">Nueva contraseña</FieldLabel>
<Input
id="password"
type="password"
autoComplete="new-password"
{...form.register('password')}
/>
<FieldError errors={[form.formState.errors.password]} />
</Field>
<Field data-invalid={!!form.formState.errors.confirmPassword}>
<FieldLabel htmlFor="confirmPassword">Repite la contraseña</FieldLabel>
<Input
id="confirmPassword"
type="password"
autoComplete="new-password"
{...form.register('confirmPassword')}
/>
<FieldError errors={[form.formState.errors.confirmPassword]} />
</Field>
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? 'Guardando…' : 'Cambiar contraseña'}
</Button>
</FieldGroup>
<div className="flex items-center justify-between text-sm">
<Button type="button" variant="link" className="h-auto p-0" onClick={onChangeEmail}>
Usar otro correo
</Button>
<Button
type="button"
variant="link"
className="h-auto p-0"
disabled={resending}
onClick={resend}
>
{resending ? 'Reenviando…' : 'Reenviar código'}
</Button>
</div>
<BackToSignIn redirect={redirect} />
</form>
</CardContent>
</>
)
}
function BackToSignIn({ redirect }: { redirect?: string }) {
return (
<p className="text-muted-foreground text-center text-sm">
¿Recordaste tu contraseña?{' '}
<Link
to="/sign-in"
search={redirect ? { redirect } : {}}
className="text-foreground font-medium underline-offset-4 hover:underline"
>
Inicia sesión
</Link>
</p>
)
}

View File

@@ -85,7 +85,19 @@ function SignInPage() {
</Field>
<Field data-invalid={!!form.formState.errors.password}>
<FieldLabel htmlFor="password">Contraseña</FieldLabel>
<div className="flex items-center justify-between">
<FieldLabel htmlFor="password">Contraseña</FieldLabel>
<Link
to="/forgot-password"
search={() => {
const email = form.getValues('email')
return { redirect, email: email || undefined }
}}
className="text-muted-foreground text-sm underline-offset-4 hover:text-foreground hover:underline"
>
¿Olvidaste tu contraseña?
</Link>
</div>
<Input
id="password"
type="password"