diff --git a/lib/auth-db-sync.test.ts b/lib/auth-db-sync.test.ts new file mode 100644 index 00000000..da3ad511 --- /dev/null +++ b/lib/auth-db-sync.test.ts @@ -0,0 +1,20 @@ +import Database from 'better-sqlite3'; +import { getCredentialPasswordHashFromDb } from './auth-db-sync'; + +describe('getCredentialPasswordHashFromDb', () => { + let db: Database.Database; + + beforeEach(() => { + db = new Database(':memory:'); + db.exec('CREATE TABLE account (userId TEXT, providerId TEXT, password TEXT)'); + db.prepare('INSERT INTO account VALUES (?, ?, ?)').run('1', 'credential', 'sqlite-hash'); + db.prepare('INSERT INTO account VALUES (?, ?, ?)').run('2', 'google', 'oauth-hash'); + }); + afterEach(() => db.close()); + + it('reads the password from the user credential account only', () => { + expect(getCredentialPasswordHashFromDb(db, '1')).toBe('sqlite-hash'); + expect(getCredentialPasswordHashFromDb(db, '2')).toBeUndefined(); + expect(getCredentialPasswordHashFromDb(db, '3')).toBeUndefined(); + }); +}); diff --git a/lib/auth-db-sync.ts b/lib/auth-db-sync.ts index 4e599877..b8912f83 100644 --- a/lib/auth-db-sync.ts +++ b/lib/auth-db-sync.ts @@ -3,6 +3,16 @@ import path from 'path'; const dbPath = path.join(process.cwd(), 'config', 'better_auth.sqlite'); +export function getCredentialPasswordHashFromDb( + db: Database.Database, + userId: string +): string | undefined { + const account = db + .prepare("SELECT password FROM account WHERE userId = ? AND providerId = 'credential' LIMIT 1") + .get(userId) as { password: string | null } | undefined; + return account?.password ?? undefined; +} + /** * Sync helpers: keep the better-auth SQLite DB in step with users.json * after account mutations. These are synchronous (better-sqlite3 API). @@ -20,6 +30,15 @@ export function syncUsernameChange(userId: string, newUsername: string): void { } } +export function getCredentialPasswordHash(userId: string): string | undefined { + const db = new Database(dbPath); + try { + return getCredentialPasswordHashFromDb(db, userId); + } finally { + db.close(); + } +} + export function syncPasswordChange(userId: string, newPasswordHash: string): void { const db = new Database(dbPath); try { diff --git a/lib/auth-legacy-schema.test.ts b/lib/auth-legacy-schema.test.ts index d6e36a41..7412eb04 100644 --- a/lib/auth-legacy-schema.test.ts +++ b/lib/auth-legacy-schema.test.ts @@ -1,5 +1,5 @@ import Database from 'better-sqlite3'; -import { dropLegacyAccountIssuer } from './auth-legacy-schema'; +import { dropLegacyAccountIssuer, repairCredentialAccountIds } from './auth-legacy-schema'; // Schema created by better-auth 1.7.2 (BorgWarehouse 3.6.x fresh installs) const LEGACY_SCHEMA = ` @@ -19,6 +19,37 @@ describe('dropLegacyAccountIssuer', () => { beforeEach(() => { db = new Database(':memory:'); }); + + describe('repairCredentialAccountIds', () => { + let db: Database.Database; + + beforeEach(() => { + db = new Database(':memory:'); + db.exec(LEGACY_SCHEMA); + db.prepare( + "INSERT INTO account VALUES ('0-credential', 'local:credential', 'admin', 'credential', '0', 'hash', 'now', 'now')" + ).run(); + }); + afterEach(() => db.close()); + + it('repairs migrated credential accounts whose accountId is still the username', () => { + expect(repairCredentialAccountIds(db)).toBe(1); + expect( + db.prepare('SELECT accountId, userId FROM account WHERE providerId = ?').get('credential') + ).toEqual({ accountId: '0', userId: '0' }); + }); + + it('is idempotent for already-correct accounts', () => { + repairCredentialAccountIds(db); + expect(repairCredentialAccountIds(db)).toBe(0); + }); + + it('does nothing when the account table is not present', () => { + const emptyDb = new Database(':memory:'); + expect(repairCredentialAccountIds(emptyDb)).toBe(0); + emptyDb.close(); + }); + }); afterEach(() => db.close()); it('drops the issuer column and its index while keeping existing accounts', () => { diff --git a/lib/auth-legacy-schema.ts b/lib/auth-legacy-schema.ts index 39164073..4fcb1fc1 100644 --- a/lib/auth-legacy-schema.ts +++ b/lib/auth-legacy-schema.ts @@ -1,5 +1,28 @@ import type Database from 'better-sqlite3'; +/** + * Repairs credential account identities left behind by earlier users.json migrations. + * The accountId for Better Auth credential accounts must always be the user id. + */ +export function repairCredentialAccountIds(db: Database.Database): number { + const accountTable = db + .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='account'") + .get(); + if (!accountTable) return 0; + + const changed = db + .prepare( + "UPDATE account SET accountId = userId " + + "WHERE providerId = 'credential' AND accountId != userId" + ) + .run().changes; + + if (changed > 0) { + console.warn(`[better-auth] Repaired ${changed} credential account identity row(s).`); + } + return changed; +} + /** * Removes the `account.issuer` column introduced by better-auth 1.7.0 through 1.7.2 * (BorgWarehouse 3.6.2 → 3.7.0). better-auth >= 1.7.3 identifies accounts by diff --git a/lib/auth-migrate.ts b/lib/auth-migrate.ts index e5d64078..32a4a9e7 100644 --- a/lib/auth-migrate.ts +++ b/lib/auth-migrate.ts @@ -3,6 +3,7 @@ import Database from 'better-sqlite3'; import { existsSync, writeFileSync } from 'fs'; import path from 'path'; import { authOptions } from '~/lib/auth-options'; +import { repairCredentialAccountIds } from '~/lib/auth-legacy-schema'; import { ConfigService } from '~/services'; const dbPath = path.join(process.cwd(), 'config', 'better_auth.sqlite'); @@ -31,6 +32,12 @@ export async function ensureSchemaReady(): Promise { try { const { runMigrations } = await getMigrations(authOptions); await runMigrations(); + const db = new Database(dbPath); + try { + repairCredentialAccountIds(db); + } finally { + db.close(); + } migrationDone = true; } catch (error) { console.error('[better-auth] Schema migration error:', error); diff --git a/pages/api/v1/account/password.test.ts b/pages/api/v1/account/password.test.ts index 2f17e523..bafd539b 100644 --- a/pages/api/v1/account/password.test.ts +++ b/pages/api/v1/account/password.test.ts @@ -2,15 +2,21 @@ import { createMocks } from 'node-mocks-http'; import handler from '~/pages/api/v1/account/password'; import { getSession } from '~/helpers/getServerSession'; import { ConfigService, AuthService } from '~/services'; +import { getCredentialPasswordHash, syncPasswordChange } from '~/lib/auth-db-sync'; vi.mock('~/helpers/getServerSession'); vi.mock('~/services'); -vi.mock('~/lib/auth-db-sync'); +vi.mock('~/lib/auth-db-sync', () => ({ + getCredentialPasswordHash: vi.fn(), + syncPasswordChange: vi.fn(), +})); describe('PUT /api/account/updatePassword', () => { beforeEach(() => { vi.clearAllMocks(); vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.mocked(getCredentialPasswordHash).mockReturnValue(undefined); + vi.mocked(AuthService.verifyPassword).mockResolvedValue(false); }); it('should return 401 if not authenticated', async () => { @@ -62,9 +68,7 @@ describe('PUT /api/account/updatePassword', () => { await handler(req, res); expect(res._getStatusCode()).toBe(400); - expect(res._getJSONData()).toEqual({ - message: 'User is incorrect. Please, logout to update your session.', - }); + expect(res._getJSONData()).toEqual({ message: 'Old password is incorrect.' }); }); it('should return 400 if old password is incorrect', async () => { @@ -76,6 +80,7 @@ describe('PUT /api/account/updatePassword', () => { { id: 1, username: 'Lovelace', password: 'hashedpass', roles: [], email: 'love@example.com' }, ]); + vi.mocked(getCredentialPasswordHash).mockReturnValue('sqlite-hash'); vi.mocked(AuthService.verifyPassword).mockResolvedValue(false); const { req, res } = createMocks({ @@ -93,7 +98,7 @@ describe('PUT /api/account/updatePassword', () => { const oldUser = { id: 1, username: 'Lovelace', - password: 'hashedpass', + password: 'stale-json-hash', roles: [], email: 'love@example.com', }; @@ -103,8 +108,11 @@ describe('PUT /api/account/updatePassword', () => { }); vi.mocked(ConfigService.getUsersList).mockResolvedValue([oldUser]); + vi.mocked(getCredentialPasswordHash).mockReturnValue('sqlite-hash'); - vi.mocked(AuthService.verifyPassword).mockResolvedValue(true); + vi.mocked(AuthService.verifyPassword).mockImplementation(async (_password, hash) => + hash === 'sqlite-hash' + ); vi.mocked(AuthService.hashPassword).mockResolvedValue('newHashedPassword'); vi.mocked(ConfigService.updateUsersList).mockResolvedValue(); @@ -115,13 +123,36 @@ describe('PUT /api/account/updatePassword', () => { await handler(req, res); - expect(AuthService.verifyPassword).toHaveBeenCalledWith('oldpass', 'hashedpass'); + expect(getCredentialPasswordHash).toHaveBeenCalledWith('1'); + expect(AuthService.verifyPassword).toHaveBeenCalledWith('oldpass', 'sqlite-hash'); expect(AuthService.hashPassword).toHaveBeenCalledWith('newpass'); expect(ConfigService.updateUsersList).toHaveBeenCalledWith([ { ...oldUser, password: 'newHashedPassword' }, ]); expect(res._getStatusCode()).toBe(200); expect(res._getJSONData()).toEqual({ message: 'Successful API send' }); + expect(syncPasswordChange).toHaveBeenCalledWith('1', 'newHashedPassword'); + }); + + it('should change the SQLite password even when there is no legacy JSON user entry', async () => { + vi.mocked(getSession).mockResolvedValue({ + user: { name: 'Lovelace', email: 'love@example.com', id: '1' }, + }); + vi.mocked(ConfigService.getUsersList).mockResolvedValue([]); + vi.mocked(getCredentialPasswordHash).mockReturnValue('sqlite-hash'); + vi.mocked(AuthService.verifyPassword).mockResolvedValue(true); + vi.mocked(AuthService.hashPassword).mockResolvedValue('newHashedPassword'); + + const { req, res } = createMocks({ + method: 'PUT', + body: { oldPassword: 'oldpass', newPassword: 'newpass' }, + }); + + await handler(req, res); + + expect(syncPasswordChange).toHaveBeenCalledWith('1', 'newHashedPassword'); + expect(ConfigService.updateUsersList).not.toHaveBeenCalled(); + expect(res._getStatusCode()).toBe(200); }); it('should return 500 if there is a file system error (ENOENT)', async () => { @@ -129,6 +160,8 @@ describe('PUT /api/account/updatePassword', () => { user: { name: 'Lovelace', email: 'love@example.com', id: '1' }, }); + vi.mocked(getCredentialPasswordHash).mockReturnValue('sqlite-hash'); + vi.mocked(AuthService.verifyPassword).mockResolvedValue(true); vi.mocked(ConfigService.getUsersList).mockRejectedValue({ code: 'ENOENT' }); const { req, res } = createMocks({ @@ -150,6 +183,8 @@ describe('PUT /api/account/updatePassword', () => { user: { name: 'Lovelace', email: 'love@example.com', id: '1' }, }); + vi.mocked(getCredentialPasswordHash).mockReturnValue('sqlite-hash'); + vi.mocked(AuthService.verifyPassword).mockResolvedValue(true); vi.mocked(ConfigService.getUsersList).mockRejectedValue({ code: 'SOMETHING_ELSE' }); const { req, res } = createMocks({ diff --git a/pages/api/v1/account/password.ts b/pages/api/v1/account/password.ts index 139c8ea4..5e0ee90f 100644 --- a/pages/api/v1/account/password.ts +++ b/pages/api/v1/account/password.ts @@ -1,7 +1,7 @@ import { findUserIndexBySession } from '~/helpers/functions'; import { ConfigService, AuthService } from '~/services'; import { getSession } from '~/helpers/getServerSession'; -import { syncPasswordChange } from '~/lib/auth-db-sync'; +import { getCredentialPasswordHash, syncPasswordChange } from '~/lib/auth-db-sync'; import { NextApiRequest, NextApiResponse } from 'next'; import { ErrorResponse, PasswordSettingDTO } from '~/types'; import ApiResponse from '~/helpers/functions/apiResponse'; @@ -26,28 +26,31 @@ export default async function handler( } try { - const usersList = await ConfigService.getUsersList(); - const userIndex = findUserIndexBySession(usersList, session); - const user = usersList[userIndex]; - - if (userIndex === -1 || !user) { + const userId = session.user.id; + if (!userId) { return res.status(400).json({ message: 'User is incorrect. Please, logout to update your session.', }); } - const isValidPassword = await AuthService.verifyPassword(oldPassword, user.password); + const currentPasswordHash = getCredentialPasswordHash(userId); + const isValidPassword = + currentPasswordHash && (await AuthService.verifyPassword(oldPassword, currentPasswordHash)); if (!isValidPassword) { return res.status(400).json({ message: 'Old password is incorrect.' }); } + const usersList = await ConfigService.getUsersList(); + const userIndex = findUserIndexBySession(usersList, session); const newPasswordHash = await AuthService.hashPassword(newPassword); - const updatedUsersList = usersList.map((user, index) => - index === userIndex ? { ...user, password: newPasswordHash } : user - ); + syncPasswordChange(userId, newPasswordHash); - await ConfigService.updateUsersList(updatedUsersList); - syncPasswordChange(session.user.id!, newPasswordHash); + if (userIndex !== -1) { + const updatedUsersList = usersList.map((user, index) => + index === userIndex ? { ...user, password: newPasswordHash } : user + ); + await ConfigService.updateUsersList(updatedUsersList); + } return res.status(200).json({ message: 'Successful API send' }); } catch (error) {