normogen/web/normogen-web/src/services/api.ts
goose 7a641dec00 feat: zero-knowledge recovery (Phase 2) — wrapped-DEK model
Introduces a wrapped-DEK recovery model so a forgotten password doesn't lose
all encrypted data. The encryption key becomes a random DEK (not derived from
the password); the DEK is wrapped under both a password-derived KEK and a
recovery-phrase-derived KEK, and both wrapped forms are stored on the server.

Crypto (crypto/keys.ts):
- DEK generation (random AES-256-GCM), KEK derivation (PBKDF2 password/recovery),
  wrapDek/unwrapDek/rewrapDek.
- setupEncryption(password, recoveryPhrase?) — generates a DEK, wraps under both
  KEKs, returns wrapped forms + recovery proof.
- unlockWithPassword(password, wrappedDek) — derives password KEK, unwraps DEK.
- unlockWithRecovery(phrase, wrappedDek) — derives recovery KEK, unwraps DEK.

Backend:
- User model: wrapped_dek, wrapped_dek_iv, recovery_wrapped_dek,
  recovery_wrapped_dek_iv fields.
- RegisterRequest accepts wrapped-DEK fields; stored verbatim.
- AuthResponse returns wrapped_dek + wrapped_dek_iv (for login unwrapping).
- New GET /api/auth/recovery-info?email= — returns recovery-wrapped DEK.
- RecoverPasswordRequest gains new_wrapped_dek + new_wrapped_dek_iv.
- change-password also accepts + stores re-wrapped DEK.

Frontend:
- Auth store: login unwraps DEK from response; new recover() action fetches
  recovery-wrapped DEK, unwraps with phrase, re-wraps under new password.
- RecoveryPage (new): email + recovery phrase + new password flow.
- LoginPage: 'Forgot password? Recover' link. App.tsx: /recover route.

Verified: backend 21 tests, 0 warnings; frontend build clean, 20 tests.
2026-06-29 03:34:24 -03:00

378 lines
12 KiB
TypeScript

