Files
Momento/memento-note/lib/mobile-auth.ts
Antigravity df2b9c2c7b
All checks were successful
CI / Lint, Unit Tests & Build (push) Successful in 5m21s
CI / Deploy production (on server) (push) Successful in 23s
fix(audit): mobile critique + sécurité mobile + verifyMobileToken async
Mobile fixes (CRITIQUE):
- theme.ts: C.surface + emerald/blue/amber/purple ajoutés (crash Révision fix)
- note/[id].tsx: édition préserve le HTML (titre seulement, contenu read-only)
  + message explicatif 'utilisez la version web'
- store.ts: logout appelle POST /api/mobile/auth/logout avant clearToken

Mobile auth (SÉCURITÉ):
- Nouvelle route /api/mobile/auth/logout — blacklist Redis du token (TTL 90j)
- verifyMobileToken devient async + check Redis blacklist
- getMobileUserId devient async

Note: Publication IA mode + templates déjà dans note-editor-toolbar.tsx (pas manquant)
Note: Structured Views Wizard déjà branché via StructuredViewsIntro (pas orphelin)
2026-07-05 16:30:01 +00:00

56 lines
2.0 KiB
TypeScript

/**
* Mobile auth helper — validates Bearer token and returns userId
* Token format: base64url(userId:timestamp:hmac)
*/
import { createHmac, timingSafeEqual } from 'crypto'
function getSecret(): string {
const secret = process.env.NEXTAUTH_SECRET
if (!secret) {
throw new Error('NEXTAUTH_SECRET is required for mobile auth')
}
return secret
}
export function createMobileToken(userId: string): string {
const ts = Date.now()
const payload = `${userId}:${ts}`
const sig = createHmac('sha256', getSecret()).update(payload).digest('hex')
return Buffer.from(`${payload}:${sig}`).toString('base64url')
}
export async function verifyMobileToken(token: string): Promise<string | null> {
try {
// Check Redis blacklist first (non-blocking — if Redis is down, allow)
try {
const { redis } = await import('@/lib/redis')
const revoked = await redis.get(`mobile:revoked:${token}`)
if (revoked) return null
} catch {}
const decoded = Buffer.from(token, 'base64url').toString('utf-8')
const lastColon = decoded.lastIndexOf(':')
if (lastColon === -1) return null
const sig = decoded.slice(lastColon + 1)
const payload = decoded.slice(0, lastColon)
const secondColon = payload.lastIndexOf(':')
if (secondColon === -1) return null
const userId = payload.slice(0, secondColon)
const ts = payload.slice(secondColon + 1)
const expected = createHmac('sha256', getSecret()).update(payload).digest('hex')
const sigBuf = Buffer.from(sig)
const expectedBuf = Buffer.from(expected)
if (sigBuf.length !== expectedBuf.length || !timingSafeEqual(sigBuf, expectedBuf)) return null
if (Date.now() - Number(ts) > 90 * 24 * 60 * 60 * 1000) return null
return userId
} catch {
return null
}
}
export async function getMobileUserId(request: Request): Promise<string | null> {
const auth = request.headers.get('Authorization')
if (!auth?.startsWith('Bearer ')) return null
return verifyMobileToken(auth.slice(7))
}