All backend auth now goes through our own token service — Firebase Auth
dependency is fully removed from auth paths. FCM (firebase-admin messaging)
is still used for push.
Schema:
- auth_sessions (multi-device refresh tokens, bcrypt-hashed)
- otp_requests (Fazpass reference + rate-limit history)
- customers.email + google_sub + apple_sub (social identity)
- control_center_users.password_hash + failed_login_count + lockout_until
- firebase_uid columns made nullable (drop in later cleanup migration)
- 6 new app_config keys for OTP + CC lockout tuning
Services:
- password.service.js — bcrypt cost 12 + complexity (min 8, digit + upper +
lower)
- token.service.js — JWT HS256 access (1h) + opaque refresh (30d, bcrypt-
hashed, rotated on use); session_id claim pre-wires future Valkey-based
instant revocation; revokeSession + revokeAllSessionsForUser helpers
- social-identity.service.js — Google via google-auth-library, Apple via
jwks-rsa + jsonwebtoken
- otp.service.js — Fazpass stub (generates locally, logs the code) clearly
marked for replacement once real API docs arrive; rate-limit + resend
cooldown + verify-attempts all configurable via app_config
- auth.service.js — orchestrator: signInAnonymous, completeCustomer/Mitra-
PhoneSignIn, signInWithGoogle, signInWithApple, signInCcUser, refresh,
logout; reject-on-existing for identity conflicts
- cc-user.service.js — email+password helpers + lockout counters
Routes & middleware:
- authenticate middleware now verifies our JWT and attaches
request.auth = { userType, userId, sessionId }
- WebSocket handshake verifies our JWT (no more Firebase lookup)
- All existing routes updated to use request.auth.userId instead of
request.firebaseUser.uid
- New public routes:
/api/shared/auth/anonymous /refresh /logout
/api/client/auth/otp/request /otp/verify /google /apple /me /profile
/api/mitra/auth/otp/request /otp/verify /me
- New internal routes:
/internal/auth/login /refresh /logout /me (httpOnly cookie refresh)
/internal/control-center-users (accepts plain password, bcrypt-hashed)
/internal/control-center-users/me/password (self-service change)
/internal/control-center-users/:id/password (admin forced reset)
- Deleted legacy customer.routes.js (anonymous + link handled by auth now)
- app.internal.js: @fastify/cookie + CORS credentials for CC httpOnly cookie
Config:
- AUTH_JWT_SECRET + ACCESS_TOKEN_TTL_SECONDS + REFRESH_TOKEN_TTL_DAYS env
- FAZPASS_* env vars (TBD until real API docs)
- GOOGLE_OAUTH_CLIENT_IDS, APPLE_SERVICES_ID/TEAM_ID/KEY_ID/PRIVATE_KEY
- ADMIN_EMAIL + ADMIN_PASSWORD for seed
- CC_ORIGIN for internal-app CORS origin allowlist
Dependencies:
- Added: bcrypt, jsonwebtoken, jwks-rsa, google-auth-library, @fastify/cookie
- Kept: firebase-admin (messaging only)
Still outstanding: Fazpass API integration (stub in place), Apple Developer
prereqs for end-to-end iOS testing, client_app/mitra_app/control_center auth
flow rewrites.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
122 lines
4.9 KiB
JavaScript
122 lines
4.9 KiB
JavaScript
import { authenticate } from '../../plugins/auth.js'
|
|
import { getMessages } from '../../services/chat.service.js'
|
|
import { getSessionClosures } from '../../services/closure.service.js'
|
|
import { registerDeviceToken } from '../../services/notification.service.js'
|
|
import { flipSessionSensitivity } from '../../services/sensitivity.service.js'
|
|
import { getDb } from '../../db/client.js'
|
|
import { TopicSensitivity, UserType } from '../../constants.js'
|
|
|
|
const sql = getDb()
|
|
|
|
const resolveUser = async (request, reply) => {
|
|
if (request.auth?.userType !== UserType.CUSTOMER && request.auth?.userType !== UserType.MITRA) {
|
|
return reply.code(403).send({
|
|
success: false,
|
|
error: { code: 'FORBIDDEN', message: 'Customer or mitra account required' },
|
|
})
|
|
}
|
|
request.userType = request.auth.userType
|
|
request.userId = request.auth.userId
|
|
}
|
|
|
|
// Verify session belongs to the authenticated user
|
|
const verifySessionOwnership = async (request, reply) => {
|
|
const { sessionId } = request.params
|
|
const [session] = await sql`
|
|
SELECT id FROM chat_sessions
|
|
WHERE id = ${sessionId}
|
|
AND (customer_id = ${request.userId} OR mitra_id = ${request.userId})
|
|
`
|
|
if (!session) {
|
|
return reply.code(403).send({
|
|
success: false,
|
|
error: { code: 'FORBIDDEN', message: 'You do not have access to this session' },
|
|
})
|
|
}
|
|
}
|
|
|
|
export const sharedChatRoutes = async (app) => {
|
|
// Get messages for a session (paginated)
|
|
app.get('/chat/:sessionId/messages', { preHandler: [authenticate, resolveUser, verifySessionOwnership] }, async (request, reply) => {
|
|
const { sessionId } = request.params
|
|
const { limit, before } = request.query
|
|
const messages = await getMessages(sessionId, {
|
|
limit: limit ? parseInt(limit) : 50,
|
|
before,
|
|
})
|
|
return reply.send({ success: true, data: messages })
|
|
})
|
|
|
|
// Get session info
|
|
app.get('/chat/:sessionId/info', { preHandler: [authenticate, resolveUser, verifySessionOwnership] }, async (request, reply) => {
|
|
const { sessionId } = request.params
|
|
const { getSessionById } = await import('../../services/session.service.js')
|
|
const session = await getSessionById(sessionId)
|
|
if (!session) {
|
|
return reply.code(404).send({ success: false, error: { code: 'NOT_FOUND', message: 'Session not found' } })
|
|
}
|
|
return reply.send({ success: true, data: session })
|
|
})
|
|
|
|
// Get full transcript (read-only, for history)
|
|
app.get('/chat/:sessionId/transcript', { preHandler: [authenticate, resolveUser, verifySessionOwnership] }, async (request, reply) => {
|
|
const { sessionId } = request.params
|
|
const messages = await getMessages(sessionId, { limit: 10000 })
|
|
const closures = await getSessionClosures(sessionId)
|
|
return reply.send({ success: true, data: { messages, closures } })
|
|
})
|
|
|
|
// Register FCM device token
|
|
app.post('/device-token', { preHandler: [authenticate, resolveUser] }, async (request, reply) => {
|
|
const { token } = request.body
|
|
if (!token) {
|
|
return reply.code(400).send({ success: false, error: { code: 'BAD_REQUEST', message: 'Token is required' } })
|
|
}
|
|
await registerDeviceToken(request.userType, request.userId, token)
|
|
return reply.send({ success: true })
|
|
})
|
|
|
|
// Submit goodbye/closure message
|
|
app.post('/sessions/:sessionId/close-message', { preHandler: [authenticate, resolveUser, verifySessionOwnership] }, async (request, reply) => {
|
|
const { sessionId } = request.params
|
|
const { message } = request.body
|
|
if (!message) {
|
|
return reply.code(400).send({ success: false, error: { code: 'BAD_REQUEST', message: 'Message is required' } })
|
|
}
|
|
const { submitClosureMessage } = await import('../../services/closure.service.js')
|
|
const closure = await submitClosureMessage(sessionId, request.userType, request.userId, message)
|
|
return reply.send({ success: true, data: closure })
|
|
})
|
|
|
|
// Mitra flips session topic sensitivity (regular <-> sensitive)
|
|
app.patch('/chat/sessions/:sessionId/topic', { preHandler: [authenticate, resolveUser] }, async (request, reply) => {
|
|
if (request.userType !== UserType.MITRA) {
|
|
return reply.code(403).send({
|
|
success: false,
|
|
error: { code: 'FORBIDDEN', message: 'Only mitra can change topic sensitivity' },
|
|
})
|
|
}
|
|
const { sessionId } = request.params
|
|
const { topic_sensitivity } = request.body || {}
|
|
if (topic_sensitivity !== TopicSensitivity.REGULAR && topic_sensitivity !== TopicSensitivity.SENSITIVE) {
|
|
return reply.code(400).send({
|
|
success: false,
|
|
error: { code: 'BAD_REQUEST', message: 'topic_sensitivity must be regular or sensitive' },
|
|
})
|
|
}
|
|
try {
|
|
const result = await flipSessionSensitivity({
|
|
sessionId,
|
|
mitraId: request.userId,
|
|
toValue: topic_sensitivity,
|
|
})
|
|
return reply.send({ success: true, data: result })
|
|
} catch (err) {
|
|
return reply.code(err.statusCode || 500).send({
|
|
success: false,
|
|
error: { code: err.code || 'INTERNAL', message: err.message },
|
|
})
|
|
}
|
|
})
|
|
}
|