diff --git a/src/client/plugin/credentials.ts b/src/client/plugin/credentials.ts index 9843bbc..867f828 100644 --- a/src/client/plugin/credentials.ts +++ b/src/client/plugin/credentials.ts @@ -4,6 +4,8 @@ // thinks we are logged in. // +import { parseJwt } from "./lib" + export interface Credentials { username: string uiToken: string @@ -31,6 +33,22 @@ export function isLoggedIn() { ) } +export function isTokenExpired() { + const token = localStorage.getItem("token") + if (typeof token !== "string") { + return true + } + + const payload = parseJwt(token) + if (!payload) { + return true + } + + // Report as expired before (real expiry - 30s) + const jsTimestamp = payload.exp * 1000 - 30000 + return Date.now() >= jsTimestamp +} + export function validateCredentials(credentials: Credentials) { return ( true && credentials.username && credentials.uiToken && credentials.npmToken diff --git a/src/client/plugin/init.ts b/src/client/plugin/init.ts index 8e45462..6ddf167 100644 --- a/src/client/plugin/init.ts +++ b/src/client/plugin/init.ts @@ -3,12 +3,17 @@ import { clearCredentials, Credentials, isLoggedIn, + isTokenExpired, saveCredentials, validateCredentials, } from "./credentials" import { interruptClick, parseCookies, retry } from "./lib" function saveAndRemoveCookies() { + if (isTokenExpired()) { + clearCredentials() + } + if (isLoggedIn()) { return } diff --git a/src/client/plugin/lib.ts b/src/client/plugin/lib.ts index ce9a7a0..d744917 100644 --- a/src/client/plugin/lib.ts +++ b/src/client/plugin/lib.ts @@ -15,6 +15,19 @@ export function parseCookies(cookieStr: string) { ) } +export function parseJwt(token: string) { + const base64Url = token.split(".")[1] + const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/") + const jsonPayload = decodeURIComponent( + atob(base64) + .split("") + .map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2)) + .join(""), + ) + + return JSON.parse(jsonPayload) +} + export function retry(action: () => void) { for (let i = 0; i < 10; i++) { setTimeout(() => action(), 100 * i)