-
Notifications
You must be signed in to change notification settings - Fork 0
feat(auth): implement refresh tokens #355
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
GTR1701
wants to merge
7
commits into
main
Choose a base branch
from
feat/refresh-token
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
b5b1b22
feat(auth): create access token refreshing functionality
GTR1701 e342d31
chore(auth): remove duplicate return type
GTR1701 efc5476
chore(auth): soft-patch toast message circular import
GTR1701 703d786
feat(auth): improve refresh token logic
GTR1701 4c3e14d
test(auth): get token status util test
GTR1701 dffc102
chore(auth): rename doRefreshToken to performTokenRefresh
GTR1701 5967fe9
chore(auth): refresh token code cleanup
GTR1701 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,7 @@ | ||
| export const AUTH_STATE_COOKIE_NAME = "topwr_auth"; | ||
|
|
||
| /** | ||
| * When an access token has less than this percentage of its total lifetime remaining, | ||
| * a background refresh is triggered alongside the outgoing request. | ||
| */ | ||
| export const REFRESH_THRESHOLD_PERCENT = 20; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,5 @@ | ||
| export * from "./schemas/auth-state-schema"; | ||
|
|
||
| export * from "./utils/get-auth-state.node"; | ||
| export * from "./utils/get-cookie-options"; | ||
| export * from "./utils/get-token-status"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
10 changes: 10 additions & 0 deletions
10
src/features/authentication/utils/decode-base64-url-segment.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| export function decodeBase64UrlSegment(segment: string): string { | ||
| const base64 = segment.replaceAll("-", "+").replaceAll("_", "/"); | ||
| const paddingLength = base64.length % 4; | ||
| if (paddingLength === 1) { | ||
| throw new Error("Invalid base64url segment"); | ||
| } | ||
| const padded = | ||
| paddingLength === 0 ? base64 : base64 + "=".repeat(4 - paddingLength); | ||
| return atob(padded); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| import { decodeBase64UrlSegment } from "./decode-base64-url-segment"; | ||
|
|
||
| export function decodeJwtPayload(token: string): { iat?: number } | null { | ||
| try { | ||
| const parts = token.split("."); | ||
| if (parts.length !== 3) { | ||
| return null; | ||
| } | ||
| const decoded = decodeBase64UrlSegment(parts[1]); | ||
| return JSON.parse(decoded) as { iat?: number }; | ||
| } catch { | ||
| return null; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| import Cookies from "js-cookie"; | ||
|
|
||
| import { deferClientToast } from "@/features/toaster"; | ||
|
|
||
| // import { getToastMessages } from "@/lib/get-toast-messages"; | ||
|
|
||
| import { AUTH_STATE_COOKIE_NAME } from "../constants"; | ||
|
|
||
| /** | ||
| * Clears the local auth state, saves a deferred toast, and redirects to the | ||
| * login page. Must only be called in a browser context. | ||
| */ | ||
| export function forceLogout(): void { | ||
| Cookies.remove(AUTH_STATE_COOKIE_NAME); | ||
| deferClientToast({ | ||
| level: "warning", | ||
| // TODO: Resolve the circular dependency issue to get the message from getToastMessages.auth.sessionExpired, | ||
| message: "Twoja sesja wygasła. Proszę zalogować się ponownie.", | ||
| }); | ||
|
GTR1701 marked this conversation as resolved.
|
||
| window.location.href = "/login"; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
188 changes: 188 additions & 0 deletions
188
src/features/authentication/utils/get-token-status.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,188 @@ | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | ||
|
|
||
| import { REFRESH_THRESHOLD_PERCENT } from "../constants"; | ||
| import type { AuthState } from "../types/internal"; | ||
| import { getTokenStatus } from "./get-token-status"; | ||
|
|
||
| function encodeJwtPayload(payload: Record<string, unknown>): string { | ||
| const json = JSON.stringify(payload); | ||
| const base64 = btoa(json); | ||
| return base64.replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); | ||
| } | ||
|
|
||
| function makeToken(payload: Record<string, unknown>): string { | ||
| return `header.${encodeJwtPayload(payload)}.signature`; | ||
| } | ||
|
|
||
| const NOW = 1_000_000_000_000; | ||
|
|
||
| function makeAuthState( | ||
| options: Partial<AuthState> & { | ||
| accessTokenIat?: number | null; | ||
| } = {}, | ||
| ): AuthState { | ||
| const { | ||
| accessTokenIat, | ||
| accessToken, | ||
| accessTokenExpiresAt = NOW + 10_000, | ||
| refreshTokenExpiresAt = NOW + 100_000, | ||
| ...rest | ||
| } = options; | ||
|
|
||
| const iat = | ||
| accessTokenIat === undefined | ||
| ? Math.floor((NOW - 50_000) / 1000) // issued 50 s ago by default | ||
| : accessTokenIat; | ||
|
|
||
| const token = | ||
| accessToken ?? (iat === null ? makeToken({}) : makeToken({ iat })); | ||
|
|
||
| return { | ||
| user: null as unknown as AuthState["user"], | ||
| refreshToken: "refresh.token.sig", | ||
| accessToken: token, | ||
| accessTokenExpiresAt, | ||
| refreshTokenExpiresAt, | ||
| ...rest, | ||
| }; | ||
| } | ||
|
|
||
| describe("getTokenStatus", () => { | ||
| beforeEach(() => { | ||
| vi.useFakeTimers(); | ||
| vi.setSystemTime(NOW); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| vi.useRealTimers(); | ||
| }); | ||
|
|
||
| describe('"both-expired"', () => { | ||
| it("returns both-expired when refresh token is expired", () => { | ||
| const state = makeAuthState({ refreshTokenExpiresAt: NOW - 1 }); | ||
| expect(getTokenStatus(state)).toBe("both-expired"); | ||
| }); | ||
|
|
||
| it("returns both-expired when refresh token expires exactly now", () => { | ||
| const state = makeAuthState({ refreshTokenExpiresAt: NOW }); | ||
| expect(getTokenStatus(state)).toBe("both-expired"); | ||
| }); | ||
|
|
||
| it("returns both-expired even when access token is still valid", () => { | ||
| const state = makeAuthState({ | ||
| accessTokenExpiresAt: NOW + 10_000, | ||
| refreshTokenExpiresAt: NOW - 1, | ||
| }); | ||
| expect(getTokenStatus(state)).toBe("both-expired"); | ||
| }); | ||
| }); | ||
|
|
||
| describe('"expired"', () => { | ||
| it("returns expired when access token is expired but refresh is still valid", () => { | ||
| const state = makeAuthState({ | ||
| accessTokenExpiresAt: NOW - 1, | ||
| refreshTokenExpiresAt: NOW + 100_000, | ||
| }); | ||
| expect(getTokenStatus(state)).toBe("expired"); | ||
| }); | ||
|
|
||
| it("returns expired when access token expires exactly now", () => { | ||
| const state = makeAuthState({ | ||
| accessTokenExpiresAt: NOW, | ||
| refreshTokenExpiresAt: NOW + 100_000, | ||
| }); | ||
| expect(getTokenStatus(state)).toBe("expired"); | ||
| }); | ||
| }); | ||
|
|
||
| describe('"expiring-soon"', () => { | ||
| it("returns expiring-soon when remaining lifetime is just below the threshold", () => { | ||
| // total lifetime = 100 s, threshold = 20 % → trigger at 20 s remaining | ||
| const issuedAt = NOW - 80_000; // 80 s ago | ||
| const expiresAt = NOW + 19_999; // 19.999 s left → < 20 % | ||
| const state = makeAuthState({ | ||
| accessTokenIat: Math.floor(issuedAt / 1000), | ||
| accessTokenExpiresAt: expiresAt, | ||
| refreshTokenExpiresAt: NOW + 1_000_000, | ||
| }); | ||
| expect(getTokenStatus(state)).toBe("expiring-soon"); | ||
| }); | ||
|
|
||
| it("returns expiring-soon exactly at the threshold boundary (< not <=)", () => { | ||
| const totalMs = 100_000; | ||
| const thresholdMs = (REFRESH_THRESHOLD_PERCENT / 100) * totalMs; // 20 000 ms | ||
| const issuedAt = NOW - (totalMs - thresholdMs + 1); // remaining = thresholdMs - 1 | ||
| const expiresAt = NOW + thresholdMs - 1; | ||
| const state = makeAuthState({ | ||
| accessTokenIat: Math.floor(issuedAt / 1000), | ||
| accessTokenExpiresAt: expiresAt, | ||
| refreshTokenExpiresAt: NOW + 1_000_000, | ||
| }); | ||
| expect(getTokenStatus(state)).toBe("expiring-soon"); | ||
| }); | ||
|
|
||
| it("returns ok (not expiring-soon) when remaining lifetime equals the threshold exactly", () => { | ||
| const totalMs = 100_000; | ||
| const thresholdMs = (REFRESH_THRESHOLD_PERCENT / 100) * totalMs; // 20 000 ms | ||
| const issuedAt = NOW - (totalMs - thresholdMs); | ||
| const expiresAt = NOW + thresholdMs; | ||
| const state = makeAuthState({ | ||
| accessTokenIat: Math.floor(issuedAt / 1000), | ||
| accessTokenExpiresAt: expiresAt, | ||
| refreshTokenExpiresAt: NOW + 1_000_000, | ||
| }); | ||
| expect(getTokenStatus(state)).toBe("ok"); | ||
| }); | ||
| }); | ||
|
|
||
| describe('"ok"', () => { | ||
| it("returns ok when access token has plenty of lifetime left", () => { | ||
| const state = makeAuthState({ | ||
| accessTokenIat: Math.floor((NOW - 1000) / 1000), | ||
| accessTokenExpiresAt: NOW + 99_000, | ||
| refreshTokenExpiresAt: NOW + 1_000_000, | ||
| }); | ||
| expect(getTokenStatus(state)).toBe("ok"); | ||
| }); | ||
| }); | ||
|
|
||
| describe("missing / invalid iat", () => { | ||
| it("returns ok when iat is absent from the payload", () => { | ||
| const token = makeToken({}); // no iat field | ||
| const state = makeAuthState({ | ||
| accessToken: token, | ||
| accessTokenExpiresAt: NOW + 10_000, | ||
| refreshTokenExpiresAt: NOW + 100_000, | ||
| }); | ||
| expect(getTokenStatus(state)).toBe("ok"); | ||
| }); | ||
|
|
||
| it("returns ok when the token is not a valid JWT (no payload segment)", () => { | ||
| const state = makeAuthState({ | ||
| accessToken: "not-a-jwt", | ||
| accessTokenExpiresAt: NOW + 10_000, | ||
| refreshTokenExpiresAt: NOW + 100_000, | ||
| }); | ||
| expect(getTokenStatus(state)).toBe("ok"); | ||
| }); | ||
|
|
||
| it("returns ok when the payload is not valid JSON", () => { | ||
| const state = makeAuthState({ | ||
| accessToken: "header.!!!invalid_base64!!$.signature", | ||
| accessTokenExpiresAt: NOW + 10_000, | ||
| refreshTokenExpiresAt: NOW + 100_000, | ||
| }); | ||
| expect(getTokenStatus(state)).toBe("ok"); | ||
| }); | ||
|
|
||
| it("returns ok when totalLifetimeMs is zero (iat === expiresAt)", () => { | ||
| const expiresAt = NOW + 10_000; | ||
| const state = makeAuthState({ | ||
| accessTokenIat: Math.floor(expiresAt / 1000), // iat == expiry → totalLifetimeMs = 0 | ||
| accessTokenExpiresAt: expiresAt, | ||
| refreshTokenExpiresAt: NOW + 100_000, | ||
| }); | ||
| expect(getTokenStatus(state)).toBe("ok"); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| import { REFRESH_THRESHOLD_PERCENT } from "../constants"; | ||
| import type { AuthState, TokenStatus } from "../types/internal"; | ||
| import { decodeJwtPayload } from "./decode-jwt-payload"; | ||
|
|
||
| /** | ||
| * Determines the validity status of the current access token. | ||
| * | ||
| * - `"both-expired"` – both access and refresh tokens are expired; user must re-login. | ||
| * - `"expired"` – access token is expired but refresh token is still valid. | ||
| * - `"expiring-soon"` – access token will expire within {@link REFRESH_THRESHOLD_PERCENT}% of its total lifetime. | ||
| * - `"ok"` – access token is valid. | ||
| */ | ||
| export function getTokenStatus(authState: AuthState): TokenStatus { | ||
|
GTR1701 marked this conversation as resolved.
|
||
| const now = Date.now(); | ||
|
|
||
| if (now >= authState.refreshTokenExpiresAt) { | ||
| return "both-expired"; | ||
| } | ||
|
|
||
| if (now >= authState.accessTokenExpiresAt) { | ||
| return "expired"; | ||
| } | ||
|
|
||
| const payload = decodeJwtPayload(authState.accessToken); | ||
| if (payload?.iat != null) { | ||
| const issuedAtMs = payload.iat * 1000; | ||
| const totalLifetimeMs = authState.accessTokenExpiresAt - issuedAtMs; | ||
| const remainingMs = authState.accessTokenExpiresAt - now; | ||
| if ( | ||
| totalLifetimeMs > 0 && | ||
| remainingMs / totalLifetimeMs < REFRESH_THRESHOLD_PERCENT / 100 | ||
| ) { | ||
| return "expiring-soon"; | ||
| } | ||
| } | ||
|
|
||
| return "ok"; | ||
| } | ||
60 changes: 60 additions & 0 deletions
60
src/features/authentication/utils/perform-token-refresh.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| import Cookies from "js-cookie"; | ||
|
|
||
| import { env } from "@/config/env"; | ||
| import type { RefreshTokenResponse } from "@/features/backend/types"; | ||
| import { logger, parseError } from "@/features/logging"; | ||
|
|
||
| import { AUTH_STATE_COOKIE_NAME } from "../constants"; | ||
| import { AuthStateSchema } from "../schemas/auth-state-schema"; | ||
| import type { AuthState } from "../types/internal"; | ||
| import { getAuthStateNode } from "./get-auth-state.node"; | ||
| import { getCookieOptions } from "./get-cookie-options"; | ||
|
|
||
| export async function performTokenRefresh( | ||
| authState: AuthState, | ||
| ): Promise<AuthState | null> { | ||
| try { | ||
| const url = `${env.NEXT_PUBLIC_API_URL}/api/v1/auth/refresh`; | ||
| const response = await fetch(url, { | ||
| method: "POST", | ||
| headers: { "Content-Type": "application/json" }, | ||
| body: JSON.stringify({ refreshToken: authState.refreshToken }), | ||
| }); | ||
|
|
||
| if (!response.ok) { | ||
| logger.warn({ status: response.status }, "Token refresh request failed"); | ||
| return null; | ||
| } | ||
|
|
||
| const { newAccessToken } = (await response.json()) as RefreshTokenResponse; | ||
| const now = Date.now(); | ||
| const currentState = getAuthStateNode(); | ||
| if (currentState == null) { | ||
| return null; | ||
| } | ||
|
|
||
| const parsed = AuthStateSchema.safeParse({ | ||
| accessToken: newAccessToken.accessToken, | ||
| accessTokenExpiresAt: now + newAccessToken.accessExpiresInMs, | ||
| refreshToken: authState.refreshToken, | ||
| refreshTokenExpiresAt: authState.refreshTokenExpiresAt, | ||
| user: currentState.user, | ||
| }); | ||
|
|
||
| if (!parsed.success) { | ||
| logger.error( | ||
| parsed.error.format(), | ||
| "Token refresh response does not match expected schema", | ||
| ); | ||
| return null; | ||
| } | ||
|
|
||
| const newState = parsed.data; | ||
| Object.assign(currentState, newState); | ||
| Cookies.set(AUTH_STATE_COOKIE_NAME, ...getCookieOptions(currentState)); | ||
| return currentState; | ||
| } catch (error) { | ||
| logger.error(parseError(error), "Token refresh failed"); | ||
| return null; | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.