import axios, { AxiosInstance, AxiosError, InternalAxiosRequestConfig } from 'axios';
import {
User,
LoginRequest,
RegisterRequest,
AuthTokens,
Medication,
CreateMedicationRequest,
UpdateMedicationRequest,
DrugInteraction,
CheckInteractionRequest,
CheckNewMedicationRequest,
HealthStat,
CreateHealthStatRequest,
TrendData,
ApiError,
DoseLog,
LogDoseRequest,
AdherenceStats,
MedicationWireResponse,
AppointmentWireResponse,
ProfileWireResponse,
EncryptedFieldWire,
CreateAppointmentRequest,
UpdateAppointmentRequest,
} from '../types/api';
// API base URL. In dev this is "/api", proxied by the Vite dev server to the
// backend (see vite.config.ts). For a production build pointed at a remote
// backend, set VITE_API_URL to the absolute URL at build time.
const API_BASE = import.meta.env.VITE_API_URL || '/api';
class ApiService {
private client: AxiosInstance;
private token: string | null = null;
private refreshToken: string | null = null;
private refreshing: Promise<string | null> | null = null;
constructor() {
this.client = axios.create({
baseURL: API_BASE,
headers: {
'Content-Type': 'application/json',
},
});
// Load tokens from localStorage (single source of truth shared with the
// zustand auth store's persist).
this.token = localStorage.getItem('token');
this.refreshToken = localStorage.getItem('refresh_token');
if (this.token) {
this.setAuthHeader(this.token);
}
// Request interceptor: attach the access token.
this.client.interceptors.request.use(
(config) => {
if (this.token) {
config.headers.Authorization = `Bearer ${this.token}`;
}
return config;
},
(error) => Promise.reject(error),
);
// Response interceptor: on 401, attempt ONE silent refresh; if it fails,
// clear credentials and redirect to /login.
this.client.interceptors.response.use(
(response) => response,
async (error: AxiosError) => {
const original = error.config as InternalAxiosRequestConfig & {
_retried?: boolean;
_noRefresh?: boolean;
};
if (
error.response?.status === 401 &&
!original._retried &&
!original._noRefresh &&
this.refreshToken
) {
original._retried = true;
const newToken = await this.doRefresh();
if (newToken) {
original.headers!.Authorization = `Bearer ${newToken}`;
return this.client.request(original);
}
// Refresh failed: drop credentials and bounce to login.
this.clearCredentials();
if (window.location.pathname !== '/login') {
window.location.href = '/login';
}
return Promise.reject(this.handleError(error));
}
return Promise.reject(this.handleError(error));
},
);
}
private handleError(error: AxiosError): ApiError {
if (error.response) {
const data = error.response.data as Record<string, unknown>;
return {
message:
(data.error as string) ||
(data.message as string) ||
'An error occurred',
code: String(error.response.status),
details: data,
};
} else if (error.request) {
return {
message: 'No response from server',
code: 'NETWORK_ERROR',
};
} else {
return {
message: error.message || 'Unknown error',
code: 'UNKNOWN',
};
}
}
private setAuthHeader(token: string) {
this.client.defaults.headers.common['Authorization'] = `Bearer ${token}`;
}
setTokens(accessToken: string, refreshToken: string) {
this.token = accessToken;
this.refreshToken = refreshToken;
localStorage.setItem('token', accessToken);
localStorage.setItem('refresh_token', refreshToken);
this.setAuthHeader(accessToken);
}
setToken(token: string) {
this.token = token;
localStorage.setItem('token', token);
this.setAuthHeader(token);
}
getToken(): string | null {
return this.token;
}
getRefreshToken(): string | null {
return this.refreshToken;
}
clearCredentials() {
this.token = null;
this.refreshToken = null;
localStorage.removeItem('token');
localStorage.removeItem('refresh_token');
delete this.client.defaults.headers.common['Authorization'];
}
/** Log out: revoke the refresh token server-side, then clear local state. */
async logout() {
if (this.refreshToken) {
try {
await this.client.post('/auth/logout', { refresh_token: this.refreshToken });
} catch {
// Best-effort: even if the server call fails, drop local credentials.
}
}
this.clearCredentials();
}
/** Perform a single in-flight refresh, deduped across concurrent requests. */
private async doRefresh(): Promise<string | null> {
if (this.refreshing) return this.refreshing;
if (!this.refreshToken) return null;
this.refreshing = (async () => {
try {
const response = await this.client.post<AuthTokens>('/auth/refresh', {
refresh_token: this.refreshToken,
});
const { token, refresh_token } = response.data;
this.setTokens(token, refresh_token);
return token;
} catch {
return null;
} finally {
this.refreshing = null;
}
})();
return this.refreshing;
}
// ---- Authentication ----
async login(email: string, _password: string): Promise<AuthTokens> {
// _password is used in the request body below; renamed only to satisfy the
// interface signature kept for store compatibility.
const response = await this.client.post<AuthTokens>('/auth/login', {
email,
password: _password,
});
this.setTokens(response.data.token, response.data.refresh_token);
return response.data;
}
async register(data: RegisterRequest): Promise<AuthTokens> {
const response = await this.client.post<AuthTokens>('/auth/register', data);
this.setTokens(response.data.token, response.data.refresh_token);
return response.data;
}
async getCurrentUser(): Promise<User> {
const response = await this.client.get<User>('/users/me');
return response.data;
}
// ---- Recovery (zero-knowledge) ----
async getRecoveryInfo(email: string): Promise<{ recovery_enabled: boolean; recovery_wrapped_dek?: string; recovery_wrapped_dek_iv?: string }> {
const response = await this.client.get('/auth/recovery-info', { params: { email } });
return response.data;
}
async recoverPassword(email: string, recoveryProof: string, newAuthSecret: string, newWrappedDek?: string, newWrappedDekIv?: string): Promise<void> {
await this.client.post('/auth/recover-password', {
email,
recovery_phrase: recoveryProof,
new_password: newAuthSecret,
new_wrapped_dek: newWrappedDek,
new_wrapped_dek_iv: newWrappedDekIv,
});
}
// ---- Profile (zero-knowledge: opaque encrypted name) ----
async getProfile(): Promise<ProfileWireResponse> {
const response = await this.client.get<ProfileWireResponse>('/profiles/me');
return response.data;
}
async updateProfileName(nameData: string, nameIv: string): Promise<ProfileWireResponse> {
const response = await this.client.put<ProfileWireResponse>('/profiles/me', {
name_data: nameData,
name_iv: nameIv,
});
return response.data;
}
// ---- Medications (zero-knowledge: opaque encrypted blobs) ----
async getMedications(): Promise<MedicationWireResponse[]> {
const response = await this.client.get<MedicationWireResponse[]>('/medications');
return response.data;
}
async getMedication(id: string): Promise<MedicationWireResponse> {
const response = await this.client.get<MedicationWireResponse>(`/medications/${id}`);
return response.data;
}
async createMedication(data: CreateMedicationRequest): Promise<MedicationWireResponse> {
const response = await this.client.post<MedicationWireResponse>('/medications', data);
return response.data;
}
async updateMedication(id: string, data: UpdateMedicationRequest): Promise<MedicationWireResponse> {
const response = await this.client.post<MedicationWireResponse>(`/medications/${id}`, data);
return response.data;
}
async deleteMedication(id: string): Promise<void> {
await this.client.post(`/medications/${id}/delete`);
}
// ---- Dose logging + adherence (not encrypted — counts/flags only) ----
async logDose(medicationId: string, req: LogDoseRequest): Promise<DoseLog> {
const response = await this.client.post<DoseLog>(`/medications/${medicationId}/log`, req);
return response.data;
}
async getAdherence(medicationId: string): Promise<AdherenceStats> {
const response = await this.client.get<AdherenceStats>(`/medications/${medicationId}/adherence`);
return response.data;
}
// ---- Appointments (zero-knowledge: opaque encrypted blobs) ----
async getAppointments(status?: string): Promise<AppointmentWireResponse[]> {
const response = await this.client.get<AppointmentWireResponse[]>('/appointments', {
params: status ? { status } : undefined,
});
return response.data;
}
async getAppointment(id: string): Promise<AppointmentWireResponse> {
const response = await this.client.get<AppointmentWireResponse>(`/appointments/${id}`);
return response.data;
}
async createAppointment(data: CreateAppointmentRequest): Promise<AppointmentWireResponse> {
const response = await this.client.post<AppointmentWireResponse>('/appointments', data);
return response.data;
}
async updateAppointment(id: string, data: UpdateAppointmentRequest): Promise<AppointmentWireResponse> {
const response = await this.client.post<AppointmentWireResponse>(`/appointments/${id}`, data);
return response.data;
}
async deleteAppointment(id: string): Promise<void> {
await this.client.post(`/appointments/${id}/delete`);
}
// ---- Drug Interactions (Phase 2.8) ----
async checkInteractions(medications: string[]): Promise<DrugInteraction[]> {
const response = await this.client.post<DrugInteraction[]>('/interactions/check', {
medications,
});
return response.data;
}
async checkNewMedication(name: string, dosage: string): Promise<DrugInteraction[]> {
const response = await this.client.post<DrugInteraction[]>('/interactions/check-new', {
name,
dosage,
});
return response.data;
}
// ---- Health Statistics ----
async getHealthStats(): Promise<HealthStat[]> {
const response = await this.client.get<HealthStat[]>('/health-stats');
return response.data;
}
async getHealthStat(id: string): Promise<HealthStat> {
const response = await this.client.get<HealthStat>(`/health-stats/${id}`);
return response.data;
}
async createHealthStat(data: CreateHealthStatRequest): Promise<HealthStat> {
const response = await this.client.post<HealthStat>('/health-stats', data);
return response.data;
}
async updateHealthStat(id: string, data: Partial<CreateHealthStatRequest>): Promise<HealthStat> {
const response = await this.client.put<HealthStat>(`/health-stats/${id}`, data);
return response.data;
}
async deleteHealthStat(id: string): Promise<void> {
await this.client.delete(`/health-stats/${id}`);
}
async getHealthTrends(): Promise<TrendData[]> {
const response = await this.client.get<TrendData[]>('/health-stats/trends');
return response.data;
}
// NOTE: lab-results endpoints are intentionally absent — the backend has no
// /lab-results routes yet. The LabResult type stays in types/api.ts for when
// those routes land.
}
// Export singleton instance
export const apiService = new ApiService();
export default apiService;
// Satisfy the unused-import linter for types referenced only via generics above.
export type {
LoginRequest,
CheckInteractionRequest,
CheckNewMedicationRequest,
};