diff --git a/src/app/api/it-hilfe/accept-offer-via-token/__tests__/route.test.ts b/src/app/api/it-hilfe/accept-offer-via-token/__tests__/route.test.ts new file mode 100644 index 000000000..56cae0934 --- /dev/null +++ b/src/app/api/it-hilfe/accept-offer-via-token/__tests__/route.test.ts @@ -0,0 +1,224 @@ +/** + * @jest-environment node + * + * Tests for POST /api/it-hilfe/accept-offer-via-token + * + * The route delegates state changes to @/lib/it-hilfe/accept-offer and + * token verification to @/lib/it-hilfe/offer-accept-tokens, so these tests + * mock both modules and verify the route's response mapping for each + * documented failure mode + the happy path. + */ + +const mockVerify = jest.fn() +const mockLookup = jest.fn() +const mockAccept = jest.fn() + +jest.mock('@/lib/it-hilfe/offer-accept-tokens', () => ({ + verifyOfferAcceptToken: (...args: unknown[]) => mockVerify(...args), +})) + +jest.mock('@/lib/it-hilfe/accept-offer', () => ({ + acceptOffer: (...args: unknown[]) => mockAccept(...args), + lookupOfferRequestId: (...args: unknown[]) => mockLookup(...args), +})) + +jest.mock('@/lib/api/helpers', () => { + const { NextResponse } = jest.requireActual('next/server') + return { + apiSuccess: (data: unknown, status = 200) => NextResponse.json({ success: true, data }, { status }), + apiError: (_err: unknown, msg: string, status = 500) => NextResponse.json({ success: false, error: msg }, { status }), + apiNotFound: (msg: string) => NextResponse.json({ success: false, error: msg }, { status: 404 }), + apiBadRequest: (msg: string) => NextResponse.json({ success: false, error: msg }, { status: 400 }), + } +}) + +jest.mock('@/lib/logger', () => ({ + logger: { info: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() }, +})) + +jest.mock('@/config/error-messages', () => ({ + ERROR_MESSAGES: { INTERNAL_SERVER_ERROR: 'Server error' }, +})) + +import { NextRequest } from 'next/server' +import { POST } from '../route' + +const VALID_OFFER_ID = '11111111-2222-3333-4444-555555555555' +const VALID_REQUEST_ID = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' +const VALID_HELPER_ID = '00000000-1111-2222-3333-444444444444' +const VALID_TOKEN = 'fake-token-string' + +function makeRequest(body: unknown): NextRequest { + return new NextRequest('http://localhost/api/it-hilfe/accept-offer-via-token', { + method: 'POST', + body: typeof body === 'string' ? body : JSON.stringify(body), + headers: { 'content-type': 'application/json' }, + }) +} + +beforeEach(() => { + jest.clearAllMocks() +}) + +// ============================================================================ +// Happy path +// ============================================================================ + +describe('POST /api/it-hilfe/accept-offer-via-token — happy path', () => { + it('accepts a valid token and returns 200 with requestId + helperId', async () => { + mockVerify.mockReturnValueOnce({ ok: true, offerId: VALID_OFFER_ID, expiresAt: new Date() }) + mockLookup.mockResolvedValueOnce(VALID_REQUEST_ID) + mockAccept.mockResolvedValueOnce({ + ok: true, + requestId: VALID_REQUEST_ID, + offerId: VALID_OFFER_ID, + helperId: VALID_HELPER_ID, + }) + + const res = await POST(makeRequest({ token: VALID_TOKEN })) + expect(res.status).toBe(200) + const body = await res.json() + expect(body).toEqual({ + success: true, + data: { requestId: VALID_REQUEST_ID, helperId: VALID_HELPER_ID }, + }) + + expect(mockVerify).toHaveBeenCalledWith(VALID_TOKEN) + expect(mockLookup).toHaveBeenCalledWith(VALID_OFFER_ID) + expect(mockAccept).toHaveBeenCalledWith({ + requestId: VALID_REQUEST_ID, + offerId: VALID_OFFER_ID, + acceptingUserId: null, + }) + }) +}) + +// ============================================================================ +// Body validation +// ============================================================================ + +describe('body validation', () => { + it('returns 400 when body is missing token field', async () => { + const res = await POST(makeRequest({})) + expect(res.status).toBe(400) + expect(mockVerify).not.toHaveBeenCalled() + }) + + it('returns 400 when token is not a string', async () => { + const res = await POST(makeRequest({ token: 123 })) + expect(res.status).toBe(400) + expect(mockVerify).not.toHaveBeenCalled() + }) + + it('returns 400 when body is invalid JSON', async () => { + const res = await POST(makeRequest('{ not json')) + expect(res.status).toBe(400) + expect(mockVerify).not.toHaveBeenCalled() + }) +}) + +// ============================================================================ +// Token verify failures +// ============================================================================ + +describe('token verify failures', () => { + it('returns 400 with reason=malformed when verify says malformed', async () => { + mockVerify.mockReturnValueOnce({ ok: false, reason: 'malformed' }) + const res = await POST(makeRequest({ token: 'garbage' })) + expect(res.status).toBe(400) + const body = await res.json() + expect(body.reason).toBe('malformed') + expect(mockLookup).not.toHaveBeenCalled() + expect(mockAccept).not.toHaveBeenCalled() + }) + + it('returns 410 with reason=expired when verify says expired', async () => { + mockVerify.mockReturnValueOnce({ ok: false, reason: 'expired' }) + const res = await POST(makeRequest({ token: 'old-token' })) + expect(res.status).toBe(410) + const body = await res.json() + expect(body.reason).toBe('expired') + }) + + it('returns 400 with reason=invalid_signature when verify says invalid_signature', async () => { + mockVerify.mockReturnValueOnce({ ok: false, reason: 'invalid_signature' }) + const res = await POST(makeRequest({ token: 'tampered' })) + expect(res.status).toBe(400) + const body = await res.json() + expect(body.reason).toBe('invalid_signature') + }) +}) + +// ============================================================================ +// Offer lookup failures +// ============================================================================ + +describe('offer lookup', () => { + it('returns 404 when the offer ID encoded in the token has no row', async () => { + mockVerify.mockReturnValueOnce({ ok: true, offerId: VALID_OFFER_ID, expiresAt: new Date() }) + mockLookup.mockResolvedValueOnce(null) + const res = await POST(makeRequest({ token: VALID_TOKEN })) + expect(res.status).toBe(404) + expect(mockAccept).not.toHaveBeenCalled() + }) +}) + +// ============================================================================ +// acceptOffer state failures (mapped to HTTP) +// ============================================================================ + +describe('acceptOffer state failures', () => { + beforeEach(() => { + mockVerify.mockReturnValue({ ok: true, offerId: VALID_OFFER_ID, expiresAt: new Date() }) + mockLookup.mockResolvedValue(VALID_REQUEST_ID) + }) + + it('returns 404 on request_not_found', async () => { + mockAccept.mockResolvedValueOnce({ ok: false, reason: 'request_not_found' }) + const res = await POST(makeRequest({ token: VALID_TOKEN })) + expect(res.status).toBe(404) + expect((await res.json()).reason).toBe('request_not_found') + }) + + it('returns 404 on offer_not_found', async () => { + mockAccept.mockResolvedValueOnce({ ok: false, reason: 'offer_not_found' }) + const res = await POST(makeRequest({ token: VALID_TOKEN })) + expect(res.status).toBe(404) + expect((await res.json()).reason).toBe('offer_not_found') + }) + + it('returns 409 on request_not_open (already matched/completed)', async () => { + mockAccept.mockResolvedValueOnce({ ok: false, reason: 'request_not_open' }) + const res = await POST(makeRequest({ token: VALID_TOKEN })) + expect(res.status).toBe(409) + expect((await res.json()).reason).toBe('request_not_open') + }) + + it('returns 409 on offer_not_pending (already accepted/rejected/withdrawn)', async () => { + mockAccept.mockResolvedValueOnce({ ok: false, reason: 'offer_not_pending' }) + const res = await POST(makeRequest({ token: VALID_TOKEN })) + expect(res.status).toBe(409) + expect((await res.json()).reason).toBe('offer_not_pending') + }) + + it('returns 403 on not_authorized (defensive — should not happen with null acceptingUserId)', async () => { + mockAccept.mockResolvedValueOnce({ ok: false, reason: 'not_authorized' }) + const res = await POST(makeRequest({ token: VALID_TOKEN })) + expect(res.status).toBe(403) + expect((await res.json()).reason).toBe('not_authorized') + }) +}) + +// ============================================================================ +// Unexpected errors +// ============================================================================ + +describe('unexpected errors', () => { + it('returns 500 when acceptOffer throws', async () => { + mockVerify.mockReturnValueOnce({ ok: true, offerId: VALID_OFFER_ID, expiresAt: new Date() }) + mockLookup.mockResolvedValueOnce(VALID_REQUEST_ID) + mockAccept.mockRejectedValueOnce(new Error('db connection lost')) + const res = await POST(makeRequest({ token: VALID_TOKEN })) + expect(res.status).toBe(500) + }) +}) diff --git a/src/app/api/it-hilfe/accept-offer-via-token/route.ts b/src/app/api/it-hilfe/accept-offer-via-token/route.ts new file mode 100644 index 000000000..329c8ad79 --- /dev/null +++ b/src/app/api/it-hilfe/accept-offer-via-token/route.ts @@ -0,0 +1,107 @@ +import { NextRequest, NextResponse } from 'next/server' +import { apiError, apiSuccess, apiBadRequest, apiNotFound } from '@/lib/api/helpers' +import { ERROR_MESSAGES } from '@/config/error-messages' +import { logger } from '@/lib/logger' +import { verifyOfferAcceptToken } from '@/lib/it-hilfe/offer-accept-tokens' +import { acceptOffer, lookupOfferRequestId, type AcceptOfferReason } from '@/lib/it-hilfe/accept-offer' + +/** + * POST /api/it-hilfe/accept-offer-via-token + * Body: { token: string } + * + * One-tap offer acceptance from an emailed link. The HMAC-signed token + * is the proof of authorization — it encodes the offerId and was sent + * to the request owner's verified email when the offer was created. + * + * The page route at /it-hilfe/accept (commit 2b-2) renders a single + * "Confirm" button that POSTs to this endpoint, deliberately keeping + * the state-mutating action behind a click to defeat email-prefetcher + * pre-clicks. + * + * Returns the requestId on success so the page route can redirect to + * /it-hilfe/?accepted=1. + */ +export async function POST(request: NextRequest) { + try { + const body = await request.json().catch(() => null) + const token = body && typeof body.token === 'string' ? body.token : null + if (!token) { + return apiBadRequest('Token fehlt') + } + + const verifyResult = verifyOfferAcceptToken(token) + if (!verifyResult.ok) { + return badRequestForVerifyReason(verifyResult.reason) + } + + const { offerId } = verifyResult + const requestId = await lookupOfferRequestId(offerId) + if (!requestId) { + return apiNotFound('Angebot') + } + + const result = await acceptOffer({ + requestId, + offerId, + acceptingUserId: null, // token-driven; auth established by signature + }) + + if (!result.ok) { + return badRequestForAcceptReason(result.reason) + } + + logger.info('Accepted offer via token', { requestId, offerId, helperId: result.helperId }) + return apiSuccess({ requestId: result.requestId, helperId: result.helperId }) + } catch (error) { + logger.error('Error accepting offer via token', { error }) + return apiError(error, ERROR_MESSAGES.INTERNAL_SERVER_ERROR) + } +} + +function badRequestForVerifyReason(reason: 'malformed' | 'expired' | 'invalid_signature'): NextResponse { + // 410 Gone for expired; 400 for the rest. Lets the page route distinguish. + const messages: Record = { + malformed: 'Token ungültig', + expired: 'Dieser Link ist abgelaufen', + invalid_signature: 'Token ungültig', + } + const status = reason === 'expired' ? 410 : 400 + return NextResponse.json( + { success: false, error: messages[reason], reason }, + { status } + ) +} + +function badRequestForAcceptReason(reason: AcceptOfferReason): NextResponse { + // request_not_found / offer_not_found → 404 + // offer_not_pending / request_not_open → 409 Conflict (state-level failure) + // not_authorized → 403 (should not happen on this route since acceptingUserId is null, + // but mapped defensively) + switch (reason) { + case 'request_not_found': + return NextResponse.json( + { success: false, error: 'Anfrage nicht gefunden', reason }, + { status: 404 } + ) + case 'offer_not_found': + return NextResponse.json( + { success: false, error: 'Angebot nicht gefunden', reason }, + { status: 404 } + ) + case 'not_authorized': + return NextResponse.json( + { success: false, error: 'Nicht berechtigt', reason }, + { status: 403 } + ) + case 'request_not_open': + return NextResponse.json( + { success: false, error: 'Diese Anfrage kann keine Angebote mehr akzeptieren', reason }, + { status: 409 } + ) + case 'offer_not_pending': + return NextResponse.json( + { success: false, error: 'Dieses Angebot wurde bereits bearbeitet', reason }, + { status: 409 } + ) + } +} diff --git a/src/lib/it-hilfe/accept-offer.ts b/src/lib/it-hilfe/accept-offer.ts index 560d39e97..5e887dc43 100644 --- a/src/lib/it-hilfe/accept-offer.ts +++ b/src/lib/it-hilfe/accept-offer.ts @@ -68,6 +68,20 @@ const offTable = getTableName(itHilfeOffers) const uTable = getTableName(users) const convTable = getTableName(conversations) +/** + * Resolve an offer's parent requestId. Returns null if the offer doesn't + * exist. Used by the token-driven accept route, where the signed token + * only encodes the offerId and the route needs the requestId to call + * acceptOffer(). + */ +export async function lookupOfferRequestId(offerId: string): Promise { + const result = await db.execute(sql` + SELECT request_id FROM ${sql.raw(offTable)} WHERE id = ${offerId} + `) + if (result.rows.length === 0) return null + return (result.rows[0] as unknown as { request_id: string }).request_id +} + /** * Accept an offer atomically. Fetches request + offer, validates state, * mutates inside a transaction, then triggers notifications (fire-and-forget).