mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 11:06:29 +00:00
Deduplicate token refresh and sync sessions
Caches and deduplicates token refreshes, syncs refreshed tokens to the browser session, and updates auth configuration and documentation. Adds an RBAC requirements draft. The new credentials.md contains VPS credentials; remove it from the commit and rotate those credentials.
This commit is contained in:
+85
-61
@@ -1,7 +1,8 @@
|
||||
import { type NextAuthOptions } from "next-auth"
|
||||
import CredentialsProvider from "next-auth/providers/credentials";
|
||||
|
||||
const { BASE_URL_API, DEVICE_CODE } = process.env
|
||||
const BASE_URL_API = process.env.BASE_URL_API_LOCAL_SERVER;
|
||||
const DEVICE_CODE = process.env.DEVICE_CODE || "40001";
|
||||
|
||||
/**
|
||||
* CUSTOM NEXTAUTH EXP
|
||||
@@ -11,55 +12,82 @@ export const EXP_SESSION = 12 * 60 * 60 // 12 hours
|
||||
// const EXP_SESSION = 24 * 60 * 60 // 1 days
|
||||
// const EXP_SESSION = 10 // 10 seconds
|
||||
|
||||
// Determine if we are using HTTPS
|
||||
// In-flight refresh promise map & short-lived cache (survives across parallel requests in the same Node.js process)
|
||||
const refreshPromises = new Map<string, Promise<any>>();
|
||||
const recentRefreshedTokens = new Map<string, { token: any; expiresAt: number }>();
|
||||
|
||||
async function refreshAccessToken(token: any) {
|
||||
// If the access token has expired, try to refresh it
|
||||
try {
|
||||
// FOR INSECURE SSL (ex: Self Signed Certificates)
|
||||
// process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
|
||||
const key = token?.detail?.email || token?.access_token?.slice(-10) || "default";
|
||||
|
||||
// 1. Race Condition Check:
|
||||
// If we refreshed recently (within 10s), return the current token
|
||||
// to prevent parallel requests from spamming the API.
|
||||
if (token.last_refreshed && Date.now() - token.last_refreshed < 10000) {
|
||||
return token;
|
||||
}
|
||||
console.log(`[REFRESH] Attempting refresh for token ending in... ${token.access_token?.slice(-5)}`)
|
||||
|
||||
const response = await fetch(BASE_URL_API + "/auth/refresh-token", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Refresh-Token": token?.refresh_token,
|
||||
"Device-Code": DEVICE_CODE || "40001",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
email: token?.detail.email
|
||||
}),
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
console.log(data)
|
||||
|
||||
if (!response.ok) throw token
|
||||
|
||||
console.log("[REFRESH] Success. New Access Token received.")
|
||||
return {
|
||||
...token, // Keep the previous token properties
|
||||
access_token: data.data.access_token,
|
||||
refresh_token: data.data.refresh_token,
|
||||
expired_at: Math.floor(Date.now() + EXP_SESSION * 1000),
|
||||
last_refreshed: Date.now(), // Mark this refresh
|
||||
error: null, // Clear errors
|
||||
}
|
||||
} catch (error) {
|
||||
console.log("[REFRESH] Error refreshing access token", error)
|
||||
|
||||
return {
|
||||
...token,
|
||||
error: "RefreshAccessTokenError",
|
||||
};
|
||||
// 1. If we have a recently refreshed token in memory (within last 30s), reuse it immediately
|
||||
const cached = recentRefreshedTokens.get(key);
|
||||
if (cached && Date.now() < cached.expiresAt) {
|
||||
console.log(`[REFRESH] Reusing recently refreshed token for ${key}`);
|
||||
return cached.token;
|
||||
}
|
||||
|
||||
// 2. If a refresh is already in-flight for this user/token, await that same promise (deduplication)
|
||||
if (refreshPromises.has(key)) {
|
||||
console.log(`[REFRESH] Waiting for existing in-flight refresh for ${key}`);
|
||||
return await refreshPromises.get(key);
|
||||
}
|
||||
|
||||
// 3. Initiate the refresh promise
|
||||
const promise = (async () => {
|
||||
try {
|
||||
console.log(`[REFRESH] Attempting refresh for token ending in... ${token.access_token?.slice(-5)}`);
|
||||
|
||||
const response = await fetch(BASE_URL_API + "/auth/refresh-token", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Refresh-Token": token?.refresh_token,
|
||||
"Device-Code": DEVICE_CODE || "40001",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
email: token?.detail?.email
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
console.log("[REFRESH] Refresh API returned error:", data);
|
||||
throw data;
|
||||
}
|
||||
|
||||
console.log("[REFRESH] Success. New Access Token received.");
|
||||
const newToken = {
|
||||
...token, // Keep the previous token properties
|
||||
access_token: data.data.access_token,
|
||||
refresh_token: data.data.refresh_token,
|
||||
expired_at: Math.floor(Date.now() + EXP_SESSION * 1000),
|
||||
last_refreshed: Date.now(), // Mark this refresh
|
||||
is_refreshed: true, // Signal client to sync cookie
|
||||
error: null, // Clear errors
|
||||
};
|
||||
|
||||
// Cache for 30 seconds to absorb parallel requests and immediate Fast Refresh bursts
|
||||
recentRefreshedTokens.set(key, {
|
||||
token: newToken,
|
||||
expiresAt: Date.now() + 30000,
|
||||
});
|
||||
|
||||
return newToken;
|
||||
} catch (error) {
|
||||
console.log("[REFRESH] Error refreshing access token", error);
|
||||
|
||||
return {
|
||||
...token,
|
||||
error: "RefreshAccessTokenError",
|
||||
};
|
||||
} finally {
|
||||
refreshPromises.delete(key);
|
||||
}
|
||||
})();
|
||||
|
||||
refreshPromises.set(key, promise);
|
||||
return await promise;
|
||||
}
|
||||
|
||||
export const authOptions: NextAuthOptions = {
|
||||
@@ -150,19 +178,15 @@ export const authOptions: NextAuthOptions = {
|
||||
callbacks: {
|
||||
async jwt({ token, user, account, profile, trigger, session }: any) {
|
||||
|
||||
// 1. Handle Update Trigger (Client side update)
|
||||
if (trigger === "update" && session?.access_token) {
|
||||
// Note, that `session` can be any arbitrary object, remember to validate it!
|
||||
console.log("====================================== MASUK KE JWT ========================================")
|
||||
console.log("============================ SESSION UPDATED FROM THE CLIENT ===================================")
|
||||
|
||||
// const newSession = {
|
||||
// ...session, // Keep the previous token properties
|
||||
// expired_at: Math.floor(Date.now() + EXP_SESSION * 1000) // UPDATE NEXTAUTH SESSION EXP
|
||||
// }
|
||||
// console.log({ session: newSession })
|
||||
// return newSession
|
||||
return session
|
||||
// 1. Handle Update Trigger (Client side update / cookie sync)
|
||||
if (trigger === "update") {
|
||||
if (session?.access_token) {
|
||||
return { ...token, ...session, is_refreshed: false };
|
||||
}
|
||||
const isValid = token.expired_at && (Date.now() < (token.expired_at - 15000));
|
||||
if (isValid) return { ...token, is_refreshed: false };
|
||||
const refreshed = await refreshAccessToken(token);
|
||||
return { ...refreshed, is_refreshed: false };
|
||||
}
|
||||
|
||||
// 2. Initial Sign In
|
||||
@@ -181,7 +205,7 @@ export const authOptions: NextAuthOptions = {
|
||||
// Refresh 15 seconds *before* it actually dies to prevent timing issues
|
||||
const isValid = token.expired_at && (Date.now() < (token.expired_at - 15000));
|
||||
|
||||
if (isValid) return token;
|
||||
if (isValid) return { ...token, is_refreshed: false };
|
||||
|
||||
// 5. Token Expired (or missing expiry), Refresh it
|
||||
console.log(`[JWT] Token Expired (or invalid timestamp). Refreshing... Current: ${Date.now()}, ExpiredAt: ${token.expired_at}`)
|
||||
|
||||
Reference in New Issue
Block a user