API de acortador de links con autenticacion real de admin para panel Vue.
- Cloudflare Workers
- Hono
- Cloudflare KV
Usa .env.example como base para local.
Variables principales:
APP_ENV:developmentoproductionFRONTEND_ORIGIN: origen del frontend para CORSSESSION_COOKIE_NAME: nombre de cookie de sesionSESSION_TTL_SECONDS: TTL de sesion en segundosCOOKIE_SAME_SITE:Lax,StrictoNoneCOOKIE_SECURE:trueofalseSEED_ADMIN_ENABLED: habilita seed inicial por envSEED_ADMIN_USERNAME: username del seedSEED_ADMIN_PASSWORD_HASH: hash bcrypt del seed
Body JSON:
{ "username": "admin", "password": "admin123" }
Respuesta 200:
{ "user": { "id": "...", "username": "admin", "role": "admin" } }
Setea cookie de sesion httpOnly compatible con credentials: include.
Respuesta 200:
{ "user": { "id": "...", "username": "admin", "role": "admin" } }
Si no hay sesion valida: 401.
Invalida sesion y limpia cookie.
Respuesta: 204.
Middlewares:
requireAuth: valida sesion desde cookierequireAdmin: valida sesion y rol admin
Respuestas:
- 401 si no autenticado
- 403 si no autorizado
Publica:
GET /:nameredirige al link
Protegidas por admin:
GET /api/linksPOST /api/linksPUT /api/links/:nameDELETE /api/links/:name
Se implementa equivalente de tabla users usando KV:
- key:
__auth:user:<username> - value:
idusernameunicopasswordhash bcryptroleuser/admincreated_atupdated_at
Sesiones:
- key:
__auth:session:<session-id> - value:
{ id, user, created_at } - expiracion por TTL
Detalle de migracion y rollback en:
migrations/001_users_kv_equivalent.md
- Genera hash bcrypt:
bun run auth:hash "tu-password-segura"
- Configura:
SEED_ADMIN_ENABLED=trueSEED_ADMIN_USERNAME=adminSEED_ADMIN_PASSWORD_HASH=<hash generado>
- Inicia el worker y realiza login.
El admin se crea automaticamente si no existe.
- Login:
curl -i -X POST http://127.0.0.1:8787/api/auth/login
-H "Origin: http://localhost:5173"
-H "Content-Type: application/json"
-d '{"username":"admin","password":"admin123"}'
-c cookie.txt
- Me:
curl -i http://127.0.0.1:8787/api/auth/me
-H "Origin: http://localhost:5173"
-b cookie.txt
- Crear link (admin):
curl -i -X POST http://127.0.0.1:8787/api/links
-H "Origin: http://localhost:5173"
-H "Content-Type: application/json"
-b cookie.txt
-d '{"name":"promo","url":"https://example.com"}'
- Logout:
curl -i -X POST http://127.0.0.1:8787/api/auth/logout
-H "Origin: http://localhost:5173"
-b cookie.txt
bun run test