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
@@ -0,0 +1,4 @@
import { handlers } from '@/lib/auth';
export const { GET, POST } = handlers;
export const runtime = 'nodejs';
+79
View File
@@ -0,0 +1,79 @@
'use client';
import { useState, type FormEvent } from 'react';
import { useRouter } from 'next/navigation';
import { signIn } from 'next-auth/react';
export function LoginForm() {
const router = useRouter();
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const form = e.currentTarget;
const email = (form.elements.namedItem('email') as HTMLInputElement).value;
const password = (form.elements.namedItem('password') as HTMLInputElement).value;
setBusy(true);
setError(null);
try {
const result = await signIn('credentials', { email, password, redirect: false });
if (result?.error) {
setError('Email ou password incorretos. Tente novamente.');
} else {
router.push('/maintenance');
router.refresh();
}
} catch {
setError('Erro inesperado. Tente novamente.');
} finally {
setBusy(false);
}
}
return (
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
<div className="flex flex-col gap-1.5">
<label htmlFor="email" className="text-sm font-medium">
Email
</label>
<input
id="email"
name="email"
type="email"
required
autoComplete="email"
disabled={busy}
className="rounded-lg border border-border bg-background px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary disabled:opacity-50"
placeholder="admin@demo.local"
/>
</div>
<div className="flex flex-col gap-1.5">
<label htmlFor="password" className="text-sm font-medium">
Password
</label>
<input
id="password"
name="password"
type="password"
required
autoComplete="current-password"
disabled={busy}
className="rounded-lg border border-border bg-background px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary disabled:opacity-50"
/>
</div>
{error && <p className="text-sm text-destructive">{error}</p>}
<button
type="submit"
disabled={busy}
className="mt-2 w-full rounded-xl bg-primary py-3 text-sm font-semibold text-primary-foreground transition-opacity hover:opacity-90 active:scale-[0.98] disabled:opacity-50"
>
{busy ? 'A entrar…' : 'Entrar'}
</button>
</form>
);
}
+15
View File
@@ -0,0 +1,15 @@
import { LoginForm } from './login-form';
export default function LoginPage() {
return (
<main className="mx-auto flex min-h-screen max-w-sm flex-col justify-center gap-8 p-6">
<header className="text-center">
<h1 className="text-2xl font-bold tracking-tight">FieldOps</h1>
<p className="mt-1 text-sm text-muted-foreground">
Acesso à consola de manutenção
</p>
</header>
<LoginForm />
</main>
);
}
+2
View File
@@ -4,6 +4,7 @@ import { z } from 'zod';
export const env = createEnv({
server: {
DATABASE_URL: z.string().url(),
AUTH_SECRET: z.string().min(1, 'AUTH_SECRET is required'),
AUTH_DEV_AUTOLOGIN: z
.string()
.optional()
@@ -17,6 +18,7 @@ export const env = createEnv({
},
runtimeEnv: {
DATABASE_URL: process.env.DATABASE_URL,
AUTH_SECRET: process.env.AUTH_SECRET,
AUTH_DEV_AUTOLOGIN: process.env.AUTH_DEV_AUTOLOGIN,
LOG_LEVEL: process.env.LOG_LEVEL,
NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL,
+44
View File
@@ -0,0 +1,44 @@
import type { NextAuthConfig } from 'next-auth';
/**
* Edge-safe portion of the Auth.js config for admin-web.
* Imported by middleware — no Credentials provider, no Prisma.
*/
export const authConfig = {
trustHost: true,
session: { strategy: 'jwt' },
pages: {
signIn: '/login',
},
// Distinct cookie names prevent session collision with operator-pwa on localhost
// (cookies are not isolated by port — only by name and domain).
cookies: {
sessionToken: { name: 'fieldops-admin.session-token' },
callbackUrl: { name: 'fieldops-admin.callback-url' },
csrfToken: { name: 'fieldops-admin.csrf-token' },
},
callbacks: {
async jwt({ token, user }) {
if (user) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const u = user as any;
token.id = u.id;
token.role = u.role;
token.tenantId = u.tenantId;
}
return token;
},
async session({ session, token }) {
if (token && session.user) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(session.user as any).id = token.id;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(session.user as any).role = token.role;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(session.user as any).tenantId = token.tenantId;
}
return session;
},
},
providers: [],
} satisfies NextAuthConfig;
+65 -11
View File
@@ -1,18 +1,72 @@
import NextAuth from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { prisma } from '@repo/db';
import { authenticateCredential } from '@repo/api';
import type { SessionUser } from '@repo/api';
import { authConfig } from './auth.config';
// v0.1 admin-web auth: AUTH_DEV_AUTOLOGIN=true → always admin@demo.local.
// No session/cookie mechanism needed for the demo phase.
const AUTH_SECRET = process.env['AUTH_SECRET'];
export const { handlers, auth, signIn, signOut } = NextAuth({
...authConfig,
secret: AUTH_SECRET,
providers: [
Credentials({
name: 'Email + password',
credentials: {
email: { label: 'Email', type: 'email' },
password: { label: 'Password', type: 'password' },
},
async authorize(credentials) {
const email = credentials?.email;
const password = credentials?.password;
if (typeof email !== 'string' || typeof password !== 'string') return null;
const u = await authenticateCredential({
email,
secret: password,
allowedRoles: ['ADMIN', 'SUPERVISOR'],
});
if (!u) return null;
return {
id: u.id,
email: u.email,
name: u.email,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
role: u.role as any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
tenantId: u.tenantId as any,
};
},
}),
],
});
/**
* Resolve the current user for server-side code (RSC, route handlers, tRPC).
* Falls back to dev autologin only outside production.
*/
export async function resolveUser(): Promise<SessionUser | null> {
if (process.env['AUTH_DEV_AUTOLOGIN'] !== 'true') return null;
const session = await auth();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const u = session?.user as any;
if (u?.id && u?.tenantId) {
return { id: u.id, email: u.email, role: u.role, tenantId: u.tenantId };
}
const admin = await prisma.user.findFirst({ where: { email: 'admin@demo.local' } });
if (!admin) return null;
const autologinAllowed =
process.env['AUTH_DEV_AUTOLOGIN'] === 'true' && process.env.NODE_ENV !== 'production';
if (autologinAllowed) {
const admin = await prisma.user.findFirst({ where: { email: 'admin@demo.local' } });
if (admin) {
return {
id: admin.id,
email: admin.email,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
role: admin.role as any,
tenantId: admin.tenantId,
};
}
}
return {
id: admin.id,
email: admin.email,
role: admin.role as 'ADMIN',
tenantId: admin.tenantId,
};
return null;
}
+26
View File
@@ -0,0 +1,26 @@
import NextAuth from 'next-auth';
import { authConfig } from './lib/auth.config';
const { auth } = NextAuth(authConfig);
export default auth((req) => {
const isLoggedIn = !!req.auth?.user;
const isAutologin =
process.env['AUTH_DEV_AUTOLOGIN'] === 'true' && process.env.NODE_ENV !== 'production';
const { pathname } = req.nextUrl;
if (pathname === '/login') {
if (isLoggedIn) return Response.redirect(new URL('/maintenance', req.url));
return;
}
if (!isLoggedIn && !isAutologin) {
return Response.redirect(new URL('/login', req.url));
}
});
export const config = {
matcher: [
'/((?!api/auth|api/trpc|_next/static|_next/image|favicon.ico).*)',
],
};
+1
View File
@@ -1,4 +1,5 @@
import type { NextConfig } from 'next';
import './env'; // Validate env vars at build time
const config: NextConfig = {
transpilePackages: ['@repo/db', '@repo/api', '@repo/ui', '@repo/storage'],
+1
View File
@@ -23,6 +23,7 @@
"@trpc/server": "^11.0.0",
"lucide-react": "^0.469.0",
"next": "15.3.9",
"next-auth": "5.0.0-beta.25",
"pino": "^9.5.0",
"pino-pretty": "^11.3.0",
"react": "^19.0.0",