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
+284
View File
@@ -0,0 +1,284 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextRequest, NextResponse } from 'next/server'
import { parseJsonResponse, createQueuedMockSupabase } from '@/tests/helpers'
// team/accept uses the service client for all DB work (invite acceptance can
// run before the user has any company membership). requireAuth only gates the
// caller's identity + MFA.
const { supabase: serviceSupabase, enqueue, reset, findCalls } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => serviceSupabase,
}))
vi.mock('@/lib/auth/invite-tokens', () => ({
hashInviteToken: (t: string) => `hash-${t}`,
}))
import { GET, POST } from '../route'
const mockUser = { id: 'user-1', email: '[email protected]' }
function makeReq(body: unknown) {
return new Request('http://localhost/api/team/accept', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}) as never
}
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: serviceSupabase, error: null })
})
describe('POST /api/team/accept', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: serviceSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await POST(makeReq({ token: 'abc' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
})
it('returns 400 when the token is missing', async () => {
const res = await POST(makeReq({}))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(400)
expect(body.error).toContain('Token')
})
it('accepts a valid company invite', async () => {
const future = new Date(Date.now() + 86_400_000).toISOString()
// 1. company_invitations lookup
enqueue({
data: {
id: 'inv-1',
company_id: 'company-1',
email: '[email protected]',
role: 'member',
status: 'pending',
expires_at: future,
},
})
// 2. company_members insert
enqueue({ error: null })
// 3. user_preferences upsert
enqueue({ error: null })
// 4. company_invitations update -> accepted
enqueue({ error: null })
const res = await POST(makeReq({ token: 'abc' }))
const { status, body } = await parseJsonResponse<{ data: { type: string; companyId: string } }>(res)
expect(status).toBe(200)
expect(body.data).toEqual({ type: 'company', companyId: 'company-1' })
})
it('returns 403 when the invite email does not match the user', async () => {
const future = new Date(Date.now() + 86_400_000).toISOString()
enqueue({
data: {
id: 'inv-1',
company_id: 'company-1',
email: '[email protected]',
role: 'member',
status: 'pending',
expires_at: future,
},
})
const res = await POST(makeReq({ token: 'abc' }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(403)
expect(body.error).toContain('matchar inte')
})
})
// WL-08 invite unfreeze: the same token endpoint accepts byrå-team
// invitations. from() consumption order for the team path:
// 1. company_invitations lookup (miss)
// 2. team_invitations lookup
// 3. team_members insert
// 4. user_preferences read (active company?)
// 5. companies read (first team company) [only when no active company]
// 6. user_preferences upsert [only when a company was found]
// 7. team_invitations update -> accepted
describe('POST /api/team/accept (byrå-team invitations)', () => {
const future = new Date(Date.now() + 86_400_000).toISOString()
const teamInvite = (overrides: Record<string, unknown> = {}) => ({
id: 'tinv-1',
team_id: 'team-byra',
email: '[email protected]',
role: 'member',
status: 'pending',
expires_at: future,
teams: { name: 'Siffran AB', kind: 'byra' },
...overrides,
})
it('accepts a valid byrå invite and points a company-less user at a team company', async () => {
enqueue({ data: null, error: { code: 'PGRST116' } }) // no company invite
enqueue({ data: teamInvite() })
enqueue({ error: null }) // team_members insert
enqueue({ data: null }) // user_preferences read: no active company
enqueue({ data: { id: 'company-9' } }) // first team company
enqueue({ error: null }) // user_preferences upsert
enqueue({ error: null }) // invitation -> accepted
const res = await POST(makeReq({ token: 'abc' }))
const { status, body } = await parseJsonResponse<{
data: { type: string; teamId: string; teamName: string }
}>(res)
expect(status).toBe(200)
expect(body.data).toEqual({ type: 'team', teamId: 'team-byra', teamName: 'Siffran AB' })
// The membership row is what triggers the DB-side company sync.
const inserts = findCalls('team_members', 'insert')
expect(inserts).toHaveLength(1)
expect(inserts[0]![0]).toEqual({
team_id: 'team-byra',
user_id: 'user-1',
role: 'member',
})
expect(findCalls('user_preferences', 'upsert')).toHaveLength(1)
})
it('never hijacks an existing active company', async () => {
enqueue({ data: null, error: { code: 'PGRST116' } })
enqueue({ data: teamInvite() })
enqueue({ error: null }) // team_members insert
enqueue({ data: { active_company_id: 'my-own-firma' } }) // has active company
enqueue({ error: null }) // invitation -> accepted
const res = await POST(makeReq({ token: 'abc' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(findCalls('user_preferences', 'upsert')).toHaveLength(0)
})
it('never mints a team owner from an invitation row', async () => {
enqueue({ data: null, error: { code: 'PGRST116' } })
enqueue({ data: teamInvite({ role: 'owner' }) }) // hand-edited row
enqueue({ error: null })
enqueue({ data: { active_company_id: 'my-own-firma' } })
enqueue({ error: null })
const res = await POST(makeReq({ token: 'abc' }))
expect(res.status).toBe(200)
const inserts = findCalls('team_members', 'insert')
expect((inserts[0]![0] as { role: string }).role).toBe('member')
})
it('rejects a personal-team invitation token as invalid (kind gate)', async () => {
enqueue({ data: null, error: { code: 'PGRST116' } })
enqueue({ data: teamInvite({ teams: { name: 'Personal', kind: 'personal' } }) })
const res = await POST(makeReq({ token: 'abc' }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(400)
expect(body.error).toBe('Inbjudan är ogiltig.')
})
it('returns 403 when the team invite email does not match the user', async () => {
enqueue({ data: null, error: { code: 'PGRST116' } })
enqueue({ data: teamInvite({ email: '[email protected]' }) })
const res = await POST(makeReq({ token: 'abc' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(403)
})
it('returns 410 and marks an expired team invite', async () => {
const past = new Date(Date.now() - 86_400_000).toISOString()
enqueue({ data: null, error: { code: 'PGRST116' } })
enqueue({ data: teamInvite({ expires_at: past }) })
enqueue({ error: null }) // invitation -> expired
const res = await POST(makeReq({ token: 'abc' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(410)
const updates = findCalls('team_invitations', 'update')
expect(updates[0]![0]).toEqual({ status: 'expired' })
})
it('returns 409 when already a team member', async () => {
enqueue({ data: null, error: { code: 'PGRST116' } })
enqueue({ data: teamInvite() })
enqueue({ error: { code: '23505' } }) // duplicate membership
const res = await POST(makeReq({ token: 'abc' }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(409)
expect(body.error).toBe('Du är redan medlem.')
})
})
describe('GET /api/team/accept (byrå-team invitations)', () => {
function makeGetReq(token: string) {
return new NextRequest(`http://localhost/api/team/accept?token=${token}`)
}
it('returns team invite info with companyName doubling as the team name', async () => {
const future = new Date(Date.now() + 86_400_000).toISOString()
enqueue({ data: null, error: { code: 'PGRST116' } }) // no company invite
enqueue({
data: {
id: 'tinv-1',
team_id: 'team-byra',
email: '[email protected]',
role: 'member',
status: 'pending',
expires_at: future,
teams: { name: 'Siffran AB', kind: 'byra' },
},
})
enqueue({ data: true }) // rpc check_email_exists
const res = await GET(makeGetReq('abc'))
const { status, body } = await parseJsonResponse<{
data: {
type: string
companyName: string
teamName: string
email: string
expired: boolean
alreadyHasAccount: boolean
}
}>(res)
expect(status).toBe(200)
expect(body.data.type).toBe('team')
expect(body.data.teamName).toBe('Siffran AB')
// The invite page renders companyName as "what you are joining".
expect(body.data.companyName).toBe('Siffran AB')
expect(body.data.expired).toBe(false)
expect(body.data.alreadyHasAccount).toBe(true)
})
it('treats a personal-team invitation token as not found', async () => {
enqueue({ data: null, error: { code: 'PGRST116' } })
enqueue({
data: {
id: 'tinv-1',
team_id: 'team-p',
email: '[email protected]',
role: 'member',
status: 'pending',
expires_at: new Date(Date.now() + 86_400_000).toISOString(),
teams: { name: 'Personal', kind: 'personal' },
},
})
const res = await GET(makeGetReq('abc'))
const { status } = await parseJsonResponse(res)
expect(status).toBe(404)
})
})
+232
View File
@@ -0,0 +1,232 @@
import { createServiceClient } from '@/lib/supabase/server'
import { NextResponse, type NextRequest } from 'next/server'
import { requireAuth } from '@/lib/auth/require-auth'
import { hashInviteToken } from '@/lib/auth/invite-tokens'
import { acceptPendingTeamInviteByToken } from '@/lib/company/pending-invites'
interface TeamInviteRow {
id: string
team_id: string
email: string
role: string
status: string
expires_at: string
teams: { name: string; kind: string } | null
}
/**
* GET /api/team/accept?token=xxx
* Validates an invite token and returns invite info (for the invite page).
* Handles both company invitations and byrå-team invitations (WL-08 invite
* unfreeze). Team invitations resolve only for teams with kind='byra':
* personal teams are uninvitable, so a token pointing at one is invalid.
* No auth required: this is a public endpoint.
*/
export async function GET(request: NextRequest) {
const token = request.nextUrl.searchParams.get('token')
if (!token) {
return NextResponse.json({ error: 'Token saknas.' }, { status: 400 })
}
const tokenHash = hashInviteToken(token)
const serviceClient = createServiceClient()
const { data: companyInvite } = await serviceClient
.from('company_invitations')
.select('id, email, status, expires_at, company_id, companies:company_id(name)')
.eq('token_hash', tokenHash)
.single()
if (companyInvite) {
if (companyInvite.status !== 'pending') {
return NextResponse.json({ error: 'Inbjudan har redan använts.' }, { status: 410 })
}
const expired = new Date(companyInvite.expires_at) < new Date()
const { data: alreadyHasAccount } = await serviceClient.rpc('check_email_exists', {
email_to_check: companyInvite.email,
})
return NextResponse.json({
data: {
type: 'company',
companyName: (companyInvite.companies as unknown as { name: string })?.name || 'Företag',
email: companyInvite.email,
expired,
alreadyHasAccount,
},
})
}
// No company invitation for this token: try byrå-team invitations.
const { data: teamInviteRaw } = await serviceClient
.from('team_invitations')
.select('id, team_id, email, role, status, expires_at, teams:team_id(name, kind)')
.eq('token_hash', tokenHash)
.single()
const teamInvite = teamInviteRaw as unknown as TeamInviteRow | null
// Kind gate: invitations exist for byrå teams only. A personal-team token
// (or a team whose kind was reverted after issue) is indistinguishable from
// an invalid token on purpose.
if (!teamInvite || teamInvite.teams?.kind !== 'byra') {
return NextResponse.json({ error: 'Inbjudan hittades inte eller är ogiltig.' }, { status: 404 })
}
if (teamInvite.status !== 'pending') {
return NextResponse.json({ error: 'Inbjudan har redan använts.' }, { status: 410 })
}
const expired = new Date(teamInvite.expires_at) < new Date()
const { data: alreadyHasAccount } = await serviceClient.rpc('check_email_exists', {
email_to_check: teamInvite.email,
})
const teamName = teamInvite.teams?.name || 'Team'
return NextResponse.json({
data: {
type: 'team',
// companyName doubles as "what you are joining" for the invite page,
// which renders it for every invite type: kept for compatibility.
companyName: teamName,
teamName,
email: teamInvite.email,
expired,
alreadyHasAccount,
},
})
}
/**
* POST /api/team/accept
* Accepts a company or byrå-team invite after the user has signed up.
*
* Team acceptance inserts a team_members row; the DB sync trigger
* (sync_team_member_to_companies) then grants membership in every company
* attached to the team, so no company_members writes happen here.
*/
export async function POST(request: NextRequest) {
const { user, error } = await requireAuth()
if (error) return error
const body = await request.json()
const token = body.token as string
if (!token) {
return NextResponse.json({ error: 'Token saknas.' }, { status: 400 })
}
const tokenHash = hashInviteToken(token)
const serviceClient = createServiceClient()
const { data: companyInvite, error: companyLookupError } = await serviceClient
.from('company_invitations')
.select('id, company_id, email, role, status, expires_at')
.eq('token_hash', tokenHash)
.single()
if (companyLookupError && companyLookupError.code !== 'PGRST116') {
console.error('[team/accept] company lookup error:', companyLookupError.message)
}
if (companyInvite) {
return acceptCompanyInvite(serviceClient, user, companyInvite)
}
// No company invitation for this token: try byrå-team invitations. The
// acceptance itself lives in the shared helper (lib/company/pending-invites)
// so the callback and onboarding recovery accept team invites the same way;
// this route only maps the outcome onto its long-standing HTTP contract.
const outcome = await acceptPendingTeamInviteByToken(user, token)
switch (outcome.status) {
case 'accepted':
return NextResponse.json({
data: { type: 'team', teamId: outcome.teamId, teamName: outcome.teamName },
})
case 'already_member':
return NextResponse.json({ error: 'Du är redan medlem.' }, { status: 409 })
case 'expired':
return NextResponse.json({ error: 'Inbjudan har gått ut.' }, { status: 410 })
case 'wrong_email':
return NextResponse.json({ error: 'E-postadressen matchar inte inbjudan.' }, { status: 403 })
case 'error':
return NextResponse.json({ error: 'Kunde inte lägga till medlem.' }, { status: 500 })
case 'invalid':
default:
return NextResponse.json({ error: 'Inbjudan är ogiltig.' }, { status: 400 })
}
}
/** The pre-existing company-invite acceptance flow, unchanged. */
async function acceptCompanyInvite(
serviceClient: ReturnType<typeof createServiceClient>,
user: { id: string; email?: string | null },
companyInvite: {
id: string
company_id: string
email: string
role: string
status: string
expires_at: string
},
) {
if (companyInvite.status !== 'pending') {
return NextResponse.json({ error: 'Inbjudan är ogiltig.' }, { status: 400 })
}
if (new Date(companyInvite.expires_at) < new Date()) {
await serviceClient
.from('company_invitations')
.update({ status: 'expired' })
.eq('id', companyInvite.id)
return NextResponse.json({ error: 'Inbjudan har gått ut.' }, { status: 410 })
}
if (user.email?.toLowerCase() !== companyInvite.email.toLowerCase()) {
return NextResponse.json({ error: 'E-postadressen matchar inte inbjudan.' }, { status: 403 })
}
// Add user to company
const { error: memberError } = await serviceClient
.from('company_members')
.insert({
company_id: companyInvite.company_id,
user_id: user.id,
role: companyInvite.role,
source: 'direct',
})
if (memberError) {
if (memberError.code === '23505') {
return NextResponse.json({ error: 'Du är redan medlem.' }, { status: 409 })
}
return NextResponse.json({ error: 'Kunde inte lägga till medlem.' }, { status: 500 })
}
// Set active company. Non-fatal on failure: the membership insert already
// succeeded and middleware falls back to it, but log so silent
// persistence failures (#701) are observable.
const { error: prefError } = await serviceClient
.from('user_preferences')
.upsert({
user_id: user.id,
active_company_id: companyInvite.company_id,
}, { onConflict: 'user_id' })
if (prefError) {
console.error('[team/accept] failed to set active company', prefError)
}
// Mark invite as accepted
await serviceClient
.from('company_invitations')
.update({ status: 'accepted' })
.eq('id', companyInvite.id)
return NextResponse.json({
data: { type: 'company', companyId: companyInvite.company_id },
})
}
@@ -0,0 +1,246 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { parseJsonResponse, createQueuedMockSupabase, createMockRouteParams } from '@/tests/helpers'
// DELETE /api/team/invite/[id] (WL-08 invite unfreeze): revoking a pending
// byrå-team invitation, gated on team kind and owner/admin role.
const { supabase: serviceSupabase, enqueue, reset, findCalls } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => serviceSupabase,
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
vi.mock('@/lib/auth/invite-tokens', () => ({
generateInviteToken: () => ({ token: 'gnubok_inv_fresh-token', hash: 'hash-fresh-token' }),
getInviteExpiry: () => new Date('2099-01-08T00:00:00Z'),
}))
// The brand/sender/template wiring inside the helper is covered for real by
// the POST /api/team/invite tests; here it is mocked so the resend tests
// exercise only the route's own gates and writes.
const sendTeamInviteMailMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/email/send-team-invite', () => ({
sendTeamInviteMail: sendTeamInviteMailMock,
}))
import { DELETE, POST } from '../route'
const mockUser = { id: 'user-1', email: '[email protected]' }
const req = new Request('http://localhost/api/team/invite/invite-1', {
method: 'DELETE',
}) as never
const routeParams = createMockRouteParams({ id: 'invite-1' })
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: serviceSupabase, error: null })
sendTeamInviteMailMock.mockResolvedValue({
inviteUrl: 'https://app.gnubok.se/invite/gnubok_inv_fresh-token',
emailSent: true,
})
})
describe('DELETE /api/team/invite/[id]', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: serviceSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await DELETE(req, routeParams)
expect(res.status).toBe(401)
})
it('returns 404 when the invitation does not exist', async () => {
enqueue({ data: null })
const res = await DELETE(req, routeParams)
const { status } = await parseJsonResponse(res)
expect(status).toBe(404)
})
it('returns 403 with the legacy message for a personal-team invitation', async () => {
enqueue({
data: { id: 'invite-1', team_id: 'team-p', status: 'pending', teams: { kind: 'personal' } },
})
const res = await DELETE(req, routeParams)
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(403)
expect(body.error).toBe('Teaminbjudningar är inaktiverade.')
})
it('returns 403 when the caller is a plain team member', async () => {
enqueue({
data: { id: 'invite-1', team_id: 'team-b', status: 'pending', teams: { kind: 'byra' } },
})
enqueue({ data: { role: 'member' } })
const res = await DELETE(req, routeParams)
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(403)
expect(body.error).toBe('Behörighet saknas.')
})
it('returns 409 when the invitation was already used', async () => {
enqueue({
data: { id: 'invite-1', team_id: 'team-b', status: 'accepted', teams: { kind: 'byra' } },
})
enqueue({ data: { role: 'owner' } })
const res = await DELETE(req, routeParams)
const { status } = await parseJsonResponse(res)
expect(status).toBe(409)
})
it('revokes a pending invitation for a byrå admin', async () => {
enqueue({
data: { id: 'invite-1', team_id: 'team-b', status: 'pending', teams: { kind: 'byra' } },
})
enqueue({ data: { role: 'admin' } })
// team_invitations update
enqueue({ data: null })
const res = await DELETE(req, routeParams)
const { status, body } = await parseJsonResponse<{ data: { id: string; status: string } }>(res)
expect(status).toBe(200)
expect(body.data).toEqual({ id: 'invite-1', status: 'revoked' })
const updates = findCalls('team_invitations', 'update')
expect(updates).toHaveLength(1)
expect(updates[0]![0]).toEqual({ status: 'revoked' })
})
})
// POST /api/team/invite/[id]: re-send a pending byrå-team invitation with a
// fresh token and expiry (the recovery path when the original mail was lost).
const postReq = new Request('http://localhost/api/team/invite/invite-1', {
method: 'POST',
}) as never
const pendingInvite = {
id: 'invite-1',
team_id: 'team-b',
email: '[email protected]',
role: 'admin',
status: 'pending',
teams: { kind: 'byra' },
}
describe('POST /api/team/invite/[id]', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: serviceSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await POST(postReq, routeParams)
expect(res.status).toBe(401)
})
it('returns 404 when the invitation does not exist', async () => {
enqueue({ data: null })
const res = await POST(postReq, routeParams)
const { status } = await parseJsonResponse(res)
expect(status).toBe(404)
})
it('returns 403 with the legacy message for a personal-team invitation', async () => {
enqueue({ data: { ...pendingInvite, teams: { kind: 'personal' } } })
const res = await POST(postReq, routeParams)
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(403)
expect(body.error).toBe('Teaminbjudningar är inaktiverade.')
})
it('returns 403 when the caller is a plain team member', async () => {
enqueue({ data: pendingInvite })
enqueue({ data: { role: 'member' } })
const res = await POST(postReq, routeParams)
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(403)
expect(body.error).toBe('Behörighet saknas.')
expect(sendTeamInviteMailMock).not.toHaveBeenCalled()
})
it('returns 409 when the invitation was already used', async () => {
enqueue({ data: { ...pendingInvite, status: 'accepted' } })
enqueue({ data: { role: 'owner' } })
const res = await POST(postReq, routeParams)
const { status } = await parseJsonResponse(res)
expect(status).toBe(409)
expect(sendTeamInviteMailMock).not.toHaveBeenCalled()
})
it('re-issues the token and re-sends the mail for a byrå admin', async () => {
enqueue({ data: pendingInvite })
enqueue({ data: { role: 'admin' } })
// team_invitations update (token, invited_by, expiry)
enqueue({ data: null })
const res = await POST(postReq, routeParams)
const { status, body } = await parseJsonResponse<{
data: {
id: string
teamId: string
email: string
role: string
status: string
email_sent: boolean
inviteUrl: string
}
}>(res)
expect(status).toBe(200)
expect(body.data.id).toBe('invite-1')
expect(body.data.teamId).toBe('team-b')
expect(body.data.email).toBe('[email protected]')
expect(body.data.role).toBe('admin')
expect(body.data.status).toBe('pending')
expect(body.data.email_sent).toBe(true)
expect(body.data.inviteUrl).toBe('https://app.gnubok.se/invite/gnubok_inv_fresh-token')
// A fresh token hash replaces the old one (invalidating any mailed link),
// and the raw token never touches the DB write.
const updates = findCalls('team_invitations', 'update')
expect(updates).toHaveLength(1)
expect(updates[0]![0]).toMatchObject({
token_hash: 'hash-fresh-token',
invited_by: 'user-1',
expires_at: '2099-01-08T00:00:00.000Z',
})
expect(sendTeamInviteMailMock).toHaveBeenCalledWith({
teamId: 'team-b',
email: '[email protected]',
inviterEmail: '[email protected]',
token: 'gnubok_inv_fresh-token',
})
})
it('keeps the invitation valid and returns the link when the mail send fails', async () => {
sendTeamInviteMailMock.mockResolvedValue({
inviteUrl: 'https://app.gnubok.se/invite/gnubok_inv_fresh-token',
emailSent: false,
})
enqueue({ data: pendingInvite })
enqueue({ data: { role: 'owner' } })
enqueue({ data: null })
const res = await POST(postReq, routeParams)
const { status, body } = await parseJsonResponse<{
data: { email_sent: boolean; inviteUrl: string }
}>(res)
expect(status).toBe(200)
expect(body.data.email_sent).toBe(false)
expect(body.data.inviteUrl).toContain('/invite/gnubok_inv_fresh-token')
})
})
+177
View File
@@ -0,0 +1,177 @@
import { createServiceClient } from '@/lib/supabase/server'
import { NextResponse, type NextRequest } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { requireAuth } from '@/lib/auth/require-auth'
import { generateInviteToken, getInviteExpiry } from '@/lib/auth/invite-tokens'
import { sendTeamInviteMail } from '@/lib/email/send-team-invite'
// Loads the email extension so the re-send path gets the Resend
// implementation instead of the noop default (same as POST /api/team/invite).
ensureInitialized()
/**
* Kept verbatim from the pre-unfreeze hardcoded 403: personal teams remain
* uninvitable (WL-08), so their (theoretical) invitations stay untouchable.
*/
const PERSONAL_TEAM_MESSAGE = 'Teaminbjudningar är inaktiverade.'
interface InviteRow {
id: string
team_id: string
email: string
role: string
status: string
teams: { kind: string } | null
}
/**
* Shared gate chain for acting on an existing invitation: it must exist, its
* team must be kind='byra' (personal-team invitations are frozen surface),
* and the caller must be owner/admin of that team. Returns the invitation row
* or the error response to bubble.
*/
async function loadInviteForManagement(
serviceClient: ReturnType<typeof createServiceClient>,
inviteId: string,
userId: string,
): Promise<{ invite: InviteRow } | { response: NextResponse }> {
const { data: invitation } = await serviceClient
.from('team_invitations')
.select('id, team_id, email, role, status, teams:team_id(kind)')
.eq('id', inviteId)
.maybeSingle()
const invite = invitation as unknown as InviteRow | null
if (!invite) {
return { response: NextResponse.json({ error: 'Inbjudan hittades inte.' }, { status: 404 }) }
}
// Kind gate first: personal-team invitations are frozen surface, byrå only.
if (invite.teams?.kind !== 'byra') {
return { response: NextResponse.json({ error: PERSONAL_TEAM_MESSAGE }, { status: 403 }) }
}
// Role gate: the caller must be owner/admin of the invitation's team.
const { data: membership } = await serviceClient
.from('team_members')
.select('role')
.eq('team_id', invite.team_id)
.eq('user_id', userId)
.maybeSingle()
const callerRole = (membership as { role: string } | null)?.role
if (!callerRole || !['owner', 'admin'].includes(callerRole)) {
return { response: NextResponse.json({ error: 'Behörighet saknas.' }, { status: 403 }) }
}
return { invite }
}
/**
* POST /api/team/invite/[id]
* Re-send a pending byrå-team invitation (WL-08 follow-up: the Arbore case,
* where the original mail never reached the invitee and the inviter had no
* recovery path).
*
* Same gates as DELETE. Only pending invitations can be re-sent (an expired
* pending one is revived: the token and expiry are re-issued in place, which
* also invalidates any previously mailed link). The response mirrors POST
* /api/team/invite so the client gets a fresh shareable inviteUrl regardless
* of whether the mail went out.
*/
export async function POST(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const { user, error } = await requireAuth()
if (error) return error
const { id } = await params
const serviceClient = createServiceClient()
const loaded = await loadInviteForManagement(serviceClient, id, user.id)
if ('response' in loaded) return loaded.response
const { invite } = loaded
if (invite.status !== 'pending') {
return NextResponse.json({ error: 'Inbjudan har redan använts.' }, { status: 409 })
}
const { token, hash } = generateInviteToken()
const expiresAt = getInviteExpiry()
const { error: updateError } = await serviceClient
.from('team_invitations')
.update({
token_hash: hash,
invited_by: user.id,
expires_at: expiresAt.toISOString(),
})
.eq('id', invite.id)
if (updateError) {
return NextResponse.json({ error: 'Kunde inte skicka om inbjudan.' }, { status: 500 })
}
const { inviteUrl, emailSent } = await sendTeamInviteMail({
teamId: invite.team_id,
email: invite.email,
inviterEmail: user.email || '',
token,
})
return NextResponse.json({
data: {
id: invite.id,
teamId: invite.team_id,
email: invite.email,
role: invite.role,
status: 'pending',
expires_at: expiresAt.toISOString(),
email_sent: emailSent,
// Always returned so the inviter can share the link directly when the
// mail did not go out (or never arrives).
inviteUrl,
},
})
}
/**
* DELETE /api/team/invite/[id]
* Revoke a pending byrå-team invitation (WL-08 invite unfreeze).
*
* Same gates as POST /api/team/invite: the invitation's team must be
* kind='byra' and the caller must be team owner or admin. Revocation is a
* status flip (not a row delete) so the (team, email) unique pair keeps its
* history and a later re-invite reuses the row.
*/
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const { user, error } = await requireAuth()
if (error) return error
const { id } = await params
const serviceClient = createServiceClient()
const loaded = await loadInviteForManagement(serviceClient, id, user.id)
if ('response' in loaded) return loaded.response
const { invite } = loaded
if (invite.status !== 'pending') {
return NextResponse.json({ error: 'Inbjudan har redan använts.' }, { status: 409 })
}
const { error: revokeError } = await serviceClient
.from('team_invitations')
.update({ status: 'revoked' })
.eq('id', invite.id)
if (revokeError) {
return NextResponse.json({ error: 'Kunde inte återkalla inbjudan.' }, { status: 500 })
}
return NextResponse.json({ data: { id: invite.id, status: 'revoked' } })
}
+327
View File
@@ -0,0 +1,327 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { parseJsonResponse, createQueuedMockSupabase } from '@/tests/helpers'
// POST /api/team/invite (WL-08 invite unfreeze): invites are allowed ONLY for
// byrå teams (kind='byra') and only by team owner/admin. Personal teams keep
// the legacy 403 message.
const { supabase: serviceSupabase, enqueue, reset, findCalls } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => serviceSupabase,
}))
vi.mock('@/lib/auth/invite-tokens', () => ({
generateInviteToken: () => ({ token: 'gnubok_inv_test-token', hash: 'hash-test-token' }),
getInviteExpiry: () => new Date('2099-01-08T00:00:00Z'),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
const sendEmailMock = vi.fn()
const isConfiguredMock = vi.fn()
vi.mock('@/lib/email/service', () => ({
getEmailService: () => ({ isConfigured: isConfiguredMock, sendEmail: sendEmailMock }),
}))
// The brand resolver is mocked (no DB); brand-sender and the templates run
// for real so the test covers the actual sender/link wiring.
const resolveBrandForTeamMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/branding/resolve', () => ({
resolveBrandForTeam: resolveBrandForTeamMock,
}))
vi.mock('@/lib/branding/service', () => ({
getBranding: () => ({ appName: 'Accounted', appUrl: 'https://app.gnubok.se' }),
}))
import { POST } from '../route'
const SIFFRA_BRAND = {
id: 'brand-1',
teamId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
domain: 'app.siffra.se',
appName: 'Siffra',
logoUrl: null,
brandColor: '#123456',
chromeColor: null,
fontKey: 'default',
supportEmail: '[email protected]',
authEmailFrom: '[email protected]',
senderDomain: 'post.siffra.se',
senderDomainStatus: 'verified',
resendDomainId: 'rd-1',
signupMode: 'open',
}
const mockUser = { id: 'user-1', email: '[email protected]' }
const BYRA_TEAM_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
const PERSONAL_TEAM_ID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
const UNKNOWN_TEAM_ID = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc'
function makeReq(body: unknown) {
return new Request('http://localhost/api/team/invite', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}) as never
}
const byraMembership = (role: string) => ({
team_id: BYRA_TEAM_ID,
role,
teams: { id: BYRA_TEAM_ID, name: 'Siffran AB', kind: 'byra', created_at: '2026-01-01T00:00:00Z' },
})
const personalMembership = () => ({
team_id: PERSONAL_TEAM_ID,
role: 'owner',
teams: {
id: PERSONAL_TEAM_ID,
name: 'Personal',
kind: 'personal',
created_at: '2026-01-02T00:00:00Z',
},
})
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: serviceSupabase, error: null })
resolveBrandForTeamMock.mockResolvedValue(null)
isConfiguredMock.mockReturnValue(true)
sendEmailMock.mockResolvedValue({ success: true, messageId: 'msg-1' })
})
describe('POST /api/team/invite', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: serviceSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await POST(makeReq({ email: '[email protected]' }))
expect(res.status).toBe(401)
})
it('returns 400 on an invalid email', async () => {
const res = await POST(makeReq({ email: 'not-an-email' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
})
it('returns 403 with the legacy message for a personal-team-only user', async () => {
enqueue({ data: [personalMembership()] })
const res = await POST(makeReq({ email: '[email protected]' }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(403)
expect(body.error).toBe('Teaminbjudningar är inaktiverade. Bjud in via enskilda företag.')
})
it('returns 403 with the legacy message when explicitly targeting the personal team', async () => {
enqueue({ data: [personalMembership(), byraMembership('owner')] })
const res = await POST(makeReq({ email: '[email protected]', teamId: PERSONAL_TEAM_ID }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(403)
expect(body.error).toBe('Teaminbjudningar är inaktiverade. Bjud in via enskilda företag.')
})
it('returns 404 for a teamId outside the caller memberships', async () => {
enqueue({ data: [personalMembership(), byraMembership('owner')] })
const res = await POST(makeReq({ email: '[email protected]', teamId: UNKNOWN_TEAM_ID }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(404)
})
it('returns 403 when the caller is a plain team member', async () => {
enqueue({ data: [byraMembership('member'), personalMembership()] })
const res = await POST(makeReq({ email: '[email protected]' }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(403)
expect(body.error).toBe('Behörighet saknas.')
})
it('creates an invitation and returns the accept link for a byrå admin', async () => {
// 1. caller memberships (personal + byrå: multi-team is the normal shape)
enqueue({ data: [personalMembership(), byraMembership('admin')] })
// 2. profiles lookup (invitee has no account yet)
enqueue({ data: null })
// 3. existing invitation lookup
enqueue({ data: null })
// 4. team_invitations insert
enqueue({ data: { id: 'invite-1' } })
const res = await POST(makeReq({ email: '[email protected]', role: 'member' }))
const { status, body } = await parseJsonResponse<{
data: {
id: string
teamId: string
email: string
role: string
status: string
email_sent: boolean
inviteUrl: string
}
}>(res)
expect(status).toBe(200)
expect(body.data.id).toBe('invite-1')
expect(body.data.teamId).toBe(BYRA_TEAM_ID)
// Email lowercased by the schema
expect(body.data.email).toBe('[email protected]')
expect(body.data.role).toBe('member')
expect(body.data.status).toBe('pending')
// Brandless team: mail goes out with platform defaults on the canonical URL.
expect(body.data.email_sent).toBe(true)
expect(body.data.inviteUrl).toBe('https://app.gnubok.se/invite/gnubok_inv_test-token')
expect(sendEmailMock).toHaveBeenCalledTimes(1)
const mail = sendEmailMock.mock.calls[0]![0] as {
to: string
subject: string
html: string
fromName?: string
fromAddress?: string
replyTo?: string
}
expect(mail.to).toBe('[email protected]')
expect(mail.fromName).toBeUndefined()
expect(mail.fromAddress).toBeUndefined()
expect(mail.html).toContain('https://app.gnubok.se/invite/gnubok_inv_test-token')
// The insert went to team_invitations with the hashed token, never the raw.
const inserts = findCalls('team_invitations', 'insert')
expect(inserts).toHaveLength(1)
expect(inserts[0]![0]).toMatchObject({
team_id: BYRA_TEAM_ID,
email: '[email protected]',
role: 'member',
token_hash: 'hash-test-token',
status: 'pending',
})
})
it('sends the invite mail in the byrå brand: brand sender, brand-domain link', async () => {
resolveBrandForTeamMock.mockResolvedValue(SIFFRA_BRAND)
enqueue({ data: [byraMembership('admin')] })
enqueue({ data: null })
enqueue({ data: null })
enqueue({ data: { id: 'invite-1' } })
const res = await POST(makeReq({ email: '[email protected]' }))
const { status, body } = await parseJsonResponse<{
data: { email_sent: boolean; inviteUrl: string }
}>(res)
expect(status).toBe(200)
expect(resolveBrandForTeamMock).toHaveBeenCalledWith(BYRA_TEAM_ID)
expect(body.data.email_sent).toBe(true)
expect(body.data.inviteUrl).toBe('https://app.siffra.se/invite/gnubok_inv_test-token')
const mail = sendEmailMock.mock.calls[0]![0] as {
subject: string
html: string
fromName?: string
fromAddress?: string
replyTo?: string
}
expect(mail.fromName).toBe('Siffra')
expect(mail.fromAddress).toBe('[email protected]')
expect(mail.replyTo).toBe('[email protected]')
// Branded byrå: the subject names the byrå in its own casing, with no
// platform wording ("Du har blivit inbjuden till Siffra").
expect(mail.subject).toContain('Siffra')
expect(mail.html).toContain('https://app.siffra.se/invite/gnubok_inv_test-token')
expect(mail.html).not.toMatch(/accounted/i)
})
it('keeps the invitation valid when the mail send fails (email_sent: false)', async () => {
sendEmailMock.mockResolvedValue({ success: false, error: 'provider down' })
enqueue({ data: [byraMembership('owner')] })
enqueue({ data: null })
enqueue({ data: null })
enqueue({ data: { id: 'invite-1' } })
const res = await POST(makeReq({ email: '[email protected]' }))
const { status, body } = await parseJsonResponse<{
data: { id: string; email_sent: boolean; inviteUrl: string }
}>(res)
expect(status).toBe(200)
expect(body.data.id).toBe('invite-1')
expect(body.data.email_sent).toBe(false)
// The accept link is still returned so the inviter can share it directly.
expect(body.data.inviteUrl).toContain('/invite/gnubok_inv_test-token')
})
it('skips the mail when the email service is not configured', async () => {
isConfiguredMock.mockReturnValue(false)
enqueue({ data: [byraMembership('owner')] })
enqueue({ data: null })
enqueue({ data: null })
enqueue({ data: { id: 'invite-1' } })
const res = await POST(makeReq({ email: '[email protected]' }))
const { status, body } = await parseJsonResponse<{
data: { email_sent: boolean }
}>(res)
expect(status).toBe(200)
expect(body.data.email_sent).toBe(false)
expect(sendEmailMock).not.toHaveBeenCalled()
})
it('returns 409 when the invitee is already a team member', async () => {
enqueue({ data: [byraMembership('owner')] })
// profiles lookup -> existing account
enqueue({ data: { id: 'user-2' } })
// team_members lookup -> already a member
enqueue({ data: { id: 'tm-2' } })
const res = await POST(makeReq({ email: '[email protected]' }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(409)
expect(body.error).toBe('Denna person är redan medlem.')
})
it('returns 409 when a live pending invitation already exists', async () => {
enqueue({ data: [byraMembership('owner')] })
enqueue({ data: null })
enqueue({
data: { id: 'invite-1', status: 'pending', expires_at: '2099-01-01T00:00:00Z' },
})
const res = await POST(makeReq({ email: '[email protected]' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(409)
})
it('re-issues a revoked invitation in place', async () => {
enqueue({ data: [byraMembership('owner')] })
enqueue({ data: null })
enqueue({
data: { id: 'invite-1', status: 'revoked', expires_at: '2099-01-01T00:00:00Z' },
})
// team_invitations update
enqueue({ data: { id: 'invite-1' } })
const res = await POST(makeReq({ email: '[email protected]', role: 'admin' }))
const { status, body } = await parseJsonResponse<{ data: { id: string; role: string } }>(res)
expect(status).toBe(200)
expect(body.data.id).toBe('invite-1')
expect(body.data.role).toBe('admin')
const updates = findCalls('team_invitations', 'update')
expect(updates).toHaveLength(1)
expect(updates[0]![0]).toMatchObject({ status: 'pending', token_hash: 'hash-test-token' })
})
})
+216
View File
@@ -0,0 +1,216 @@
import { createServiceClient } from '@/lib/supabase/server'
import { NextResponse, type NextRequest } from 'next/server'
import { z } from 'zod'
import { ensureInitialized } from '@/lib/init'
import { requireAuth } from '@/lib/auth/require-auth'
import { validateBody } from '@/lib/api/validate'
import { generateInviteToken, getInviteExpiry } from '@/lib/auth/invite-tokens'
import { sendTeamInviteMail } from '@/lib/email/send-team-invite'
// Loads the email extension so getEmailService() returns the Resend
// implementation instead of the noop default (same reason as the company
// invite route: without this the invite mail silently no-ops in a fresh
// process).
ensureInitialized()
/**
* Kept verbatim from the pre-unfreeze hardcoded 403: personal teams remain
* uninvitable (WL-08), and this is the message their members still see.
*/
const PERSONAL_TEAM_MESSAGE = 'Teaminbjudningar är inaktiverade. Bjud in via enskilda företag.'
const InviteSchema = z.object({
email: z.string().trim().toLowerCase().pipe(z.string().email('Ogiltig e-postadress.')),
// Team invitations never mint owners: the schema is the first gate, and the
// accept route re-checks (defense in depth against a hand-edited row).
role: z.enum(['admin', 'member']).default('member'),
// Optional explicit team target for users in several teams; validated
// against the caller's own memberships below.
teamId: z.string().uuid().optional(),
})
interface TeamMembershipRow {
team_id: string
role: string
teams: { id: string; name: string; kind: string; created_at: string } | null
}
/**
* POST /api/team/invite
* Invite a consultant to a byrå team (WL-08 invite unfreeze).
*
* Gates, in order:
* - authenticated (MFA enforced by requireAuth on hosted)
* - the target team is kind='byra' (personal teams keep the legacy 403)
* - the caller is team owner or admin
*
* Team-scoped rather than company-scoped (requireAuth, not withRouteContext):
* a byrå admin's active company is irrelevant to team membership, mirroring
* GET /api/team/members.
*
* The invitation email is sent in the byrå team's brand (WL-13): sender
* identity via getSenderForBrand(resolveBrandForTeam(teamId)) and the accept
* link on the brand's home domain, canonical for brandless teams. A send
* failure never fails the invite (email_sent: false + the link is returned,
* so the inviter can always share it directly).
*/
export async function POST(request: NextRequest) {
const { user, error } = await requireAuth()
if (error) return error
const validation = await validateBody(request, InviteSchema, {
operation: 'team.invite',
})
if (!validation.success) return validation.response
const { email, role, teamId: requestedTeamId } = validation.data
const serviceClient = createServiceClient()
// All of the caller's team memberships, with the team kind: the one-team-
// per-user assumption is gone (a consultant sits in their own personal team
// AND the byrå team).
const { data: memberships } = await serviceClient
.from('team_members')
.select('team_id, role, teams:team_id(id, name, kind, created_at)')
.eq('user_id', user.id)
const rows = (memberships ?? []) as unknown as TeamMembershipRow[]
let target: TeamMembershipRow | undefined
if (requestedTeamId) {
target = rows.find((m) => m.team_id === requestedTeamId)
if (!target) {
return NextResponse.json({ error: 'Team hittades inte.' }, { status: 404 })
}
} else {
// Default target: the caller's byrå team when one exists. Deterministic
// tie-break by team creation time for the (unexpected) multi-byrå case.
target = rows
.filter((m) => m.teams?.kind === 'byra')
.sort((a, b) => (a.teams?.created_at ?? '').localeCompare(b.teams?.created_at ?? ''))[0]
}
// Kind gate: invites exist for byrå teams only. A personal-team target (or
// no byrå membership at all) gets the exact legacy message.
if (!target || target.teams?.kind !== 'byra') {
return NextResponse.json({ error: PERSONAL_TEAM_MESSAGE }, { status: 403 })
}
// Role gate: team owner/admin may invite; members may not.
if (!['owner', 'admin'].includes(target.role)) {
return NextResponse.json({ error: 'Behörighet saknas.' }, { status: 403 })
}
const teamId = target.team_id
// Already a member? (profiles.email is lowercased like the schema output.)
const { data: profile } = await serviceClient
.from('profiles')
.select('id')
.eq('email', email)
.maybeSingle()
if (profile) {
const { data: existingMember } = await serviceClient
.from('team_members')
.select('id')
.eq('team_id', teamId)
.eq('user_id', (profile as { id: string }).id)
.maybeSingle()
if (existingMember) {
return NextResponse.json({ error: 'Denna person är redan medlem.' }, { status: 409 })
}
}
// Existing invitation for (team, email): a live pending one blocks; a
// spent or expired one is re-issued in place (unique constraint on the pair).
const { data: existingInvite } = await serviceClient
.from('team_invitations')
.select('id, status, expires_at')
.eq('team_id', teamId)
.eq('email', email)
.maybeSingle()
const existing = existingInvite as
| { id: string; status: string; expires_at: string }
| null
if (
existing &&
existing.status === 'pending' &&
new Date(existing.expires_at) > new Date()
) {
return NextResponse.json(
{ error: 'En inbjudan har redan skickats till denna e-post.' },
{ status: 409 },
)
}
const { token, hash } = generateInviteToken()
const expiresAt = getInviteExpiry()
let invitationId: string
if (existing) {
const { data: updated, error: updateError } = await serviceClient
.from('team_invitations')
.update({
role,
token_hash: hash,
invited_by: user.id,
status: 'pending',
expires_at: expiresAt.toISOString(),
})
.eq('id', existing.id)
.select('id')
.single()
if (updateError || !updated) {
return NextResponse.json({ error: 'Kunde inte skapa inbjudan.' }, { status: 500 })
}
invitationId = (updated as { id: string }).id
} else {
const { data: inserted, error: insertError } = await serviceClient
.from('team_invitations')
.insert({
team_id: teamId,
email,
role,
token_hash: hash,
invited_by: user.id,
status: 'pending',
expires_at: expiresAt.toISOString(),
})
.select('id')
.single()
if (insertError || !inserted) {
return NextResponse.json({ error: 'Kunde inte skapa inbjudan.' }, { status: 500 })
}
invitationId = (inserted as { id: string }).id
}
// Brand mail (WL-13) via the shared helper: the byrå team's brand drives
// sender identity and the accept link's base URL; a brandless team gets the
// canonical URL and the platform sender exactly as before. Non-blocking: a
// failed send leaves the invitation valid and surfaces email_sent: false so
// the inviter knows to share the link directly.
const { inviteUrl, emailSent } = await sendTeamInviteMail({
teamId,
email,
inviterEmail: user.email || '',
token,
})
return NextResponse.json({
data: {
id: invitationId,
teamId,
email,
role,
status: 'pending',
expires_at: expiresAt.toISOString(),
email_sent: emailSent,
// The accept link is always returned so the inviter can share it
// directly, e.g. when the mail bounced or the service is unconfigured.
inviteUrl,
},
})
}
@@ -0,0 +1,241 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
createMockRequest,
createMockRouteParams,
createQueuedMockSupabase,
parseJsonResponse,
} from '@/tests/helpers'
// PATCH/DELETE /api/team/members/[id] (WL-08 gap fix, the last frozen team
// surface): byrå-only role changes and removals with last-owner protection.
// Company-side effects are the DB triggers' job (AFTER UPDATE re-sync,
// BEFORE DELETE source='team' cleanup) and are pg-tested, not mocked here.
const { supabase: serviceSupabase, enqueue, reset, findCalls } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => serviceSupabase,
}))
import { PATCH, DELETE } from '../route'
const mockUser = { id: 'user-1', email: '[email protected]' }
const routeParams = createMockRouteParams({ id: 'tm-target' })
const patchReq = (role: string) =>
createMockRequest('/api/team/members/tm-target', { method: 'PATCH', body: { role } })
const deleteReq = () =>
createMockRequest('/api/team/members/tm-target', { method: 'DELETE' })
const targetRow = (overrides: Partial<{ role: string; kind: string; user_id: string }> = {}) => ({
id: 'tm-target',
team_id: 'team-b',
user_id: overrides.user_id ?? 'user-2',
role: overrides.role ?? 'member',
teams: { kind: overrides.kind ?? 'byra' },
})
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: serviceSupabase, error: null })
})
describe('PATCH /api/team/members/[id]', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: serviceSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await PATCH(patchReq('admin'), routeParams)
expect(res.status).toBe(401)
})
it('returns 400 for an invalid role', async () => {
const res = await PATCH(patchReq('viewer'), routeParams)
expect(res.status).toBe(400)
})
it('returns 404 when the membership row does not exist', async () => {
enqueue({ data: null })
const { status } = await parseJsonResponse(await PATCH(patchReq('admin'), routeParams))
expect(status).toBe(404)
})
it('returns 403 with the legacy message for a personal-team membership', async () => {
enqueue({ data: targetRow({ kind: 'personal' }) })
const { status, body } = await parseJsonResponse<{ error: string }>(
await PATCH(patchReq('admin'), routeParams),
)
expect(status).toBe(403)
expect(body.error).toBe('Team har bara en ägare och kan inte ändras.')
})
it('returns 403 when the caller is a plain team member', async () => {
enqueue({ data: targetRow() })
enqueue({ data: { role: 'member' } })
const { status, body } = await parseJsonResponse<{ error: string }>(
await PATCH(patchReq('admin'), routeParams),
)
expect(status).toBe(403)
expect(body.error).toBe('Behörighet saknas.')
})
it('only an owner may grant the owner role', async () => {
enqueue({ data: targetRow() })
enqueue({ data: { role: 'admin' } })
const { status } = await parseJsonResponse(await PATCH(patchReq('owner'), routeParams))
expect(status).toBe(403)
expect(findCalls('team_members', 'update')).toHaveLength(0)
})
it("only an owner may change an owner's role", async () => {
enqueue({ data: targetRow({ role: 'owner' }) })
enqueue({ data: { role: 'admin' } })
const { status } = await parseJsonResponse(await PATCH(patchReq('member'), routeParams))
expect(status).toBe(403)
expect(findCalls('team_members', 'update')).toHaveLength(0)
})
it('returns 409 when demoting the last owner', async () => {
enqueue({ data: targetRow({ role: 'owner' }) })
enqueue({ data: { role: 'owner' } })
// owner count
enqueue({ data: null, count: 1 })
const { status, body } = await parseJsonResponse<{ error: string }>(
await PATCH(patchReq('admin'), routeParams),
)
expect(status).toBe(409)
expect(body.error).toBe('Teamet måste ha minst en ägare.')
expect(findCalls('team_members', 'update')).toHaveLength(0)
})
it('demotes a non-last owner when the caller is an owner', async () => {
enqueue({ data: targetRow({ role: 'owner' }) })
enqueue({ data: { role: 'owner' } })
enqueue({ data: null, count: 2 })
// update
enqueue({ data: null })
const { status, body } = await parseJsonResponse<{
data: { id: string; role: string }
}>(await PATCH(patchReq('admin'), routeParams))
expect(status).toBe(200)
expect(body.data).toMatchObject({ id: 'tm-target', role: 'admin' })
const updates = findCalls('team_members', 'update')
expect(updates).toHaveLength(1)
expect(updates[0]![0]).toEqual({ role: 'admin' })
})
it('promotes a member to admin for a byrå admin caller', async () => {
enqueue({ data: targetRow({ role: 'member' }) })
enqueue({ data: { role: 'admin' } })
// update
enqueue({ data: null })
const { status, body } = await parseJsonResponse<{
data: { id: string; user_id: string; team_id: string; role: string }
}>(await PATCH(patchReq('admin'), routeParams))
expect(status).toBe(200)
expect(body.data).toEqual({
id: 'tm-target',
user_id: 'user-2',
team_id: 'team-b',
role: 'admin',
})
const updates = findCalls('team_members', 'update')
expect(updates).toHaveLength(1)
expect(updates[0]![0]).toEqual({ role: 'admin' })
})
it('is a no-op (no write) when the role is unchanged', async () => {
enqueue({ data: targetRow({ role: 'admin' }) })
enqueue({ data: { role: 'owner' } })
const { status, body } = await parseJsonResponse<{ data: { role: string } }>(
await PATCH(patchReq('admin'), routeParams),
)
expect(status).toBe(200)
expect(body.data.role).toBe('admin')
expect(findCalls('team_members', 'update')).toHaveLength(0)
})
})
describe('DELETE /api/team/members/[id]', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: serviceSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await DELETE(deleteReq(), routeParams)
expect(res.status).toBe(401)
})
it('returns 404 when the membership row does not exist', async () => {
enqueue({ data: null })
const { status } = await parseJsonResponse(await DELETE(deleteReq(), routeParams))
expect(status).toBe(404)
})
it('returns 403 with the legacy message for a personal-team membership', async () => {
enqueue({ data: targetRow({ kind: 'personal' }) })
const { status, body } = await parseJsonResponse<{ error: string }>(
await DELETE(deleteReq(), routeParams),
)
expect(status).toBe(403)
expect(body.error).toBe('Team har bara en ägare och kan inte ändras.')
})
it('returns 403 when the caller is a plain team member', async () => {
enqueue({ data: targetRow() })
enqueue({ data: { role: 'member' } })
const { status } = await parseJsonResponse(await DELETE(deleteReq(), routeParams))
expect(status).toBe(403)
expect(findCalls('team_members', 'delete')).toHaveLength(0)
})
it('only an owner may remove an owner', async () => {
enqueue({ data: targetRow({ role: 'owner' }) })
enqueue({ data: { role: 'admin' } })
const { status } = await parseJsonResponse(await DELETE(deleteReq(), routeParams))
expect(status).toBe(403)
expect(findCalls('team_members', 'delete')).toHaveLength(0)
})
it('returns 409 when removing the last owner', async () => {
enqueue({ data: targetRow({ role: 'owner', user_id: 'user-1' }) })
enqueue({ data: { role: 'owner' } })
enqueue({ data: null, count: 1 })
const { status, body } = await parseJsonResponse<{ error: string }>(
await DELETE(deleteReq(), routeParams),
)
expect(status).toBe(409)
expect(body.error).toBe('Teamet måste ha minst en ägare.')
expect(findCalls('team_members', 'delete')).toHaveLength(0)
})
it('removes a member for a byrå admin; company cleanup is the trigger', async () => {
enqueue({ data: targetRow({ role: 'member' }) })
enqueue({ data: { role: 'admin' } })
// delete
enqueue({ data: null })
const { status, body } = await parseJsonResponse<{
data: { id: string; removed: boolean }
}>(await DELETE(deleteReq(), routeParams))
expect(status).toBe(200)
expect(body.data).toEqual({ id: 'tm-target', removed: true })
expect(findCalls('team_members', 'delete')).toHaveLength(1)
// The route never touches company_members: the BEFORE DELETE sync trigger
// owns that cleanup (migration 20260331010000).
expect(findCalls('company_members', 'delete')).toHaveLength(0)
})
})
+223
View File
@@ -0,0 +1,223 @@
import { createServiceClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
/**
* Kept verbatim from the pre-unfreeze hardcoded 403: personal teams remain
* single-user shells (WL-08), and this is the message their members still see.
*/
const PERSONAL_TEAM_MESSAGE = 'Team har bara en ägare och kan inte ändras.'
const RoleSchema = z.object({
role: z.enum(['owner', 'admin', 'member']),
})
interface TargetRow {
id: string
team_id: string
user_id: string
role: string
teams: { kind: string } | null
}
/**
* Shared gates for both verbs. Returns the target row and the caller's team
* role, or the error response to short-circuit with:
* - 404 when the membership row does not exist
* - 403 (legacy message) when the row's team is not a byrå team
* - 403 when the caller is not owner/admin of that team
*/
async function resolveTargetAndCaller(
serviceClient: ReturnType<typeof createServiceClient>,
memberId: string,
callerUserId: string,
): Promise<
| { error: NextResponse; target?: undefined; callerRole?: undefined }
| { error?: undefined; target: TargetRow; callerRole: 'owner' | 'admin' }
> {
const { data } = await serviceClient
.from('team_members')
.select('id, team_id, user_id, role, teams:team_id(kind)')
.eq('id', memberId)
.maybeSingle()
const target = data as unknown as TargetRow | null
if (!target) {
return { error: NextResponse.json({ error: 'Medlem hittades inte.' }, { status: 404 }) }
}
// Kind gate first: personal teams keep the exact legacy 403 (WL-08).
if (target.teams?.kind !== 'byra') {
return { error: NextResponse.json({ error: PERSONAL_TEAM_MESSAGE }, { status: 403 }) }
}
const { data: membership } = await serviceClient
.from('team_members')
.select('role')
.eq('team_id', target.team_id)
.eq('user_id', callerUserId)
.maybeSingle()
const callerRole = (membership as { role: string } | null)?.role
if (callerRole !== 'owner' && callerRole !== 'admin') {
return { error: NextResponse.json({ error: 'Behörighet saknas.' }, { status: 403 }) }
}
return { target, callerRole }
}
/** Count of owner rows in the team: the last-owner protections read this. */
async function countTeamOwners(
serviceClient: ReturnType<typeof createServiceClient>,
teamId: string,
): Promise<number> {
const { count } = await serviceClient
.from('team_members')
.select('id', { count: 'exact', head: true })
.eq('team_id', teamId)
.eq('role', 'owner')
return count ?? 0
}
/**
* PATCH /api/team/members/[id]
* Change a byrå team member's role (WL-08 gap fix: the last frozen surface).
*
* Gates, in order: authenticated + MFA (withRouteContext), the membership's
* team is kind='byra' (personal teams keep the legacy 403 verbatim), caller
* is team owner/admin. Owner-role protections on top:
* - the owner role is only granted by an owner
* - an owner's role is only changed by an owner
* - the last owner can never be demoted (409)
*
* The route only writes team_members.role. Propagating the new role into
* every client company's company_members rows is the job of the AFTER UPDATE
* trigger team_member_sync_role_update (migration 20260826130100): same
* owner/admin -> admin, member -> member mapping as the INSERT sync, and it
* never mints a company owner. Deliberately not duplicated here.
*
* No requireWrite: that option gates on the caller's role in the ACTIVE
* COMPANY, which is the wrong dimension for a team-scoped mutation (a byrå
* owner may have any company active). The team owner/admin gate above is the
* authorization.
*/
export const PATCH = withRouteContext<{ params: Promise<{ id: string }> }>(
'team_members.update_role',
async (request, ctx, { params }) => {
const { id } = await params
const validation = await validateBody(request, RoleSchema, {
operation: 'team_members.update_role',
})
if (!validation.success) return validation.response
const { role: newRole } = validation.data
const serviceClient = createServiceClient()
const resolved = await resolveTargetAndCaller(serviceClient, id, ctx.user.id)
if (resolved.error) return resolved.error
const { target, callerRole } = resolved
// Owner role is only granted by an owner.
if (newRole === 'owner' && callerRole !== 'owner') {
return NextResponse.json(
{ error: 'Endast en ägare kan utse en annan ägare.' },
{ status: 403 },
)
}
// An owner's role is only changed by an owner (an admin must not be able
// to demote the byrå's owners).
if (target.role === 'owner' && callerRole !== 'owner') {
return NextResponse.json(
{ error: 'Endast en ägare kan ändra en ägares roll.' },
{ status: 403 },
)
}
// Demoting an owner: the team must keep at least one owner.
if (target.role === 'owner' && newRole !== 'owner') {
const owners = await countTeamOwners(serviceClient, target.team_id)
if (owners <= 1) {
return NextResponse.json(
{ error: 'Teamet måste ha minst en ägare.' },
{ status: 409 },
)
}
}
if (target.role === newRole) {
// No-op: skip the write (and the re-sync cascade it would fire).
return NextResponse.json({
data: { id: target.id, user_id: target.user_id, team_id: target.team_id, role: newRole },
})
}
const { error } = await serviceClient
.from('team_members')
.update({ role: newRole })
.eq('id', target.id)
if (error) {
return NextResponse.json({ error: 'Kunde inte ändra rollen.' }, { status: 500 })
}
return NextResponse.json({
data: { id: target.id, user_id: target.user_id, team_id: target.team_id, role: newRole },
})
},
)
/**
* DELETE /api/team/members/[id]
* Remove a member from a byrå team (WL-08 gap fix).
*
* Same gates as PATCH. Protections: an owner is only removed by an owner, and
* the last owner can never be removed (409).
*
* The route only deletes the team_members row. Cleaning the member out of
* every client company is the job of the BEFORE DELETE trigger
* team_member_sync_delete / remove_team_member_from_companies (migration
* 20260331010000): it deletes the company_members rows with source='team' for
* the team's companies and leaves source='direct' memberships untouched.
* Deliberately not duplicated here.
*/
export const DELETE = withRouteContext<{ params: Promise<{ id: string }> }>(
'team_members.remove',
async (_request, ctx, { params }) => {
const { id } = await params
const serviceClient = createServiceClient()
const resolved = await resolveTargetAndCaller(serviceClient, id, ctx.user.id)
if (resolved.error) return resolved.error
const { target, callerRole } = resolved
if (target.role === 'owner') {
// Owners are only removed by owners; the last owner is never removed.
if (callerRole !== 'owner') {
return NextResponse.json(
{ error: 'Endast en ägare kan ta bort en ägare.' },
{ status: 403 },
)
}
const owners = await countTeamOwners(serviceClient, target.team_id)
if (owners <= 1) {
return NextResponse.json(
{ error: 'Teamet måste ha minst en ägare.' },
{ status: 409 },
)
}
}
const { error } = await serviceClient
.from('team_members')
.delete()
.eq('id', target.id)
if (error) {
return NextResponse.json({ error: 'Kunde inte ta bort medlemmen.' }, { status: 500 })
}
return NextResponse.json({ data: { id: target.id, removed: true } })
},
)
@@ -0,0 +1,220 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextRequest, NextResponse } from 'next/server'
import { parseJsonResponse, createQueuedMockSupabase } from '@/tests/helpers'
// GET /api/team/members under the multi-team model (WL-08): a user may belong
// to several teams (personal shell + byrå). Default target is the byrå team;
// ?teamId= selects explicitly, validated against the caller's memberships.
const { supabase: serviceSupabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => serviceSupabase,
}))
import { GET } from '../route'
const mockUser = { id: 'user-1', email: '[email protected]' }
const BYRA_TEAM_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
const PERSONAL_TEAM_ID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
const byraMembership = (role: string) => ({
team_id: BYRA_TEAM_ID,
role,
teams: { id: BYRA_TEAM_ID, name: 'Siffran AB', kind: 'byra', created_at: '2026-02-01T00:00:00Z' },
})
const personalMembership = () => ({
team_id: PERSONAL_TEAM_ID,
role: 'owner',
teams: {
id: PERSONAL_TEAM_ID,
name: 'Personal',
kind: 'personal',
created_at: '2026-01-01T00:00:00Z',
},
})
function makeReq(searchParams?: Record<string, string>) {
const url = new URL('http://localhost/api/team/members')
for (const [k, v] of Object.entries(searchParams ?? {})) {
url.searchParams.set(k, v)
}
return new NextRequest(url)
}
interface MembersBody {
data: {
members: { user_id: string; email: string; role: string; is_current_user: boolean }[]
invitations: { id: string; email: string; role: string; status: string }[]
teamName: string | null
teamId: string | null
teamKind: string | null
isOwner: boolean
hasTeam: boolean
canInvite: boolean
teams: { id: string; name: string | null; kind: string; role: string }[]
ownsCompany?: boolean
}
}
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: serviceSupabase, error: null })
})
describe('GET /api/team/members', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: serviceSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await GET(makeReq())
expect(res.status).toBe(401)
})
it('returns the empty shape for a teamless user', async () => {
// 1. memberships
enqueue({ data: [] })
// 2. owned-company probe
enqueue({ data: { id: 'cm-1' } })
const { status, body } = await parseJsonResponse<MembersBody>(await GET(makeReq()))
expect(status).toBe(200)
expect(body.data.hasTeam).toBe(false)
expect(body.data.members).toEqual([])
expect(body.data.teamId).toBeNull()
expect(body.data.ownsCompany).toBe(true)
})
it('defaults to the byrå team when the user is in both a personal and a byrå team', async () => {
// 1. memberships (personal listed FIRST: order must not matter)
enqueue({ data: [personalMembership(), byraMembership('admin')] })
// 2. byrå roster
enqueue({
data: [
{ id: 'tm-1', team_id: BYRA_TEAM_ID, user_id: 'user-9', role: 'owner', joined_at: '2026-02-01' },
{ id: 'tm-2', team_id: BYRA_TEAM_ID, user_id: 'user-1', role: 'admin', joined_at: '2026-02-02' },
],
})
// 3. profiles
enqueue({
data: [
{ id: 'user-9', email: '[email protected]' },
{ id: 'user-1', email: '[email protected]' },
],
})
const { status, body } = await parseJsonResponse<MembersBody>(await GET(makeReq()))
expect(status).toBe(200)
expect(body.data.teamId).toBe(BYRA_TEAM_ID)
expect(body.data.teamKind).toBe('byra')
expect(body.data.teamName).toBe('Siffran AB')
expect(body.data.canInvite).toBe(true)
expect(body.data.isOwner).toBe(false)
expect(body.data.members).toHaveLength(2)
expect(body.data.members[1]).toMatchObject({
user_id: 'user-1',
email: '[email protected]',
is_current_user: true,
})
// Both memberships surface so the client can offer a switcher.
expect(body.data.teams.map((t) => t.id).sort()).toEqual(
[BYRA_TEAM_ID, PERSONAL_TEAM_ID].sort(),
)
})
it('returns pending invitations for a byrå admin', async () => {
enqueue({ data: [byraMembership('admin')] })
// roster
enqueue({
data: [
{ id: 'tm-2', team_id: BYRA_TEAM_ID, user_id: 'user-1', role: 'admin', joined_at: '2026-02-02' },
],
})
// profiles
enqueue({ data: [{ id: 'user-1', email: '[email protected]' }] })
// pending invitations
enqueue({
data: [
{
id: 'inv-1',
email: '[email protected]',
role: 'member',
status: 'pending',
created_at: '2026-07-01T00:00:00Z',
expires_at: '2026-08-15T00:00:00Z',
},
],
})
const { body } = await parseJsonResponse<MembersBody>(await GET(makeReq()))
expect(body.data.canInvite).toBe(true)
expect(body.data.invitations).toHaveLength(1)
expect(body.data.invitations[0]).toMatchObject({ id: 'inv-1', email: '[email protected]' })
})
it('a byrå plain member gets no invitation list', async () => {
enqueue({ data: [byraMembership('member')] })
enqueue({
data: [
{ id: 'tm-2', team_id: BYRA_TEAM_ID, user_id: 'user-1', role: 'member', joined_at: '2026-02-02' },
],
})
enqueue({ data: [{ id: 'user-1', email: '[email protected]' }] })
const { body } = await parseJsonResponse<MembersBody>(await GET(makeReq()))
expect(body.data.invitations).toEqual([])
})
it('a byrå plain member cannot invite', async () => {
enqueue({ data: [byraMembership('member')] })
enqueue({
data: [
{ id: 'tm-2', team_id: BYRA_TEAM_ID, user_id: 'user-1', role: 'member', joined_at: '2026-02-02' },
],
})
enqueue({ data: [{ id: 'user-1', email: '[email protected]' }] })
const { body } = await parseJsonResponse<MembersBody>(await GET(makeReq()))
expect(body.data.canInvite).toBe(false)
})
it('?teamId= targets the personal team explicitly', async () => {
enqueue({ data: [personalMembership(), byraMembership('admin')] })
// personal roster
enqueue({
data: [
{ id: 'tm-3', team_id: PERSONAL_TEAM_ID, user_id: 'user-1', role: 'owner', joined_at: '2026-01-01' },
],
})
enqueue({ data: [{ id: 'user-1', email: '[email protected]' }] })
const { status, body } = await parseJsonResponse<MembersBody>(
await GET(makeReq({ teamId: PERSONAL_TEAM_ID })),
)
expect(status).toBe(200)
expect(body.data.teamId).toBe(PERSONAL_TEAM_ID)
expect(body.data.teamKind).toBe('personal')
expect(body.data.isOwner).toBe(true)
// Personal teams are never invitable regardless of role.
expect(body.data.canInvite).toBe(false)
})
it('returns 404 for a teamId outside the caller memberships', async () => {
enqueue({ data: [personalMembership()] })
const { status } = await parseJsonResponse(
await GET(makeReq({ teamId: 'cccccccc-cccc-4ccc-8ccc-cccccccccccc' })),
)
expect(status).toBe(404)
})
})
+173
View File
@@ -0,0 +1,173 @@
import { createServiceClient } from '@/lib/supabase/server'
import { NextResponse, type NextRequest } from 'next/server'
import { requireAuth } from '@/lib/auth/require-auth'
/**
* GET /api/team/members
* Returns the member roster for one of the caller's teams.
*
* Multi-team model (WL-08): a user may belong to several teams (their own
* personal shell AND a byrå team), so the old `.limit(1)` single-membership
* read is gone. Selection:
* - `?teamId=` targets an explicit team, validated against the caller's own
* memberships (404 otherwise)
* - default: the caller's byrå team when one exists, else the personal team
*
* Team-scoped (not company-scoped): a brand-new user with no company must
* still get a valid empty response (ownsCompany: false), so this uses
* requireAuth() directly rather than withRouteContext, which would require an
* active company context. requireAuth still enforces MFA (AAL2) on hosted.
*
* Read-only: team role changes are re-synced to company_members by the
* DB trigger (team_member_sync_role_update); this route just reflects the
* current rows and never writes roles.
*/
export async function GET(request: NextRequest) {
const { user, error } = await requireAuth()
if (error) return error
const serviceClient = createServiceClient()
// Every team membership the user holds, with each team's name and kind.
const { data: myMemberships } = await serviceClient
.from('team_members')
.select('team_id, role, teams:team_id(id, name, kind, created_at)')
.eq('user_id', user.id)
const memberships = (myMemberships ?? []) as unknown as {
team_id: string
role: string
teams: { id: string; name: string; kind: string; created_at: string } | null
}[]
if (memberships.length === 0) {
// User is not in any team: check if they own a company (could start a team)
const { data: ownedCompany } = await serviceClient
.from('company_members')
.select('id')
.eq('user_id', user.id)
.eq('role', 'owner')
.limit(1)
.maybeSingle()
return NextResponse.json({
data: {
members: [],
invitations: [],
teamName: null,
teamId: null,
teamKind: null,
isOwner: false,
hasTeam: false,
canInvite: false,
teams: [],
ownsCompany: !!ownedCompany,
},
})
}
const requestedTeamId = request.nextUrl.searchParams.get('teamId')
let myMembership: (typeof memberships)[number] | undefined
if (requestedTeamId) {
myMembership = memberships.find((m) => m.team_id === requestedTeamId)
if (!myMembership) {
return NextResponse.json({ error: 'Team hittades inte.' }, { status: 404 })
}
} else {
// Default: byrå team first (that is the roster a consultant cares about),
// else the personal team. Deterministic tie-break on team creation time.
const byCreated = (a: (typeof memberships)[number], b: (typeof memberships)[number]) =>
(a.teams?.created_at ?? '').localeCompare(b.teams?.created_at ?? '')
myMembership =
memberships.filter((m) => m.teams?.kind === 'byra').sort(byCreated)[0] ??
[...memberships].sort(byCreated)[0]
}
const teamId = myMembership.team_id
const teamKind = myMembership.teams?.kind ?? 'personal'
const isOwner = myMembership.role === 'owner'
const canInvite = teamKind === 'byra' && ['owner', 'admin'].includes(myMembership.role)
// Team name from the joined row; fall back to a direct read when the join
// is absent (defensive: service role bypasses RLS so it should be present).
let teamName = myMembership.teams?.name ?? null
if (!teamName) {
const { data: team } = await serviceClient
.from('teams')
.select('name')
.eq('id', teamId)
.single()
teamName = (team as { name: string } | null)?.name ?? null
}
// Fetch all team members (owner is a real row now)
const { data: members, error: membersError } = await serviceClient
.from('team_members')
.select('id, team_id, user_id, role, joined_at')
.eq('team_id', teamId)
.order('joined_at', { ascending: true })
if (membersError) {
return NextResponse.json({ error: 'Kunde inte hämta teammedlemmar.' }, { status: 500 })
}
// Fetch emails from profiles
const userIds = (members || []).map((m) => m.user_id)
const { data: profiles } = await serviceClient
.from('profiles')
.select('id, email')
.in('id', userIds)
const emailMap = new Map((profiles || []).map((p) => [p.id, p.email]))
// Pending invitations: only meaningful (and only shown) on byrå teams for
// callers who may manage invites; everyone else gets an empty list so the
// payload shape stays constant. Revoked/accepted rows are history, not
// roster state, so only status='pending' is returned (the client derives
// "expired" from expires_at).
let invitations: {
id: string
email: string
role: string
status: string
created_at: string
expires_at: string
}[] = []
if (canInvite) {
const { data: inviteRows } = await serviceClient
.from('team_invitations')
.select('id, email, role, status, created_at, expires_at')
.eq('team_id', teamId)
.eq('status', 'pending')
.order('created_at', { ascending: true })
invitations = (inviteRows ?? []) as typeof invitations
}
return NextResponse.json({
data: {
members: (members || []).map((m) => ({
id: m.id,
user_id: m.user_id,
email: emailMap.get(m.user_id) || '',
role: m.role,
joined_at: m.joined_at,
is_current_user: m.user_id === user.id,
})),
invitations,
teamName,
teamId,
teamKind,
isOwner,
hasTeam: true,
canInvite,
// All of the caller's teams, so the client can offer a team switcher.
teams: memberships.map((m) => ({
id: m.team_id,
name: m.teams?.name ?? null,
kind: m.teams?.kind ?? 'personal',
role: m.role,
})),
},
})
}