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
13 changes: 11 additions & 2 deletions src/app/api/auth/backup-pin/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@ function getServiceRoleClient() {

const supabaseClient = createClient(process.env.NEXT_PUBLIC_SUPABASE_URL, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY);

function getBearerToken(authHeader) {
if (typeof authHeader !== 'string') return null;

const match = authHeader.match(/^Bearer\s+(.+)$/i);
const token = match?.[1]?.trim();

return token || null;
}

/**
* Authenticate user from request cookies
* @param {Request} request
Expand All @@ -24,8 +33,8 @@ async function authenticateUser(request) {
try {
// Try Authorization header first (used during registration)
const authHeader = request.headers.get('authorization');
if (authHeader?.startsWith('Bearer ')) {
const token = authHeader.substring(7);
const token = getBearerToken(authHeader);
if (token) {
const { data: { user }, error } = await supabaseClient.auth.getUser(token);
if (!error && user) {
return { user };
Expand Down
31 changes: 31 additions & 0 deletions src/app/api/auth/backup-pin/route.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,35 @@ describe('backup PIN cookie authentication', () => {
expect(body).toEqual({ hasPin: true });
expect(mocks.authGetUser).toHaveBeenCalledWith('access-token');
});

it('normalizes bearer scheme casing and extra spaces', async () => {
const { GET } = await import('./route.js');
const response = await GET(
new Request('https://qrypt.chat/api/auth/backup-pin', {
headers: {
authorization: 'bearer access-token '
}
})
);
const body = await response.json();

expect(response.status).toBe(200);
expect(body).toEqual({ hasPin: true });
expect(mocks.authGetUser).toHaveBeenCalledWith('access-token');
});

it('ignores an empty bearer header and falls back to cookies', async () => {
const { GET } = await import('./route.js');
const response = await GET(
new Request('https://qrypt.chat/api/auth/backup-pin', {
headers: {
authorization: 'Bearer ',
cookie: `sb-xydzwxwsbgmznthiiscl-auth-token=${cookieValue('cookie-token')}`
}
})
);

expect(response.status).toBe(200);
expect(mocks.authGetUser).toHaveBeenCalledWith('cookie-token');
});
});
Loading