Skip to content
Merged
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
7 changes: 4 additions & 3 deletions src/app/api/auth/salt/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,10 @@ export async function POST(request) {
}

const { salt } = await request.json();
if (!salt) {
if (typeof salt !== 'string' || !salt.trim()) {
return NextResponse.json({ error: 'Missing salt' }, { status: 400 });
}
const normalizedSalt = salt.trim();

// Verify the authenticated user has a record and look up their phone.
const { data: existing } = await getServiceRoleClient()
Expand All @@ -124,15 +125,15 @@ export async function POST(request) {

const { error } = await getServiceRoleClient()
.from('users')
.update({ salt })
.update({ salt: normalizedSalt })
.eq('auth_user_id', user.id);

if (error) {
console.error('Salt POST update error:', error);
return NextResponse.json({ error: 'Failed to store salt' }, { status: 500 });
}

return NextResponse.json({ salt, existing: false });
return NextResponse.json({ salt: normalizedSalt, existing: false });
} catch (error) {
console.error('Salt POST error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
Expand Down
44 changes: 43 additions & 1 deletion src/app/api/auth/salt/route.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';

const mocks = vi.hoisted(() => ({
authGetUser: vi.fn(),
serviceFrom: vi.fn()
serviceFrom: vi.fn(),
updateUser: vi.fn(() => ({
eq: vi.fn(() => Promise.resolve({ error: null }))
}))
}));

vi.mock('@supabase/supabase-js', () => ({
Expand All @@ -27,6 +30,7 @@ function createUsersQuery() {
const query = {
select: vi.fn(() => query),
eq: vi.fn(() => query),
update: mocks.updateUser,
single: vi.fn(() =>
Promise.resolve({
data: { salt: 'stored-salt' },
Expand All @@ -37,6 +41,14 @@ function createUsersQuery() {
return query;
}

function postSaltRequest(body, headers = { authorization: 'Bearer access-token' }) {
return new Request('https://qrypt.chat/api/auth/salt', {
method: 'POST',
headers,
body: JSON.stringify(body)
});
}

describe('salt cookie authentication', () => {
beforeEach(() => {
vi.resetModules();
Expand Down Expand Up @@ -100,4 +112,34 @@ describe('salt cookie authentication', () => {
expect(response.status).toBe(200);
expect(mocks.authGetUser).toHaveBeenCalledWith('cookie-token');
});

it('rejects non-string salts before querying the user record', async () => {
const { POST } = await import('./route.js');
const response = await POST(postSaltRequest({ salt: { value: 'abc' } }));
const body = await response.json();

expect(response.status).toBe(400);
expect(body.error).toBe('Missing salt');
expect(mocks.serviceFrom).not.toHaveBeenCalled();
});

it('trims new salts before storing and returning them', async () => {
mocks.serviceFrom.mockImplementation((table) => {
if (table !== 'users') throw new Error(`Unexpected table: ${table}`);
const query = createUsersQuery();
query.single.mockResolvedValueOnce({
data: { salt: null, phone_number: '+15551234567' },
error: null
});
return query;
});

const { POST } = await import('./route.js');
const response = await POST(postSaltRequest({ salt: ' client-salt ' }));
const body = await response.json();

expect(response.status).toBe(200);
expect(body).toEqual({ salt: 'client-salt', existing: false });
expect(mocks.updateUser).toHaveBeenCalledWith({ salt: 'client-salt' });
});
});
Loading