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';
@@ -0,0 +1,3 @@
-- AlterTable
ALTER TABLE "User" ADD COLUMN "failedAttempts" INTEGER NOT NULL DEFAULT 0,
ADD COLUMN "lockedUntil" TIMESTAMP(3);
+8 -6
View File
@@ -37,12 +37,14 @@ model Tenant {
}
model User {
id String @id @default(cuid())
tenantId String
email String
passwordHash String?
role UserRole @default(OPERATOR)
createdAt DateTime @default(now())
id String @id @default(cuid())
tenantId String
email String
passwordHash String?
role UserRole @default(OPERATOR)
createdAt DateTime @default(now())
failedAttempts Int @default(0)
lockedUntil DateTime?
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
+26 -9
View File
@@ -8,12 +8,19 @@ const here = path.dirname(fileURLToPath(import.meta.url));
loadEnv({ path: path.resolve(here, '../../../.env') });
const { PrismaClient, UserRole } = await import('@prisma/client');
const { hashSecret } = await import('../src/crypto.js');
const prisma = new PrismaClient();
const DEMO_TENANT_NAME = 'Demo Factory';
const DEMO_ADMIN_EMAIL = 'admin@demo.local';
const DEMO_ADMIN_PASSWORD = 'admin1234';
const OPERATOR_EMAILS = ['op1@demo.local', 'op2@demo.local', 'op3@demo.local'];
const OPERATORS = [
{ email: 'op1@demo.local', pin: '1111' },
{ email: 'op2@demo.local', pin: '2222' },
{ email: 'op3@demo.local', pin: '3333' },
];
const WORKSTATIONS = [
{ code: 'CTR04', name: 'Controlo 04', area: 'Montagem' },
@@ -38,23 +45,33 @@ async function main() {
tenantId: tenant.id,
email: DEMO_ADMIN_EMAIL,
role: UserRole.ADMIN,
passwordHash: await hashSecret(DEMO_ADMIN_PASSWORD),
},
});
await prisma.user.createMany({
data: OPERATOR_EMAILS.map((email) => ({
tenantId: tenant.id,
email,
role: UserRole.OPERATOR,
})),
});
for (const op of OPERATORS) {
await prisma.user.create({
data: {
tenantId: tenant.id,
email: op.email,
role: UserRole.OPERATOR,
passwordHash: await hashSecret(op.pin),
},
});
}
await prisma.workstation.createMany({
data: WORKSTATIONS.map((ws) => ({ tenantId: tenant.id, ...ws })),
});
console.warn(
`Seed complete — tenant=${tenant.id} (${tenant.name}), admin=${DEMO_ADMIN_EMAIL}, operators=${OPERATOR_EMAILS.length}, workstations=${WORKSTATIONS.length}`,
`Seed complete — tenant=${tenant.id} (${tenant.name})`,
);
console.warn(
` admin: ${DEMO_ADMIN_EMAIL} / ${DEMO_ADMIN_PASSWORD}`,
);
console.warn(
` operadores: ${OPERATORS.map((o) => `${o.email}=${o.pin}`).join(' | ')}`,
);
}
+23
View File
@@ -0,0 +1,23 @@
import { randomBytes, scrypt as _scrypt, timingSafeEqual } from 'node:crypto';
import { promisify } from 'node:util';
const scrypt = promisify(_scrypt);
const KEYLEN = 64;
/** Returns "scrypt$<saltHex>$<hashHex>". Works for both passwords (admin) and PINs (operator). */
export async function hashSecret(plain: string): Promise<string> {
const salt = randomBytes(16);
const derived = (await scrypt(plain, salt, KEYLEN)) as Buffer;
return `scrypt$${salt.toString('hex')}$${derived.toString('hex')}`;
}
/** Constant-time verification. Returns false for null/malformed stored values — never throws. */
export async function verifySecret(plain: string, stored: string | null): Promise<boolean> {
if (!stored) return false;
const [scheme, saltHex, hashHex] = stored.split('$');
if (scheme !== 'scrypt' || !saltHex || !hashHex) return false;
const salt = Buffer.from(saltHex, 'hex');
const expected = Buffer.from(hashHex, 'hex');
const derived = (await scrypt(plain, salt, expected.length)) as Buffer;
return derived.length === expected.length && timingSafeEqual(derived, expected);
}
+1
View File
@@ -2,3 +2,4 @@ export { prisma, type DbClient } from './client';
export { tenantScoped, type TenantScopedClient } from './tenant-extension';
export { Prisma, UserRole, MaintenanceRequestStatus } from '@prisma/client';
export type { User, Tenant, Workstation, DomainEvent, MaintenanceRequest } from '@prisma/client';
export { hashSecret, verifySecret } from './crypto';