MAI CALL - auth v0.2

# O que mudou
1 Schema: failedAttempts + lockedUntil em User; migration auth_v0_2_lockout aplicada; crypto.ts com hashSecret/verifySecret (Node scrypt nativo, zero deps)
2 packages/api/src/auth.ts — authenticateCredential com lockout de 5 tentativas
3 Seed reescrito: admin hashed admin1234, operadores hashed 1111/2222/3333
4 Porta das traseiras fechada: AUTH_DEV_AUTOLOGIN ignorado quando NODE_ENV=production, em ambas as apps
5 operator-pwa: Credentials provider usa PIN + allowedRoles:['OPERATOR']; cookies fieldops-op.*
6 Picker em 2 estados: lista → teclado PIN (botões grandes, dots de progresso, mensagem de erro sem dar pistas)
7 admin-web: Auth.js completo (auth.config, auth.ts, route handler, middleware, /login page, AUTH_SECRET no env) com cookies fieldops-admin.*
8 scripts/auth-smoke.ts (11/11 ✓); .env.example e README atualizados
This commit is contained in:
2026-05-30 11:54:38 +01:00
parent bed5419409
commit 1bc837e606
25 changed files with 1119 additions and 80 deletions
+43
View File
@@ -0,0 +1,43 @@
import { prisma, verifySecret } from '@repo/db';
import type { SessionUser } from './context';
const MAX_ATTEMPTS = 5;
const LOCK_MS = 5 * 60_000;
/**
* Authenticates by email + secret (PIN or password), restricted to the given roles.
* Uses the unscoped Prisma client: login happens before a tenant is known.
* Returns the SessionUser on success, null on any failure (wrong credentials, wrong role, lockout).
*/
export async function authenticateCredential(opts: {
email: string;
secret: string;
allowedRoles: SessionUser['role'][];
}): Promise<SessionUser | null> {
const user = await prisma.user.findFirst({ where: { email: opts.email } });
if (!user) return null;
if (!opts.allowedRoles.includes(user.role)) return null;
if (user.lockedUntil && user.lockedUntil > new Date()) return null;
const ok = await verifySecret(opts.secret, user.passwordHash);
if (!ok) {
const attempts = user.failedAttempts + 1;
await prisma.user.update({
where: { id: user.id },
data: {
failedAttempts: attempts,
lockedUntil: attempts >= MAX_ATTEMPTS ? new Date(Date.now() + LOCK_MS) : null,
},
});
return null;
}
if (user.failedAttempts !== 0 || user.lockedUntil) {
await prisma.user.update({
where: { id: user.id },
data: { failedAttempts: 0, lockedUntil: null },
});
}
return { id: user.id, email: user.email, role: user.role, tenantId: user.tenantId };
}
+1
View File
@@ -1,3 +1,4 @@
export { appRouter, type AppRouter } from './routers/_app';
export { createTRPCContext, type Context, type SessionUser } from './context';
export { createCallerFactory } from './trpc';
export { authenticateCredential } from './auth';