-
Notifications
You must be signed in to change notification settings - Fork 32
fix(idp): invalidate other sessions on password reset and change #1297
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
laskevych
wants to merge
1
commit into
main
Choose a base branch
from
idp/invalidate-other-sessions-on-password-reset-and-change
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
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
70 changes: 70 additions & 0 deletions
70
packages/idp-better-auth/src/auth/auth-config.session-revocation.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,70 @@ | ||
| import { afterEach, describe, expect, it } from '@jest/globals'; | ||
| import Database from 'better-sqlite3'; | ||
| import { getMigrations } from 'better-auth/db/migration'; | ||
| import { createBetterAuthConfig } from './auth-config.js'; | ||
| import type { BetterAuthConfig } from '../types/index.js'; | ||
|
|
||
| /** | ||
| * Security regression test: the exposed Better Auth `/change-password` | ||
| * endpoint must revoke the user's other sessions even when the caller does not | ||
| * opt in via `revokeOtherSessions`. The auth config forces it on via a hook. | ||
| */ | ||
| describe('idp-better-auth — change-password session invalidation', () => { | ||
| const EMAIL = 'user@test.io'; | ||
| const PASSWORD = 'Passw0rd1'; | ||
|
|
||
| let db: InstanceType<typeof Database>; | ||
|
|
||
| afterEach(() => { | ||
| db?.close(); | ||
| }); | ||
|
|
||
| async function buildAuth() { | ||
| db = new Database(':memory:'); | ||
| const config = { | ||
| baseURL: 'http://localhost:3000', | ||
| secret: 'x'.repeat(40), | ||
| magicLinkTtl: 3600, | ||
| } as unknown as BetterAuthConfig; | ||
|
|
||
| const auth = await createBetterAuthConfig(config, { adapter: db }); | ||
| const { runMigrations } = await getMigrations(auth.options); | ||
| await runMigrations(); | ||
| return auth; | ||
| } | ||
|
|
||
| function sessionTokens(): string[] { | ||
| return (db.prepare('SELECT token FROM session').all() as Array<{ token: string }>).map( | ||
| r => r.token | ||
| ); | ||
| } | ||
|
|
||
| it('revokes other sessions when the client omits revokeOtherSessions', async () => { | ||
| const auth = await buildAuth(); | ||
|
|
||
| const signUpRes = await auth.api.signUpEmail({ | ||
| body: { email: EMAIL, password: PASSWORD, name: 'User' }, | ||
| asResponse: true, | ||
| }); | ||
| const setCookie = signUpRes.headers.get('set-cookie') ?? ''; | ||
| const tokenMatch = setCookie.match(/refreshToken=([^;]+)/); | ||
| expect(tokenMatch?.[1]).toBeTruthy(); | ||
| const sessionAToken = decodeURIComponent(tokenMatch![1]).split('.')[0]; | ||
|
|
||
| // A second, independent session for the same user. | ||
| await auth.api.signInEmail({ body: { email: EMAIL, password: PASSWORD } }); | ||
| expect(sessionTokens()).toHaveLength(2); | ||
|
|
||
| const resp = await auth.api.changePassword({ | ||
| // intentionally no `revokeOtherSessions` — the config hook forces it | ||
| body: { currentPassword: PASSWORD, newPassword: 'NewPassw0rd1' }, | ||
| headers: { cookie: `refreshToken=${tokenMatch![1]}` }, | ||
| asResponse: true, | ||
| }); | ||
| expect(resp.status).toBe(200); | ||
|
|
||
| const remaining = sessionTokens(); | ||
| expect(remaining).toHaveLength(1); | ||
| expect(remaining).not.toContain(sessionAToken); | ||
| }); | ||
| }); |
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
56 changes: 56 additions & 0 deletions
56
packages/idp-better-auth/src/store/SqliteDatabaseStore.session-revocation.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,56 @@ | ||
| import { afterEach, beforeEach, describe, expect, it } from '@jest/globals'; | ||
| import { SqliteDatabaseStore } from './SqliteDatabaseStore.js'; | ||
|
|
||
| /** | ||
| * Verifies the raw SQL of the session-revocation helpers against a real | ||
| * in-memory SQLite database. | ||
| */ | ||
| describe('SqliteDatabaseStore — session revocation SQL', () => { | ||
| let store: SqliteDatabaseStore; | ||
|
|
||
| beforeEach(async () => { | ||
| store = new SqliteDatabaseStore(':memory:'); | ||
| await store.connect(); | ||
| const db = (await store.getAdapter()) as { | ||
| prepare: (sql: string) => { run: (...args: unknown[]) => unknown }; | ||
| }; | ||
| db.prepare('CREATE TABLE session (token TEXT PRIMARY KEY, userId TEXT)').run(); | ||
| db.prepare('INSERT INTO session (token, userId) VALUES (?, ?)').run('tok-current', 'user-1'); | ||
| db.prepare('INSERT INTO session (token, userId) VALUES (?, ?)').run('tok-other', 'user-1'); | ||
| db.prepare('INSERT INTO session (token, userId) VALUES (?, ?)').run('tok-elsewhere', 'user-2'); | ||
| }); | ||
|
|
||
| afterEach(async () => { | ||
| await store.shutdown(); | ||
| }); | ||
|
|
||
| function rows(): Array<{ token: string; userId: string }> { | ||
| const adapter = ( | ||
| store as unknown as { | ||
| db: { prepare: (sql: string) => { all: () => Array<{ token: string; userId: string }> } }; | ||
| } | ||
| ).db; | ||
| return adapter.prepare('SELECT token, userId FROM session').all(); | ||
| } | ||
|
|
||
| function tokensFor(userId: string): string[] { | ||
| return rows() | ||
| .filter(r => r.userId === userId) | ||
| .map(r => r.token); | ||
| } | ||
|
|
||
| it('revokeOtherUserSessions deletes all of the user’s sessions except the current one', async () => { | ||
| await store.revokeOtherUserSessions('user-1', 'tok-current'); | ||
|
|
||
| expect(tokensFor('user-1')).toEqual(['tok-current']); | ||
| // Other users are untouched. | ||
| expect(tokensFor('user-2')).toEqual(['tok-elsewhere']); | ||
| }); | ||
|
|
||
| it('revokeUserSessions deletes every session for the user', async () => { | ||
| await store.revokeUserSessions('user-1'); | ||
|
|
||
| expect(tokensFor('user-1')).toEqual([]); | ||
| expect(tokensFor('user-2')).toEqual(['tok-elsewhere']); | ||
| }); | ||
| }); |
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
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.
🔴 Blocking: This hook only covers @owox/idp-better-auth. @owox/idp-owox-better-auth has a separate createBetterAuthConfig, and BetterAuthProxyHandler forwards every /auth/better-auth/* route there, so /auth/better-auth/change-password can still omit revokeOtherSessions and keep other sessions alive. Please add the same hook to the OWOX Better Auth config or centralize this config behavior.
🤖 Reviewed by Codex (GPT-5.5)