feat(auth): renovacao silenciosa de sessao em background via refresh token e interceptor resiliente
This commit is contained in:
parent
5b5d707a36
commit
7c77e476f2
@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "maestri-remote-agent",
|
"name": "maestri-remote-agent",
|
||||||
"version": "1.0.30",
|
"version": "1.0.31",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"description": "Gateway Local do Maestri Remote para estações de trabalho",
|
"description": "Gateway Local do Maestri Remote para estações de trabalho",
|
||||||
"bin": {
|
"bin": {
|
||||||
|
|||||||
203
public/app.js
203
public/app.js
@ -532,6 +532,112 @@ function getAuthToken() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getRefreshToken() {
|
||||||
|
try {
|
||||||
|
return localStorage.getItem('maestri_refresh_token') || null;
|
||||||
|
} catch (e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setAuthSession(token, refreshToken, user) {
|
||||||
|
try {
|
||||||
|
if (token) localStorage.setItem('maestri_auth_token', token);
|
||||||
|
if (refreshToken) localStorage.setItem('maestri_refresh_token', refreshToken);
|
||||||
|
if (user) localStorage.setItem('maestri_user', JSON.stringify(user));
|
||||||
|
} catch (e) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearAuthSession() {
|
||||||
|
try {
|
||||||
|
localStorage.removeItem('maestri_auth_token');
|
||||||
|
localStorage.removeItem('maestri_refresh_token');
|
||||||
|
localStorage.removeItem('maestri_user');
|
||||||
|
} catch (e) {}
|
||||||
|
currentAuthUser = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
let activeRefreshPromise = null;
|
||||||
|
|
||||||
|
async function refreshAuthSession() {
|
||||||
|
const refreshToken = getRefreshToken();
|
||||||
|
if (!refreshToken) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deduplicação: reaproveita a Promise se já houver uma renovação silenciosa em andamento
|
||||||
|
if (activeRefreshPromise) {
|
||||||
|
return activeRefreshPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
activeRefreshPromise = (async () => {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${getApiBaseUrl()}/api/auth/refresh`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ refreshToken })
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
const data = await res.json();
|
||||||
|
if (data && data.token) {
|
||||||
|
setAuthSession(data.token, data.refreshToken || refreshToken, data.user);
|
||||||
|
if (data.user) {
|
||||||
|
updateUserBadge(data.user);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 401 ou 403 indica que o refresh token expirou ou foi revogado
|
||||||
|
if (res.status === 401 || res.status === 403) {
|
||||||
|
console.warn('[Auth] Refresh token inválido ou expirado. Sessão encerrada.');
|
||||||
|
clearAuthSession();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Erro transitório de rede ou servidor
|
||||||
|
return false;
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('[Auth] Falha de rede ao tentar renovar sessão:', err.message);
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
activeRefreshPromise = null;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
return activeRefreshPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchWithAuth(url, options = {}) {
|
||||||
|
let token = getAuthToken();
|
||||||
|
const headers = { ...(options.headers || {}) };
|
||||||
|
if (token) {
|
||||||
|
headers['Authorization'] = `Bearer ${token}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
res = await fetch(url, { ...options, headers });
|
||||||
|
} catch (netErr) {
|
||||||
|
throw netErr;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (res.status === 401 && getRefreshToken()) {
|
||||||
|
const refreshed = await refreshAuthSession();
|
||||||
|
if (refreshed) {
|
||||||
|
const newToken = getAuthToken();
|
||||||
|
const retryHeaders = { ...(options.headers || {}) };
|
||||||
|
if (newToken) {
|
||||||
|
retryHeaders['Authorization'] = `Bearer ${newToken}`;
|
||||||
|
}
|
||||||
|
return await fetch(url, { ...options, headers: retryHeaders });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
function getSavedAuthUser() {
|
function getSavedAuthUser() {
|
||||||
try {
|
try {
|
||||||
const raw = localStorage.getItem('maestri_user');
|
const raw = localStorage.getItem('maestri_user');
|
||||||
@ -583,14 +689,12 @@ function updateUserBadge(user) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function syncStationToServer(method, pathSuffix, body) {
|
async function syncStationToServer(method, pathSuffix, body) {
|
||||||
const token = getAuthToken();
|
if (!getAuthToken() && !getRefreshToken()) return null;
|
||||||
if (!token) return null;
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${getApiBaseUrl()}${pathSuffix}`, {
|
const res = await fetchWithAuth(`${getApiBaseUrl()}${pathSuffix}`, {
|
||||||
method,
|
method,
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json'
|
||||||
'Authorization': `Bearer ${token}`
|
|
||||||
},
|
},
|
||||||
body: body ? JSON.stringify(body) : undefined
|
body: body ? JSON.stringify(body) : undefined
|
||||||
});
|
});
|
||||||
@ -608,12 +712,9 @@ async function syncStationToServer(method, pathSuffix, body) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function syncStationsFromServer() {
|
async function syncStationsFromServer() {
|
||||||
const token = getAuthToken();
|
if (!getAuthToken() && !getRefreshToken()) return getSavedStations();
|
||||||
if (!token) return getSavedStations();
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${getApiBaseUrl()}/api/stations`, {
|
const res = await fetchWithAuth(`${getApiBaseUrl()}/api/stations`);
|
||||||
headers: { 'Authorization': `Bearer ${token}` }
|
|
||||||
});
|
|
||||||
if (res.status === 401) {
|
if (res.status === 401) {
|
||||||
logoutUser();
|
logoutUser();
|
||||||
return [];
|
return [];
|
||||||
@ -811,21 +912,18 @@ async function startGoogleLogin() {
|
|||||||
};
|
};
|
||||||
activeAuthPollCleanup = cleanup;
|
activeAuthPollCleanup = cleanup;
|
||||||
|
|
||||||
const finalizeSuccess = async (token, user) => {
|
const finalizeSuccess = async (token, user, refreshToken) => {
|
||||||
if (finished) return;
|
if (finished) return;
|
||||||
finished = true;
|
finished = true;
|
||||||
cleanup();
|
cleanup();
|
||||||
try {
|
setAuthSession(token, refreshToken, user);
|
||||||
localStorage.setItem('maestri_auth_token', token);
|
|
||||||
localStorage.setItem('maestri_user', JSON.stringify(user || {}));
|
|
||||||
} catch (e) {}
|
|
||||||
await completeAuthenticatedStartup(user);
|
await completeAuthenticatedStartup(user);
|
||||||
};
|
};
|
||||||
|
|
||||||
const onWindowMessage = (event) => {
|
const onWindowMessage = (event) => {
|
||||||
const data = event?.data;
|
const data = event?.data;
|
||||||
if (data && data.type === 'MAESTRI_AUTH_SUCCESS' && data.token) {
|
if (data && data.type === 'MAESTRI_AUTH_SUCCESS' && data.token) {
|
||||||
finalizeSuccess(data.token, data.user);
|
finalizeSuccess(data.token, data.user, data.refreshToken);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -842,7 +940,7 @@ async function startGoogleLogin() {
|
|||||||
if (!pollRes.ok) return;
|
if (!pollRes.ok) return;
|
||||||
const data = await pollRes.json();
|
const data = await pollRes.json();
|
||||||
if (data.status === 'completed' && data.token) {
|
if (data.status === 'completed' && data.token) {
|
||||||
await finalizeSuccess(data.token, data.user);
|
await finalizeSuccess(data.token, data.user, data.refreshToken);
|
||||||
} else if (data.status === 'expired') {
|
} else if (data.status === 'expired') {
|
||||||
finished = true;
|
finished = true;
|
||||||
cleanup();
|
cleanup();
|
||||||
@ -5261,11 +5359,9 @@ function logoutUser() {
|
|||||||
});
|
});
|
||||||
stationPool.clear();
|
stationPool.clear();
|
||||||
|
|
||||||
localStorage.removeItem('maestri_auth_token');
|
clearAuthSession();
|
||||||
localStorage.removeItem('maestri_user');
|
|
||||||
localStorage.removeItem('maestri_pin');
|
localStorage.removeItem('maestri_pin');
|
||||||
localStorage.removeItem('maestri_stations');
|
localStorage.removeItem('maestri_stations');
|
||||||
currentAuthUser = null;
|
|
||||||
currentPin = null;
|
currentPin = null;
|
||||||
ws = null;
|
ws = null;
|
||||||
|
|
||||||
@ -5434,9 +5530,11 @@ async function initApp() {
|
|||||||
}
|
}
|
||||||
initOtaChecker();
|
initOtaChecker();
|
||||||
|
|
||||||
// Gate obrigatório de autenticação Google SSO
|
// Gate obrigatório de autenticação Google SSO com renovação silenciosa via refresh token
|
||||||
const token = getAuthToken();
|
let token = getAuthToken();
|
||||||
if (!token) {
|
const refreshToken = getRefreshToken();
|
||||||
|
|
||||||
|
if (!token && !refreshToken) {
|
||||||
if (pinFromUrl && pinFromUrl.length >= 4) {
|
if (pinFromUrl && pinFromUrl.length >= 4) {
|
||||||
try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {}
|
try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {}
|
||||||
}
|
}
|
||||||
@ -5444,10 +5542,36 @@ async function initApp() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Se o access token está ausente mas temos refresh token, tenta renovação silenciosa imediata
|
||||||
|
if (!token && refreshToken) {
|
||||||
|
const refreshed = await refreshAuthSession();
|
||||||
|
if (refreshed) {
|
||||||
|
token = getAuthToken();
|
||||||
|
} else {
|
||||||
|
if (pinFromUrl && pinFromUrl.length >= 4) {
|
||||||
|
try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {}
|
||||||
|
}
|
||||||
|
showAuthScreen();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const meRes = await fetch(`${getApiBaseUrl()}/api/auth/me`, {
|
let meRes = await fetch(`${getApiBaseUrl()}/api/auth/me`, {
|
||||||
headers: { 'Authorization': `Bearer ${token}` }
|
headers: { 'Authorization': `Bearer ${token}` }
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Se respondeu 401, tenta renovação silenciosa via refresh token antes de deslogar
|
||||||
|
if (meRes.status === 401 && getRefreshToken()) {
|
||||||
|
const refreshed = await refreshAuthSession();
|
||||||
|
if (refreshed) {
|
||||||
|
token = getAuthToken();
|
||||||
|
meRes = await fetch(`${getApiBaseUrl()}/api/auth/me`, {
|
||||||
|
headers: { 'Authorization': `Bearer ${token}` }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (meRes.ok) {
|
if (meRes.ok) {
|
||||||
const data = await meRes.json();
|
const data = await meRes.json();
|
||||||
if (data && data.user) {
|
if (data && data.user) {
|
||||||
@ -5460,8 +5584,7 @@ async function initApp() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (meRes.status === 401) {
|
if (meRes.status === 401) {
|
||||||
localStorage.removeItem('maestri_auth_token');
|
clearAuthSession();
|
||||||
localStorage.removeItem('maestri_user');
|
|
||||||
if (pinFromUrl && pinFromUrl.length >= 4) {
|
if (pinFromUrl && pinFromUrl.length >= 4) {
|
||||||
try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {}
|
try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {}
|
||||||
}
|
}
|
||||||
@ -5483,6 +5606,34 @@ async function initApp() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Listener para renovação proativa quando o app volta do background
|
||||||
|
const checkTokenExpiryAndRefresh = async () => {
|
||||||
|
const currentToken = getAuthToken();
|
||||||
|
const currentRefresh = getRefreshToken();
|
||||||
|
if (!currentToken || !currentRefresh) return;
|
||||||
|
try {
|
||||||
|
const parts = currentToken.split('.');
|
||||||
|
if (parts.length === 3) {
|
||||||
|
const payload = JSON.parse(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')));
|
||||||
|
const nowSec = Math.floor(Date.now() / 1000);
|
||||||
|
if (typeof payload.exp === 'number' && payload.exp - nowSec < 300) {
|
||||||
|
await refreshAuthSession();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener('visibilitychange', () => {
|
||||||
|
if (!document.hidden) checkTokenExpiryAndRefresh();
|
||||||
|
});
|
||||||
|
window.addEventListener('focus', checkTokenExpiryAndRefresh);
|
||||||
|
window.addEventListener('resume', checkTokenExpiryAndRefresh);
|
||||||
|
|
||||||
|
window.logoutUser = logoutUser;
|
||||||
|
window.getRefreshToken = getRefreshToken;
|
||||||
|
window.refreshAuthSession = refreshAuthSession;
|
||||||
|
window.fetchWithAuth = fetchWithAuth;
|
||||||
|
|
||||||
if (document.readyState === 'loading') {
|
if (document.readyState === 'loading') {
|
||||||
window.addEventListener('DOMContentLoaded', initApp);
|
window.addEventListener('DOMContentLoaded', initApp);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
BIN
public/bundles/bundle-1.0.31.zip
Normal file
BIN
public/bundles/bundle-1.0.31.zip
Normal file
Binary file not shown.
Binary file not shown.
@ -1,9 +1,9 @@
|
|||||||
{
|
{
|
||||||
"version": "1.0.30",
|
"version": "1.0.31",
|
||||||
"buildId": "80e2a090",
|
"buildId": "58d9c94c",
|
||||||
"releasedAt": "2026-11-22T02:08:06.061Z",
|
"releasedAt": "2026-11-22T15:34:43.243Z",
|
||||||
"bundleUrl": "/bundles/bundle-1.0.30.zip",
|
"bundleUrl": "/bundles/bundle-1.0.31.zip",
|
||||||
"latestUrl": "/bundles/bundle-latest.zip",
|
"latestUrl": "/bundles/bundle-latest.zip",
|
||||||
"checksum": "6c29b0b1a4fd55a8ec77b89647273c243e8246492d76092394dbbeb755ea4dbe",
|
"checksum": "32f6f2b500796a5da1019d302e454e008bc058094a56c1ac3e4c8dafbe612eed",
|
||||||
"sizeBytes": 74169
|
"sizeBytes": 75171
|
||||||
}
|
}
|
||||||
Binary file not shown.
@ -2,7 +2,9 @@ import crypto from 'node:crypto';
|
|||||||
|
|
||||||
const FLOW_PENDING_TTL_MS = 5 * 60 * 1000;
|
const FLOW_PENDING_TTL_MS = 5 * 60 * 1000;
|
||||||
const FLOW_COMPLETED_TTL_MS = 2 * 60 * 1000;
|
const FLOW_COMPLETED_TTL_MS = 2 * 60 * 1000;
|
||||||
const DEFAULT_JWT_TTL_SECONDS = 30 * 24 * 60 * 60;
|
const DEFAULT_ACCESS_TOKEN_TTL_SECONDS = 3600; // 1 hora
|
||||||
|
const DEFAULT_REFRESH_TOKEN_TTL_SECONDS = 30 * 24 * 60 * 60; // 30 dias
|
||||||
|
const DEFAULT_JWT_TTL_SECONDS = DEFAULT_ACCESS_TOKEN_TTL_SECONDS;
|
||||||
|
|
||||||
function base64UrlEncodeJson(obj) {
|
function base64UrlEncodeJson(obj) {
|
||||||
return Buffer.from(JSON.stringify(obj), 'utf8').toString('base64url');
|
return Buffer.from(JSON.stringify(obj), 'utf8').toString('base64url');
|
||||||
@ -28,6 +30,8 @@ export class AuthService {
|
|||||||
clientSecret = process.env.KEYCLOAK_CLIENT_SECRET,
|
clientSecret = process.env.KEYCLOAK_CLIENT_SECRET,
|
||||||
redirectUri = process.env.KEYCLOAK_REDIRECT_URI || 'https://remote.winicomw.ddnsfree.com/api/auth/callback',
|
redirectUri = process.env.KEYCLOAK_REDIRECT_URI || 'https://remote.winicomw.ddnsfree.com/api/auth/callback',
|
||||||
jwtSecret = process.env.AUTH_JWT_SECRET,
|
jwtSecret = process.env.AUTH_JWT_SECRET,
|
||||||
|
accessTokenTtlSeconds = Number(process.env.AUTH_ACCESS_TOKEN_TTL_SECONDS) || DEFAULT_ACCESS_TOKEN_TTL_SECONDS,
|
||||||
|
refreshTokenTtlSeconds = Number(process.env.AUTH_REFRESH_TOKEN_TTL_SECONDS) || DEFAULT_REFRESH_TOKEN_TTL_SECONDS,
|
||||||
dbService = null,
|
dbService = null,
|
||||||
fetchFn = globalThis.fetch
|
fetchFn = globalThis.fetch
|
||||||
} = {}) {
|
} = {}) {
|
||||||
@ -36,10 +40,12 @@ export class AuthService {
|
|||||||
this.clientSecret = clientSecret || '';
|
this.clientSecret = clientSecret || '';
|
||||||
this.redirectUri = redirectUri;
|
this.redirectUri = redirectUri;
|
||||||
this.jwtSecret = jwtSecret || '';
|
this.jwtSecret = jwtSecret || '';
|
||||||
|
this.accessTokenTtlSeconds = accessTokenTtlSeconds;
|
||||||
|
this.refreshTokenTtlSeconds = refreshTokenTtlSeconds;
|
||||||
this.dbService = dbService;
|
this.dbService = dbService;
|
||||||
this.fetchFn = fetchFn;
|
this.fetchFn = fetchFn;
|
||||||
|
|
||||||
this.flows = new Map(); // flowId -> { status, state, nonce, codeVerifier, redirectUri, expiresAt, token?, user? }
|
this.flows = new Map(); // flowId -> { status, state, nonce, codeVerifier, redirectUri, expiresAt, token?, refreshToken?, user? }
|
||||||
this.stateToFlow = new Map(); // state -> flowId
|
this.stateToFlow = new Map(); // state -> flowId
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -187,20 +193,21 @@ export class AuthService {
|
|||||||
await this.dbService.upsertUser(profile);
|
await this.dbService.upsertUser(profile);
|
||||||
}
|
}
|
||||||
|
|
||||||
const sessionToken = this.signJwt({
|
const tokens = this.generateTokens(profile);
|
||||||
sub: profile.id,
|
|
||||||
email: profile.email,
|
|
||||||
name: profile.name,
|
|
||||||
picture: profile.picture
|
|
||||||
});
|
|
||||||
|
|
||||||
flow.status = 'completed';
|
flow.status = 'completed';
|
||||||
flow.token = sessionToken;
|
flow.token = tokens.token;
|
||||||
|
flow.refreshToken = tokens.refreshToken;
|
||||||
flow.user = profile;
|
flow.user = profile;
|
||||||
flow.expiresAt = Date.now() + FLOW_COMPLETED_TTL_MS;
|
flow.expiresAt = Date.now() + FLOW_COMPLETED_TTL_MS;
|
||||||
delete flow.codeVerifier;
|
delete flow.codeVerifier;
|
||||||
|
|
||||||
return { token: sessionToken, user: profile, mode: flow.mode || 'web' };
|
return {
|
||||||
|
token: tokens.token,
|
||||||
|
refreshToken: tokens.refreshToken,
|
||||||
|
user: profile,
|
||||||
|
mode: flow.mode || 'web'
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
pollFlow(flowId) {
|
pollFlow(flowId) {
|
||||||
@ -216,6 +223,7 @@ export class AuthService {
|
|||||||
const result = {
|
const result = {
|
||||||
status: 'completed',
|
status: 'completed',
|
||||||
token: flow.token,
|
token: flow.token,
|
||||||
|
refreshToken: flow.refreshToken,
|
||||||
user: flow.user
|
user: flow.user
|
||||||
};
|
};
|
||||||
this.flows.delete(flowId);
|
this.flows.delete(flowId);
|
||||||
@ -225,6 +233,70 @@ export class AuthService {
|
|||||||
return { status: 'pending' };
|
return { status: 'pending' };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
generateTokens(userPayload) {
|
||||||
|
if (!userPayload || (!userPayload.id && !userPayload.sub)) {
|
||||||
|
throw new Error('Identificador do usuário é obrigatório para gerar tokens.');
|
||||||
|
}
|
||||||
|
const userId = userPayload.id || userPayload.sub;
|
||||||
|
const token = this.signJwt({
|
||||||
|
sub: userId,
|
||||||
|
email: userPayload.email || null,
|
||||||
|
name: userPayload.name || null,
|
||||||
|
picture: userPayload.picture || null,
|
||||||
|
token_type: 'access'
|
||||||
|
}, this.accessTokenTtlSeconds);
|
||||||
|
|
||||||
|
const refreshToken = this.signJwt({
|
||||||
|
sub: userId,
|
||||||
|
email: userPayload.email || null,
|
||||||
|
name: userPayload.name || null,
|
||||||
|
picture: userPayload.picture || null,
|
||||||
|
token_type: 'refresh'
|
||||||
|
}, this.refreshTokenTtlSeconds);
|
||||||
|
|
||||||
|
return { token, refreshToken };
|
||||||
|
}
|
||||||
|
|
||||||
|
async refreshSession(refreshToken) {
|
||||||
|
if (!refreshToken || typeof refreshToken !== 'string') {
|
||||||
|
throw new Error('Refresh token não fornecido.');
|
||||||
|
}
|
||||||
|
const payload = this.verifyJwt(refreshToken, 'refresh');
|
||||||
|
if (!payload || payload.token_type !== 'refresh') {
|
||||||
|
throw new Error('Refresh token inválido ou expirado.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let userProfile = {
|
||||||
|
id: payload.sub,
|
||||||
|
email: payload.email || null,
|
||||||
|
name: payload.name || null,
|
||||||
|
picture: payload.picture || null
|
||||||
|
};
|
||||||
|
|
||||||
|
if (this.dbService && this.dbService.isConfigured()) {
|
||||||
|
try {
|
||||||
|
const dbUser = await this.dbService.getUser(payload.sub);
|
||||||
|
if (dbUser) {
|
||||||
|
userProfile = {
|
||||||
|
id: dbUser.id,
|
||||||
|
email: dbUser.email || userProfile.email,
|
||||||
|
name: dbUser.name || userProfile.name,
|
||||||
|
picture: dbUser.picture || userProfile.picture
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
// Fallback seguro usando claims do payload do refresh token
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokens = this.generateTokens(userProfile);
|
||||||
|
return {
|
||||||
|
token: tokens.token,
|
||||||
|
refreshToken: tokens.refreshToken,
|
||||||
|
user: userProfile
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
signJwt(payload, expiresInSeconds = DEFAULT_JWT_TTL_SECONDS) {
|
signJwt(payload, expiresInSeconds = DEFAULT_JWT_TTL_SECONDS) {
|
||||||
if (!this.jwtSecret) {
|
if (!this.jwtSecret) {
|
||||||
throw new Error('AUTH_JWT_SECRET não configurado.');
|
throw new Error('AUTH_JWT_SECRET não configurado.');
|
||||||
@ -244,7 +316,7 @@ export class AuthService {
|
|||||||
return `${signingInput}.${signature}`;
|
return `${signingInput}.${signature}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
verifyJwt(token) {
|
verifyJwt(token, expectedType = null) {
|
||||||
if (!this.jwtSecret || !token || typeof token !== 'string') return null;
|
if (!this.jwtSecret || !token || typeof token !== 'string') return null;
|
||||||
const parts = token.split('.');
|
const parts = token.split('.');
|
||||||
if (parts.length !== 3) return null;
|
if (parts.length !== 3) return null;
|
||||||
@ -267,6 +339,9 @@ export class AuthService {
|
|||||||
if (typeof payload.exp === 'number' && payload.exp <= Math.floor(Date.now() / 1000)) {
|
if (typeof payload.exp === 'number' && payload.exp <= Math.floor(Date.now() / 1000)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
if (expectedType && payload.token_type && payload.token_type !== expectedType) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
return payload;
|
return payload;
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
@ -282,7 +357,7 @@ export class AuthService {
|
|||||||
|
|
||||||
requireAuth(req, res) {
|
requireAuth(req, res) {
|
||||||
const token = this.extractBearerToken(req);
|
const token = this.extractBearerToken(req);
|
||||||
const payload = this.verifyJwt(token);
|
const payload = this.verifyJwt(token, 'access');
|
||||||
if (!payload) {
|
if (!payload) {
|
||||||
res.writeHead(401, {
|
res.writeHead(401, {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
|
|||||||
@ -87,6 +87,18 @@ export class DbService {
|
|||||||
return res.rows[0];
|
return res.rows[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getUser(userId) {
|
||||||
|
if (!userId) return null;
|
||||||
|
const pool = await this._requirePool();
|
||||||
|
const res = await pool.query(
|
||||||
|
`SELECT id, email, name, picture, created_at, updated_at
|
||||||
|
FROM users
|
||||||
|
WHERE id = $1`,
|
||||||
|
[String(userId)]
|
||||||
|
);
|
||||||
|
return res.rows[0] || null;
|
||||||
|
}
|
||||||
|
|
||||||
async listStations(userId) {
|
async listStations(userId) {
|
||||||
const pool = await this._requirePool();
|
const pool = await this._requirePool();
|
||||||
const res = await pool.query(
|
const res = await pool.query(
|
||||||
|
|||||||
@ -55,7 +55,7 @@ function escapeHtml(str) {
|
|||||||
.replace(/'/g, ''');
|
.replace(/'/g, ''');
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderAuthCallbackHtml({ ok, token, user, mode = 'web', errorMessage }) {
|
function renderAuthCallbackHtml({ ok, token, refreshToken, user, mode = 'web', errorMessage }) {
|
||||||
if (!ok) {
|
if (!ok) {
|
||||||
return `<!DOCTYPE html>
|
return `<!DOCTYPE html>
|
||||||
<html lang="pt-BR">
|
<html lang="pt-BR">
|
||||||
@ -68,9 +68,11 @@ function renderAuthCallbackHtml({ ok, token, user, mode = 'web', errorMessage })
|
|||||||
const safePayloadJson = JSON.stringify({
|
const safePayloadJson = JSON.stringify({
|
||||||
type: 'MAESTRI_AUTH_SUCCESS',
|
type: 'MAESTRI_AUTH_SUCCESS',
|
||||||
token,
|
token,
|
||||||
|
refreshToken: refreshToken || '',
|
||||||
user
|
user
|
||||||
}).replace(/</g, '\\u003c');
|
}).replace(/</g, '\\u003c');
|
||||||
const safeTokenJson = JSON.stringify(token).replace(/</g, '\\u003c');
|
const safeTokenJson = JSON.stringify(token).replace(/</g, '\\u003c');
|
||||||
|
const safeRefreshTokenJson = JSON.stringify(refreshToken || '').replace(/</g, '\\u003c');
|
||||||
const safeUserJson = JSON.stringify(user || {}).replace(/</g, '\\u003c');
|
const safeUserJson = JSON.stringify(user || {}).replace(/</g, '\\u003c');
|
||||||
const safeModeJson = JSON.stringify(mode === 'app' ? 'app' : 'web');
|
const safeModeJson = JSON.stringify(mode === 'app' ? 'app' : 'web');
|
||||||
|
|
||||||
@ -94,6 +96,9 @@ function renderAuthCallbackHtml({ ok, token, user, mode = 'web', errorMessage })
|
|||||||
}
|
}
|
||||||
if (${safeModeJson} === 'web') {
|
if (${safeModeJson} === 'web') {
|
||||||
localStorage.setItem('maestri_auth_token', ${safeTokenJson});
|
localStorage.setItem('maestri_auth_token', ${safeTokenJson});
|
||||||
|
if (${safeRefreshTokenJson}) {
|
||||||
|
localStorage.setItem('maestri_refresh_token', ${safeRefreshTokenJson});
|
||||||
|
}
|
||||||
localStorage.setItem('maestri_user', JSON.stringify(${safeUserJson}));
|
localStorage.setItem('maestri_user', JSON.stringify(${safeUserJson}));
|
||||||
window.location.replace('/');
|
window.location.replace('/');
|
||||||
}
|
}
|
||||||
@ -160,7 +165,13 @@ export function createRelayHttpHandler({
|
|||||||
'Content-Type': 'text/html; charset=utf-8',
|
'Content-Type': 'text/html; charset=utf-8',
|
||||||
'Cache-Control': 'no-cache, no-store, must-revalidate'
|
'Cache-Control': 'no-cache, no-store, must-revalidate'
|
||||||
});
|
});
|
||||||
return res.end(renderAuthCallbackHtml({ ok: true, token: result.token, user: result.user, mode: result.mode }));
|
return res.end(renderAuthCallbackHtml({
|
||||||
|
ok: true,
|
||||||
|
token: result.token,
|
||||||
|
refreshToken: result.refreshToken,
|
||||||
|
user: result.user,
|
||||||
|
mode: result.mode
|
||||||
|
}));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
res.writeHead(400, {
|
res.writeHead(400, {
|
||||||
'Content-Type': 'text/html; charset=utf-8',
|
'Content-Type': 'text/html; charset=utf-8',
|
||||||
@ -188,6 +199,23 @@ export function createRelayHttpHandler({
|
|||||||
return sendJson(res, 200, { user });
|
return sendJson(res, 200, { user });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (pathname === '/api/auth/refresh' && req.method === 'POST') {
|
||||||
|
if (!authService || !authService.isConfigured()) {
|
||||||
|
return sendJson(res, 503, { error: 'Serviço de autenticação indisponível.' });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const body = await readJsonBody(req).catch(() => ({}));
|
||||||
|
const refreshToken = body?.refreshToken;
|
||||||
|
if (!refreshToken) {
|
||||||
|
return sendJson(res, 400, { error: 'refreshToken é obrigatório.' });
|
||||||
|
}
|
||||||
|
const result = await authService.refreshSession(refreshToken);
|
||||||
|
return sendJson(res, 200, result);
|
||||||
|
} catch (err) {
|
||||||
|
return sendJson(res, 401, { error: err.message || 'Falha ao renovar sessão.' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 3. Estações sincronizadas por usuário autenticado
|
// 3. Estações sincronizadas por usuário autenticado
|
||||||
if (pathname === '/api/stations' && req.method === 'GET') {
|
if (pathname === '/api/stations' && req.method === 'GET') {
|
||||||
const user = authService?.requireAuth(req, res);
|
const user = authService?.requireAuth(req, res);
|
||||||
|
|||||||
@ -20,6 +20,12 @@ function createInMemoryPool() {
|
|||||||
return { rows: [], rowCount: 0 };
|
return { rows: [], rowCount: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (normalized.startsWith('SELECT id, email, name, picture, created_at, updated_at FROM users WHERE id =')) {
|
||||||
|
const [userId] = params;
|
||||||
|
const user = users.get(userId);
|
||||||
|
return { rows: user ? [user] : [], rowCount: user ? 1 : 0 };
|
||||||
|
}
|
||||||
|
|
||||||
if (normalized.startsWith('INSERT INTO users')) {
|
if (normalized.startsWith('INSERT INTO users')) {
|
||||||
const [id, email, name, picture] = params;
|
const [id, email, name, picture] = params;
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
@ -376,4 +382,131 @@ describe('Auth OIDC PKCE & User Stations Persistence', () => {
|
|||||||
await new Promise(resolve => server.close(resolve));
|
await new Promise(resolve => server.close(resolve));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('AuthService emite access token e refresh token, e renova sessão silenciosamente via refreshSession', async () => {
|
||||||
|
const pool = createInMemoryPool();
|
||||||
|
const db = new DbService({ pool });
|
||||||
|
const issuer = 'https://auth.winicomw.ddnsfree.com/realms/maestri';
|
||||||
|
const clientId = 'maestri-remote';
|
||||||
|
|
||||||
|
const auth = new AuthService({
|
||||||
|
issuer,
|
||||||
|
clientId,
|
||||||
|
jwtSecret: 'test-refresh-jwt-secret-key-32b',
|
||||||
|
accessTokenTtlSeconds: 1, // 1 segundo para teste de expiração
|
||||||
|
refreshTokenTtlSeconds: 60, // 60 segundos
|
||||||
|
dbService: db
|
||||||
|
});
|
||||||
|
|
||||||
|
await db.ensureSchema();
|
||||||
|
await db.upsertUser({ id: 'user-ref-1', email: 'ref@example.com', name: 'Ref User', picture: 'https://img/ref' });
|
||||||
|
|
||||||
|
// 1. Geração de par de tokens
|
||||||
|
const tokens = auth.generateTokens({ id: 'user-ref-1', email: 'ref@example.com', name: 'Ref User', picture: 'https://img/ref' });
|
||||||
|
assert.ok(tokens.token, 'Deve conter access token');
|
||||||
|
assert.ok(tokens.refreshToken, 'Deve conter refresh token');
|
||||||
|
|
||||||
|
// Access token validado com token_type: access
|
||||||
|
const verifiedAccess = auth.verifyJwt(tokens.token, 'access');
|
||||||
|
assert.equal(verifiedAccess.sub, 'user-ref-1');
|
||||||
|
assert.equal(verifiedAccess.token_type, 'access');
|
||||||
|
|
||||||
|
// Refresh token rejeitado como access token
|
||||||
|
assert.equal(auth.verifyJwt(tokens.refreshToken, 'access'), null, 'Refresh token não deve ser aceito como access token');
|
||||||
|
|
||||||
|
// Refresh token aceito com token_type: refresh
|
||||||
|
const verifiedRefresh = auth.verifyJwt(tokens.refreshToken, 'refresh');
|
||||||
|
assert.equal(verifiedRefresh.sub, 'user-ref-1');
|
||||||
|
assert.equal(verifiedRefresh.token_type, 'refresh');
|
||||||
|
|
||||||
|
// 2. Renovação de sessão com refresh token válido
|
||||||
|
const renewed = await auth.refreshSession(tokens.refreshToken);
|
||||||
|
assert.ok(renewed.token);
|
||||||
|
assert.ok(renewed.refreshToken);
|
||||||
|
assert.equal(renewed.user.id, 'user-ref-1');
|
||||||
|
assert.equal(renewed.user.name, 'Ref User');
|
||||||
|
|
||||||
|
// Novo access token é válido
|
||||||
|
const verifiedNewAccess = auth.verifyJwt(renewed.token, 'access');
|
||||||
|
assert.equal(verifiedNewAccess.sub, 'user-ref-1');
|
||||||
|
|
||||||
|
// 3. Rejeita renovação com access token passado como refresh token
|
||||||
|
await assert.rejects(
|
||||||
|
async () => auth.refreshSession(tokens.token),
|
||||||
|
/Refresh token inválido ou expirado/
|
||||||
|
);
|
||||||
|
|
||||||
|
// 4. Rejeita token adulterado
|
||||||
|
await assert.rejects(
|
||||||
|
async () => auth.refreshSession(tokens.refreshToken + 'fake'),
|
||||||
|
/Refresh token inválido ou expirado/
|
||||||
|
);
|
||||||
|
|
||||||
|
// 5. Rejeita refresh token expirado
|
||||||
|
const expiredAuth = new AuthService({
|
||||||
|
issuer,
|
||||||
|
clientId,
|
||||||
|
jwtSecret: 'test-refresh-jwt-secret-key-32b',
|
||||||
|
refreshTokenTtlSeconds: -10, // Já expirado
|
||||||
|
dbService: db
|
||||||
|
});
|
||||||
|
const expiredTokens = expiredAuth.generateTokens({ id: 'user-ref-1' });
|
||||||
|
await assert.rejects(
|
||||||
|
async () => expiredAuth.refreshSession(expiredTokens.refreshToken),
|
||||||
|
/Refresh token inválido ou expirado/
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Rota POST /api/auth/refresh renova tokens com refresh token válido e rejeita token expirado/inválido', async () => {
|
||||||
|
const pool = createInMemoryPool();
|
||||||
|
const db = new DbService({ pool });
|
||||||
|
const auth = new AuthService({
|
||||||
|
issuer: 'https://auth.winicomw.ddnsfree.com/realms/maestri',
|
||||||
|
clientId: 'maestri-remote',
|
||||||
|
jwtSecret: 'test-http-refresh-jwt-secret-32b',
|
||||||
|
accessTokenTtlSeconds: 3600,
|
||||||
|
refreshTokenTtlSeconds: 86400,
|
||||||
|
dbService: db
|
||||||
|
});
|
||||||
|
|
||||||
|
await db.ensureSchema();
|
||||||
|
await db.upsertUser({ id: 'http-ref-user', email: 'http-ref@example.com', name: 'HTTP Ref User' });
|
||||||
|
const initialTokens = auth.generateTokens({ id: 'http-ref-user', email: 'http-ref@example.com', name: 'HTTP Ref User' });
|
||||||
|
|
||||||
|
const handler = createRelayHttpHandler({
|
||||||
|
authService: auth,
|
||||||
|
dbService: db,
|
||||||
|
publicDir: new URL('../public', import.meta.url).pathname
|
||||||
|
});
|
||||||
|
|
||||||
|
const server = http.createServer(handler);
|
||||||
|
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. Sem body -> 400
|
||||||
|
const noBody = await makeHttpRequest(server, 'POST', '/api/auth/refresh', { body: {} });
|
||||||
|
assert.equal(noBody.status, 400);
|
||||||
|
assert.match(noBody.json.error, /refreshToken é obrigatório/);
|
||||||
|
|
||||||
|
// 2. Token inválido -> 401
|
||||||
|
const invalidToken = await makeHttpRequest(server, 'POST', '/api/auth/refresh', { body: { refreshToken: 'invalid.jwt.token' } });
|
||||||
|
assert.equal(invalidToken.status, 401);
|
||||||
|
|
||||||
|
// 3. Refresh token válido -> 200 com novos tokens
|
||||||
|
const validRes = await makeHttpRequest(server, 'POST', '/api/auth/refresh', { body: { refreshToken: initialTokens.refreshToken } });
|
||||||
|
assert.equal(validRes.status, 200);
|
||||||
|
assert.ok(validRes.json.token);
|
||||||
|
assert.ok(validRes.json.refreshToken);
|
||||||
|
assert.equal(validRes.json.user.id, 'http-ref-user');
|
||||||
|
|
||||||
|
// Testa que o novo token de acesso funciona na rota /api/auth/me
|
||||||
|
const meRes = await makeHttpRequest(server, 'GET', '/api/auth/me', {
|
||||||
|
headers: { Authorization: `Bearer ${validRes.json.token}` }
|
||||||
|
});
|
||||||
|
assert.equal(meRes.status, 200);
|
||||||
|
assert.equal(meRes.json.user.id, 'http-ref-user');
|
||||||
|
} finally {
|
||||||
|
await new Promise(resolve => server.close(resolve));
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@ -3347,4 +3347,108 @@ Também verificamos running command e compiling no buffer.
|
|||||||
freshDom.window.close();
|
freshDom.window.close();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('30. Renovação Silenciosa de Sessão (Refresh Token) no Frontend e Resiliência contra 401', async () => {
|
||||||
|
const appJsContent = fs.readFileSync(path.resolve('public', 'app.js'), 'utf8');
|
||||||
|
const htmlTemplate = fs.readFileSync(path.resolve('public/index.html'), 'utf8');
|
||||||
|
const freshDom = new JSDOM(htmlTemplate, {
|
||||||
|
url: 'https://remote.winicomw.ddnsfree.com/',
|
||||||
|
runScripts: 'dangerously'
|
||||||
|
});
|
||||||
|
const w = freshDom.window;
|
||||||
|
const doc = w.document;
|
||||||
|
|
||||||
|
// Configura localStorage com token de acesso expirado e refresh token válido
|
||||||
|
w.localStorage.setItem('maestri_auth_token', 'expired-access-token');
|
||||||
|
w.localStorage.setItem('maestri_refresh_token', 'valid-refresh-token');
|
||||||
|
w.localStorage.setItem('maestri_user', JSON.stringify({ id: 'u-1', name: 'User 1', email: 'u1@example.com' }));
|
||||||
|
|
||||||
|
let refreshCalls = 0;
|
||||||
|
let meCalls = 0;
|
||||||
|
|
||||||
|
w.fetch = async (url, opts = {}) => {
|
||||||
|
const target = String(url);
|
||||||
|
if (target.includes('/api/auth/me')) {
|
||||||
|
meCalls += 1;
|
||||||
|
const authHeader = opts.headers?.Authorization || opts.headers?.authorization;
|
||||||
|
if (authHeader === 'Bearer renewed-access-token') {
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({ user: { id: 'u-1', name: 'User 1', email: 'u1@example.com' } })
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 401,
|
||||||
|
json: async () => ({ error: 'Não autenticado' })
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (target.includes('/api/auth/refresh')) {
|
||||||
|
refreshCalls += 1;
|
||||||
|
const body = JSON.parse(opts.body || '{}');
|
||||||
|
if (body.refreshToken === 'valid-refresh-token') {
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
token: 'renewed-access-token',
|
||||||
|
refreshToken: 'new-refresh-token',
|
||||||
|
user: { id: 'u-1', name: 'User 1', email: 'u1@example.com' }
|
||||||
|
})
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 401,
|
||||||
|
json: async () => ({ error: 'Refresh token inválido' })
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (target.includes('/api/stations')) {
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({ stations: [{ pin: '998877', name: 'Estação Teste' }] })
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({ status: 'ok', buildId: 'test-30', version: '1.0.3' })
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const scriptEl = doc.createElement('script');
|
||||||
|
scriptEl.textContent = appJsContent;
|
||||||
|
doc.body.appendChild(scriptEl);
|
||||||
|
await new Promise(r => setTimeout(r, 60));
|
||||||
|
|
||||||
|
const authScreen = doc.getElementById('auth-screen');
|
||||||
|
const appScreen = doc.getElementById('app-screen');
|
||||||
|
|
||||||
|
// 1. Deve ter renovado silenciosamente via /api/auth/refresh sem exibir a tela de login
|
||||||
|
assert.strictEqual(refreshCalls, 1, 'Deve ter acionado a rota /api/auth/refresh uma vez');
|
||||||
|
assert.strictEqual(w.localStorage.getItem('maestri_auth_token'), 'renewed-access-token', 'Novo token de acesso deve ser salvo');
|
||||||
|
assert.strictEqual(w.localStorage.getItem('maestri_refresh_token'), 'new-refresh-token', 'Novo refresh token deve ser salvo');
|
||||||
|
assert.strictEqual(authScreen.style.display, 'none', 'Tela de login NÃO deve ser exibida ao renovar com sucesso');
|
||||||
|
assert.strictEqual(appScreen.style.display, 'block', 'Tela do aplicativo deve ser exibida normalmente');
|
||||||
|
|
||||||
|
// 2. Quando o refresh token for inválido, deve limpar storage e exibir #auth-screen
|
||||||
|
w.localStorage.setItem('maestri_refresh_token', 'invalid-token');
|
||||||
|
const refreshedFailed = await w.refreshAuthSession();
|
||||||
|
assert.strictEqual(refreshedFailed, false, 'refreshAuthSession deve retornar false com refresh token inválido');
|
||||||
|
assert.strictEqual(w.localStorage.getItem('maestri_refresh_token'), null, 'Refresh token inválido deve ser limpo do localStorage');
|
||||||
|
|
||||||
|
// 3. logoutUser() deve limpar também maestri_refresh_token
|
||||||
|
w.localStorage.setItem('maestri_refresh_token', 'dummy-refresh');
|
||||||
|
w.logoutUser();
|
||||||
|
assert.strictEqual(w.localStorage.getItem('maestri_refresh_token'), null, 'logoutUser deve remover maestri_refresh_token');
|
||||||
|
} finally {
|
||||||
|
freshDom.window.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user