Repository navigation
feat: implement session cookie management and logout functionality #1899
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
Merged
+522
−60
Merged
Changes from all commits
Commits
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
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
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
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 |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| import { Constants } from '../../helpers/constants/constants.js'; | ||
|
|
||
| interface RequestWithCookies { | ||
| headers?: { cookie?: string | Array<string> }; | ||
| cookies?: Record<string, string>; | ||
| } | ||
|
|
||
| /** | ||
| * Every value of one cookie name, in the order the browser sent them. | ||
| * | ||
| * Express `cookie-parser` keeps only the first value of a duplicated name. A browser can hold a | ||
| * host-only copy and a domain copy of the session cookie (plan 84), so the middlewares read the | ||
| * raw header here. | ||
| */ | ||
| export function extractSessionTokens( | ||
| cookieHeader: string | Array<string> | undefined, | ||
| name: string = Constants.JWT_COOKIE_KEY_NAME, | ||
| ): Array<string> { | ||
| const raw = Array.isArray(cookieHeader) ? cookieHeader.join('; ') : cookieHeader; | ||
| if (!raw) { | ||
| return []; | ||
| } | ||
| const tokens: Array<string> = []; | ||
| for (const pair of raw.split(';')) { | ||
| const separator = pair.indexOf('='); | ||
| if (separator === -1) { | ||
| continue; | ||
| } | ||
| if (pair.slice(0, separator).trim() !== name) { | ||
| continue; | ||
| } | ||
| let value = pair.slice(separator + 1).trim(); | ||
| if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) { | ||
| value = value.slice(1, -1); | ||
| } | ||
| if (!value) { | ||
| continue; | ||
| } | ||
| tokens.push(safeDecode(value)); | ||
| } | ||
| return tokens; | ||
| } | ||
|
|
||
| /** The `iat` claim of a JWT, read without a signature check. Null for anything unreadable. */ | ||
| export function readIssuedAt(token: string): number | null { | ||
| const parts = token.split('.'); | ||
| if (parts.length < 2) { | ||
| return null; | ||
| } | ||
| try { | ||
| const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')); | ||
| return typeof payload?.iat === 'number' ? payload.iat : null; | ||
| } catch (_e) { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * The token to authenticate when the browser sent more than one session cookie (plan 84). | ||
| * | ||
| * The newest `iat` wins: the latest login states the user's intent. A tie keeps the browser | ||
| * order. A token without a readable `iat` ranks last. | ||
| */ | ||
| export function selectSessionToken(tokens: Array<string>): string | undefined { | ||
| if (tokens.length <= 1) { | ||
| return tokens[0]; | ||
| } | ||
| let best = tokens[0]; | ||
| let bestIssuedAt = readIssuedAt(best) ?? -1; | ||
| for (const token of tokens.slice(1)) { | ||
| const issuedAt = readIssuedAt(token) ?? -1; | ||
| if (issuedAt > bestIssuedAt) { | ||
| best = token; | ||
| bestIssuedAt = issuedAt; | ||
| } | ||
| } | ||
| return best; | ||
| } | ||
|
|
||
| /** | ||
| * All session tokens of a request, without duplicates. The raw `Cookie` header is the source. | ||
| * A request without the header falls back to the parsed `cookies` object, which the unit tests | ||
| * build directly. | ||
| */ | ||
| export function getSessionTokensFromRequest( | ||
| req: RequestWithCookies, | ||
| name: string = Constants.JWT_COOKIE_KEY_NAME, | ||
| ): Array<string> { | ||
| const fromHeader = extractSessionTokens(req.headers?.cookie, name); | ||
| if (fromHeader.length > 0) { | ||
| return Array.from(new Set(fromHeader)); | ||
| } | ||
| const parsed = req.cookies?.[name]; | ||
| return parsed ? [parsed] : []; | ||
| } | ||
|
|
||
| /** The one session token a request authenticates with, or undefined. */ | ||
| export function getSessionTokenFromRequest( | ||
| req: RequestWithCookies, | ||
| name: string = Constants.JWT_COOKIE_KEY_NAME, | ||
| ): string | undefined { | ||
| return selectSessionToken(getSessionTokensFromRequest(req, name)); | ||
| } | ||
|
|
||
| function safeDecode(value: string): string { | ||
| try { | ||
| return decodeURIComponent(value); | ||
| } catch (_e) { | ||
| return value; | ||
| } | ||
| } | ||
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
46 changes: 41 additions & 5 deletions
46
backend/src/entities/user/utils/get-cookie-domain-options.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 |
|---|---|---|
| @@ -1,9 +1,45 @@ | ||
| import { appConfig } from '../../../shared/config/app-config.js'; | ||
|
|
||
| export function getCookieDomainOptions(requestHostname: string): { domain: string } | undefined { | ||
| const cookieDomain = appConfig.app.cookieDomain; | ||
| if (cookieDomain && requestHostname?.includes(cookieDomain)) { | ||
| return { domain: cookieDomain }; | ||
| /** | ||
| * The registrable domains from `ROCKETADMIN_COOKIE_DOMAIN`, a comma-separated list such as | ||
| * `rocketadmin.com,sitenova.com`. A single value is a list of one. The parser drops a leading dot. | ||
| */ | ||
| export function parseCookieDomains(raw: string | null | undefined): Array<string> { | ||
| if (!raw) { | ||
| return []; | ||
| } | ||
| return undefined; | ||
| return raw | ||
| .split(',') | ||
| .map((domain) => domain.trim().toLowerCase().replace(/^\./, '')) | ||
| .filter((domain) => domain.length > 0); | ||
| } | ||
|
|
||
| /** | ||
| * The first configured domain that equals the request hostname or that is a dotted suffix of it. | ||
| * `app.sitenova.com` matches `sitenova.com`. `sitenova.com.evil.net` matches nothing. | ||
| */ | ||
| export function matchCookieDomain( | ||
| requestHostname: string | null | undefined, | ||
| domains: Array<string>, | ||
| ): string | undefined { | ||
| const hostname = requestHostname?.trim().toLowerCase(); | ||
| if (!hostname) { | ||
| return undefined; | ||
| } | ||
| return domains.find((domain) => hostname === domain || hostname.endsWith(`.${domain}`)); | ||
| } | ||
|
|
||
| /** | ||
| * The `Domain` attribute of the session cookie for a request hostname. | ||
| * | ||
| * The saas keeps an identical copy of this rule. Both services set the same cookie on the same | ||
| * hosts, so they must agree. Otherwise a browser on `rocket.sitenova.com` holds two cookies with | ||
| * the same name and a logout clears only one of them (plan 84). | ||
| */ | ||
| export function getCookieDomainOptions( | ||
| requestHostname: string, | ||
| domains: Array<string> = parseCookieDomains(appConfig.app.cookieDomain), | ||
| ): { domain: string } | undefined { | ||
| const domain = matchCookieDomain(requestHostname, domains); | ||
| return domain ? { domain } : undefined; | ||
| } |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Verify a token before letting its
iatdisplace a valid session.If a request contains a valid session cookie and a forged cookie with a larger
iat, this function selects the forged token. The middleware then verifies only that token, so authenticated requests fail while the valid cookie remains present. A subdomain can set a parent-domain cookie, making this collision feasible on a shared cookie domain. Select among verified, usable tokens rather than ranking unverified payloads alone. (developer.mozilla.org)