Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions lib/auth-db-sync.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
19 changes: 19 additions & 0 deletions lib/auth-db-sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -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 {
Expand Down
33 changes: 32 additions & 1 deletion lib/auth-legacy-schema.test.ts
Original file line number Diff line number Diff line change
@@ -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 = `
Expand All @@ -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', () => {
Expand Down
23 changes: 23 additions & 0 deletions lib/auth-legacy-schema.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down
7 changes: 7 additions & 0 deletions lib/auth-migrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -31,6 +32,12 @@ export async function ensureSchemaReady(): Promise<void> {
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);
Expand Down
49 changes: 42 additions & 7 deletions pages/api/v1/account/password.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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 () => {
Expand All @@ -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({
Expand All @@ -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',
};
Expand All @@ -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();

Expand All @@ -115,20 +123,45 @@ 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 () => {
vi.mocked(getSession).mockResolvedValue({
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({
Expand All @@ -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({
Expand Down
27 changes: 15 additions & 12 deletions pages/api/v1/account/password.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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) {
Expand Down
Loading