Phase 3.4: backend self-managed auth cutover
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>
This commit is contained in:
@@ -1,25 +1,134 @@
|
||||
import { authenticate } from '../../plugins/auth.js'
|
||||
import { getOrCreateCustomer, getCustomerByFirebaseUid, updateCustomerDisplayName } from '../../services/customer.service.js'
|
||||
import { getCustomerById, updateCustomerDisplayName } from '../../services/customer.service.js'
|
||||
import {
|
||||
completeCustomerPhoneSignIn,
|
||||
signInWithGoogle,
|
||||
signInWithApple,
|
||||
} from '../../services/auth.service.js'
|
||||
import { requestOtp, verifyOtp } from '../../services/otp.service.js'
|
||||
import { UserType } from '../../constants.js'
|
||||
|
||||
const extractDeviceInfo = (request) => ({
|
||||
user_agent: request.headers['user-agent'] || null,
|
||||
ip: request.ip || null,
|
||||
})
|
||||
|
||||
const sendAuthError = (reply, err) => reply.code(err.statusCode || 500).send({
|
||||
success: false,
|
||||
error: { code: err.code || 'INTERNAL', message: err.message },
|
||||
})
|
||||
|
||||
export const clientAuthRoutes = async (app) => {
|
||||
app.post('/verify', { preHandler: authenticate }, async (request, reply) => {
|
||||
const { uid, phone_number, name } = request.firebaseUser
|
||||
const customer = await getOrCreateCustomer({
|
||||
firebase_uid: uid,
|
||||
phone: phone_number || null,
|
||||
display_name: name || null,
|
||||
})
|
||||
return reply.send({ success: true, data: customer })
|
||||
// --- Phone OTP ---
|
||||
|
||||
app.post('/otp/request', async (request, reply) => {
|
||||
const { phone, channel } = request.body || {}
|
||||
try {
|
||||
const result = await requestOtp({
|
||||
phone,
|
||||
userType: UserType.CUSTOMER,
|
||||
ipAddress: request.ip,
|
||||
channel,
|
||||
})
|
||||
return reply.send({ success: true, data: result })
|
||||
} catch (err) {
|
||||
return sendAuthError(reply, err)
|
||||
}
|
||||
})
|
||||
|
||||
app.patch('/profile', { preHandler: authenticate }, async (request, reply) => {
|
||||
const customer = await getCustomerByFirebaseUid(request.firebaseUser.uid)
|
||||
app.post('/otp/verify', async (request, reply) => {
|
||||
const { otp_request_id, code, anonymous_customer_id } = request.body || {}
|
||||
try {
|
||||
const { phone, user_type } = await verifyOtp({ otpRequestId: otp_request_id, code })
|
||||
if (user_type !== UserType.CUSTOMER) {
|
||||
return reply.code(400).send({
|
||||
success: false,
|
||||
error: { code: 'WRONG_FLOW', message: 'This OTP was issued for a different user type' },
|
||||
})
|
||||
}
|
||||
const { tokens, profile } = await completeCustomerPhoneSignIn({
|
||||
phone,
|
||||
anonymousCustomerId: anonymous_customer_id || null,
|
||||
deviceInfo: extractDeviceInfo(request),
|
||||
})
|
||||
return reply.send({ success: true, data: { ...tokens, profile } })
|
||||
} catch (err) {
|
||||
return sendAuthError(reply, err)
|
||||
}
|
||||
})
|
||||
|
||||
// --- Google ---
|
||||
|
||||
app.post('/google', async (request, reply) => {
|
||||
const { id_token, anonymous_customer_id } = request.body || {}
|
||||
if (!id_token) {
|
||||
return reply.code(422).send({
|
||||
success: false,
|
||||
error: { code: 'VALIDATION_ERROR', message: 'id_token is required' },
|
||||
})
|
||||
}
|
||||
try {
|
||||
const { tokens, profile } = await signInWithGoogle({
|
||||
idToken: id_token,
|
||||
anonymousCustomerId: anonymous_customer_id || null,
|
||||
deviceInfo: extractDeviceInfo(request),
|
||||
})
|
||||
return reply.send({ success: true, data: { ...tokens, profile } })
|
||||
} catch (err) {
|
||||
return sendAuthError(reply, err)
|
||||
}
|
||||
})
|
||||
|
||||
// --- Apple ---
|
||||
|
||||
app.post('/apple', async (request, reply) => {
|
||||
const { id_token, anonymous_customer_id } = request.body || {}
|
||||
if (!id_token) {
|
||||
return reply.code(422).send({
|
||||
success: false,
|
||||
error: { code: 'VALIDATION_ERROR', message: 'id_token is required' },
|
||||
})
|
||||
}
|
||||
try {
|
||||
const { tokens, profile } = await signInWithApple({
|
||||
idToken: id_token,
|
||||
anonymousCustomerId: anonymous_customer_id || null,
|
||||
deviceInfo: extractDeviceInfo(request),
|
||||
})
|
||||
return reply.send({ success: true, data: { ...tokens, profile } })
|
||||
} catch (err) {
|
||||
return sendAuthError(reply, err)
|
||||
}
|
||||
})
|
||||
|
||||
// --- Current user profile ---
|
||||
|
||||
app.get('/me', { preHandler: authenticate }, async (request, reply) => {
|
||||
if (request.auth.userType !== UserType.CUSTOMER) {
|
||||
return reply.code(403).send({
|
||||
success: false,
|
||||
error: { code: 'FORBIDDEN', message: 'Customer account required' },
|
||||
})
|
||||
}
|
||||
const customer = await getCustomerById(request.auth.userId)
|
||||
if (!customer) {
|
||||
return reply.code(404).send({
|
||||
success: false,
|
||||
error: { code: 'NOT_FOUND', message: 'Customer account not found' },
|
||||
})
|
||||
}
|
||||
return reply.send({ success: true, data: customer })
|
||||
})
|
||||
|
||||
// --- Update display name ---
|
||||
|
||||
app.patch('/profile', { preHandler: authenticate }, async (request, reply) => {
|
||||
if (request.auth.userType !== UserType.CUSTOMER) {
|
||||
return reply.code(403).send({
|
||||
success: false,
|
||||
error: { code: 'FORBIDDEN', message: 'Customer account required' },
|
||||
})
|
||||
}
|
||||
const { display_name } = request.body || {}
|
||||
if (!display_name || typeof display_name !== 'string' || display_name.trim().length === 0) {
|
||||
return reply.code(422).send({
|
||||
@@ -27,7 +136,7 @@ export const clientAuthRoutes = async (app) => {
|
||||
error: { code: 'VALIDATION_ERROR', message: 'display_name is required' },
|
||||
})
|
||||
}
|
||||
const updated = await updateCustomerDisplayName(customer.id, display_name.trim())
|
||||
const updated = await updateCustomerDisplayName(request.auth.userId, display_name.trim())
|
||||
return reply.send({ success: true, data: updated })
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user