fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
+44
View File
@@ -0,0 +1,44 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { requireAuth } from '@/lib/auth/require-auth'
import { LOCALE_COOKIE, SUPPORTED_LOCALES, type Locale } from '@/i18n/config'
const BodySchema = z.object({
locale: z.enum(SUPPORTED_LOCALES),
})
export async function POST(request: Request) {
const { user, supabase, error } = await requireAuth()
if (error) return error
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })
}
const parsed = BodySchema.safeParse(body)
if (!parsed.success) {
return NextResponse.json({ error: 'Invalid locale' }, { status: 400 })
}
const locale: Locale = parsed.data.locale
const { error: upsertError } = await supabase
.from('user_preferences')
.upsert({ user_id: user.id, locale }, { onConflict: 'user_id' })
if (upsertError) {
return NextResponse.json({ error: 'Could not save language preference' }, { status: 500 })
}
const response = NextResponse.json({ data: { locale } })
response.cookies.set(LOCALE_COOKIE, locale, {
path: '/',
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
maxAge: 60 * 60 * 24 * 365,
})
return response
}
@@ -0,0 +1,155 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { parseJsonResponse } from '@/tests/helpers'
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
import { GET, PATCH } from '../route'
beforeEach(() => {
vi.clearAllMocks()
})
function unauthed() {
requireAuthMock.mockResolvedValue({
user: null,
supabase: null,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
}
function authedForGet(
row: { hide_assistant_fab?: boolean; auto_logout?: boolean } | null,
) {
const maybeSingle = vi.fn().mockResolvedValue({ data: row, error: null })
const supabase = {
from: vi.fn(() => ({
select: vi.fn(() => ({
eq: vi.fn(() => ({ maybeSingle })),
})),
})),
}
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
return { supabase }
}
function authedForPatch(upsertError: { message: string } | null = null) {
const upsert = vi.fn().mockResolvedValue({ error: upsertError })
const supabase = { from: vi.fn(() => ({ upsert })) }
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
return { upsert }
}
function patchRequest(body: unknown) {
return new Request('http://localhost/api/user/preferences', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
describe('GET /api/user/preferences', () => {
it('returns 401 when unauthenticated', async () => {
unauthed()
const res = await GET()
expect(res.status).toBe(401)
})
it('returns the stored preferences', async () => {
authedForGet({ hide_assistant_fab: true, auto_logout: true })
const res = await GET()
const { status, body } = await parseJsonResponse<{ data: unknown }>(res)
expect(status).toBe(200)
expect(body.data).toEqual({ hide_assistant_fab: true, auto_logout: true })
})
it('defaults to false when no preferences row exists', async () => {
authedForGet(null)
const res = await GET()
const { body } = await parseJsonResponse<{ data: unknown }>(res)
expect(body.data).toEqual({ hide_assistant_fab: false, auto_logout: false })
})
})
describe('PATCH /api/user/preferences', () => {
it('returns 401 when unauthenticated', async () => {
unauthed()
const res = await PATCH(patchRequest({ hide_assistant_fab: true }))
expect(res.status).toBe(401)
})
it('rejects an invalid body with 400', async () => {
authedForPatch()
const res = await PATCH(patchRequest({ hide_assistant_fab: 'yes' }))
expect(res.status).toBe(400)
})
it('rejects unknown keys with 400', async () => {
authedForPatch()
const res = await PATCH(patchRequest({ hide_assistant_fab: true, locale: 'en' }))
expect(res.status).toBe(400)
})
it('upserts the preference for the authenticated user', async () => {
const { upsert } = authedForPatch()
const res = await PATCH(patchRequest({ hide_assistant_fab: true }))
const { status, body } = await parseJsonResponse<{ data: unknown }>(res)
expect(status).toBe(200)
expect(body.data).toEqual({ hide_assistant_fab: true })
expect(upsert).toHaveBeenCalledWith(
{ user_id: 'user-1', hide_assistant_fab: true },
{ onConflict: 'user_id' }
)
})
it('writes a multi-field request as one atomic upsert', async () => {
const { upsert } = authedForPatch()
const res = await PATCH(
patchRequest({ hide_assistant_fab: true, auto_logout: false })
)
expect(res.status).toBe(200)
expect(upsert).toHaveBeenCalledTimes(1)
expect(upsert).toHaveBeenCalledWith(
{ user_id: 'user-1', hide_assistant_fab: true, auto_logout: false },
{ onConflict: 'user_id' }
)
})
it('rejects an empty body with 400', async () => {
authedForPatch()
const res = await PATCH(patchRequest({}))
expect(res.status).toBe(400)
})
it('upserts auto_logout and resets the session timeout cookie', async () => {
const { upsert } = authedForPatch()
const res = await PATCH(patchRequest({ auto_logout: true }))
const { status, body } = await parseJsonResponse<{ data: unknown }>(res)
expect(status).toBe(200)
expect(body.data).toEqual({ auto_logout: true })
expect(upsert).toHaveBeenCalledWith(
{ user_id: 'user-1', auto_logout: true },
{ onConflict: 'user_id' }
)
// The signed timeout cookie caches the opt-in; a change must clear it so
// the middleware re-mints with the new preference on the next request.
const setCookie = res.headers.get('set-cookie') ?? ''
expect(setCookie).toContain('gnubok-session-timeout=;')
})
it('does not touch the session timeout cookie for unrelated preferences', async () => {
authedForPatch()
const res = await PATCH(patchRequest({ hide_assistant_fab: true }))
expect(res.status).toBe(200)
expect(res.headers.get('set-cookie')).toBeNull()
})
it('returns 500 when the upsert fails', async () => {
authedForPatch({ message: 'boom' })
const res = await PATCH(patchRequest({ hide_assistant_fab: false }))
expect(res.status).toBe(500)
})
})
+108
View File
@@ -0,0 +1,108 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { requireAuth } from '@/lib/auth/require-auth'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { sessionTimeoutClearCookieOptions } from '@/lib/auth/session-timeout'
import { SESSION_TIMEOUT_COOKIE } from '@/lib/auth/session-timeout-shared'
// User-level UI preferences (not company-scoped), stored on user_preferences.
// Mirrors the /api/user/locale pattern: requireAuth directly because these
// must work even when the user has no active company.
const BodySchema = z
.object({
hide_assistant_fab: z.boolean().optional(),
auto_logout: z.boolean().optional(),
})
.strict()
.refine((value) => Object.keys(value).length > 0, {
message: 'At least one preference is required',
})
export async function GET() {
const { user, supabase, error } = await requireAuth()
if (error) return error
const { data } = await supabase
.from('user_preferences')
.select('hide_assistant_fab, auto_logout')
.eq('user_id', user.id)
.maybeSingle()
return NextResponse.json({
data: {
hide_assistant_fab: data?.hide_assistant_fab ?? false,
auto_logout: data?.auto_logout ?? false,
},
})
}
export async function PATCH(request: Request) {
const { user, supabase, error } = await requireAuth()
if (error) return error
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })
}
const parsed = BodySchema.safeParse(body)
if (!parsed.success) {
return NextResponse.json({ error: 'Invalid preferences' }, { status: 400 })
}
const { hide_assistant_fab, auto_logout } = parsed.data
// One literal upsert per accepted field combination: the phantom-column
// schema guard cannot resolve spread payloads, and a single write keeps a
// multi-field request atomic.
let upsertError: unknown = null
if (hide_assistant_fab !== undefined && auto_logout !== undefined) {
const { error } = await supabase
.from('user_preferences')
.upsert(
{ user_id: user.id, hide_assistant_fab, auto_logout },
{ onConflict: 'user_id' },
)
upsertError = error
} else if (hide_assistant_fab !== undefined) {
const { error } = await supabase
.from('user_preferences')
.upsert({ user_id: user.id, hide_assistant_fab }, { onConflict: 'user_id' })
upsertError = error
} else if (auto_logout !== undefined) {
const { error } = await supabase
.from('user_preferences')
.upsert({ user_id: user.id, auto_logout }, { onConflict: 'user_id' })
upsertError = error
}
if (upsertError) {
return NextResponse.json(
{
error: getErrorMessage(upsertError, {
context: 'settings',
statusCode: 500,
}),
},
{ status: 500 },
)
}
const response = NextResponse.json({ data: parsed.data })
if (parsed.data.auto_logout !== undefined) {
// The middleware caches the opt-in inside the signed timeout cookie.
// Clearing it forces a re-mint on the next request, so the change takes
// effect immediately instead of at the next login.
response.cookies.set(
SESSION_TIMEOUT_COOKIE,
'',
sessionTimeoutClearCookieOptions(),
)
}
return response
}
+66
View File
@@ -0,0 +1,66 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { requireAuth } from '@/lib/auth/require-auth'
import { createServiceClient } from '@/lib/supabase/server'
import { createLogger } from '@/lib/logger'
const log = createLogger('user/profile')
// User-scoped (not company-scoped): same shape as /api/user/locale, so it
// opts out of withRouteContext and calls requireAuth() directly (MFA still
// enforced on hosted).
const BodySchema = z.object({
full_name: z.string().min(1).max(100),
})
export async function POST(request: Request) {
const { user, supabase, error } = await requireAuth()
if (error) return error
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })
}
const parsed = BodySchema.safeParse(body)
if (!parsed.success) {
return NextResponse.json({ error: 'Invalid name' }, { status: 400 })
}
const fullName = parsed.data.full_name.trim()
if (!fullName) {
return NextResponse.json({ error: 'Invalid name' }, { status: 400 })
}
// Source of truth: profiles.full_name. Read by the account menu
// (app/(dashboard)/layout.tsx), the first-name greetings, the agent context,
// and the AGI/KU contact-person field. RLS scopes the update to the caller's
// own row (profiles_update policy: auth.uid() = id).
const { error: updateError } = await supabase
.from('profiles')
.update({ full_name: fullName })
.eq('id', user.id)
if (updateError) {
return NextResponse.json({ error: 'Could not save name' }, { status: 500 })
}
// Best-effort: keep auth user_metadata.full_name in sync so the two stores
// don't drift. It seeds profiles via the handle_new_user trigger at signup
// and is wiped on account deletion as a display-name store. updateUserById
// REPLACES user_metadata wholesale, so read-merge-write to keep other keys.
try {
const admin = createServiceClient()
const { data: current } = await admin.auth.admin.getUserById(user.id)
const priorMeta = current?.user?.user_metadata ?? {}
await admin.auth.admin.updateUserById(user.id, {
user_metadata: { ...priorMeta, full_name: fullName },
})
} catch (syncError) {
log.warn('user_metadata full_name sync failed (non-blocking)', syncError)
}
return NextResponse.json({ data: { full_name: fullName } })
}
@@ -0,0 +1,198 @@
/**
* Tests for POST /api/user/ui-state: the per-user UI preference bag
* (nav collapse/fold state, split-button create modes).
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
import { POST } from '../route'
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
})
function request(body: unknown) {
return createMockRequest('/api/user/ui-state', { method: 'POST', body })
}
describe('POST /api/user/ui-state', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await POST(request({ nav_collapsed: true }))
expect(res.status).toBe(401)
})
it('returns 400 on unknown keys (strict schema)', async () => {
const res = await POST(request({ nav_collapsed: true, evil: 'x' }))
expect(res.status).toBe(400)
})
it('returns 400 on wrong value types', async () => {
const res = await POST(request({ nav_collapsed: 'yes' }))
expect(res.status).toBe(400)
})
it('returns 400 on unknown agent_panel keys (strict schema)', async () => {
const res = await POST(request({ agent_panel: { mode: 'docked', evil: 1 } }))
expect(res.status).toBe(400)
})
it('returns 400 on an invalid agent_panel mode', async () => {
const res = await POST(request({ agent_panel: { mode: 'popup' } }))
expect(res.status).toBe(400)
})
it('returns 400 on fractional float pixels', async () => {
const res = await POST(
request({ agent_panel: { float: { x: 10.5, y: 0, w: 400, h: 500 } } }),
)
expect(res.status).toBe(400)
})
it('returns 400 on an incomplete float rect', async () => {
const res = await POST(request({ agent_panel: { float: { x: 10, y: 0, w: 400 } } }))
expect(res.status).toBe(400)
})
it('merges agent_panel keys instead of replacing the object', async () => {
enqueue({
data: {
ui_state: {
agent_panel: { mode: 'docked', dock_width: 620 },
},
},
})
enqueue({ data: null })
const { status, body } = await parseJsonResponse<{
data: { ui_state: { agent_panel: Record<string, unknown> } }
}>(await POST(request({ agent_panel: { mode: 'floating' } })))
expect(status).toBe(200)
// dock_width survives a mode-only patch: undocking must not forget the
// user's chosen docked width.
expect(body.data.ui_state.agent_panel).toEqual({ mode: 'floating', dock_width: 620 })
})
it('accepts a full agent_panel geometry payload', async () => {
enqueue({ data: null })
enqueue({ data: null })
const { status, body } = await parseJsonResponse<{
data: { ui_state: { agent_panel: Record<string, unknown> } }
}>(
await POST(
request({
agent_panel: {
mode: 'floating',
dock_width: 480,
float: { x: 1200, y: 300, w: 420, h: 640 },
},
}),
),
)
expect(status).toBe(200)
expect(body.data.ui_state.agent_panel).toEqual({
mode: 'floating',
dock_width: 480,
float: { x: 1200, y: 300, w: 420, h: 640 },
})
})
it('merges the patch into the existing ui_state', async () => {
// select existing row
enqueue({
data: { ui_state: { nav_collapsed: false, nav_folds: { register: true } } },
})
// upsert result
enqueue({ data: null })
const { status, body } = await parseJsonResponse<{
data: { ui_state: { nav_collapsed: boolean; nav_folds: Record<string, boolean> } }
}>(await POST(request({ nav_folds: { bokslut: true } })))
expect(status).toBe(200)
expect(body.data.ui_state).toEqual({
nav_collapsed: false,
nav_folds: { register: true, bokslut: true },
})
})
it('handles a missing preferences row (first write)', async () => {
enqueue({ data: null }) // no existing row
enqueue({ data: null }) // upsert
const { status, body } = await parseJsonResponse<{
data: { ui_state: { nav_collapsed: boolean } }
}>(await POST(request({ nav_collapsed: true })))
expect(status).toBe(200)
expect(body.data.ui_state).toEqual({ nav_collapsed: true })
})
it('returns 400 when a trial_expired_ack key is not a company UUID', async () => {
const res = await POST(request({ trial_expired_ack: { 'not-a-uuid': new Date().toISOString() } }))
expect(res.status).toBe(400)
})
it('returns 400 when a trial_expired_ack value is not an ISO timestamp', async () => {
const res = await POST(
request({ trial_expired_ack: { '11111111-1111-4111-8111-111111111111': 'yesterday' } }),
)
expect(res.status).toBe(400)
})
it('merges trial_expired_ack per company instead of replacing the record', async () => {
const ackedAt = '2026-08-01T10:00:00.000Z'
enqueue({
data: {
ui_state: {
trial_expired_ack: { '11111111-1111-4111-8111-111111111111': ackedAt },
},
},
})
enqueue({ data: null })
const newAck = '2026-08-19T09:00:00.000Z'
const { status, body } = await parseJsonResponse<{
data: { ui_state: { trial_expired_ack: Record<string, string> } }
}>(
await POST(
request({
trial_expired_ack: { '22222222-2222-4222-8222-222222222222': newAck },
}),
),
)
expect(status).toBe(200)
// Acking company B never clears company A's ack.
expect(body.data.ui_state.trial_expired_ack).toEqual({
'11111111-1111-4111-8111-111111111111': ackedAt,
'22222222-2222-4222-8222-222222222222': newAck,
})
})
it('returns 500 when the upsert fails', async () => {
enqueue({ data: null })
enqueue({ data: null, error: { message: 'boom' } })
const res = await POST(request({ nav_collapsed: true }))
expect(res.status).toBe(500)
})
})
+102
View File
@@ -0,0 +1,102 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { requireAuth } from '@/lib/auth/require-auth'
import type { UserUiState } from '@/types'
// Partial update: the client sends only the keys it changed. Strict schemas
// so typos fail loudly instead of accumulating junk in the jsonb bag.
const BodySchema = z
.object({
nav_collapsed: z.boolean().optional(),
nav_folds: z
.object({
register: z.boolean().optional(),
bokslut: z.boolean().optional(),
})
.strict()
.optional(),
create_mode: z.record(z.string(), z.string().max(64)).optional(),
// Assistant panel geometry. Bounds are deliberately looser than the
// client's viewport clamps: a size saved on a large screen must round-trip
// even when later read on a small one (the client re-clamps on use).
agent_panel: z
.object({
mode: z.enum(['docked', 'floating']).optional(),
dock_width: z.number().int().min(320).max(1600).optional(),
float: z
.object({
x: z.number().int().min(-8000).max(16000),
y: z.number().int().min(-8000).max(16000),
w: z.number().int().min(280).max(4000),
h: z.number().int().min(280).max(4000),
})
.strict()
.optional(),
})
.strict()
.optional(),
// One-time expired-trial dialog acknowledgement: companyId -> ISO
// timestamp of the ack. Merged per key like create_mode, so acking one
// company never clears another's.
trial_expired_ack: z
.record(z.string().uuid(), z.string().datetime())
.optional(),
})
.strict()
// User-scoped preference endpoint: no company context exists or is needed,
// so requireAuth() directly (same opt-out as /api/user/locale). RLS scopes
// user_preferences to the caller's own row.
export async function POST(request: Request) {
const { user, supabase, error } = await requireAuth()
if (error) return error
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })
}
const parsed = BodySchema.safeParse(body)
if (!parsed.success) {
return NextResponse.json({ error: 'Invalid ui_state payload' }, { status: 400 })
}
// Read-merge-write: last write wins per key. Fine for cosmetic UI state;
// concurrent tabs converge on the next read.
const { data: existing } = await supabase
.from('user_preferences')
.select('ui_state')
.eq('user_id', user.id)
.maybeSingle()
const current: UserUiState = (existing?.ui_state as UserUiState) ?? {}
const patch = parsed.data
const next: UserUiState = {
...current,
...patch,
...(patch.nav_folds
? { nav_folds: { ...current.nav_folds, ...patch.nav_folds } }
: {}),
...(patch.create_mode
? { create_mode: { ...current.create_mode, ...patch.create_mode } }
: {}),
...(patch.agent_panel
? { agent_panel: { ...current.agent_panel, ...patch.agent_panel } }
: {}),
...(patch.trial_expired_ack
? { trial_expired_ack: { ...current.trial_expired_ack, ...patch.trial_expired_ack } }
: {}),
}
const { error: upsertError } = await supabase
.from('user_preferences')
.upsert({ user_id: user.id, ui_state: next }, { onConflict: 'user_id' })
if (upsertError) {
return NextResponse.json({ error: 'Could not save UI preferences' }, { status: 500 })
}
return NextResponse.json({ data: { ui_state: next } })
}