feat(auth): add API token authentication for OpenSheets Companion

- Implement JWT-based authentication system for device access
  - Access tokens (7 day expiry) and refresh tokens (90 day expiry)
  - HMAC-SHA256 signing with timing-safe comparison
  - Token hashing with SHA-256 for secure storage

- Add device authentication endpoints:
  - POST /api/auth/device/token - Login with email/password, get tokens
  - POST /api/auth/device/refresh - Refresh access token
  - POST /api/auth/device/verify - Verify token validity
  - GET /api/auth/device/tokens - List user's API tokens
  - DELETE /api/auth/device/tokens/[id] - Revoke specific token

- Track token usage (last used timestamp and IP)
This commit is contained in:
Felipe Coutinho
2026-01-23 12:11:19 +00:00
parent 29a457ad36
commit 2532f2d6ad
6 changed files with 584 additions and 0 deletions

View File

@@ -0,0 +1,65 @@
/**
* DELETE /api/auth/device/tokens/[tokenId]
*
* Revoga um token de API específico.
* Requer sessão web autenticada.
*/
import { auth } from "@/lib/auth/config";
import { db } from "@/lib/db";
import { apiTokens } from "@/db/schema";
import { eq, and } from "drizzle-orm";
import { headers } from "next/headers";
import { NextResponse } from "next/server";
interface RouteParams {
params: Promise<{ tokenId: string }>;
}
export async function DELETE(request: Request, { params }: RouteParams) {
try {
const { tokenId } = await params;
// Verificar autenticação via sessão web
const session = await auth.api.getSession({ headers: await headers() });
if (!session?.user) {
return NextResponse.json(
{ error: "Não autenticado" },
{ status: 401 }
);
}
// Verificar se token pertence ao usuário
const token = await db.query.apiTokens.findFirst({
where: and(
eq(apiTokens.id, tokenId),
eq(apiTokens.userId, session.user.id)
),
});
if (!token) {
return NextResponse.json(
{ error: "Token não encontrado" },
{ status: 404 }
);
}
// Revogar token (soft delete)
await db
.update(apiTokens)
.set({ revokedAt: new Date() })
.where(eq(apiTokens.id, tokenId));
return NextResponse.json({
message: "Token revogado com sucesso",
tokenId,
});
} catch (error) {
console.error("[API] Error revoking device token:", error);
return NextResponse.json(
{ error: "Erro ao revogar token" },
{ status: 500 }
);
}
}