Phase 3 testing fixes: Fastify 5, SSE→WebSocket+FCM, enums, security, session lifecycle
- Upgrade Fastify 4→5 with all plugins (@fastify/websocket 11, cors 11, sensible 6) - Migrate all SSE endpoints to WebSocket + FCM push (mitra chat requests, customer pairing status) - Add flutter_local_notifications for foreground push notifications with sound - Add splash screen to both apps (hide auth loading flash) - Introduce constants/enums across entire codebase (no raw string literals) - Move price tiers from hardcoded array to app_config DB (data-driven, includes 1-min test tier) - Add session ownership validation on all shared chat routes - Add ownership checks on endSession, respondToExtension, requestExtension - Fix session timer: auto-complete expired/stale sessions on server restart - Add 5-min grace period for abandoned closing sessions - Fix extension flow: proper session_resumed handling, clearExtensionRequest, closure grace timer cleanup - Fix chat screens: ConnectChat in initState, session status check on connect - Fix customer expired view: 5-min countdown, closure state priority over expired state - Fix mitra extension UI: loading spinner, disable buttons, handle EXTENSION_RESOLVED error - Fix GoRouter navigation consistency (no more Navigator.pushNamed) - Fix goodbye view keyboard overflow (SingleChildScrollView) - Add active session card on customer home screen with refresh on navigate back - Fix PricingBottomSheet extension mode (RequestExtension instead of new pairing) - Send session_resumed to both parties on extension accept Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -101,4 +101,31 @@ export const internalConfigRoutes = async (app) => {
|
||||
const config = await setEarlyEndConfig({ mitra_enabled, customer_enabled })
|
||||
return reply.send({ success: true, data: config })
|
||||
})
|
||||
|
||||
// --- Price Tiers ---
|
||||
app.get('/price-tiers', {
|
||||
preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
|
||||
}, async (request, reply) => {
|
||||
const { getPriceTiers } = await import('../../services/pricing.service.js')
|
||||
const tiers = await getPriceTiers()
|
||||
return reply.send({ success: true, data: tiers })
|
||||
})
|
||||
|
||||
app.patch('/price-tiers', {
|
||||
preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
|
||||
}, async (request, reply) => {
|
||||
const { tiers } = request.body ?? {}
|
||||
if (!Array.isArray(tiers) || tiers.length === 0) {
|
||||
return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'tiers must be a non-empty array' } })
|
||||
}
|
||||
for (const t of tiers) {
|
||||
if (!t.duration_minutes || t.price === undefined || !t.label) {
|
||||
return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'Each tier needs duration_minutes, price, and label' } })
|
||||
}
|
||||
}
|
||||
const { getDb } = await import('../../db/client.js')
|
||||
const sql = getDb()
|
||||
await sql`UPDATE app_config SET value = ${sql.json({ tiers })}, updated_at = NOW() WHERE key = 'price_tiers'`
|
||||
return reply.send({ success: true, data: tiers })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { authenticate } from '../../plugins/auth.js'
|
||||
import { getCustomerByFirebaseUid } from '../../services/customer.service.js'
|
||||
import { createPairingRequest, cancelPairingRequest, getSessionStatus } from '../../services/pairing.service.js'
|
||||
import { createPairingRequest, cancelPairingRequest } from '../../services/pairing.service.js'
|
||||
import { getActiveSessionByCustomer, endSession, getCustomerHistory } from '../../services/session.service.js'
|
||||
import { subscribe } from '../../plugins/valkey.js'
|
||||
import { getPricingForCustomer, isValidTier, isCustomerEligibleForFreeTrial, getFreeTrial } from '../../services/pricing.service.js'
|
||||
import { requestExtension } from '../../services/extension.service.js'
|
||||
import { EndedBy } from '../../constants.js'
|
||||
|
||||
const resolveCustomer = async (request, reply) => {
|
||||
const customer = await getCustomerByFirebaseUid(request.firebaseUser.uid)
|
||||
@@ -52,7 +52,7 @@ export const clientChatRoutes = async (app) => {
|
||||
})
|
||||
}
|
||||
|
||||
if (!isValidTier(duration_minutes, price)) {
|
||||
if (!(await isValidTier(duration_minutes, price))) {
|
||||
return reply.code(400).send({
|
||||
success: false,
|
||||
error: { code: 'INVALID_TIER', message: 'Invalid price tier selection' },
|
||||
@@ -63,43 +63,6 @@ export const clientChatRoutes = async (app) => {
|
||||
return reply.code(201).send({ success: true, data: session })
|
||||
})
|
||||
|
||||
app.get('/request/:sessionId/status', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
|
||||
const { sessionId } = request.params
|
||||
|
||||
// SSE stream for real-time status updates
|
||||
reply.raw.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Connection': 'keep-alive',
|
||||
})
|
||||
|
||||
// Send current status immediately
|
||||
const current = await getSessionStatus(sessionId)
|
||||
if (current) {
|
||||
reply.raw.write(`data: ${JSON.stringify(current)}\n\n`)
|
||||
}
|
||||
|
||||
// If already in a terminal state, close
|
||||
if (current && ['active', 'completed', 'cancelled', 'expired'].includes(current.status)) {
|
||||
reply.raw.end()
|
||||
return
|
||||
}
|
||||
|
||||
// Subscribe to status updates
|
||||
const unsubscribe = subscribe(`session:${sessionId}:status`, (data) => {
|
||||
reply.raw.write(`data: ${JSON.stringify(data)}\n\n`)
|
||||
if (['paired', 'expired', 'session_ended'].includes(data.type)) {
|
||||
reply.raw.end()
|
||||
unsubscribe()
|
||||
}
|
||||
})
|
||||
|
||||
// Clean up on client disconnect
|
||||
request.raw.on('close', () => {
|
||||
unsubscribe()
|
||||
})
|
||||
})
|
||||
|
||||
app.post('/request/:sessionId/cancel', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
|
||||
const session = await cancelPairingRequest(request.params.sessionId, request.customer.id)
|
||||
return reply.send({ success: true, data: session })
|
||||
@@ -111,7 +74,7 @@ export const clientChatRoutes = async (app) => {
|
||||
})
|
||||
|
||||
app.post('/session/:sessionId/end', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
|
||||
const session = await endSession(request.params.sessionId, 'customer')
|
||||
const session = await endSession(request.params.sessionId, EndedBy.CUSTOMER, request.customer.id)
|
||||
return reply.send({ success: true, data: session })
|
||||
})
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@ import { authenticate } from '../../plugins/auth.js'
|
||||
import { getMitraByFirebaseUid } from '../../services/mitra.service.js'
|
||||
import { acceptPairingRequest, declinePairingRequest } from '../../services/pairing.service.js'
|
||||
import { getActiveSessionsByMitra, endSession, getMitraHistory } from '../../services/session.service.js'
|
||||
import { subscribe } from '../../plugins/valkey.js'
|
||||
import { respondToExtension } from '../../services/extension.service.js'
|
||||
import { EndedBy } from '../../constants.js'
|
||||
|
||||
const resolveMitra = async (request, reply) => {
|
||||
const mitra = await getMitraByFirebaseUid(request.firebaseUser.uid)
|
||||
@@ -23,31 +23,6 @@ const resolveMitra = async (request, reply) => {
|
||||
}
|
||||
|
||||
export const mitraChatRoutes = async (app) => {
|
||||
app.get('/incoming', { preHandler: [authenticate, resolveMitra] }, async (request, reply) => {
|
||||
const mitraId = request.mitra.id
|
||||
|
||||
// SSE stream for incoming chat requests
|
||||
reply.raw.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Connection': 'keep-alive',
|
||||
})
|
||||
|
||||
// Keep-alive ping
|
||||
const pingInterval = setInterval(() => {
|
||||
reply.raw.write(': ping\n\n')
|
||||
}, 15_000)
|
||||
|
||||
const unsubscribe = subscribe(`mitra:${mitraId}:requests`, (data) => {
|
||||
reply.raw.write(`data: ${JSON.stringify(data)}\n\n`)
|
||||
})
|
||||
|
||||
request.raw.on('close', () => {
|
||||
clearInterval(pingInterval)
|
||||
unsubscribe()
|
||||
})
|
||||
})
|
||||
|
||||
app.post('/:sessionId/accept', { preHandler: [authenticate, resolveMitra] }, async (request, reply) => {
|
||||
const session = await acceptPairingRequest(request.params.sessionId, request.mitra.id)
|
||||
return reply.send({ success: true, data: session })
|
||||
@@ -64,7 +39,7 @@ export const mitraChatRoutes = async (app) => {
|
||||
})
|
||||
|
||||
app.post('/sessions/:sessionId/end', { preHandler: [authenticate, resolveMitra] }, async (request, reply) => {
|
||||
const session = await endSession(request.params.sessionId, 'mitra')
|
||||
const session = await endSession(request.params.sessionId, EndedBy.MITRA, request.mitra.id)
|
||||
return reply.send({ success: true, data: session })
|
||||
})
|
||||
|
||||
|
||||
@@ -4,17 +4,21 @@ import { getMitraByFirebaseUid } from '../../services/mitra.service.js'
|
||||
import { getMessages } from '../../services/chat.service.js'
|
||||
import { getSessionClosures } from '../../services/closure.service.js'
|
||||
import { registerDeviceToken } from '../../services/notification.service.js'
|
||||
import { getDb } from '../../db/client.js'
|
||||
import { UserType } from '../../constants.js'
|
||||
|
||||
const sql = getDb()
|
||||
|
||||
const resolveUser = async (request, reply) => {
|
||||
const customer = await getCustomerByFirebaseUid(request.firebaseUser.uid)
|
||||
if (customer) {
|
||||
request.userType = 'customer'
|
||||
request.userType = UserType.CUSTOMER
|
||||
request.userId = customer.id
|
||||
return
|
||||
}
|
||||
const mitra = await getMitraByFirebaseUid(request.firebaseUser.uid)
|
||||
if (mitra) {
|
||||
request.userType = 'mitra'
|
||||
request.userType = UserType.MITRA
|
||||
request.userId = mitra.id
|
||||
return
|
||||
}
|
||||
@@ -24,9 +28,25 @@ const resolveUser = async (request, reply) => {
|
||||
})
|
||||
}
|
||||
|
||||
// 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] }, async (request, reply) => {
|
||||
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, {
|
||||
@@ -37,7 +57,7 @@ export const sharedChatRoutes = async (app) => {
|
||||
})
|
||||
|
||||
// Get session info
|
||||
app.get('/chat/:sessionId/info', { preHandler: [authenticate, resolveUser] }, async (request, reply) => {
|
||||
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)
|
||||
@@ -48,7 +68,7 @@ export const sharedChatRoutes = async (app) => {
|
||||
})
|
||||
|
||||
// Get full transcript (read-only, for history)
|
||||
app.get('/chat/:sessionId/transcript', { preHandler: [authenticate, resolveUser] }, async (request, reply) => {
|
||||
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)
|
||||
@@ -66,7 +86,7 @@ export const sharedChatRoutes = async (app) => {
|
||||
})
|
||||
|
||||
// Submit goodbye/closure message
|
||||
app.post('/sessions/:sessionId/close-message', { preHandler: [authenticate, resolveUser] }, async (request, reply) => {
|
||||
app.post('/sessions/:sessionId/close-message', { preHandler: [authenticate, resolveUser, verifySessionOwnership] }, async (request, reply) => {
|
||||
const { sessionId } = request.params
|
||||
const { message } = request.body
|
||||
if (!message) {
|
||||
|
||||
Reference in New Issue
Block a user