Invoicing & account-security polish bundle (#550)
* feat: invoicing & account-security polish bundle Five independent improvements bundled to ship together: - BankID/password lockout fix: BankID-only users could enroll MFA and brick themselves (Supabase requires AAL2 to change password or unenroll MFA, and AAL2 needs a password sign-in). New app_metadata.has_password flag tracks this; middleware gates /mfa/enroll behind it, /account/set- password is the unlock path, SecuritySettings shows a banner, and /api/account/password is the single write path that flips the flag. Backfill script for existing users. - Swish invoice payment method: company_settings.swish + invoice_show_swish columns, validation in lib/api/schemas.ts (accepts 123XXXXXXX företag or 07XXXXXXXX mobile, strips whitespace/hyphens), rendered on invoice PDFs. - Send-reminders kill switch: per-company company_settings.send_invoice_ reminders toggle in PdfPrintSettings/Automatisering. Reminder processor also tightened: positive status allowlist (sent + overdue) so terminal statuses can never match; skip when customer already responded via reminder link; race-window re-check before send. - First-invoice logo prompt: one-shot dialog when creating the first invoice without a logo (issue #520). Self-limits via head-only count. - SIE export opening-balance fallback: route IB through getOpeningBalances so the compute_prior_opening_balances RPC supplies #IB after multi-year imports where opening_balance_entry_id is intentionally NULL. Previously #IB silently went to zero and #UB collapsed to current-period movements. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(account-polish): address PR review feedback - BankID-link path (extensions/general/tic/index.ts): read-merge-write app_metadata instead of passing { bankid_linked: true } alone. updateUserById REPLACES app_metadata wholesale, so the previous code would have wiped has_password for any user who later linked BankID, causing the set-password banner to (incorrectly) reappear and blocking the standard MFA enrollment button. The comment is now corrected. - Middleware (lib/supabase/middleware.ts): thread inner returnTo through the /mfa/enroll → /account/set-password redirect so the user lands on their original destination after the full chain completes, not on /. - safeReturnTo helper (lib/auth/safe-return-to.ts): replace the starts-with-/-but-not-// guard on mfa/enroll and set-password pages. The previous guard let /\evil.com and /@evil.com through. The new helper parses against a synthetic base origin and verifies it matches. - set-password page (app/(auth)/account/set-password/page.tsx): remove CLAUDE.md design system violations — bg-gradient-to-b on page bg, inline shadow-md style on the card, space-y-5, font-medium on the h1, rounded-xl on the card. Flat surface, hairline border, font-display h1 per the design tokens. - Swish dedup (lib/payments/swish.ts): extract normaliseSwish() and isValidSwish() helpers and use them in lib/api/schemas.ts, components/settings/BankDetailsForm.tsx, and the invoicing settings page. Single source of truth for the regex. - Password route (app/api/account/password/route.ts): emit a structured success log so the audit pipeline can detect password-set events, not just failures. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.7
parent
2879f6ed17
commit
cc351158f8
@@ -0,0 +1,147 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
createServiceClient: vi.fn(),
|
||||
}))
|
||||
|
||||
import { createClient, createServiceClient } from '@/lib/supabase/server'
|
||||
import { POST } from '../route'
|
||||
|
||||
const mockCreateClient = vi.mocked(createClient)
|
||||
const mockCreateServiceClient = vi.mocked(createServiceClient)
|
||||
|
||||
function mockUserClient(opts: {
|
||||
user: { id: string } | null
|
||||
updateUserError?: { message: string; status?: number; code?: string } | null
|
||||
}) {
|
||||
const updateUser = vi.fn().mockResolvedValue({
|
||||
data: {},
|
||||
error: opts.updateUserError ?? null,
|
||||
})
|
||||
|
||||
mockCreateClient.mockResolvedValue({
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user: opts.user } }),
|
||||
updateUser,
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
return { updateUser }
|
||||
}
|
||||
|
||||
function mockService(opts: {
|
||||
priorAppMetadata?: Record<string, unknown>
|
||||
updateUserByIdError?: Error | null
|
||||
}) {
|
||||
const updateUserById = opts.updateUserByIdError
|
||||
? vi.fn().mockRejectedValue(opts.updateUserByIdError)
|
||||
: vi.fn().mockResolvedValue({ data: {}, error: null })
|
||||
|
||||
const getUserById = vi.fn().mockResolvedValue({
|
||||
data: { user: { app_metadata: opts.priorAppMetadata ?? {} } },
|
||||
})
|
||||
|
||||
mockCreateServiceClient.mockReturnValue({
|
||||
auth: { admin: { getUserById, updateUserById } },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
return { getUserById, updateUserById }
|
||||
}
|
||||
|
||||
const STRONG_PASSWORD = 'StrongP@ssword1'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('POST /api/account/password', () => {
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
mockUserClient({ user: null })
|
||||
mockService({})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 when password is too weak', async () => {
|
||||
mockUserClient({ user: { id: 'user-1' } })
|
||||
mockService({})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: 'weak' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 400 when Supabase rejects the password update', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1' },
|
||||
updateUserError: { message: 'Password too similar to old', status: 400 },
|
||||
})
|
||||
const { updateUserById } = mockService({})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await POST(req),
|
||||
)
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toContain('Password too similar')
|
||||
expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD })
|
||||
// Flag should NOT be flipped on a failed password update
|
||||
expect(updateUserById).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('flips app_metadata.has_password to true on success and preserves siblings', async () => {
|
||||
const { updateUser } = mockUserClient({ user: { id: 'user-1' } })
|
||||
const { getUserById, updateUserById } = mockService({
|
||||
priorAppMetadata: { bankid_linked: true, provider: 'email' },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data?: { ok: boolean } }>(
|
||||
await POST(req),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.ok).toBe(true)
|
||||
expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD })
|
||||
expect(getUserById).toHaveBeenCalledWith('user-1')
|
||||
expect(updateUserById).toHaveBeenCalledWith('user-1', {
|
||||
app_metadata: {
|
||||
bankid_linked: true,
|
||||
provider: 'email',
|
||||
has_password: true,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('still returns success when the flag flip fails (password is set; logged)', async () => {
|
||||
mockUserClient({ user: { id: 'user-1' } })
|
||||
mockService({ updateUserByIdError: new Error('admin down') })
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data?: { ok: boolean } }>(
|
||||
await POST(req),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.ok).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,93 @@
|
||||
import { createClient, createServiceClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
|
||||
const log = createLogger('api/account/password')
|
||||
|
||||
const SetPasswordSchema = z.object({
|
||||
password: z
|
||||
.string()
|
||||
.min(8, 'Lösenordet måste vara minst 8 tecken')
|
||||
.refine(
|
||||
(v) =>
|
||||
/[a-z]/.test(v) &&
|
||||
/[A-Z]/.test(v) &&
|
||||
/[0-9]/.test(v) &&
|
||||
/[^a-zA-Z0-9]/.test(v),
|
||||
'Lösenordet måste innehålla versaler, gemener, siffror och specialtecken',
|
||||
),
|
||||
})
|
||||
|
||||
/**
|
||||
* POST /api/account/password
|
||||
*
|
||||
* Server-routed password set/change. Wraps `supabase.auth.updateUser({ password })`
|
||||
* on the user's own session, then flips `app_metadata.has_password = true` via the
|
||||
* service client (clients can't write app_metadata).
|
||||
*
|
||||
* This route is the single write path for setting a password. SecuritySettings,
|
||||
* the reset-password page, and the new /account/set-password page all funnel
|
||||
* through here so the flag stays in sync — see lib/auth/has-password.ts.
|
||||
*
|
||||
* If the password update succeeds but the flag write fails, we log and still
|
||||
* return success: the user has a working password and the banner will show one
|
||||
* more time, but a retry will re-flip the flag.
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
const supabase = await createClient()
|
||||
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const result = await validateBody(request, SetPasswordSchema)
|
||||
if (!result.success) return result.response
|
||||
const { password } = result.data
|
||||
|
||||
const { error: updateError } = await supabase.auth.updateUser({ password })
|
||||
if (updateError) {
|
||||
log.warn('updateUser({password}) failed', {
|
||||
userId: user.id,
|
||||
code: (updateError as { code?: string }).code,
|
||||
status: updateError.status,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
updateError.message ||
|
||||
'Kunde inte uppdatera lösenord. Försök igen.',
|
||||
},
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
// Read-merge-write so we don't wipe sibling app_metadata keys.
|
||||
// updateUserById replaces app_metadata wholesale (see lib/auth/has-password.ts
|
||||
// and the comment in app/api/account/delete/route.ts).
|
||||
const service = createServiceClient()
|
||||
let flagWriteOk = false
|
||||
try {
|
||||
const { data: u } = await service.auth.admin.getUserById(user.id)
|
||||
const prior = u?.user?.app_metadata ?? {}
|
||||
await service.auth.admin.updateUserById(user.id, {
|
||||
app_metadata: { ...prior, has_password: true },
|
||||
})
|
||||
flagWriteOk = true
|
||||
} catch (err) {
|
||||
log.error('failed to flip has_password flag after successful password set', {
|
||||
userId: user.id,
|
||||
err,
|
||||
})
|
||||
// Don't surface the failure: the user has a working password. The
|
||||
// banner will show once more and a retry will succeed.
|
||||
}
|
||||
|
||||
log.info('password set', { userId: user.id, flagWriteOk })
|
||||
|
||||
return NextResponse.json({ data: { ok: true } })
|
||||
}
|
||||
Reference in New Issue
Block a user