feat(it-hilfe): POST /api/it-hilfe/accept-offer-via-token route + lookupOfferRequestId

Commit 2b-1 of the one-tap accept feature (split from the original 2b
plan: API route now, page route to follow). The new endpoint accepts
a signed token in its body, verifies it via verifyOfferAcceptToken,
resolves the offer's parent requestId via the new lookupOfferRequestId
helper, then delegates to acceptOffer with acceptingUserId: null
(authorization is established by the signature, not a session).

HTTP response mapping:
  200  → accepted; body has {requestId, helperId}
  400  → malformed body / token / signature
  410  → expired token (deliberately distinct from 400 so the page
         route in commit 2b-2 can render an "expired link" state)
  403  → not_authorized (defensive; shouldn't fire on this route)
  404  → request_not_found / offer_not_found / offer row vanished
  409  → request_not_open / offer_not_pending (state-level conflict)
  500  → anything thrown

Why POST not GET: the action is state-mutating. Email clients
(Gmail's image proxy, link-preview services) prefetch GET links and
would auto-accept the offer without the requester clicking. The
follow-up page route at /it-hilfe/accept renders a single "Confirm"
button that POSTs here, keeping the mutation behind a real click.

Why null acceptingUserId: the token itself is the proof that the
caller is the request owner — it was signed and sent to their
verified email. The helper's identity check is skipped on this path.
The defensive 'not_authorized' mapping covers the case where the
helper internals change later.

Also: added lookupOfferRequestId(offerId) to accept-offer.ts. The
token only encodes offerId; acceptOffer requires both IDs.

Tests: 14 route tests covering happy path, body validation, all 3
verify-failure shapes, missing-offer, all 5 acceptOffer Result reasons,
and unexpected throws. Existing accept-route tests (6) + token helper
tests (16) still pass — 36 total.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
g-butandClaude Opus 4.7 committed 2026-05-25 15:10:09 +02:00
1 parent 3d23c1eace
commit 0d22febdab
3 files changed
+345

No files matched your search

@@ -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)
})
})
@@ -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/<requestId>?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<typeof reason, string> = {
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 }
)
}
}
+14
View File
@@ -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<string | null> {
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).