File size: 2,966 Bytes
8f2ab79
 
a91cf53
 
 
 
 
 
 
 
 
 
 
 
 
 
61a0ecd
8f2ab79
a91cf53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f2ab79
 
61a0ecd
8f2ab79
 
 
a91cf53
8f2ab79
 
a91cf53
 
8f2ab79
 
 
 
 
 
a91cf53
8f2ab79
 
 
 
 
 
 
 
 
 
61a0ecd
8f2ab79
a91cf53
8f2ab79
 
 
 
 
a91cf53
 
 
 
8f2ab79
 
 
 
 
a91cf53
 
8f2ab79
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import axios from "axios";

/**
 * API Client with token management.
 * 
 * Security model:
 * - Access token (15min): stored in memory only (this module's closure)
 * - Refresh token (30d): stored in localStorage (TODO: migrate to HttpOnly cookie)
 * - Automatic refresh on 401
 * - Refresh token rotation on every refresh
 * 
 * NOTE: Full HttpOnly cookie auth requires backend Set-Cookie support.
 * Current implementation keeps refresh in localStorage but access in memory,
 * which is already better than both in localStorage.
 */

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "";

// Access token lives in memory only — not accessible to XSS
let accessToken: string | null = null;

export function setAccessToken(token: string | null) {
  accessToken = token;
}

export function getAccessToken(): string | null {
  return accessToken;
}

// On page load, try to restore from a previous session
if (typeof window !== "undefined") {
  // Migrate: if old localStorage access_token exists, use it then remove
  const legacy = localStorage.getItem("access_token");
  if (legacy) {
    accessToken = legacy;
    localStorage.removeItem("access_token");
  }
}

export const apiClient = axios.create({
  baseURL: `${API_BASE_URL}/api/v1`,
  headers: { "Content-Type": "application/json" },
  withCredentials: true,
});

// Attach access token from memory
apiClient.interceptors.request.use(
  (config) => {
    if (accessToken) {
      config.headers.Authorization = `Bearer ${accessToken}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// Handle 401 with refresh token rotation
apiClient.interceptors.response.use(
  (response) => response,
  async (error) => {
    const originalRequest = error.config;

    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;

      try {
        const refreshToken = localStorage.getItem("refresh_token");
        if (!refreshToken) throw new Error("No refresh token");

        // Refresh — server rotates the refresh token
        const response = await axios.post(`${API_BASE_URL}/api/v1/auth/refresh`, {
          refresh_token: refreshToken,
        });

        const { access_token, refresh_token: newRefreshToken } = response.data;

        // Store new access token in MEMORY only
        accessToken = access_token;
        // Store rotated refresh token
        localStorage.setItem("refresh_token", newRefreshToken);

        originalRequest.headers.Authorization = `Bearer ${access_token}`;
        return apiClient(originalRequest);
      } catch (refreshError) {
        // Refresh failed — clear everything and redirect
        accessToken = null;
        localStorage.removeItem("refresh_token");
        if (typeof window !== "undefined") {
          window.location.href = "/login";
        }
        return Promise.reject(refreshError);
      }
    }

    return Promise.reject(error);
  }
);

export default apiClient;