fix(api): use hash-based token validation instead of JWT

Changed all API endpoints to validate os_xxx tokens via SHA-256 hash
lookup in the database instead of expecting JWT format.

This allows tokens generated in the settings page (Ajustes → Dispositivos)
to work correctly with the Android app.

- /api/auth/device/verify: validates os_xxx tokens via hash
- /api/inbox: uses hash-based auth
- /api/inbox/batch: uses hash-based auth
- No token expiration (tokens valid until revoked)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Felipe Coutinho
2026-01-23 13:14:54 +00:00
parent b2ba3efd63
commit 2d62fd0302
4 changed files with 70 additions and 47 deletions

View File

@@ -3,9 +3,11 @@
* *
* Valida se um token de API é válido. * Valida se um token de API é válido.
* Usado pelo app Android durante o setup. * Usado pelo app Android durante o setup.
*
* Aceita tokens no formato os_xxx (hash-based, sem expiração).
*/ */
import { validateApiToken, extractBearerToken } from "@/lib/auth/api-token"; import { extractBearerToken, hashToken } from "@/lib/auth/api-token";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { apiTokens } from "@/db/schema"; import { apiTokens } from "@/db/schema";
import { eq, and, isNull } from "drizzle-orm"; import { eq, and, isNull } from "drizzle-orm";
@@ -24,47 +26,50 @@ export async function POST(request: Request) {
); );
} }
// Validar JWT // Validar token os_xxx via hash lookup
const payload = validateApiToken(token); if (!token.startsWith("os_")) {
if (!payload) {
return NextResponse.json( return NextResponse.json(
{ valid: false, error: "Token inválido ou expirado" }, { valid: false, error: "Formato de token inválido" },
{ status: 401 } { status: 401 }
); );
} }
// Verificar se token não foi revogado // Hash do token para buscar no DB
const tokenHash = hashToken(token);
// Buscar token no banco
const tokenRecord = await db.query.apiTokens.findFirst({ const tokenRecord = await db.query.apiTokens.findFirst({
where: and( where: and(
eq(apiTokens.id, payload.tokenId), eq(apiTokens.tokenHash, tokenHash),
eq(apiTokens.userId, payload.sub),
isNull(apiTokens.revokedAt) isNull(apiTokens.revokedAt)
), ),
}); });
if (!tokenRecord) { if (!tokenRecord) {
return NextResponse.json( return NextResponse.json(
{ valid: false, error: "Token revogado ou não encontrado" }, { valid: false, error: "Token inválido ou revogado" },
{ status: 401 } { status: 401 }
); );
} }
// Atualizar último uso // Atualizar último uso
const clientIp = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim()
|| request.headers.get("x-real-ip")
|| null;
await db await db
.update(apiTokens) .update(apiTokens)
.set({ .set({
lastUsedAt: new Date(), lastUsedAt: new Date(),
lastUsedIp: request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip"), lastUsedIp: clientIp,
}) })
.where(eq(apiTokens.id, payload.tokenId)); .where(eq(apiTokens.id, tokenRecord.id));
return NextResponse.json({ return NextResponse.json({
valid: true, valid: true,
userId: payload.sub, userId: tokenRecord.userId,
tokenId: payload.tokenId, tokenId: tokenRecord.id,
tokenName: tokenRecord.name, tokenName: tokenRecord.name,
expiresAt: new Date(payload.exp * 1000).toISOString(),
}); });
} catch (error) { } catch (error) {
console.error("[API] Error verifying device token:", error); console.error("[API] Error verifying device token:", error);

View File

@@ -2,10 +2,10 @@
* POST /api/inbox/batch * POST /api/inbox/batch
* *
* Recebe múltiplas notificações do app Android (sync offline). * Recebe múltiplas notificações do app Android (sync offline).
* Requer autenticação via API token. * Requer autenticação via API token (formato os_xxx).
*/ */
import { validateApiToken, extractBearerToken } from "@/lib/auth/api-token"; import { extractBearerToken, hashToken } from "@/lib/auth/api-token";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { apiTokens, inboxItems } from "@/db/schema"; import { apiTokens, inboxItems } from "@/db/schema";
import { eq, and, isNull } from "drizzle-orm"; import { eq, and, isNull } from "drizzle-orm";
@@ -55,34 +55,33 @@ export async function POST(request: Request) {
); );
} }
// Validar JWT // Validar token os_xxx via hash
const payload = validateApiToken(token); if (!token.startsWith("os_")) {
if (!payload) {
return NextResponse.json( return NextResponse.json(
{ error: "Token inválido ou expirado" }, { error: "Formato de token inválido" },
{ status: 401 } { status: 401 }
); );
} }
// Verificar se token não foi revogado const tokenHash = hashToken(token);
// Buscar token no banco
const tokenRecord = await db.query.apiTokens.findFirst({ const tokenRecord = await db.query.apiTokens.findFirst({
where: and( where: and(
eq(apiTokens.id, payload.tokenId), eq(apiTokens.tokenHash, tokenHash),
eq(apiTokens.userId, payload.sub),
isNull(apiTokens.revokedAt) isNull(apiTokens.revokedAt)
), ),
}); });
if (!tokenRecord) { if (!tokenRecord) {
return NextResponse.json( return NextResponse.json(
{ error: "Token revogado ou não encontrado" }, { error: "Token inválido ou revogado" },
{ status: 401 } { status: 401 }
); );
} }
// Rate limiting // Rate limiting
if (!checkRateLimit(payload.sub)) { if (!checkRateLimit(tokenRecord.userId)) {
return NextResponse.json( return NextResponse.json(
{ error: "Limite de requisições excedido", retryAfter: 60 }, { error: "Limite de requisições excedido", retryAfter: 60 },
{ status: 429 } { status: 429 }
@@ -101,10 +100,10 @@ export async function POST(request: Request) {
const [inserted] = await db const [inserted] = await db
.insert(inboxItems) .insert(inboxItems)
.values({ .values({
userId: payload.sub, userId: tokenRecord.userId,
sourceApp: item.sourceApp, sourceApp: item.sourceApp,
sourceAppName: item.sourceAppName, sourceAppName: item.sourceAppName,
deviceId: item.deviceId || payload.deviceId, deviceId: item.deviceId,
originalTitle: item.originalTitle, originalTitle: item.originalTitle,
originalText: item.originalText, originalText: item.originalText,
notificationTimestamp: item.notificationTimestamp, notificationTimestamp: item.notificationTimestamp,
@@ -132,13 +131,17 @@ export async function POST(request: Request) {
} }
// Atualizar último uso do token // Atualizar último uso do token
const clientIp = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim()
|| request.headers.get("x-real-ip")
|| null;
await db await db
.update(apiTokens) .update(apiTokens)
.set({ .set({
lastUsedAt: new Date(), lastUsedAt: new Date(),
lastUsedIp: request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip"), lastUsedIp: clientIp,
}) })
.where(eq(apiTokens.id, payload.tokenId)); .where(eq(apiTokens.id, tokenRecord.id));
const successCount = results.filter((r) => r.success).length; const successCount = results.filter((r) => r.success).length;
const failCount = results.filter((r) => !r.success).length; const failCount = results.filter((r) => !r.success).length;

View File

@@ -2,10 +2,10 @@
* POST /api/inbox * POST /api/inbox
* *
* Recebe uma notificação do app Android. * Recebe uma notificação do app Android.
* Requer autenticação via API token. * Requer autenticação via API token (formato os_xxx).
*/ */
import { validateApiToken, extractBearerToken } from "@/lib/auth/api-token"; import { extractBearerToken, hashToken } from "@/lib/auth/api-token";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { apiTokens, inboxItems } from "@/db/schema"; import { apiTokens, inboxItems } from "@/db/schema";
import { eq, and, isNull } from "drizzle-orm"; import { eq, and, isNull } from "drizzle-orm";
@@ -48,34 +48,33 @@ export async function POST(request: Request) {
); );
} }
// Validar JWT // Validar token os_xxx via hash
const payload = validateApiToken(token); if (!token.startsWith("os_")) {
if (!payload) {
return NextResponse.json( return NextResponse.json(
{ error: "Token inválido ou expirado" }, { error: "Formato de token inválido" },
{ status: 401 } { status: 401 }
); );
} }
// Verificar se token não foi revogado const tokenHash = hashToken(token);
// Buscar token no banco
const tokenRecord = await db.query.apiTokens.findFirst({ const tokenRecord = await db.query.apiTokens.findFirst({
where: and( where: and(
eq(apiTokens.id, payload.tokenId), eq(apiTokens.tokenHash, tokenHash),
eq(apiTokens.userId, payload.sub),
isNull(apiTokens.revokedAt) isNull(apiTokens.revokedAt)
), ),
}); });
if (!tokenRecord) { if (!tokenRecord) {
return NextResponse.json( return NextResponse.json(
{ error: "Token revogado ou não encontrado" }, { error: "Token inválido ou revogado" },
{ status: 401 } { status: 401 }
); );
} }
// Rate limiting // Rate limiting
if (!checkRateLimit(payload.sub)) { if (!checkRateLimit(tokenRecord.userId)) {
return NextResponse.json( return NextResponse.json(
{ error: "Limite de requisições excedido", retryAfter: 60 }, { error: "Limite de requisições excedido", retryAfter: 60 },
{ status: 429 } { status: 429 }
@@ -90,10 +89,10 @@ export async function POST(request: Request) {
const [inserted] = await db const [inserted] = await db
.insert(inboxItems) .insert(inboxItems)
.values({ .values({
userId: payload.sub, userId: tokenRecord.userId,
sourceApp: data.sourceApp, sourceApp: data.sourceApp,
sourceAppName: data.sourceAppName, sourceAppName: data.sourceAppName,
deviceId: data.deviceId || payload.deviceId, deviceId: data.deviceId,
originalTitle: data.originalTitle, originalTitle: data.originalTitle,
originalText: data.originalText, originalText: data.originalText,
notificationTimestamp: data.notificationTimestamp, notificationTimestamp: data.notificationTimestamp,
@@ -107,13 +106,17 @@ export async function POST(request: Request) {
.returning({ id: inboxItems.id }); .returning({ id: inboxItems.id });
// Atualizar último uso do token // Atualizar último uso do token
const clientIp = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim()
|| request.headers.get("x-real-ip")
|| null;
await db await db
.update(apiTokens) .update(apiTokens)
.set({ .set({
lastUsedAt: new Date(), lastUsedAt: new Date(),
lastUsedIp: request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip"), lastUsedIp: clientIp,
}) })
.where(eq(apiTokens.id, payload.tokenId)); .where(eq(apiTokens.id, tokenRecord.id));
return NextResponse.json( return NextResponse.json(
{ {

View File

@@ -216,6 +216,7 @@ export function extractBearerToken(authHeader: string | null): string | null {
/** /**
* Validate an API token and return the payload * Validate an API token and return the payload
* @deprecated Use validateHashToken for os_xxx tokens
*/ */
export function validateApiToken(token: string): JwtPayload | null { export function validateApiToken(token: string): JwtPayload | null {
const payload = verifyJwt(token); const payload = verifyJwt(token);
@@ -224,3 +225,14 @@ export function validateApiToken(token: string): JwtPayload | null {
} }
return payload; return payload;
} }
/**
* Validate a hash-based API token (os_xxx format)
* Returns the token hash for database lookup
*/
export function validateHashToken(token: string): { valid: boolean; tokenHash?: string } {
if (!token || !token.startsWith("os_")) {
return { valid: false };
}
return { valid: true, tokenHash: hashToken(token) };
}