diff --git a/__tests__/api/disputes-workflow.test.ts b/__tests__/api/disputes-workflow.test.ts new file mode 100644 index 0000000..b899f94 --- /dev/null +++ b/__tests__/api/disputes-workflow.test.ts @@ -0,0 +1,552 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { NextRequest } from 'next/server' + +import { + DisputeConflictError, + DisputeForbiddenError, + DisputeValidationError, +} from '@/lib/disputes/types' + +const { mockService } = vi.hoisted(() => ({ + mockService: { + createDispute: vi.fn(), + submitEvidence: vi.fn(), + getDispute: vi.fn(), + resolveDispute: vi.fn(), + reconcileResolution: vi.fn(), + }, +})) + +const { sessionState } = vi.hoisted(() => ({ + sessionState: { + token: 'token' as string | null, + payload: { walletAddress: 'GWALLET', jti: 'jti-1' } as Record | null, + }, +})) + +vi.mock('@/lib/auth/session', () => ({ + readAccessToken: vi.fn(() => sessionState.token), + verifyAccessToken: vi.fn(() => sessionState.payload), +})) + +vi.mock('@/lib/disputes', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, disputeWorkflowService: mockService } +}) + +import { POST as createDispute } from '@/app/api/contracts/[id]/disputes/route' +import { GET as getDispute } from '@/app/api/disputes/[id]/route' +import { + GET as getEvidence, + POST as submitEvidence, +} from '@/app/api/disputes/[id]/evidence/route' +import { POST as resolveDispute } from '@/app/api/disputes/[id]/resolve/route' + +const CONTRACT_ID = 'b3f1c2d4-1111-4111-8111-111111111111' +const DISPUTE_ID = 'a1f2c3d4-2222-4222-8222-222222222222' + +function context(id: string) { + return { params: Promise.resolve({ id }) } +} + +function jsonRequest( + url: string, + body: unknown, + headers: Record = {} +) { + return new NextRequest( + new Request(url, { + method: 'POST', + headers: { 'content-type': 'application/json', ...headers }, + body: JSON.stringify(body), + }) + ) +} + +function getRequest(url: string) { + return new NextRequest(new Request(url)) +} + +const createdDispute = { + id: DISPUTE_ID, + contractId: CONTRACT_ID, + status: 'open', + reason: 'The delivered work does not match the contract', +} + +beforeEach(() => { + vi.clearAllMocks() + sessionState.token = 'token' + sessionState.payload = { walletAddress: 'GWALLET', jti: 'jti-1' } +}) + +describe('POST /api/contracts/:id/disputes', () => { + it('requires authentication', async () => { + sessionState.token = null + const response = await createDispute( + jsonRequest(`http://localhost/api/contracts/${CONTRACT_ID}/disputes`, {}, { + 'idempotency-key': 'key-00000001', + }), + context(CONTRACT_ID) + ) + expect(response.status).toBe(401) + expect((await response.json()).code).toBe('AUTH_REQUIRED') + }) + + it('rejects malformed ids and bodies', async () => { + const badId = await createDispute( + jsonRequest('http://localhost/api/contracts/42/disputes', {}), + context('42') + ) + expect(badId.status).toBe(400) + expect((await badId.json()).code).toBe('INVALID_ID') + + const badBody = await createDispute( + new NextRequest( + new Request(`http://localhost/api/contracts/${CONTRACT_ID}/disputes`, { + method: 'POST', + body: 'not-json', + headers: { 'content-type': 'application/json' }, + }) + ), + context(CONTRACT_ID) + ) + expect(badBody.status).toBe(400) + expect((await badBody.json()).code).toBe('INVALID_JSON') + }) + + it('requires an idempotency key', async () => { + const response = await createDispute( + jsonRequest(`http://localhost/api/contracts/${CONTRACT_ID}/disputes`, { + reason: 'The delivered work does not match the contract', + milestoneId: 'milestone-1', + }), + context(CONTRACT_ID) + ) + expect(response.status).toBe(422) + expect((await response.json()).code).toBe('DISPUTE_VALIDATION_ERROR') + }) + + it('creates a dispute and returns 201', async () => { + mockService.createDispute.mockResolvedValue({ + dispute: createdDispute, + contractStatus: 'disputed', + replayed: false, + }) + + const response = await createDispute( + jsonRequest( + `http://localhost/api/contracts/${CONTRACT_ID}/disputes`, + { + reason: 'The delivered work does not match the contract', + milestoneId: 'milestone-1', + evidence: [{ type: 'url', url: 'https://proof.test/1' }], + }, + { 'idempotency-key': 'key-00000001' } + ), + context(CONTRACT_ID) + ) + + expect(response.status).toBe(201) + const body = await response.json() + expect(body.dispute.id).toBe(DISPUTE_ID) + expect(body.contractStatus).toBe('disputed') + expect(mockService.createDispute).toHaveBeenCalledWith( + expect.objectContaining({ + contractId: CONTRACT_ID, + actorWalletAddress: 'GWALLET', + idempotencyKey: 'key-00000001', + }) + ) + }) + + it('replays an idempotent creation with 200', async () => { + mockService.createDispute.mockResolvedValue({ + dispute: createdDispute, + contractStatus: 'disputed', + replayed: true, + }) + + const response = await createDispute( + jsonRequest( + `http://localhost/api/contracts/${CONTRACT_ID}/disputes`, + { reason: 'The delivered work does not match the contract', milestoneId: 'm-1' }, + { 'idempotency-key': 'key-00000001' } + ), + context(CONTRACT_ID) + ) + + expect(response.status).toBe(200) + expect((await response.json()).replayed).toBe(true) + }) + + it('maps authorization and conflict errors consistently', async () => { + mockService.createDispute.mockRejectedValueOnce(new DisputeForbiddenError()) + const forbidden = await createDispute( + jsonRequest( + `http://localhost/api/contracts/${CONTRACT_ID}/disputes`, + { reason: 'The delivered work does not match the contract' }, + { 'idempotency-key': 'key-00000002' } + ), + context(CONTRACT_ID) + ) + expect(forbidden.status).toBe(403) + expect((await forbidden.json()).code).toBe('DISPUTE_FORBIDDEN') + + mockService.createDispute.mockRejectedValueOnce( + new DisputeConflictError('already active', 'DISPUTE_ALREADY_EXISTS', { + existingDisputeId: DISPUTE_ID, + }) + ) + const conflict = await createDispute( + jsonRequest( + `http://localhost/api/contracts/${CONTRACT_ID}/disputes`, + { reason: 'The delivered work does not match the contract' }, + { 'idempotency-key': 'key-00000003' } + ), + context(CONTRACT_ID) + ) + expect(conflict.status).toBe(409) + const conflictBody = await conflict.json() + expect(conflictBody.existingDisputeId).toBe(DISPUTE_ID) + }) +}) + +describe('GET /api/disputes/:id', () => { + it('returns the dispute for an authorized actor', async () => { + mockService.getDispute.mockResolvedValue({ + dispute: createdDispute, + evidence: [], + resolutionAttempt: null, + attempts: [], + auditTrail: [], + }) + + const response = await getDispute( + getRequest(`http://localhost/api/disputes/${DISPUTE_ID}`), + context(DISPUTE_ID) + ) + expect(response.status).toBe(200) + expect((await response.json()).dispute.id).toBe(DISPUTE_ID) + }) + + it('returns 403 for unauthorized users without leaking details', async () => { + mockService.getDispute.mockRejectedValue(new DisputeForbiddenError()) + + const response = await getDispute( + getRequest(`http://localhost/api/disputes/${DISPUTE_ID}`), + context(DISPUTE_ID) + ) + expect(response.status).toBe(403) + const body = await response.json() + expect(body.code).toBe('DISPUTE_FORBIDDEN') + expect(body.evidence).toBeUndefined() + }) +}) + +describe('POST /api/disputes/:id/evidence', () => { + it('stores evidence references and returns 201', async () => { + mockService.submitEvidence.mockResolvedValue({ + evidence: [{ id: 'evidence-1', referenceUrl: 'https://proof.test/1' }], + duplicates: [], + }) + + const response = await submitEvidence( + jsonRequest( + `http://localhost/api/disputes/${DISPUTE_ID}/evidence`, + { references: [{ type: 'url', url: 'https://proof.test/1' }] }, + { 'idempotency-key': 'evidence-key-01' } + ), + context(DISPUTE_ID) + ) + + expect(response.status).toBe(201) + const body = await response.json() + expect(body.evidence).toHaveLength(1) + expect(mockService.submitEvidence).toHaveBeenCalledWith( + expect.objectContaining({ disputeId: DISPUTE_ID, actorWalletAddress: 'GWALLET' }) + ) + }) + + it('reports a fully duplicate submission as 200 with no new rows', async () => { + mockService.submitEvidence.mockResolvedValue({ + evidence: [], + duplicates: ['https://proof.test/1'], + }) + + const response = await submitEvidence( + jsonRequest( + `http://localhost/api/disputes/${DISPUTE_ID}/evidence`, + { references: [{ type: 'url', url: 'https://proof.test/1' }] }, + { 'idempotency-key': 'evidence-key-02' } + ), + context(DISPUTE_ID) + ) + + expect(response.status).toBe(200) + expect((await response.json()).replayed).toBe(true) + }) + + it('rejects evidence without references or description', async () => { + const response = await submitEvidence( + jsonRequest( + `http://localhost/api/disputes/${DISPUTE_ID}/evidence`, + {}, + { 'idempotency-key': 'evidence-key-03' } + ), + context(DISPUTE_ID) + ) + expect(response.status).toBe(422) + }) + + it('maps forbidden submissions to 403', async () => { + mockService.submitEvidence.mockRejectedValue(new DisputeForbiddenError()) + + const response = await submitEvidence( + jsonRequest( + `http://localhost/api/disputes/${DISPUTE_ID}/evidence`, + { references: [{ type: 'url', url: 'https://proof.test/2' }] }, + { 'idempotency-key': 'evidence-key-04' } + ), + context(DISPUTE_ID) + ) + expect(response.status).toBe(403) + }) + + it('lists evidence for authorized actors', async () => { + mockService.getDispute.mockResolvedValue({ + dispute: createdDispute, + evidence: [{ id: 'evidence-1' }], + resolutionAttempt: null, + attempts: [], + auditTrail: [], + }) + + const response = await getEvidence( + getRequest(`http://localhost/api/disputes/${DISPUTE_ID}/evidence`), + context(DISPUTE_ID) + ) + expect(response.status).toBe(200) + expect((await response.json()).evidence).toHaveLength(1) + }) +}) + +describe('POST /api/disputes/:id/resolve', () => { + const attempt = { + id: 'attempt-1', + status: 'confirmed', + outcome: 'resolved_freelancer', + txHash: 'tx-1', + } + + it('returns 200 once the resolution is confirmed on-chain', async () => { + mockService.resolveDispute.mockResolvedValue({ + state: 'confirmed', + dispute: { ...createdDispute, status: 'resolved_freelancer' }, + attempt, + contractStatus: 'completed', + replayed: false, + retryable: false, + }) + + const response = await resolveDispute( + jsonRequest( + `http://localhost/api/disputes/${DISPUTE_ID}/resolve`, + { + outcome: 'resolved_freelancer', + reasons: 'Evidence shows the freelancer delivered the agreed work', + metadata: { evidenceReviewed: true }, + }, + { 'idempotency-key': 'resolve-key-001' } + ), + context(DISPUTE_ID) + ) + + expect(response.status).toBe(200) + const body = await response.json() + expect(body.state).toBe('confirmed') + expect(body.contractStatus).toBe('completed') + expect(mockService.resolveDispute).toHaveBeenCalledWith( + expect.objectContaining({ + disputeId: DISPUTE_ID, + actorWalletAddress: 'GWALLET', + outcome: 'resolved_freelancer', + idempotencyKey: 'resolve-key-001', + }) + ) + }) + + it('returns 202 while the transaction is pending', async () => { + mockService.resolveDispute.mockResolvedValue({ + state: 'pending', + dispute: createdDispute, + attempt: { ...attempt, status: 'pending', txHash: 'tx-pending' }, + contractStatus: 'disputed', + replayed: false, + retryable: true, + }) + + const response = await resolveDispute( + jsonRequest( + `http://localhost/api/disputes/${DISPUTE_ID}/resolve`, + { outcome: 'resolved_client', reasons: 'Refund authorised after evidence review' }, + { 'idempotency-key': 'resolve-key-002' } + ), + context(DISPUTE_ID) + ) + + expect(response.status).toBe(202) + expect((await response.json()).state).toBe('pending') + }) + + it('distinguishes recoverable RPC failures (503) from reverted transactions (502)', async () => { + mockService.resolveDispute.mockResolvedValueOnce({ + state: 'failed', + dispute: createdDispute, + attempt, + contractStatus: 'disputed', + replayed: false, + retryable: true, + }) + + const recoverable = await resolveDispute( + jsonRequest( + `http://localhost/api/disputes/${DISPUTE_ID}/resolve`, + { outcome: 'resolved_client', reasons: 'Refund authorised after evidence review' }, + { 'idempotency-key': 'resolve-key-003' } + ), + context(DISPUTE_ID) + ) + expect(recoverable.status).toBe(503) + + mockService.resolveDispute.mockResolvedValueOnce({ + state: 'failed', + dispute: createdDispute, + attempt, + contractStatus: 'disputed', + replayed: false, + retryable: false, + }) + + const reverted = await resolveDispute( + jsonRequest( + `http://localhost/api/disputes/${DISPUTE_ID}/resolve`, + { outcome: 'resolved_client', reasons: 'Refund authorised after evidence review' }, + { 'idempotency-key': 'resolve-key-004' } + ), + context(DISPUTE_ID) + ) + expect(reverted.status).toBe(502) + }) + + it('validates the resolution reason and outcome before calling the service', async () => { + const missingReason = await resolveDispute( + jsonRequest( + `http://localhost/api/disputes/${DISPUTE_ID}/resolve`, + { outcome: 'resolved_client', reasons: 'short' }, + { 'idempotency-key': 'resolve-key-005' } + ), + context(DISPUTE_ID) + ) + expect(missingReason.status).toBe(422) + + const badOutcome = await resolveDispute( + jsonRequest( + `http://localhost/api/disputes/${DISPUTE_ID}/resolve`, + { outcome: 'refund-now', reasons: 'A sufficiently long resolution reason' }, + { 'idempotency-key': 'resolve-key-006' } + ), + context(DISPUTE_ID) + ) + expect(badOutcome.status).toBe(422) + expect(mockService.resolveDispute).not.toHaveBeenCalled() + }) + + it('maps duplicate resolutions and forbidden actors to 409/403', async () => { + mockService.resolveDispute.mockRejectedValueOnce( + new DisputeConflictError('already resolved', 'RESOLUTION_ALREADY_FINALISED') + ) + const conflict = await resolveDispute( + jsonRequest( + `http://localhost/api/disputes/${DISPUTE_ID}/resolve`, + { outcome: 'resolved_client', reasons: 'Refund authorised after evidence review' }, + { 'idempotency-key': 'resolve-key-007' } + ), + context(DISPUTE_ID) + ) + expect(conflict.status).toBe(409) + + mockService.resolveDispute.mockRejectedValueOnce(new DisputeForbiddenError()) + const forbidden = await resolveDispute( + jsonRequest( + `http://localhost/api/disputes/${DISPUTE_ID}/resolve`, + { outcome: 'resolved_client', reasons: 'Refund authorised after evidence review' }, + { 'idempotency-key': 'resolve-key-008' } + ), + context(DISPUTE_ID) + ) + expect(forbidden.status).toBe(403) + }) + + it('supports reconciling a pending resolution', async () => { + mockService.reconcileResolution.mockResolvedValue({ + state: 'confirmed', + dispute: createdDispute, + attempt, + contractStatus: 'completed', + replayed: true, + retryable: false, + }) + + const response = await resolveDispute( + jsonRequest( + `http://localhost/api/disputes/${DISPUTE_ID}/resolve`, + { reconcile: true }, + { 'idempotency-key': 'resolve-key-009' } + ), + context(DISPUTE_ID) + ) + expect(response.status).toBe(200) + expect(mockService.reconcileResolution).toHaveBeenCalledWith(DISPUTE_ID, 'GWALLET') + + mockService.reconcileResolution.mockResolvedValue(null) + const none = await resolveDispute( + jsonRequest( + `http://localhost/api/disputes/${DISPUTE_ID}/resolve`, + { reconcile: true }, + { 'idempotency-key': 'resolve-key-010' } + ), + context(DISPUTE_ID) + ) + expect(none.status).toBe(409) + }) + + it('rejects invalid JSON bodies with 400', async () => { + const response = await resolveDispute( + new NextRequest( + new Request(`http://localhost/api/disputes/${DISPUTE_ID}/resolve`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: '{bad', + }) + ), + context(DISPUTE_ID) + ) + expect(response.status).toBe(400) + }) + + it('maps validation errors from the service to 422', async () => { + mockService.resolveDispute.mockRejectedValue( + new DisputeValidationError('metadata exceeds the 16 KB limit') + ) + const response = await resolveDispute( + jsonRequest( + `http://localhost/api/disputes/${DISPUTE_ID}/resolve`, + { outcome: 'resolved_client', reasons: 'Refund authorised after evidence review' }, + { 'idempotency-key': 'resolve-key-011' } + ), + context(DISPUTE_ID) + ) + expect(response.status).toBe(422) + }) +}) diff --git a/__tests__/disputes/authorization.test.ts b/__tests__/disputes/authorization.test.ts new file mode 100644 index 0000000..0c7906f --- /dev/null +++ b/__tests__/disputes/authorization.test.ts @@ -0,0 +1,132 @@ +import { describe, it, expect } from 'vitest' + +import { + canCreateDispute, + canResolveDispute, + canSubmitEvidence, + canViewDispute, + classifyActor, + isIntegerId, + isUuid, +} from '@/lib/disputes/authorization' +import type { ContractRecord, DisputeActor, DisputeRecord } from '@/lib/disputes/types' + +const contract: ContractRecord = { + id: 'contract-1', + clientId: 'user-client', + freelancerId: 'user-freelancer', + status: 'disputed', + escrowStatus: 'funded', + escrowAddress: 'CESCROW', + arbiterAddress: 'GArbiterWallet', + designatedResolverId: 'user-designated', + activeDisputeId: 'dispute-1', + totalAmount: '100', + currency: 'USDC', +} + +const dispute: DisputeRecord = { + id: 'dispute-1', + contractId: contract.id, + milestoneId: 'milestone-1', + raisedBy: 'client', + raisedByUserId: 'user-client', + reason: 'reason', + desiredOutcome: null, + status: 'open', + resolverId: null, + resolutionNotes: null, + resolutionMetadata: {}, + clientRefundAmount: null, + freelancerPayoutAmount: null, + resolvedAt: null, + creationIdempotencyKey: null, + lastResolutionAttemptId: null, + createdAt: '2026-01-01T00:00:00Z', + updatedAt: '2026-01-01T00:00:00Z', +} + +function actor(overrides: Partial & { userId: string }): DisputeActor { + return { + walletAddress: 'GSomeoneElse', + role: 'freelancer', + ...overrides, + } +} + +const client = actor({ userId: 'user-client', walletAddress: 'GClient', role: 'client' }) +const freelancer = actor({ userId: 'user-freelancer', walletAddress: 'GFreelancer' }) +const outsider = actor({ userId: 'user-outsider', walletAddress: 'GOutsider' }) +const arbiter = actor({ userId: 'user-arbiter', walletAddress: 'garbiterwallet', role: 'client' }) +const designated = actor({ userId: 'user-designated', walletAddress: 'GDesignated' }) +const admin = actor({ userId: 'user-admin', walletAddress: 'GAdmin', role: 'admin' }) + +describe('classifyActor', () => { + it('identifies each role from database-backed data', () => { + expect(classifyActor(client, contract)).toBe('participant') + expect(classifyActor(freelancer, contract)).toBe('participant') + expect(classifyActor(arbiter, contract)).toBe('arbiter') + expect(classifyActor(designated, contract)).toBe('designated_resolver') + expect(classifyActor(admin, contract)).toBe('admin') + expect(classifyActor(outsider, contract)).toBe('unrelated') + }) + + it('never trusts a wallet that merely resembles an address', () => { + expect( + classifyActor(actor({ userId: 'x', walletAddress: 'GArbiterWallet2' }), contract) + ).toBe('unrelated') + }) +}) + +describe('permissions', () => { + it('allows participants, arbiters and designated resolvers to create disputes', () => { + expect(canCreateDispute(client, contract)).toBe(true) + expect(canCreateDispute(freelancer, contract)).toBe(true) + expect(canCreateDispute(arbiter, contract)).toBe(true) + expect(canCreateDispute(designated, contract)).toBe(true) + expect(canCreateDispute(admin, contract)).toBe(true) + expect(canCreateDispute(outsider, contract)).toBe(false) + }) + + it('only allows participants, arbiters, designated resolvers or admins to view', () => { + expect(canViewDispute(client, contract, dispute)).toBe(true) + expect(canViewDispute(arbiter, contract, dispute)).toBe(true) + expect(canViewDispute(designated, contract, dispute)).toBe(true) + expect(canViewDispute(admin, contract, dispute)).toBe(true) + expect(canViewDispute(outsider, contract, dispute)).toBe(false) + }) + + it('allows the dispute raiser to read their own record even without a role', () => { + expect(canViewDispute(outsider, contract, { ...dispute, raisedByUserId: 'user-outsider' })).toBe(true) + }) + + it('restricts resolution to arbiters, designated resolvers and admins', () => { + expect(canResolveDispute(arbiter, contract)).toBe(true) + expect(canResolveDispute(designated, contract)).toBe(true) + expect(canResolveDispute(admin, contract)).toBe(true) + expect(canResolveDispute(client, contract)).toBe(false) + expect(canResolveDispute(freelancer, contract)).toBe(false) + expect(canResolveDispute(outsider, contract)).toBe(false) + }) + + it('lets participants submit evidence but not unrelated users', () => { + expect(canSubmitEvidence(client, contract)).toBe(true) + expect(canSubmitEvidence(freelancer, contract)).toBe(true) + expect(canSubmitEvidence(arbiter, contract)).toBe(true) + expect(canSubmitEvidence(outsider, contract)).toBe(false) + }) + + it('does not treat an unconfigured arbiter as authorized', () => { + const noArbiter = { ...contract, arbiterAddress: null } + expect(canResolveDispute(arbiter, noArbiter)).toBe(false) + }) +}) + +describe('id helpers', () => { + it('distinguishes canonical UUID disputes from legacy integer ids', () => { + expect(isUuid('a1f2c3d4-2222-4222-8222-222222222222')).toBe(true) + expect(isUuid('42')).toBe(false) + expect(isIntegerId('42')).toBe(true) + expect(isIntegerId('abc')).toBe(false) + }) +}) diff --git a/__tests__/disputes/fakeRepository.ts b/__tests__/disputes/fakeRepository.ts new file mode 100644 index 0000000..7bbd84b --- /dev/null +++ b/__tests__/disputes/fakeRepository.ts @@ -0,0 +1,415 @@ +/** + * In-memory DisputeRepository used by the dispute workflow tests. + * + * It mirrors the database guarantees that matter for correctness: + * • one active dispute per contract + * • one pending / one confirmed resolution attempt per dispute + * • duplicate evidence references are not inserted twice + * • audit rows are append-only + */ + +import { + DisputeConflictError, + type AuditEventRecord, + type ContractRecord, + type DisputeActor, + type DisputeAuditAction, + type DisputeRecord, + type EvidenceRecord, + type EvidenceType, + type MilestoneRecord, + type ResolutionAttemptRecord, +} from '@/lib/disputes/types' +import type { + ConfirmResolutionRow, + ConfirmResolutionResult, + CreateAttemptRow, + CreateDisputeRow, + DisputeRepository, +} from '@/lib/disputes/repository' + +let seq = 0 +function id(prefix: string): string { + seq += 1 + return `${prefix}-${String(seq).padStart(4, '0')}` +} + +const ACTIVE = ['open', 'under_review', 'escalated'] + +export class FakeDisputeRepository implements DisputeRepository { + users = new Map() + contracts = new Map() + milestones = new Map() + disputes = new Map() + evidence: EvidenceRecord[] = [] + attempts = new Map() + audits: AuditEventRecord[] = [] + available = true + + seedUser(actor: DisputeActor): DisputeActor { + this.users.set(actor.walletAddress.toLowerCase(), actor) + return actor + } + + seedContract(contract: ContractRecord): ContractRecord { + this.contracts.set(contract.id, contract) + return contract + } + + seedMilestone(milestone: MilestoneRecord): MilestoneRecord { + this.milestones.set(milestone.id, milestone) + return milestone + } + + seedDispute(dispute: Partial & { id: string; contractId: string }): DisputeRecord { + const now = new Date().toISOString() + const record: DisputeRecord = { + milestoneId: null, + raisedBy: 'client', + raisedByUserId: 'user-client', + reason: 'Seeded dispute reason', + desiredOutcome: null, + status: 'open', + resolverId: null, + resolutionNotes: null, + resolutionMetadata: {}, + clientRefundAmount: null, + freelancerPayoutAmount: null, + resolvedAt: null, + creationIdempotencyKey: null, + lastResolutionAttemptId: null, + createdAt: now, + updatedAt: now, + ...dispute, + } + this.disputes.set(record.id, record) + return record + } + + isAvailable(): boolean { + return this.available + } + + async findUserByWallet(walletAddress: string): Promise { + return this.users.get(walletAddress.toLowerCase()) ?? null + } + + async getContract(contractId: string): Promise { + return this.contracts.get(contractId) ?? null + } + + async getMilestone(milestoneId: string): Promise { + return this.milestones.get(milestoneId) ?? null + } + + async getDispute(disputeId: string): Promise { + return this.disputes.get(disputeId) ?? null + } + + async getDisputeByCreationKey(contractId: string, key: string) { + for (const dispute of this.disputes.values()) { + if (dispute.contractId === contractId && dispute.creationIdempotencyKey === key) { + return dispute + } + } + return null + } + + async getActiveDisputeForContract(contractId: string) { + for (const dispute of this.disputes.values()) { + if (dispute.contractId === contractId && ACTIVE.includes(dispute.status)) { + return dispute + } + } + return null + } + + async createDisputeAtomic(input: CreateDisputeRow) { + const contract = this.contracts.get(input.contractId) + if (!contract) return null + if (await this.getActiveDisputeForContract(input.contractId)) return null + + const now = new Date().toISOString() + const dispute: DisputeRecord = { + id: id('dispute'), + contractId: input.contractId, + milestoneId: input.milestoneId, + raisedBy: input.raisedBy, + raisedByUserId: input.raisedByUserId, + reason: input.reason, + desiredOutcome: input.desiredOutcome, + status: 'open', + resolverId: null, + resolutionNotes: null, + resolutionMetadata: {}, + clientRefundAmount: null, + freelancerPayoutAmount: null, + resolvedAt: null, + creationIdempotencyKey: input.idempotencyKey, + lastResolutionAttemptId: null, + createdAt: now, + updatedAt: now, + } + this.disputes.set(dispute.id, dispute) + this.contracts.set(contract.id, { + ...contract, + status: 'disputed', + activeDisputeId: dispute.id, + }) + this.audits.push({ + id: id('audit'), + disputeId: dispute.id, + contractId: contract.id, + actorUserId: input.raisedByUserId, + actorWallet: input.actorWallet, + action: 'dispute_created', + metadata: {}, + createdAt: now, + }) + return { dispute, contractStatus: 'disputed' as const } + } + + async listEvidence(disputeId: string): Promise { + return this.evidence.filter((item) => item.disputeId === disputeId) + } + + async getEvidenceByHash(disputeId: string, contentHash: string) { + return ( + this.evidence.find( + (item) => item.disputeId === disputeId && item.contentHash === contentHash + ) ?? null + ) + } + + async insertEvidence(input: { + disputeId: string + milestoneId: string | null + submittedByUserId: string + evidenceType: EvidenceType + referenceUrl: string + label: string | null + description: string | null + contentHash: string + actorWallet: string + contractId: string + }): Promise { + const exists = await this.getEvidenceByHash(input.disputeId, input.contentHash) + if (exists) return null + + const now = new Date().toISOString() + const record: EvidenceRecord = { + id: id('evidence'), + disputeId: input.disputeId, + milestoneId: input.milestoneId, + submittedByUserId: input.submittedByUserId, + evidenceType: input.evidenceType, + referenceUrl: input.referenceUrl, + label: input.label, + description: input.description, + contentHash: input.contentHash, + createdAt: now, + } + this.evidence.push(record) + this.audits.push({ + id: id('audit'), + disputeId: input.disputeId, + contractId: input.contractId, + actorUserId: input.submittedByUserId, + actorWallet: input.actorWallet, + action: 'evidence_submitted', + metadata: { reference: input.referenceUrl }, + createdAt: now, + }) + return record + } + + async getAttempt(attemptId: string) { + return this.attempts.get(attemptId) ?? null + } + + async getAttemptByKey(disputeId: string, key: string) { + for (const attempt of this.attempts.values()) { + if (attempt.disputeId === disputeId && attempt.idempotencyKey === key) { + return attempt + } + } + return null + } + + async getPendingAttempt(disputeId: string) { + for (const attempt of this.attempts.values()) { + if (attempt.disputeId === disputeId && attempt.status === 'pending') return attempt + } + return null + } + + async getLatestAttempt(disputeId: string) { + const list = await this.listAttempts(disputeId) + return list[0] ?? null + } + + async listAttempts(disputeId: string) { + return Array.from(this.attempts.values()) + .filter((attempt) => attempt.disputeId === disputeId) + .sort((a, b) => b.createdAt.localeCompare(a.createdAt)) + } + + async createAttempt(input: CreateAttemptRow): Promise { + // Synchronous checks (no await before the insert) mirror the unique + // indexes in migration 012: exactly one pending attempt can exist. + for (const attempt of this.attempts.values()) { + if ( + attempt.disputeId === input.disputeId && + attempt.idempotencyKey === input.idempotencyKey + ) { + throw new DisputeConflictError( + 'Duplicate attempt key', + 'IDEMPOTENCY_KEY_REUSED' + ) + } + if (attempt.disputeId === input.disputeId && attempt.status === 'pending') { + throw new DisputeConflictError( + 'Another resolution attempt is already in progress', + 'RESOLUTION_IN_PROGRESS' + ) + } + } + + const now = new Date().toISOString() + const attempt: ResolutionAttemptRecord = { + id: id('attempt'), + disputeId: input.disputeId, + requestedByUserId: input.requestedByUserId, + outcome: input.outcome, + reasons: input.reasons, + metadata: input.metadata, + status: 'pending', + onchain: input.onchain, + txHash: null, + ledger: null, + errorCode: null, + errorMessage: null, + retryOf: input.retryOf, + idempotencyKey: input.idempotencyKey, + submittedAt: now, + confirmedAt: null, + failedAt: null, + createdAt: now, + updatedAt: now, + } + this.attempts.set(attempt.id, attempt) + return attempt + } + + async updateAttempt( + attemptId: string, + patch: Partial + ): Promise { + const existing = this.attempts.get(attemptId) + if (!existing) return null + const updated: ResolutionAttemptRecord = { + ...existing, + ...Object.fromEntries( + Object.entries(patch).filter(([, value]) => value !== undefined) + ), + updatedAt: new Date().toISOString(), + } + this.attempts.set(attemptId, updated) + return updated + } + + async confirmResolution( + input: ConfirmResolutionRow + ): Promise { + const dispute = this.disputes.get(input.disputeId) + const attempt = this.attempts.get(input.attemptId) + if (!dispute || !attempt) return null + if (!ACTIVE.includes(dispute.status)) return null + if (attempt.status !== 'pending') return null + + const now = new Date().toISOString() + const updatedDispute: DisputeRecord = { + ...dispute, + status: input.outcome, + resolverId: input.resolverId, + resolutionNotes: input.reasons, + resolutionMetadata: input.metadata, + clientRefundAmount: input.clientRefundAmount, + freelancerPayoutAmount: input.freelancerPayoutAmount, + resolvedAt: now, + lastResolutionAttemptId: input.attemptId, + updatedAt: now, + } + const updatedAttempt: ResolutionAttemptRecord = { + ...attempt, + status: 'confirmed', + txHash: input.txHash ?? attempt.txHash, + ledger: input.ledger ?? attempt.ledger, + confirmedAt: now, + updatedAt: now, + } + this.disputes.set(dispute.id, updatedDispute) + this.attempts.set(attempt.id, updatedAttempt) + + const contract = this.contracts.get(input.contractId) + if (contract) { + this.contracts.set(contract.id, { + ...contract, + status: input.contractStatus, + activeDisputeId: null, + }) + } + + const audit: AuditEventRecord = { + id: id('audit'), + disputeId: dispute.id, + contractId: input.contractId, + actorUserId: input.resolverId, + actorWallet: input.actorWallet, + action: 'resolution_confirmed', + metadata: { attemptId: attempt.id, txHash: input.txHash }, + createdAt: now, + } + this.audits.push(audit) + + return { + attempt: updatedAttempt, + dispute: updatedDispute, + contractStatus: input.contractStatus, + audit, + } + } + + async appendAudit(input: { + disputeId: string | null + contractId: string + actorUserId: string | null + actorWallet: string | null + action: DisputeAuditAction + metadata?: Record + }): Promise { + const audit: AuditEventRecord = { + id: id('audit'), + disputeId: input.disputeId ?? '', + contractId: input.contractId, + actorUserId: input.actorUserId, + actorWallet: input.actorWallet, + action: input.action, + metadata: input.metadata ?? {}, + createdAt: new Date().toISOString(), + } + this.audits.push(audit) + return audit + } + + async listAudit(disputeId: string, limit: number): Promise { + return this.audits.filter((audit) => audit.disputeId === disputeId).slice(0, limit) + } + + async linkAttemptToDispute(disputeId: string, attemptId: string): Promise { + const dispute = this.disputes.get(disputeId) + if (dispute) { + this.disputes.set(disputeId, { ...dispute, lastResolutionAttemptId: attemptId }) + } + } +} diff --git a/__tests__/disputes/service.test.ts b/__tests__/disputes/service.test.ts new file mode 100644 index 0000000..f1caea9 --- /dev/null +++ b/__tests__/disputes/service.test.ts @@ -0,0 +1,847 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest' + +import { DisputeWorkflowService, evidenceFingerprint } from '@/lib/disputes/service' +import { + DisputeChainError, + DisputeConflictError, + DisputeError, + DisputeForbiddenError, + DisputeIneligibleError, + DisputeValidationError, + type ContractRecord, + type DisputeActor, + type ResolutionAttemptRecord, +} from '@/lib/disputes/types' +import type { + ChainResolutionRequest, + ChainResolutionSubmission, + DisputeChainGateway, +} from '@/lib/disputes/blockchain' +import { FakeDisputeRepository } from './fakeRepository' + +const CLIENT: DisputeActor = { + userId: 'user-client', + walletAddress: 'GCLIENTWALLET', + role: 'client', +} +const FREELANCER: DisputeActor = { + userId: 'user-freelancer', + walletAddress: 'GFREELANCERWALLET', + role: 'freelancer', +} +const OUTSIDER: DisputeActor = { + userId: 'user-outsider', + walletAddress: 'GOUTSIDERWALLET', + role: 'freelancer', +} +const ARBITER: DisputeActor = { + userId: 'user-arbiter', + walletAddress: 'GARBITERWALLET', + role: 'client', +} +const DESIGNATED: DisputeActor = { + userId: 'user-designated', + walletAddress: 'GDESIGNATEDWALLET', + role: 'freelancer', +} +const ADMIN: DisputeActor = { + userId: 'user-admin', + walletAddress: 'GADMINWALLET', + role: 'admin', +} + +class FakeChain implements DisputeChainGateway { + submissions: ChainResolutionRequest[] = [] + verified: string[] = [] + submission: ChainResolutionSubmission = { + txHash: 'tx-hash-1', + state: 'confirmed', + ledger: 42, + } + submissionError: Error | null = null + verification: 'confirmed' | 'failed' | 'pending' | 'unknown' = 'pending' + + async submitResolution(request: ChainResolutionRequest): Promise { + this.submissions.push(request) + if (this.submissionError) throw this.submissionError + return this.submission + } + + async verifyResolution(txHash: string): Promise<'confirmed' | 'failed' | 'pending' | 'unknown'> { + this.verified.push(txHash) + return this.verification + } +} + +interface Harness { + repo: FakeDisputeRepository + chain: FakeChain + service: DisputeWorkflowService + contract: ContractRecord +} + +function setup(overrides: Partial = {}): Harness { + const repo = new FakeDisputeRepository() + const chain = new FakeChain() + + repo.seedUser(CLIENT) + repo.seedUser(FREELANCER) + repo.seedUser(OUTSIDER) + repo.seedUser(ARBITER) + repo.seedUser(DESIGNATED) + repo.seedUser(ADMIN) + + const contract: ContractRecord = { + id: 'contract-1', + clientId: CLIENT.userId, + freelancerId: FREELANCER.userId, + status: 'active', + escrowStatus: 'funded', + escrowAddress: 'CESCROWCONTRACT', + arbiterAddress: ARBITER.walletAddress, + designatedResolverId: DESIGNATED.userId, + activeDisputeId: null, + totalAmount: '1000.000000', + currency: 'USDC', + ...overrides, + } + repo.seedContract(contract) + repo.seedMilestone({ + id: 'milestone-1', + contractId: contract.id, + status: 'submitted', + amount: '1000.000000', + }) + + return { + repo, + chain, + contract, + service: new DisputeWorkflowService(repo, chain), + } +} + +function creationInput(overrides: Record = {}) { + return { + contractId: 'contract-1', + actorWalletAddress: CLIENT.walletAddress, + reason: 'Deliverable does not match the agreed specification', + milestoneId: 'milestone-1', + idempotencyKey: 'create-key-0001', + ...overrides, + } +} + +function resolutionInput(overrides: Record = {}) { + return { + disputeId: '', + actorWalletAddress: ARBITER.walletAddress, + outcome: 'resolved_freelancer' as const, + reasons: 'Milestone evidence proves the freelancer delivered as specified', + metadata: { reviewedEvidence: true }, + idempotencyKey: 'resolve-key-0001', + ...overrides, + } +} + +async function createOpenDispute(harness: Harness, actor = CLIENT) { + const result = await harness.service.createDispute( + creationInput({ actorWalletAddress: actor.walletAddress }) as never + ) + return result.dispute +} + +beforeEach(() => { + // Each test builds its own harness; nothing global to reset. +}) + +describe('createDispute', () => { + it('creates a dispute for a contract participant and audits the transition', async () => { + const harness = setup() + + const result = await harness.service.createDispute( + creationInput({ evidence: [{ type: 'url', url: 'https://proof.example/1.pdf' }] }) as never + ) + + expect(result.replayed).toBe(false) + expect(result.dispute.status).toBe('open') + expect(result.dispute.raisedBy).toBe('client') + expect(result.contractStatus).toBe('disputed') + expect(harness.repo.contracts.get('contract-1')?.status).toBe('disputed') + expect(harness.repo.contracts.get('contract-1')?.activeDisputeId).toBe(result.dispute.id) + + const actions = harness.repo.audits.map((audit) => audit.action) + expect(actions).toContain('dispute_created') + }) + + it('allows the arbitrator and designated decision-maker to open a dispute', async () => { + const arbiterHarness = setup() + const arbiterResult = await arbiterHarness.service.createDispute( + creationInput({ actorWalletAddress: ARBITER.walletAddress }) as never + ) + expect(arbiterResult.dispute.raisedBy).toBe('admin') + + const designatedHarness = setup() + const designatedResult = await designatedHarness.service.createDispute( + creationInput({ actorWalletAddress: DESIGNATED.walletAddress }) as never + ) + expect(designatedResult.dispute.reason).toContain('Deliverable') + }) + + it('rejects unrelated users and records the authorization decision', async () => { + const harness = setup() + + await expect( + harness.service.createDispute( + creationInput({ actorWalletAddress: OUTSIDER.walletAddress }) as never + ) + ).rejects.toBeInstanceOf(DisputeForbiddenError) + + expect(harness.repo.disputes.size).toBe(0) + expect(harness.repo.audits.map((a) => a.action)).toContain('authorization_denied') + }) + + it('rejects unauthenticated wallets that have no platform account', async () => { + const harness = setup() + await expect( + harness.service.createDispute( + creationInput({ actorWalletAddress: 'GUNKNOWNTWALLET' }) as never + ) + ).rejects.toMatchObject({ code: 'USER_NOT_FOUND', status: 401 }) + }) + + it('rejects creation when the contract is not active or escrow is unfunded', async () => { + const completed = setup({ status: 'completed' }) + await expect( + completed.service.createDispute(creationInput() as never) + ).rejects.toBeInstanceOf(DisputeIneligibleError) + + const unfunded = setup({ escrowStatus: 'unfunded' }) + await expect( + unfunded.service.createDispute(creationInput() as never) + ).rejects.toBeInstanceOf(DisputeIneligibleError) + }) + + it('rejects duplicate disputes on the same contract', async () => { + const harness = setup() + await createOpenDispute(harness) + + await expect( + harness.service.createDispute( + creationInput({ idempotencyKey: 'create-key-0002' }) as never + ) + ).rejects.toMatchObject({ code: 'DISPUTE_ALREADY_EXISTS', status: 409 }) + }) + + it('replays the original dispute for an identical idempotent request', async () => { + const harness = setup() + const first = await createOpenDispute(harness) + const replay = await harness.service.createDispute(creationInput() as never) + + expect(replay.replayed).toBe(true) + expect(replay.dispute.id).toBe(first.id) + expect(harness.repo.disputes.size).toBe(1) + }) + + it('rejects milestones that belong to another contract', async () => { + const harness = setup() + harness.repo.seedMilestone({ + id: 'foreign-milestone', + contractId: 'other-contract', + status: 'submitted', + amount: '10', + }) + + await expect( + harness.service.createDispute( + creationInput({ milestoneId: 'foreign-milestone' }) as never + ) + ).rejects.toBeInstanceOf(DisputeValidationError) + }) + + it('requires a milestone for on-chain escrowed contracts', async () => { + const harness = setup() + await expect( + harness.service.createDispute( + creationInput({ milestoneId: undefined }) as never + ) + ).rejects.toBeInstanceOf(DisputeValidationError) + }) + + it('reports 503 when storage is unavailable', async () => { + const harness = setup() + harness.repo.available = false + await expect( + harness.service.createDispute(creationInput() as never) + ).rejects.toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }) + }) +}) + +describe('submitEvidence', () => { + it('stores references for participants and is idempotent per reference', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + const reference = { type: 'ipfs' as const, url: 'ipfs://bafyproof', label: 'proof' } + + const first = await harness.service.submitEvidence({ + disputeId: dispute.id, + actorWalletAddress: FREELANCER.walletAddress, + references: [reference], + idempotencyKey: 'evidence-key-1', + }) + expect(first.evidence).toHaveLength(1) + expect(first.duplicates).toHaveLength(0) + + const replay = await harness.service.submitEvidence({ + disputeId: dispute.id, + actorWalletAddress: FREELANCER.walletAddress, + references: [reference], + idempotencyKey: 'evidence-key-2', + }) + expect(replay.evidence).toHaveLength(0) + expect(replay.duplicates).toEqual([reference.url]) + expect(harness.repo.evidence).toHaveLength(1) + }) + + it('fingerprints include the label so distinct evidence is not merged', () => { + const a = evidenceFingerprint({ type: 'url', url: 'https://x.test/a' }) + const b = evidenceFingerprint({ + type: 'url', + url: 'https://x.test/a', + label: 'screenshot', + }) + expect(a).not.toBe(b) + }) + + it('forbids unrelated users from adding evidence', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + + await expect( + harness.service.submitEvidence({ + disputeId: dispute.id, + actorWalletAddress: OUTSIDER.walletAddress, + references: [{ type: 'url', url: 'https://x.test/leak' }], + idempotencyKey: 'evidence-key-3', + }) + ).rejects.toBeInstanceOf(DisputeForbiddenError) + }) + + it('allows the arbitrator to add evidence', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + + const result = await harness.service.submitEvidence({ + disputeId: dispute.id, + actorWalletAddress: ARBITER.walletAddress, + references: [{ type: 'transaction', url: 'https://stellar.test/tx/abc' }], + idempotencyKey: 'evidence-key-4', + }) + expect(result.evidence).toHaveLength(1) + }) + + it('refuses evidence on a closed dispute', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + const resolved = await harness.service.resolveDispute( + resolutionInput({ disputeId: dispute.id }) as never + ) + expect(resolved.state).toBe('confirmed') + + await expect( + harness.service.submitEvidence({ + disputeId: dispute.id, + actorWalletAddress: CLIENT.walletAddress, + references: [{ type: 'url', url: 'https://x.test/late' }], + idempotencyKey: 'evidence-key-5', + }) + ).rejects.toMatchObject({ code: 'DISPUTE_CLOSED', status: 409 }) + }) +}) + +describe('getDispute', () => { + it('returns evidence, attempts and the audit trail to participants', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + await harness.service.submitEvidence({ + disputeId: dispute.id, + actorWalletAddress: CLIENT.walletAddress, + references: [{ type: 'url', url: 'https://x.test/evidence' }], + idempotencyKey: 'evidence-key-6', + }) + + const result = await harness.service.getDispute( + dispute.id, + FREELANCER.walletAddress + ) + expect(result.dispute.id).toBe(dispute.id) + expect(result.evidence).toHaveLength(1) + expect(result.auditTrail.map((event) => event.action)).toEqual([ + 'dispute_created', + 'evidence_submitted', + ]) + }) + + it('hides private dispute details from unrelated users', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + + await expect( + harness.service.getDispute(dispute.id, OUTSIDER.walletAddress) + ).rejects.toMatchObject({ code: 'DISPUTE_FORBIDDEN', status: 403 }) + }) + + it('lets admins and designated resolvers read any dispute', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + + await expect( + harness.service.getDispute(dispute.id, ADMIN.walletAddress) + ).resolves.toBeTruthy() + await expect( + harness.service.getDispute(dispute.id, DESIGNATED.walletAddress) + ).resolves.toBeTruthy() + }) +}) + +describe('resolveDispute', () => { + it('confirms an arbiter resolution only after on-chain verification', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + harness.chain.submission = { txHash: 'tx-confirmed', state: 'confirmed', ledger: 99 } + + const result = await harness.service.resolveDispute( + resolutionInput({ + disputeId: dispute.id, + clientRefundAmount: undefined, + }) as never + ) + + expect(result.state).toBe('confirmed') + expect(result.attempt.status).toBe('confirmed') + expect(result.attempt.txHash).toBe('tx-confirmed') + expect(result.dispute.status).toBe('resolved_freelancer') + expect(result.contractStatus).toBe('completed') + expect(harness.repo.contracts.get('contract-1')?.status).toBe('completed') + expect(harness.repo.contracts.get('contract-1')?.activeDisputeId).toBeNull() + expect(harness.chain.submissions[0]).toMatchObject({ + contractAddress: 'CESCROWCONTRACT', + milestoneId: 'milestone-1', + releaseToFreelancer: true, + }) + expect(harness.repo.audits.map((a) => a.action)).toEqual( + expect.arrayContaining(['resolution_requested', 'resolution_confirmed']) + ) + }) + + it('forbids contract participants who are not arbitrators from resolving', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + + await expect( + harness.service.resolveDispute( + resolutionInput({ + disputeId: dispute.id, + actorWalletAddress: CLIENT.walletAddress, + }) as never + ) + ).rejects.toBeInstanceOf(DisputeForbiddenError) + + expect(harness.chain.submissions).toHaveLength(0) + expect((await harness.repo.getDispute(dispute.id))?.status).toBe('open') + }) + + it('allows the designated decision-maker and admins to resolve', async () => { + const designatedHarness = setup() + const designatedDispute = await createOpenDispute(designatedHarness) + const designated = await designatedHarness.service.resolveDispute( + resolutionInput({ + disputeId: designatedDispute.id, + actorWalletAddress: DESIGNATED.walletAddress, + }) as never + ) + expect(designated.state).toBe('confirmed') + + const adminHarness = setup() + const adminDispute = await createOpenDispute(adminHarness) + const admin = await adminHarness.service.resolveDispute( + resolutionInput({ + disputeId: adminDispute.id, + actorWalletAddress: ADMIN.walletAddress, + }) as never + ) + expect(admin.state).toBe('confirmed') + }) + + it('rejects a second resolution of the same dispute', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + await harness.service.resolveDispute( + resolutionInput({ disputeId: dispute.id }) as never + ) + + await expect( + harness.service.resolveDispute( + resolutionInput({ + disputeId: dispute.id, + idempotencyKey: 'resolve-key-0002', + }) as never + ) + ).rejects.toMatchObject({ code: 'RESOLUTION_ALREADY_FINALISED', status: 409 }) + }) + + it('replays a confirmed attempt for a repeated idempotency key', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + const input = resolutionInput({ disputeId: dispute.id }) + + const first = await harness.service.resolveDispute(input as never) + const replay = await harness.service.resolveDispute(input as never) + + expect(first.state).toBe('confirmed') + expect(replay.state).toBe('confirmed') + expect(replay.replayed).toBe(true) + expect(harness.chain.submissions).toHaveLength(1) + }) + + it('rejects reusing an idempotency key with a different payload', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + const input = resolutionInput({ disputeId: dispute.id }) + await harness.service.resolveDispute(input as never) + + await expect( + harness.service.resolveDispute( + resolutionInput({ + disputeId: dispute.id, + outcome: 'resolved_client', + }) as never + ) + ).rejects.toMatchObject({ code: 'IDEMPOTENCY_KEY_REUSED', status: 409 }) + }) + + it('prevents concurrent resolutions from both succeeding', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + // Hold the chain call so both requests overlap. + let release: (value: ChainResolutionSubmission) => void = () => {} + harness.chain.submitResolution = (request: ChainResolutionRequest) => { + harness.chain.submissions.push(request) + return new Promise((resolve) => { + release = resolve + }) + } + + // Attach handlers immediately so a fast rejection is never reported as an + // unhandled promise rejection. + const settle = (promise: Promise) => + promise.then( + (value) => ({ status: 'fulfilled' as const, value }), + (reason) => ({ status: 'rejected' as const, reason }) + ) + + const first = settle( + harness.service.resolveDispute( + resolutionInput({ disputeId: dispute.id, idempotencyKey: 'concurrent-key-1' }) as never + ) + ) + const second = settle( + harness.service.resolveDispute( + resolutionInput({ disputeId: dispute.id, idempotencyKey: 'concurrent-key-2' }) as never + ) + ) + + // Wait until the first request is inside the chain submission. + await vi.waitFor(() => { + expect(harness.chain.submissions).toHaveLength(1) + }) + release({ txHash: 'tx-race', state: 'confirmed', ledger: 1 }) + + const outcomes = await Promise.all([first, second]) + const fulfilled = outcomes.filter((o) => o.status === 'fulfilled') + const rejected = outcomes.filter((o) => o.status === 'rejected') + + expect(fulfilled).toHaveLength(1) + expect(rejected).toHaveLength(1) + expect((rejected[0] as { reason: unknown }).reason).toMatchObject({ + code: 'RESOLUTION_IN_PROGRESS', + }) + const attempts = await harness.repo.listAttempts(dispute.id) + expect(attempts.filter((a) => a.status === 'confirmed')).toHaveLength(1) + }) + + it('tracks a pending blockchain transaction without resolving the dispute', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + harness.chain.submission = { txHash: 'tx-pending', state: 'pending' } + + const result = await harness.service.resolveDispute( + resolutionInput({ disputeId: dispute.id }) as never + ) + + expect(result.state).toBe('pending') + expect(result.attempt.status).toBe('pending') + expect(result.attempt.txHash).toBe('tx-pending') + expect((await harness.repo.getDispute(dispute.id))?.status).toBe('open') + expect(harness.repo.contracts.get('contract-1')?.status).toBe('disputed') + expect(harness.repo.audits.map((a) => a.action)).toContain('resolution_pending') + }) + + it('keeps the dispute open when the transaction reverts, and does not retry blindly', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + harness.chain.submission = { + txHash: 'tx-reverted', + state: 'failed', + errorCode: 'InvalidMilestoneStatus', + errorMessage: 'Milestone is not disputed on-chain', + } + + const result = await harness.service.resolveDispute( + resolutionInput({ disputeId: dispute.id }) as never + ) + + expect(result.state).toBe('failed') + expect(result.retryable).toBe(false) + expect(result.attempt.errorCode).toBe('InvalidMilestoneStatus') + expect((await harness.repo.getDispute(dispute.id))?.status).toBe('open') + expect(harness.repo.audits.map((a) => a.action)).toContain('resolution_failed') + }) + + it('records RPC failures as recoverable and preserves the dispute record', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + harness.chain.submissionError = new DisputeChainError( + 'RPC timeout', + 'BLOCKCHAIN_UNAVAILABLE', + true + ) + + const result = await harness.service.resolveDispute( + resolutionInput({ disputeId: dispute.id }) as never + ) + + expect(result.state).toBe('failed') + expect(result.retryable).toBe(true) + expect(result.attempt.errorCode).toBe('BLOCKCHAIN_UNAVAILABLE') + expect(await harness.repo.getDispute(dispute.id)).not.toBeNull() + expect((await harness.repo.getDispute(dispute.id))?.status).toBe('open') + }) + + it('retries a failed attempt with the same idempotency key and confirms it', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + harness.chain.submission = { + txHash: 'tx-failed', + state: 'failed', + errorCode: 'CONTRACT_REVERTED', + errorMessage: 'reverted', + } + + const input = resolutionInput({ disputeId: dispute.id }) + const failed = await harness.service.resolveDispute(input as never) + expect(failed.state).toBe('failed') + + harness.chain.submission = { txHash: 'tx-retried', state: 'confirmed', ledger: 7 } + const retried = await harness.service.resolveDispute(input as never) + + expect(retried.state).toBe('confirmed') + expect(retried.attempt.txHash).toBe('tx-retried') + expect((await harness.repo.getDispute(dispute.id))?.status).toBe('resolved_freelancer') + expect(harness.repo.audits.map((a) => a.action)).toContain('resolution_retried') + }) + + it('retries a specific failed attempt id and links the new attempt', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + harness.chain.submissionError = new DisputeChainError('down', 'BLOCKCHAIN_UNAVAILABLE', true) + + const failed = await harness.service.resolveDispute( + resolutionInput({ disputeId: dispute.id, idempotencyKey: 'first-try-key' }) as never + ) + expect(failed.state).toBe('failed') + + harness.chain.submissionError = null + harness.chain.submission = { txHash: 'tx-recovered', state: 'confirmed', ledger: 12 } + + const retried = await harness.service.resolveDispute( + resolutionInput({ + disputeId: dispute.id, + idempotencyKey: 'retry-key-0001', + retryAttemptId: failed.attempt.id, + }) as never + ) + + expect(retried.state).toBe('confirmed') + expect(retried.attempt.retryOf).toBe(failed.attempt.id) + }) + + it('reconciles a pending transaction once the chain confirms it', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + harness.chain.submission = { txHash: 'tx-late', state: 'pending' } + const pending = await harness.service.resolveDispute( + resolutionInput({ disputeId: dispute.id }) as never + ) + expect(pending.state).toBe('pending') + + harness.chain.verification = 'confirmed' + const reconciled = await harness.service.reconcileResolution( + dispute.id, + ARBITER.walletAddress + ) + + expect(reconciled?.state).toBe('confirmed') + expect(reconciled?.attempt.txHash).toBe('tx-late') + expect((await harness.repo.getDispute(dispute.id))?.status).toBe('resolved_freelancer') + expect(harness.chain.verified).toEqual(['tx-late']) + }) + + it('leaves the dispute unresolved while reconciliation is still pending', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + harness.chain.submission = { txHash: 'tx-waiting', state: 'pending' } + await harness.service.resolveDispute(resolutionInput({ disputeId: dispute.id }) as never) + + harness.chain.verification = 'unknown' + const reconciled = await harness.service.reconcileResolution( + dispute.id, + ARBITER.walletAddress + ) + + expect(reconciled?.state).toBe('pending') + expect((await harness.repo.getDispute(dispute.id))?.status).toBe('open') + }) + + it('withdraws off-chain without calling the escrow contract', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + + const result = await harness.service.resolveDispute( + resolutionInput({ + disputeId: dispute.id, + outcome: 'withdrawn', + reasons: 'Parties reached an agreement outside arbitration', + }) as never + ) + + expect(result.state).toBe('confirmed') + expect(result.attempt.onchain).toBe(false) + expect(result.attempt.txHash).toBeNull() + expect(result.contractStatus).toBe('active') + expect(harness.chain.submissions).toHaveLength(0) + expect(harness.repo.contracts.get('contract-1')?.activeDisputeId).toBeNull() + }) + + it('refuses split resolutions on-chain but allows them off-chain', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + + await expect( + harness.service.resolveDispute( + resolutionInput({ + disputeId: dispute.id, + outcome: 'resolved_split', + clientRefundAmount: '400.000000', + freelancerPayoutAmount: '600.000000', + }) as never + ) + ).rejects.toBeInstanceOf(DisputeForbiddenError) + expect(harness.chain.submissions).toHaveLength(0) + + const offchain = setup({ escrowAddress: null }) + const offchainDispute = await createOpenDispute(offchain) + const result = await offchain.service.resolveDispute( + resolutionInput({ + disputeId: offchainDispute.id, + outcome: 'resolved_split', + clientRefundAmount: '400.000000', + freelancerPayoutAmount: '600.000000', + }) as never + ) + expect(result.state).toBe('confirmed') + expect(result.dispute.clientRefundAmount).toBe('400.000000') + expect(result.dispute.freelancerPayoutAmount).toBe('600.000000') + }) + + it('never confirms a resolution when the attempt cannot be persisted', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + harness.chain.submission = { txHash: 'tx-1', state: 'confirmed' } + + // Simulate a concurrent winner: the dispute is finalized behind our back. + const original = harness.repo.confirmResolution.bind(harness.repo) + let calls = 0 + harness.repo.confirmResolution = async (input) => { + calls += 1 + if (calls === 1) return null + return original(input) + } + + await expect( + harness.service.resolveDispute(resolutionInput({ disputeId: dispute.id }) as never) + ).rejects.toMatchObject({ code: 'RESOLUTION_ALREADY_FINALISED' }) + expect((await harness.repo.getDispute(dispute.id))?.status).toBe('open') + }) + + it('keeps an append-only audit trail for the whole lifecycle', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + await harness.service.submitEvidence({ + disputeId: dispute.id, + actorWalletAddress: FREELANCER.walletAddress, + references: [{ type: 'url', url: 'https://x.test/final' }], + idempotencyKey: 'evidence-key-final', + }) + await expect( + harness.service.resolveDispute( + resolutionInput({ + disputeId: dispute.id, + actorWalletAddress: OUTSIDER.walletAddress, + }) as never + ) + ).rejects.toBeInstanceOf(DisputeForbiddenError) + await harness.service.resolveDispute( + resolutionInput({ disputeId: dispute.id }) as never + ) + + const actions = harness.repo.audits.map((audit) => audit.action) + expect(actions).toEqual([ + 'dispute_created', + 'evidence_submitted', + 'authorization_denied', + 'resolution_requested', + 'resolution_confirmed', + ]) + expect(harness.repo.audits.every((audit) => Boolean(audit.createdAt))).toBe(true) + }) +}) + +describe('error mapping', () => { + it('exposes typed status codes for consistent API responses', () => { + expect(new DisputeConflictError('x', 'DISPUTE_CLOSED').status).toBe(409) + expect(new DisputeValidationError('x').status).toBe(422) + expect(new DisputeError('x', 'CODE', 418).status).toBe(418) + }) + + it('does not confirm an attempt when the chain reports a revert during reconciliation', async () => { + const harness = setup() + const dispute = await createOpenDispute(harness) + harness.chain.submission = { txHash: 'tx-revert-late', state: 'pending' } + const pending = await harness.service.resolveDispute( + resolutionInput({ disputeId: dispute.id }) as never + ) + + harness.chain.verification = 'failed' + const reconciled = await harness.service.reconcileResolution( + dispute.id, + ARBITER.walletAddress + ) + + expect(reconciled?.state).toBe('failed') + const stored = (await harness.repo.getAttempt( + pending.attempt.id + )) as ResolutionAttemptRecord + expect(stored.status).toBe('failed') + }) +}) diff --git a/__tests__/disputes/validation.test.ts b/__tests__/disputes/validation.test.ts new file mode 100644 index 0000000..1413147 --- /dev/null +++ b/__tests__/disputes/validation.test.ts @@ -0,0 +1,156 @@ +import { describe, it, expect } from 'vitest' + +import { + assertSplitAmounts, + parseCreateDisputeInput, + parseIdempotencyKey, + parseResolveDisputeInput, + parseSubmitEvidenceInput, + toBaseUnits, +} from '@/lib/disputes/validation' +import { DisputeValidationError } from '@/lib/disputes/types' + +const KEY = 'idempotency-key-0001' + +describe('parseIdempotencyKey', () => { + it('accepts a header key and falls back to the body', () => { + expect(parseIdempotencyKey(KEY, undefined)).toBe(KEY) + expect(parseIdempotencyKey(undefined, KEY)).toBe(KEY) + }) + + it('rejects missing, short or malformed keys', () => { + expect(() => parseIdempotencyKey(null, undefined)).toThrow(DisputeValidationError) + expect(() => parseIdempotencyKey('short', undefined)).toThrow(DisputeValidationError) + expect(() => parseIdempotencyKey('bad key with spaces!!', undefined)).toThrow( + DisputeValidationError + ) + }) +}) + +describe('parseCreateDisputeInput', () => { + it('parses a valid payload', () => { + const parsed = parseCreateDisputeInput( + { + reason: 'Delivered work does not match the agreed specification', + milestoneId: 'milestone-1', + evidence: [{ type: 'url', url: 'https://proof.test/a', label: 'scope' }], + }, + KEY + ) + + expect(parsed.idempotencyKey).toBe(KEY) + expect(parsed.evidence[0]).toEqual({ + type: 'url', + url: 'https://proof.test/a', + label: 'scope', + description: undefined, + }) + }) + + it('rejects short reasons, bad evidence types and oversized lists', () => { + expect(() => parseCreateDisputeInput({ reason: 'too short' }, KEY)).toThrow( + DisputeValidationError + ) + expect(() => + parseCreateDisputeInput( + { + reason: 'Delivered work does not match the specification', + evidence: [{ type: 'executable', url: 'https://x.test' }], + }, + KEY + ) + ).toThrow(DisputeValidationError) + expect(() => + parseCreateDisputeInput( + { + reason: 'Delivered work does not match the specification', + evidence: Array.from({ length: 21 }, (_, i) => ({ + type: 'url', + url: `https://x.test/${i}`, + })), + }, + KEY + ) + ).toThrow(DisputeValidationError) + }) + + it('rejects non-object bodies', () => { + expect(() => parseCreateDisputeInput(null, KEY)).toThrow(DisputeValidationError) + expect(() => parseCreateDisputeInput([], KEY)).toThrow(DisputeValidationError) + }) +}) + +describe('parseSubmitEvidenceInput', () => { + it('requires references or a description', () => { + expect(() => parseSubmitEvidenceInput({}, KEY)).toThrow(DisputeValidationError) + const parsed = parseSubmitEvidenceInput( + { description: 'Written statement from the client' }, + KEY + ) + expect(parsed.references).toEqual([]) + expect(parsed.description).toBe('Written statement from the client') + }) +}) + +describe('parseResolveDisputeInput', () => { + it('requires a documented reason and a valid outcome', () => { + expect(() => + parseResolveDisputeInput({ outcome: 'resolved_client', reasons: 'nope' }, KEY) + ).toThrow(DisputeValidationError) + expect(() => + parseResolveDisputeInput( + { outcome: 'resolved_everything', reasons: 'A documented resolution reason' }, + KEY + ) + ).toThrow(DisputeValidationError) + }) + + it('accepts metadata and rejects non-object metadata', () => { + const parsed = parseResolveDisputeInput( + { + outcome: 'resolved_client', + reasons: 'Evidence shows the deliverable was never submitted', + metadata: { evidenceIds: ['e1'], reviewedBy: 'arbiter' }, + }, + KEY + ) + expect(parsed.metadata).toEqual({ evidenceIds: ['e1'], reviewedBy: 'arbiter' }) + + expect(() => + parseResolveDisputeInput( + { + outcome: 'resolved_client', + reasons: 'Evidence shows the deliverable was never submitted', + metadata: ['not', 'an', 'object'], + }, + KEY + ) + ).toThrow(DisputeValidationError) + }) +}) + +describe('amount handling', () => { + it('parses decimal strings exactly', () => { + expect(toBaseUnits('1.000001', 'amount')).toBe(BigInt(1000001)) + expect(() => toBaseUnits('1.0000001', 'amount')).toThrow(DisputeValidationError) + expect(() => toBaseUnits('-1', 'amount')).toThrow(DisputeValidationError) + }) + + it('requires split amounts to sum to the contract total', () => { + expect(() => + assertSplitAmounts('resolved_split', '1000.000000', '400.000000', '600.000000') + ).not.toThrow() + + expect(() => + assertSplitAmounts('resolved_split', '1000.000000', '400.000000', '500.000000') + ).toThrow(DisputeValidationError) + + expect(() => assertSplitAmounts('resolved_split', '1000.000000')).toThrow( + DisputeValidationError + ) + }) + + it('does not enforce split amounts for other outcomes', () => { + expect(() => assertSplitAmounts('resolved_client', '1000')).not.toThrow() + }) +}) diff --git a/app/api/contracts/[id]/disputes/route.ts b/app/api/contracts/[id]/disputes/route.ts new file mode 100644 index 0000000..3993039 --- /dev/null +++ b/app/api/contracts/[id]/disputes/route.ts @@ -0,0 +1,76 @@ +/** + * POST /api/contracts/:id/disputes + * + * Open a dispute on a contract. Only contract participants, the arbitrator or + * a designated decision-maker may raise one, and only while the contract is + * active/paused with funded escrow. + * + * Body: + * reason string (>= 10 chars) + * desiredOutcome? string + * milestoneId? uuid (required for on-chain escrowed contracts) + * evidence? Array<{ type, url, label? }> + * + * Headers: + * Idempotency-Key string (required; a replay returns the original dispute) + */ + +export const dynamic = 'force-dynamic' + +import { NextRequest, NextResponse } from 'next/server' + +import { withAuthCtx } from '@/lib/auth/middleware' +import { + disputeWorkflowService, + isUuid, + parseCreateDisputeInput, +} from '@/lib/disputes' +import { + disputeErrorResponse, + invalidIdResponse, + invalidJsonResponse, +} from '@/lib/disputes/http' + +type RouteContext = { params: Promise<{ id: string }> } + +export const POST = withAuthCtx( + async (request: NextRequest, auth, context: RouteContext) => { + const { id } = await context.params + if (!isUuid(id)) return invalidIdResponse('contract') + + let body: unknown + try { + body = await request.json() + } catch { + return invalidJsonResponse() + } + + try { + const parsed = parseCreateDisputeInput( + body, + request.headers.get('idempotency-key') + ) + + const result = await disputeWorkflowService.createDispute({ + contractId: id, + actorWalletAddress: auth.walletAddress, + reason: parsed.reason, + desiredOutcome: parsed.desiredOutcome, + milestoneId: parsed.milestoneId, + evidence: parsed.evidence, + idempotencyKey: parsed.idempotencyKey, + }) + + return NextResponse.json( + { + dispute: result.dispute, + contractStatus: result.contractStatus, + replayed: result.replayed, + }, + { status: result.replayed ? 200 : 201 } + ) + } catch (error) { + return disputeErrorResponse(error) + } + } +) diff --git a/app/api/disputes/[id]/evidence/route.ts b/app/api/disputes/[id]/evidence/route.ts index 2453ce7..d7c894a 100644 --- a/app/api/disputes/[id]/evidence/route.ts +++ b/app/api/disputes/[id]/evidence/route.ts @@ -15,6 +15,15 @@ import { removeEncryptedFile, storeEncryptedFile, } from "@/lib/security/fileEncryption"; +import { + disputeWorkflowService, + isUuid, + parseSubmitEvidenceInput, +} from "@/lib/disputes"; +import { + disputeErrorResponse, + invalidJsonResponse, +} from "@/lib/disputes/http"; type RouteContext = { params: Promise<{ id: string }> }; type AuthLike = { walletAddress: string }; @@ -152,6 +161,27 @@ async function logEvidenceAction( export const GET = withAuthCtx( async (request: NextRequest, auth, context: RouteContext) => { const { id } = await context.params; + + // Contract-scoped (UUID) disputes are served by the dispute workflow, which + // enforces participant/arbitrator authorization before returning evidence. + if (isUuid(id)) { + try { + const result = await disputeWorkflowService.getDispute( + id, + auth.walletAddress, + ); + return NextResponse.json( + { + evidence: result.evidence, + resolutionAttempt: result.resolutionAttempt, + }, + { status: 200 }, + ); + } catch (error) { + return disputeErrorResponse(error); + } + } + try { const access = await getDisputeAccess(id, auth.walletAddress); if (isAccessResponse(access)) return access; @@ -218,6 +248,42 @@ export const POST = withAuthCtx( async (request: NextRequest, auth, context: RouteContext) => { const { id } = await context.params; + // Contract-scoped disputes accept JSON evidence references. Legacy + // job-scoped disputes keep the multipart upload path below. + if (isUuid(id)) { + let body: unknown; + try { + body = await request.json(); + } catch { + return invalidJsonResponse(); + } + + try { + const parsed = parseSubmitEvidenceInput( + body, + request.headers.get("idempotency-key"), + ); + const result = await disputeWorkflowService.submitEvidence({ + disputeId: id, + actorWalletAddress: auth.walletAddress, + references: parsed.references, + description: parsed.description, + idempotencyKey: parsed.idempotencyKey, + }); + + return NextResponse.json( + { + evidence: result.evidence, + duplicates: result.duplicates, + replayed: result.evidence.length === 0, + }, + { status: result.evidence.length === 0 ? 200 : 201 }, + ); + } catch (error) { + return disputeErrorResponse(error); + } + } + let formData: FormData; try { formData = await request.formData(); diff --git a/app/api/disputes/[id]/resolve/route.ts b/app/api/disputes/[id]/resolve/route.ts index b00e78d..b976fa5 100644 --- a/app/api/disputes/[id]/resolve/route.ts +++ b/app/api/disputes/[id]/resolve/route.ts @@ -3,12 +3,27 @@ export const dynamic = 'force-dynamic' import { NextRequest, NextResponse } from 'next/server' import { sql } from '@/lib/db' import { withRbac, RbacContext } from '@/lib/auth/rbacMiddleware' +import { withAuthCtx } from '@/lib/auth/middleware' import { activityService } from '@/lib/activity' +import { + disputeWorkflowService, + isUuid, + parseResolveDisputeInput, +} from '@/lib/disputes' +import { + disputeErrorResponse, + invalidJsonResponse, +} from '@/lib/disputes/http' type RouteContext = { params: Promise<{ id: string }> } -export const POST = withRbac('dispute:resolve', async (request: NextRequest, auth: RbacContext, context: RouteContext) => { - const { id } = await context.params +/** + * Legacy job-scoped resolution (integer dispute ids). Kept for backward + * compatibility with the existing dashboard. + */ +const legacyResolve = withRbac('dispute:resolve', async (request: NextRequest, auth: RbacContext) => { + const segments = new URL(request.url).pathname.split('/').filter(Boolean) + const id = segments[segments.length - 2] ?? '' try { const body = await request.json().catch(() => ({})) const resolution = typeof body.resolution === 'string' ? body.resolution.trim() : '' @@ -86,3 +101,86 @@ export const POST = withRbac('dispute:resolve', async (request: NextRequest, aut ) } }) + +/** + * POST /api/disputes/:id/resolve + * + * Resolve a contract-scoped dispute. Only the arbitrator, a designated + * decision-maker or an admin may resolve, and the escrow contract's own + * arbiter authorization still applies on-chain. + * + * Body: + * outcome 'resolved_client' | 'resolved_freelancer' | 'resolved_split' | 'withdrawn' + * reasons string (>= 10 chars, stored immutably) + * metadata? object + * clientRefundAmount? string (split only) + * freelancerPayoutAmount? string (split only) + * retryAttemptId? uuid (retry a failed on-chain attempt) + * reconcile? boolean (verify a pending transaction) + * + * Headers: + * Idempotency-Key string (required) + */ +export const POST = withAuthCtx( + async (request: NextRequest, auth, context: RouteContext) => { + const { id } = await context.params + + if (!isUuid(id)) return legacyResolve(request) + + let body: Record + try { + const parsed = await request.json() + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return invalidJsonResponse() + } + body = parsed as Record + } catch { + return invalidJsonResponse() + } + + try { + if (body.reconcile === true) { + const reconciled = await disputeWorkflowService.reconcileResolution( + id, + auth.walletAddress + ) + if (!reconciled) { + return NextResponse.json( + { + error: 'There is no pending resolution to reconcile', + code: 'NO_PENDING_RESOLUTION', + }, + { status: 409 } + ) + } + return NextResponse.json(reconciled, { + status: reconciled.state === 'pending' ? 202 : 200, + }) + } + + const parsed = parseResolveDisputeInput( + body, + request.headers.get('idempotency-key') + ) + + const result = await disputeWorkflowService.resolveDispute({ + disputeId: id, + actorWalletAddress: auth.walletAddress, + outcome: parsed.outcome, + reasons: parsed.reasons, + metadata: parsed.metadata, + clientRefundAmount: parsed.clientRefundAmount, + freelancerPayoutAmount: parsed.freelancerPayoutAmount, + idempotencyKey: parsed.idempotencyKey, + retryAttemptId: parsed.retryAttemptId, + }) + + const status = + result.state === 'confirmed' ? 200 : result.state === 'pending' ? 202 : result.retryable ? 503 : 502 + + return NextResponse.json(result, { status }) + } catch (error) { + return disputeErrorResponse(error) + } + } +) diff --git a/app/api/disputes/[id]/route.ts b/app/api/disputes/[id]/route.ts index 5b4be71..4061cf8 100644 --- a/app/api/disputes/[id]/route.ts +++ b/app/api/disputes/[id]/route.ts @@ -3,6 +3,8 @@ export const dynamic = 'force-dynamic' import { NextRequest, NextResponse } from 'next/server' import { sql } from '@/lib/db' import { withAuthCtx } from '@/lib/auth/middleware' +import { disputeWorkflowService, isUuid } from '@/lib/disputes' +import { disputeErrorResponse } from '@/lib/disputes/http' type RouteContext = { params: Promise<{ id: string }> } type UserRow = { id: string | number; role: string } @@ -12,8 +14,28 @@ type DisputeRow = { [key: string]: unknown } -export const GET = withAuthCtx(async (_request: NextRequest, auth, context: RouteContext) => { +/** + * GET /api/disputes/:id + * + * Contract-scoped disputes (UUID ids) are served by the dispute workflow, + * which enforces participant/arbitrator authorization and only exposes + * evidence and audit history to authorized actors. + * + * Job-scoped legacy disputes (integer ids) keep the original behaviour so the + * existing dashboard continues to work. + */ +export const GET = withAuthCtx(async (request: NextRequest, auth, context: RouteContext) => { const { id } = await context.params + + if (isUuid(id)) { + try { + const result = await disputeWorkflowService.getDispute(id, auth.walletAddress) + return NextResponse.json(result, { status: 200 }) + } catch (error) { + return disputeErrorResponse(error) + } + } + try { const users = (await sql` SELECT id, role FROM users WHERE wallet_address = ${auth.walletAddress} LIMIT 1 diff --git a/docs/dispute-resolution-workflow-api.md b/docs/dispute-resolution-workflow-api.md new file mode 100644 index 0000000..f5a2600 --- /dev/null +++ b/docs/dispute-resolution-workflow-api.md @@ -0,0 +1,199 @@ +# Dispute Resolution Workflow & Authorization API (issue #247) + +Secure workflow for opening contract disputes, submitting evidence, reading +dispute details and resolving disputes in coordination with the escrow smart +contract. + +``` +POST /api/contracts/:id/disputes open a dispute +POST /api/disputes/:id/evidence attach evidence references +GET /api/disputes/:id read dispute, evidence, attempts, audit +POST /api/disputes/:id/resolve resolve (or retry / reconcile) a dispute +``` + +Contract-scoped disputes use the canonical UUID schema from +`lib/db/migrations/001_taskchain_schema.sql` and are implemented in +`lib/disputes/`. Legacy job-scoped disputes (integer ids) continue to be served +by the existing handlers in the same route files. + +## Authorization + +| Actor | Create | View | Evidence | Resolve | +| --- | --- | --- | --- | --- | +| Contract client / freelancer | ✅ | ✅ | ✅ | ❌ | +| Arbiter (`contracts.arbiter_address`) | ✅ | ✅ | ✅ | ✅ | +| Designated decision-maker (`contracts.designated_resolver_id`) | ✅ | ✅ | ✅ | ✅ | +| Admin (`users.role = 'admin'`) | ✅ | ✅ | ✅ | ✅ | +| Anyone else | ❌ 403 | ❌ 403 | ❌ 403 | ❌ 403 | + +The actor is always resolved from the JWT wallet address (`withAuthCtx`) and the +role from the database. Client-supplied ids, roles, contract ownership or +arbitrator flags are ignored. + +Backend authorization never replaces the smart contract's own checks: the +escrow contract runs `arbiter.require_auth()` inside `resolve_dispute`, so a +resolution must also be signed by the on-chain arbiter +(`STELLAR_ARBITER_SECRET`, whose public key must equal `contracts.arbiter_address`). + +Denied authorization decisions are appended to the audit trail +(`authorization_denied`). + +## Dispute creation + +`POST /api/contracts/:id/disputes` — requires `Idempotency-Key` header. + +```json +{ + "reason": "Delivered work does not match the agreed specification", + "desiredOutcome": "full refund", + "milestoneId": "uuid", + "evidence": [{ "type": "url", "url": "https://...", "label": "scope" }] +} +``` + +Eligibility is validated against the loaded contract: + +* status must be `active` or `paused`; +* escrow status must be `funded` or `partially_released`; +* `milestoneId` is required when the contract has an on-chain escrow address, + and the milestone must belong to the contract and be `submitted`, + `approved`, `expired` or `extended` (mirrors the contract's `dispute()` rules); +* only one active dispute per contract (`409 DISPUTE_ALREADY_EXISTS`). + +Responses: `201` created, `200` idempotent replay, `400`, `401`, `403`, `404`, +`409`, `422`, `503`. + +## Evidence + +`POST /api/disputes/:id/evidence` — JSON references (not file uploads): + +```json +{ + "references": [{ "type": "ipfs", "url": "ipfs://bafy...", "label": "proof" }], + "description": "Optional note" +} +``` + +Evidence is stored in `dispute_evidence_items`, linked to the dispute, and +deduplicated by `sha256(type|url|label)` per dispute: replays return `200` with +`duplicates` instead of inserting another row. Closed disputes reject new +evidence (`409 DISPUTE_CLOSED`). + +Evidence and dispute details are only returned to authorized actors. Nothing is +written to logs beyond ids/hashes. + +## Resolution + +`POST /api/disputes/:id/resolve` — requires `Idempotency-Key` header. + +```json +{ + "outcome": "resolved_freelancer", + "reasons": "Documented decision, at least 10 characters", + "metadata": { "evidenceReviewed": true }, + "clientRefundAmount": "400.000000", + "freelancerPayoutAmount": "600.000000" +} +``` + +* `reasons` is mandatory and stored immutably; `metadata` is optional (≤ 16 KB). +* `resolved_freelancer` / `resolved_client` are submitted on-chain via + `resolve_dispute(milestone_id, release_to_freelancer)`. +* `withdrawn` is an off-chain closure: the contract returns to `active`, no + funds move, no transaction is sent. +* `resolved_split` is rejected when the contract has an escrow address, because + the escrow contract is binary. It is accepted off-chain only. +* Split amounts must sum to the contract total (exact decimal comparison). + +### Transaction states + +| Result | HTTP | Meaning | +| --- | --- | --- | +| confirmed | 200 | transaction verified on-chain; dispute/contract updated | +| pending | 202 | transaction submitted but not yet verified (`attempt.status = pending`) | +| failed (retryable) | 503 | RPC unavailable/timeout; retry with the same key | +| failed (reverted) | 502 | contract rejected the call; deterministic failure | + +A dispute is **never** marked resolved until the transaction has been re-fetched +from the Soroban RPC node and reported `SUCCESS`. + +`attempts` (in `GET /api/disputes/:id`) exposes every attempt with its +`status` (`pending` / `confirmed` / `failed`), `txHash`, error code and +timestamps, so pending and confirmed resolutions are tracked separately. + +### Idempotency, concurrency and retries + +* `Idempotency-Key` is stored per dispute; a replay of the same payload returns + the original attempt (and its state) without a second on-chain transaction. +* Reusing a key with a different payload returns `409 IDEMPOTENCY_KEY_REUSED`. +* Database unique indexes guarantee one active dispute per contract, one pending + attempt per dispute and one confirmed attempt per dispute. Concurrent + resolutions lose with `409 RESOLUTION_IN_PROGRESS` or + `409 RESOLUTION_ALREADY_FINALISED`. +* Retrying a failed attempt: resend the same `Idempotency-Key`, or pass + `retryAttemptId` with a new key. The retry re-submits and links the new + attempt through `retry_of`. +* Recovering a crashed/timed-out submission: `POST /api/disputes/:id/resolve` + with `{ "reconcile": true }` re-verifies the pending transaction hash and + confirms or fails it. `409 NO_PENDING_RESOLUTION` when there is nothing to + reconcile. + +### Consistency + +Confirmation updates the attempt, the dispute and the contract in a single SQL +statement guarded by `disputes.status IN ('open','under_review','escalated')`. +If another request won the race, the attempt is failed with +`CONCURRENT_RESOLUTION` and the API returns `409` — it never reports success. + +Outcome → contract status: `resolved_freelancer` → `completed`, +`resolved_client` → `cancelled`, `resolved_split` (off-chain) → `completed`, +`withdrawn` → `active`. `active_dispute_id` is cleared. + +## Audit trail + +`dispute_audit_events` is append-only (a trigger rejects `UPDATE`/`DELETE`). +Recorded actions: `dispute_created`, `evidence_submitted`, +`authorization_denied`, `resolution_requested`, `resolution_pending`, +`resolution_confirmed`, `resolution_failed`, `resolution_retried`. + +`GET /api/disputes/:id` returns the trail, ordered by `created_at`. + +## Database + +Migration: `lib/db/migrations/012_dispute_resolution_workflow.sql`. + +Adds `contracts.arbiter_address`, `contracts.designated_resolver_id`, +`disputes.creation_idempotency_key`, `disputes.resolution_metadata`, +`disputes.last_resolution_attempt_id`, tables `dispute_evidence_items`, +`dispute_resolution_attempts`, `dispute_audit_events`, plus the unique indexes +described above. + +Apply with `npm run migrate` (or `pnpm migrate`). No smart-contract changes are +required: the workflow calls the existing `dispute` / `resolve_dispute` methods. + +## Configuration + +| Variable | Purpose | +| --- | --- | +| `STELLAR_RPC_URL` (or `SOROBAN_RPC_URL`) | Soroban RPC endpoint | +| `STELLAR_ARBITER_SECRET` | arbiter key that signs `resolve_dispute` | +| `STELLAR_NETWORK_PASSPHRASE` | network passphrase (defaults to testnet) | +| `STELLAR_CONFIRMATION_ATTEMPTS` | confirmation polls per request (default 10) | +| `STELLAR_CONFIRMATION_INTERVAL_MS` | poll interval (default 1500) | + +If the arbiter key or RPC URL is missing, resolution fails closed with +`503 BLOCKCHAIN_NOT_CONFIGURED` and the attempt remains retryable. + +## Tests + +``` +npx vitest run __tests__/disputes __tests__/api/disputes-workflow.test.ts +``` + +`__tests__/disputes/authorization.test.ts` — role matrix. +`__tests__/disputes/validation.test.ts` — payload, evidence and amount rules. +`__tests__/disputes/service.test.ts` — creation, evidence, authorization, +duplicate/concurrent resolution, pending/confirmed/reverted/RPC-failure paths, +retry, reconciliation, split/withdraw, consistency and audit completeness. +`__tests__/api/disputes-workflow.test.ts` — HTTP status/response consistency, +auth failures and error mapping. diff --git a/env.example b/env.example index ce0bc56..d5792ae 100644 --- a/env.example +++ b/env.example @@ -34,6 +34,21 @@ STELLAR_NETWORK_PASSPHRASE=Test SDF Network ; September 2015 # Platform escrow account (Stellar public key) used by the worker. ESCROW_ACCOUNT_ID=G... +# ─── Dispute Resolution API (issue #247) ───────────────────────────────────── +# Secret key of the arbiter that signs `resolve_dispute` escrow calls. +# The backend never derives authorization from this key: the escrow contract +# still requires the arbiter signature, and the wallet must match +# contracts.arbiter_address. Without it, resolutions fail closed (HTTP 503) +# and the resolution attempt is stored as retryable. +# STELLAR_ARBITER_SECRET=S... + +# Soroban RPC endpoint used for dispute resolution (falls back to SOROBAN_RPC_URL). +# STELLAR_RPC_URL=https://soroban-testnet.stellar.org + +# How long to wait for on-chain confirmation before returning 202 (pending). +# STELLAR_CONFIRMATION_ATTEMPTS=10 +# STELLAR_CONFIRMATION_INTERVAL_MS=1500 + # ─── File Upload (Milestone Deliverables) ────────────────────────────────────── # 32-byte hex key used to encrypt deliverable files at rest. # Generate one with: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" diff --git a/lib/db/migrations/012_dispute_resolution_workflow.sql b/lib/db/migrations/012_dispute_resolution_workflow.sql new file mode 100644 index 0000000..ac5bc8d --- /dev/null +++ b/lib/db/migrations/012_dispute_resolution_workflow.sql @@ -0,0 +1,176 @@ +-- 012_dispute_resolution_workflow.sql +-- +-- Dispute Resolution Workflow & Authorization API (issue #247) +-- +-- Extends the canonical (UUID) contract schema with everything the dispute +-- workflow needs: +-- * arbitrator / designated decision-maker configuration on contracts +-- * evidence references stored separately from the free-form JSONB column +-- * resolution attempts that track on-chain transactions separately for +-- pending / confirmed / failed states +-- * an append-only audit trail for every dispute lifecycle event +-- * database-level guarantees against duplicate disputes, duplicate evidence +-- and duplicate/concurrent resolutions. + +-- ── Contracts: arbitration configuration ───────────────────────────────────── +ALTER TABLE contracts + ADD COLUMN IF NOT EXISTS arbiter_address TEXT, + ADD COLUMN IF NOT EXISTS designated_resolver_id UUID + REFERENCES users (id) ON DELETE SET NULL; + +COMMENT ON COLUMN contracts.arbiter_address IS + 'Stellar address of the arbitrator authorised to resolve disputes on-chain. Mirrors the escrow contract Arbiter.'; +COMMENT ON COLUMN contracts.designated_resolver_id IS + 'Optional platform user allowed to arbitrate this contract in addition to admins and the on-chain arbiter.'; + +CREATE INDEX IF NOT EXISTS idx_contracts_arbiter_address + ON contracts (arbiter_address) + WHERE arbiter_address IS NOT NULL; + +CREATE INDEX IF NOT EXISTS idx_contracts_designated_resolver + ON contracts (designated_resolver_id) + WHERE designated_resolver_id IS NOT NULL; + +-- ── Disputes: idempotent creation + resolution metadata ────────────────────── +ALTER TABLE disputes + ADD COLUMN IF NOT EXISTS creation_idempotency_key TEXT, + ADD COLUMN IF NOT EXISTS resolution_metadata JSONB NOT NULL DEFAULT '{}'::jsonb, + ADD COLUMN IF NOT EXISTS last_resolution_attempt_id UUID; + +-- A client may only create one dispute per contract for a given idempotency key. +CREATE UNIQUE INDEX IF NOT EXISTS uq_disputes_contract_creation_key + ON disputes (contract_id, creation_idempotency_key) + WHERE creation_idempotency_key IS NOT NULL; + +-- A contract can never have more than one open dispute. Concurrent creation +-- requests race on this index; only one INSERT can win. +CREATE UNIQUE INDEX IF NOT EXISTS uq_disputes_one_active_per_contract + ON disputes (contract_id) + WHERE status IN ('open', 'under_review', 'escalated'); + +-- ── Evidence references ────────────────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS dispute_evidence_items ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + dispute_id UUID NOT NULL REFERENCES disputes (id) ON DELETE RESTRICT, + milestone_id UUID REFERENCES milestones (id) ON DELETE SET NULL, + submitted_by_user_id UUID NOT NULL REFERENCES users (id) ON DELETE RESTRICT, + + evidence_type TEXT NOT NULL + CHECK (evidence_type IN ('url', 'ipfs', 'document', 'transaction', 'other')), + reference_url TEXT NOT NULL CHECK (length(btrim(reference_url)) > 0), + label TEXT, + description TEXT, + -- sha256(evidence_type|reference_url|label) — used to reject duplicate + -- submissions of the same reference against the same dispute. + content_hash TEXT NOT NULL, + + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + + CONSTRAINT uq_dispute_evidence_reference UNIQUE (dispute_id, content_hash) +); + +CREATE INDEX IF NOT EXISTS idx_dispute_evidence_items_dispute + ON dispute_evidence_items (dispute_id, created_at ASC); +CREATE INDEX IF NOT EXISTS idx_dispute_evidence_items_submitter + ON dispute_evidence_items (submitted_by_user_id); + +-- ── Resolution attempts ────────────────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS dispute_resolution_attempts ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + dispute_id UUID NOT NULL REFERENCES disputes (id) ON DELETE RESTRICT, + requested_by_user_id UUID NOT NULL REFERENCES users (id) ON DELETE RESTRICT, + + outcome dispute_status NOT NULL + CHECK (outcome IN ('resolved_client', 'resolved_freelancer', 'resolved_split', 'withdrawn')), + -- Documented resolution reason. Short one-liners are rejected by the API. + reasons TEXT NOT NULL CHECK (length(btrim(reasons)) >= 10), + metadata JSONB NOT NULL DEFAULT '{}'::jsonb, + + -- On-chain transaction tracking. `pending` is never treated as resolved. + status TEXT NOT NULL DEFAULT 'pending' + CHECK (status IN ('pending', 'confirmed', 'failed')), + onchain BOOLEAN NOT NULL DEFAULT TRUE, + tx_hash TEXT, + ledger INTEGER, + error_code TEXT, + error_message TEXT, + retry_of UUID REFERENCES dispute_resolution_attempts (id) ON DELETE SET NULL, + + -- Client supplied idempotency key. Unique per dispute so a replayed request + -- cannot create a second attempt or a second on-chain transaction. + idempotency_key TEXT NOT NULL, + + submitted_at TIMESTAMPTZ, + confirmed_at TIMESTAMPTZ, + failed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + + CONSTRAINT uq_resolution_attempt_key UNIQUE (dispute_id, idempotency_key) +); + +-- At most one in-flight resolution per dispute (blocks concurrent resolutions). +CREATE UNIQUE INDEX IF NOT EXISTS uq_dispute_pending_resolution + ON dispute_resolution_attempts (dispute_id) + WHERE status = 'pending'; + +-- A dispute can only be resolved once. +CREATE UNIQUE INDEX IF NOT EXISTS uq_dispute_confirmed_resolution + ON dispute_resolution_attempts (dispute_id) + WHERE status = 'confirmed'; + +CREATE INDEX IF NOT EXISTS idx_resolution_attempts_dispute + ON dispute_resolution_attempts (dispute_id, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_resolution_attempts_status + ON dispute_resolution_attempts (status, created_at ASC); +CREATE INDEX IF NOT EXISTS idx_resolution_attempts_tx + ON dispute_resolution_attempts (tx_hash) + WHERE tx_hash IS NOT NULL; + +-- ── Append-only audit trail ────────────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS dispute_audit_events ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + -- Nullable so authorization decisions taken before a dispute exists (for + -- example a rejected creation request) are still auditable. + dispute_id UUID REFERENCES disputes (id) ON DELETE RESTRICT, + contract_id UUID NOT NULL REFERENCES contracts (id) ON DELETE RESTRICT, + actor_user_id UUID REFERENCES users (id) ON DELETE RESTRICT, + actor_wallet TEXT, + action TEXT NOT NULL CHECK (action IN ( + 'dispute_created', + 'evidence_submitted', + 'authorization_denied', + 'resolution_requested', + 'resolution_pending', + 'resolution_confirmed', + 'resolution_failed', + 'resolution_retried' + )), + metadata JSONB NOT NULL DEFAULT '{}'::jsonb, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS idx_dispute_audit_events_dispute + ON dispute_audit_events (dispute_id, created_at ASC); +CREATE INDEX IF NOT EXISTS idx_dispute_audit_events_contract + ON dispute_audit_events (contract_id, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_dispute_audit_events_action + ON dispute_audit_events (action, created_at DESC); + +-- Audit rows are immutable: the database itself refuses UPDATE and DELETE. +CREATE OR REPLACE FUNCTION dispute_audit_events_reject_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'dispute_audit_events is append-only (attempted %)', TG_OP; +END; +$$; + +DROP TRIGGER IF EXISTS trg_dispute_audit_events_immutable ON dispute_audit_events; +CREATE TRIGGER trg_dispute_audit_events_immutable + BEFORE UPDATE OR DELETE ON dispute_audit_events + FOR EACH ROW EXECUTE FUNCTION dispute_audit_events_reject_mutation(); + +COMMENT ON TABLE dispute_audit_events IS + 'Append-only audit trail for the dispute resolution workflow. UPDATE/DELETE are rejected by trigger.'; diff --git a/lib/disputes/authorization.ts b/lib/disputes/authorization.ts new file mode 100644 index 0000000..9da5090 --- /dev/null +++ b/lib/disputes/authorization.ts @@ -0,0 +1,181 @@ +/** + * Dispute Resolution Workflow — Authorization + * + * Pure, dependency-free authorization rules. Route handlers and the service + * layer must never trust a client supplied role, contract owner or arbitrator + * flag: the actor is resolved from the access token's wallet address and the + * contract is loaded from the database, then these rules decide. + * + * Roles that may act on a dispute: + * • participant — contract client or freelancer (create / view / evidence) + * • arbiter — wallet matching contracts.arbiter_address (all actions) + * • designated_resolver — contracts.designated_resolver_id (all actions) + * • admin — platform administrator (all actions) + * + * Resolution additionally requires the on-chain arbiter signature. These + * checks never replace the smart contract's own `arbiter.require_auth()`; + * they only decide whether the backend is willing to submit the request. + */ + +import type { ContractRecord, DisputeActor, DisputeRecord } from './types' +import { DisputeForbiddenError } from './types' + +const UUID_RE = + /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i +const INTEGER_ID_RE = /^\d{1,19}$/ + +export function isUuid(value: string): boolean { + return UUID_RE.test(value) +} + +/** Legacy (job-scoped) routes use integer ids — used to keep them working. */ +export function isIntegerId(value: string): boolean { + return INTEGER_ID_RE.test(value) +} + +export type DisputeActorKind = + | 'admin' + | 'arbiter' + | 'designated_resolver' + | 'participant' + | 'unrelated' + +export function classifyActor( + actor: DisputeActor, + contract: ContractRecord +): DisputeActorKind { + if (actor.role === 'admin') return 'admin' + + const wallet = actor.walletAddress?.trim().toLowerCase() + const arbiter = contract.arbiterAddress?.trim().toLowerCase() + if (wallet && arbiter && wallet === arbiter) return 'arbiter' + + if (contract.designatedResolverId && actor.userId === contract.designatedResolverId) { + return 'designated_resolver' + } + + if (actor.userId === contract.clientId || actor.userId === contract.freelancerId) { + return 'participant' + } + + return 'unrelated' +} + +export function isContractParticipant( + actor: DisputeActor, + contract: ContractRecord +): boolean { + return ( + actor.userId === contract.clientId || actor.userId === contract.freelancerId + ) +} + +const CREATE_ALLOWED: DisputeActorKind[] = [ + 'admin', + 'arbiter', + 'designated_resolver', + 'participant', +] +const VIEW_ALLOWED: DisputeActorKind[] = [ + 'admin', + 'arbiter', + 'designated_resolver', + 'participant', +] +const RESOLVE_ALLOWED: DisputeActorKind[] = [ + 'admin', + 'arbiter', + 'designated_resolver', +] + +export function canCreateDispute(actor: DisputeActor, contract: ContractRecord): boolean { + return CREATE_ALLOWED.includes(classifyActor(actor, contract)) +} + +export function canViewDispute( + actor: DisputeActor, + contract: ContractRecord, + dispute: DisputeRecord +): boolean { + if (canCreateDispute(actor, contract)) return true + // A user who raised the dispute (e.g. an admin whose role changed) may + // still read their own record. + return dispute.raisedByUserId === actor.userId +} + +export function canSubmitEvidence( + actor: DisputeActor, + contract: ContractRecord +): boolean { + return VIEW_ALLOWED.includes(classifyActor(actor, contract)) +} + +export function canResolveDispute( + actor: DisputeActor, + contract: ContractRecord +): boolean { + return RESOLVE_ALLOWED.includes(classifyActor(actor, contract)) +} + +export function assertCanCreateDispute( + actor: DisputeActor, + contract: ContractRecord +): void { + if (!canCreateDispute(actor, contract)) { + throw new DisputeForbiddenError( + 'Only contract participants, the arbitrator or a designated decision-maker can open a dispute' + ) + } +} + +export function assertCanViewDispute( + actor: DisputeActor, + contract: ContractRecord, + dispute: DisputeRecord +): void { + if (!canViewDispute(actor, contract, dispute)) { + throw new DisputeForbiddenError( + 'Only contract participants, the arbitrator or a designated decision-maker can view this dispute' + ) + } +} + +export function assertCanSubmitEvidence( + actor: DisputeActor, + contract: ContractRecord +): void { + if (!canSubmitEvidence(actor, contract)) { + throw new DisputeForbiddenError( + 'Only contract participants, the arbitrator or a designated decision-maker can submit evidence' + ) + } +} + +export function assertCanResolveDispute( + actor: DisputeActor, + contract: ContractRecord +): void { + if (!canResolveDispute(actor, contract)) { + throw new DisputeForbiddenError( + 'Only the arbitrator, a designated decision-maker or an admin can resolve this dispute' + ) + } +} + +/** + * Resolution outcomes are constrained by the escrow contract: + * `resolve_dispute(milestone_id, release_to_freelancer)` is binary, so a split + * resolution cannot be expressed on-chain. Refuse it rather than silently + * mis-allocate funds. + */ +export function assertOutcomeSupportedOnChain( + outcome: string, + contract: ContractRecord +): void { + if (!contract.escrowAddress) return + if (outcome === 'resolved_split') { + throw new DisputeForbiddenError( + 'Split resolutions are not supported by the escrow contract; resolve fully to the client or freelancer' + ) + } +} diff --git a/lib/disputes/blockchain.ts b/lib/disputes/blockchain.ts new file mode 100644 index 0000000..5aa6548 --- /dev/null +++ b/lib/disputes/blockchain.ts @@ -0,0 +1,191 @@ +/** + * Dispute Resolution Workflow — Blockchain Gateway + * + * Wraps the escrow contract's `resolve_dispute(milestone_id, release_to_freelancer)` + * call behind a small interface so the service can be tested without an RPC + * endpoint. + * + * Security / reliability rules encoded here: + * • The on-chain arbiter signature is required by the contract itself + * (`arbiter.require_auth()`); the gateway signs with the configured arbiter + * key and refuses to run without it. Backend authorization never replaces + * the contract's own authorization. + * • A submission is only reported as `confirmed` after the transaction has + * been independently re-fetched from the RPC node and reported SUCCESS. + * • RPC failures/timeouts are surfaced as retryable DisputeChainError so the + * service can persist a recoverable failed/pending attempt instead of + * losing the record. + */ + +import { Keypair, Networks, TransactionBuilder } from '@stellar/stellar-sdk' +import { + SorobanContractClient, +} from '@/lib/soroban/sdk/client' +import { DisputeChainError } from './types' + +export type ChainSubmissionState = 'confirmed' | 'pending' | 'failed' + +export interface ChainResolutionRequest { + contractAddress: string + /** Escrow milestones are addressed on-chain by their u32 id. */ + milestoneId: string + /** true → funds go to the freelancer, false → funds go back to the client. */ + releaseToFreelancer: boolean + disputeId: string +} + +export interface ChainResolutionSubmission { + txHash: string | null + state: ChainSubmissionState + ledger?: number | null + errorCode?: string + errorMessage?: string +} + +export interface DisputeChainGateway { + submitResolution(request: ChainResolutionRequest): Promise + verifyResolution( + txHash: string, + contractAddress?: string + ): Promise<'confirmed' | 'failed' | 'pending' | 'unknown'> +} + +export interface SorobanDisputeChainGatewayConfig { + rpcUrl: string + networkPassphrase: string + arbiterSecret: string + /** How many ledgers to wait for confirmation inside a single request. */ + confirmationAttempts?: number + confirmationIntervalMs?: number +} + +function readConfig(): SorobanDisputeChainGatewayConfig { + const rpcUrl = ( + process.env.STELLAR_RPC_URL?.trim() ?? process.env.SOROBAN_RPC_URL?.trim() + ) + const arbiterSecret = process.env.STELLAR_ARBITER_SECRET?.trim() + const networkPassphrase = + process.env.STELLAR_NETWORK_PASSPHRASE?.trim() || Networks.TESTNET + + if (!rpcUrl || !arbiterSecret) { + throw new DisputeChainError( + 'On-chain dispute resolution is not configured (STELLAR_RPC_URL / STELLAR_ARBITER_SECRET)', + 'BLOCKCHAIN_NOT_CONFIGURED', + true + ) + } + + return { + rpcUrl, + arbiterSecret, + networkPassphrase, + confirmationAttempts: Number(process.env.STELLAR_CONFIRMATION_ATTEMPTS ?? 10), + confirmationIntervalMs: Number(process.env.STELLAR_CONFIRMATION_INTERVAL_MS ?? 1500), + } +} + +export class SorobanDisputeChainGateway implements DisputeChainGateway { + constructor(private readonly config?: SorobanDisputeChainGatewayConfig) {} + + private buildClient(contractAddress: string): SorobanContractClient { + const config = this.config ?? readConfig() + const arbiter = Keypair.fromSecret(config.arbiterSecret) + + return new SorobanContractClient({ + contractId: contractAddress, + sourcePublicKey: arbiter.publicKey(), + networkPassphrase: config.networkPassphrase, + rpcUrl: config.rpcUrl, + confirmationAttempts: config.confirmationAttempts, + confirmationIntervalMs: config.confirmationIntervalMs, + signTransaction: async (unsignedXdr: string) => { + const transaction = TransactionBuilder.fromXDR( + unsignedXdr, + config.networkPassphrase + ) + transaction.sign(arbiter) + return transaction.toXDR() + }, + }) + } + + async submitResolution( + request: ChainResolutionRequest + ): Promise { + if (!request.contractAddress) { + throw new DisputeChainError( + 'Contract has no on-chain escrow address', + 'BLOCKCHAIN_NOT_CONFIGURED', + false + ) + } + + let result + try { + result = await this.buildClient(request.contractAddress).resolveDispute( + request.contractAddress, + request.milestoneId, + request.releaseToFreelancer + ) + } catch (err) { + throw new DisputeChainError( + err instanceof Error ? err.message : 'Escrow RPC call failed', + 'BLOCKCHAIN_UNAVAILABLE', + true + ) + } + + if (result.status === 'failed') { + // A reverted transaction is deterministic: retrying the exact same call + // will not help, so report it as a non-retryable failure. + return { + txHash: result.hash, + state: 'failed', + errorCode: result.error?.code ?? 'CONTRACT_REVERTED', + errorMessage: result.error?.message ?? 'Escrow contract rejected the resolution', + } + } + + if (!result.hash) { + return { + txHash: null, + state: 'pending', + errorCode: 'TX_HASH_PENDING', + errorMessage: 'Transaction was accepted but no hash was returned yet', + } + } + + // Never trust the submission response alone — re-fetch the transaction. + const verified = await this.verifyResolution(result.hash, request.contractAddress) + if (verified === 'failed') { + return { + txHash: result.hash, + state: 'failed', + errorCode: 'CONTRACT_REVERTED', + errorMessage: 'Resolution transaction failed on-chain', + } + } + + return { + txHash: result.hash, + state: verified === 'confirmed' ? 'confirmed' : 'pending', + ledger: result.ledger ?? null, + } + } + + async verifyResolution( + txHash: string, + contractAddress?: string + ): Promise<'confirmed' | 'failed' | 'pending' | 'unknown'> { + const address = contractAddress ?? process.env.STELLAR_ESCROW_CONTRACT_ID ?? '' + if (!address) return 'unknown' + try { + const client = this.buildClient(address) + return await client.getTransactionStatus(txHash) + } catch { + return 'unknown' + } + } +} + +export const sorobanDisputeChainGateway = new SorobanDisputeChainGateway() diff --git a/lib/disputes/http.ts b/lib/disputes/http.ts new file mode 100644 index 0000000..361f5d4 --- /dev/null +++ b/lib/disputes/http.ts @@ -0,0 +1,43 @@ +/** + * Consistent HTTP mapping for dispute workflow errors. + * + * Every endpoint returns `{ error, code, ...details }`, matching the rest of + * the API. Unknown errors are logged server-side and reported as a generic + * 500 so internal details never leak to clients. + */ + +import { NextResponse } from 'next/server' +import { DisputeError } from './types' + +export function disputeErrorResponse(error: unknown): NextResponse { + if (error instanceof DisputeError) { + return NextResponse.json( + { + error: error.message, + code: error.code, + ...(error.details ?? {}), + }, + { status: error.status } + ) + } + + console.error('[disputes] Unexpected error:', error) + return NextResponse.json( + { error: 'Internal server error', code: 'INTERNAL_ERROR' }, + { status: 500 } + ) +} + +export function invalidIdResponse(kind: string): NextResponse { + return NextResponse.json( + { error: `Invalid ${kind} id`, code: 'INVALID_ID' }, + { status: 400 } + ) +} + +export function invalidJsonResponse(): NextResponse { + return NextResponse.json( + { error: 'Request body must be valid JSON', code: 'INVALID_JSON' }, + { status: 400 } + ) +} diff --git a/lib/disputes/index.ts b/lib/disputes/index.ts new file mode 100644 index 0000000..d449c3a --- /dev/null +++ b/lib/disputes/index.ts @@ -0,0 +1,45 @@ +/** + * Dispute Resolution Workflow — Public API + * + * Controllers import the singleton service and error mapper from here. + * Repositories and blockchain adapters are internal so route handlers cannot + * bypass authorization or transaction tracking. + */ + +export { + disputeWorkflowService, + DisputeWorkflowService, + evidenceFingerprint, +} from './service' +export { + DisputeError, + DisputeValidationError, + DisputeNotFoundError, + DisputeForbiddenError, + DisputeConflictError, + DisputeIneligibleError, + DisputeChainError, + disputeErrorToStatus, +} from './types' +export type { + CreateDisputeInput, + CreateDisputeResult, + SubmitEvidenceInput, + SubmitEvidenceResult, + GetDisputeResult, + ResolveDisputeInput, + ResolveDisputeResult, + DisputeOutcome, + DisputeRecord, + EvidenceRecord, + ResolutionAttemptRecord, + AuditEventRecord, +} from './types' +export { + parseCreateDisputeInput, + parseSubmitEvidenceInput, + parseResolveDisputeInput, +} from './validation' +export { isUuid } from './authorization' +export type { DisputeRepository, ConfirmResolutionRow } from './repository' +export type { DisputeChainGateway, ChainResolutionSubmission } from './blockchain' diff --git a/lib/disputes/repository.ts b/lib/disputes/repository.ts new file mode 100644 index 0000000..6c4881c --- /dev/null +++ b/lib/disputes/repository.ts @@ -0,0 +1,753 @@ +/** + * Dispute Resolution Workflow — Repository + * + * SQL access for the workflow. The interface is deliberately narrow so the + * service can be unit-tested with an in-memory fake (see __tests__/disputes). + * + * Concurrency / atomicity notes: + * • createDisputeAtomic performs the dispute INSERT, the contract transition + * and the audit append in ONE statement, guarded by the partial unique + * indexes from migration 012. A concurrent duplicate returns null instead + * of creating a second dispute. + * • confirmResolution flips the attempt, the dispute and the contract in one + * statement, guarded by `disputes.status IN (active…)`, so only the first + * concurrent confirmation wins. A loser receives null. + */ + +import { sql } from '@/lib/db' +import { + ACTIVE_DISPUTE_STATUSES, + DisputeConflictError, + type AuditEventRecord, + type ContractRecord, + type DisputeActor, + type DisputeAuditAction, + type DisputeOutcome, + type DisputeRecord, + type DisputeStatus, + type EvidenceRecord, + type EvidenceType, + type MilestoneRecord, + type ResolutionAttemptRecord, +} from './types' + +type Row = Record + +function str(value: unknown): string { + return value == null ? '' : String(value) +} + +function strOrNull(value: unknown): string | null { + return value == null ? null : String(value) +} + +function numOrNull(value: unknown): number | null { + if (value == null) return null + const n = Number(value) + return Number.isFinite(n) ? n : null +} + +function json(value: unknown): Record { + if (value && typeof value === 'object' && !Array.isArray(value)) { + return value as Record + } + if (typeof value === 'string') { + try { + const parsed = JSON.parse(value) + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {} + } catch { + return {} + } + } + return {} +} + +function toActor(row: Row): DisputeActor { + return { + userId: str(row.id), + walletAddress: str(row.wallet_address), + role: str(row.role), + } +} + +export function mapContract(row: Row): ContractRecord { + return { + id: str(row.id), + clientId: str(row.client_id), + freelancerId: str(row.freelancer_id), + status: str(row.status) as ContractRecord['status'], + escrowStatus: str(row.escrow_status) as ContractRecord['escrowStatus'], + escrowAddress: strOrNull(row.escrow_address), + arbiterAddress: strOrNull(row.arbiter_address), + designatedResolverId: strOrNull(row.designated_resolver_id), + activeDisputeId: strOrNull(row.active_dispute_id), + totalAmount: str(row.total_amount), + currency: str(row.currency), + } +} + +export function mapDispute(row: Row): DisputeRecord { + return { + id: str(row.id), + contractId: str(row.contract_id), + milestoneId: strOrNull(row.milestone_id), + raisedBy: str(row.raised_by) as DisputeRecord['raisedBy'], + raisedByUserId: str(row.raised_by_user_id), + reason: str(row.reason), + desiredOutcome: strOrNull(row.desired_outcome), + status: str(row.status) as DisputeStatus, + resolverId: strOrNull(row.resolver_id), + resolutionNotes: strOrNull(row.resolution_notes), + resolutionMetadata: json(row.resolution_metadata), + clientRefundAmount: strOrNull(row.client_refund_amount), + freelancerPayoutAmount: strOrNull(row.freelancer_payout_amount), + resolvedAt: strOrNull(row.resolved_at), + creationIdempotencyKey: strOrNull(row.creation_idempotency_key), + lastResolutionAttemptId: strOrNull(row.last_resolution_attempt_id), + createdAt: str(row.created_at), + updatedAt: str(row.updated_at), + } +} + +export function mapEvidence(row: Row): EvidenceRecord { + return { + id: str(row.id), + disputeId: str(row.dispute_id), + milestoneId: strOrNull(row.milestone_id), + submittedByUserId: str(row.submitted_by_user_id), + evidenceType: str(row.evidence_type) as EvidenceType, + referenceUrl: str(row.reference_url), + label: strOrNull(row.label), + description: strOrNull(row.description), + contentHash: str(row.content_hash), + createdAt: str(row.created_at), + } +} + +export function mapAttempt(row: Row): ResolutionAttemptRecord { + return { + id: str(row.id), + disputeId: str(row.dispute_id), + requestedByUserId: str(row.requested_by_user_id), + outcome: str(row.outcome) as DisputeOutcome, + reasons: str(row.reasons), + metadata: json(row.metadata), + status: str(row.status) as ResolutionAttemptRecord['status'], + onchain: row.onchain !== false, + txHash: strOrNull(row.tx_hash), + ledger: numOrNull(row.ledger), + errorCode: strOrNull(row.error_code), + errorMessage: strOrNull(row.error_message), + retryOf: strOrNull(row.retry_of), + idempotencyKey: str(row.idempotency_key), + submittedAt: strOrNull(row.submitted_at), + confirmedAt: strOrNull(row.confirmed_at), + failedAt: strOrNull(row.failed_at), + createdAt: str(row.created_at), + updatedAt: str(row.updated_at), + } +} + +export function mapAudit(row: Row): AuditEventRecord { + return { + id: str(row.id), + disputeId: str(row.dispute_id), + contractId: str(row.contract_id), + actorUserId: strOrNull(row.actor_user_id), + actorWallet: strOrNull(row.actor_wallet), + action: str(row.action) as DisputeAuditAction, + metadata: json(row.metadata), + createdAt: str(row.created_at), + } +} + +export interface CreateDisputeRow { + contractId: string + milestoneId: string | null + raisedBy: 'client' | 'freelancer' | 'admin' + raisedByUserId: string + reason: string + desiredOutcome: string | null + idempotencyKey: string + evidence: Array> + actorWallet: string +} + +export interface CreateAttemptRow { + disputeId: string + requestedByUserId: string + outcome: DisputeOutcome + reasons: string + metadata: Record + onchain: boolean + idempotencyKey: string + retryOf: string | null +} + +export interface ConfirmResolutionRow { + disputeId: string + contractId: string + attemptId: string + resolverId: string + outcome: DisputeOutcome + reasons: string + metadata: Record + txHash: string | null + ledger: number | null + contractStatus: ContractRecord['status'] + clientRefundAmount: string | null + freelancerPayoutAmount: string | null + actorWallet: string +} + +export interface ConfirmResolutionResult { + attempt: ResolutionAttemptRecord + dispute: DisputeRecord + contractStatus: ContractRecord['status'] + audit: AuditEventRecord | null +} + +export interface DisputeRepository { + isAvailable(): boolean + findUserByWallet(walletAddress: string): Promise + getContract(contractId: string): Promise + getMilestone(milestoneId: string): Promise + getDispute(disputeId: string): Promise + getDisputeByCreationKey(contractId: string, key: string): Promise + getActiveDisputeForContract(contractId: string): Promise + createDisputeAtomic(input: CreateDisputeRow): Promise<{ dispute: DisputeRecord; contractStatus: ContractRecord['status'] } | null> + listEvidence(disputeId: string): Promise + insertEvidence(input: { + disputeId: string + milestoneId: string | null + submittedByUserId: string + evidenceType: EvidenceType + referenceUrl: string + label: string | null + description: string | null + contentHash: string + actorWallet: string + contractId: string + }): Promise + getEvidenceByHash(disputeId: string, contentHash: string): Promise + getAttempt(attemptId: string): Promise + getAttemptByKey(disputeId: string, key: string): Promise + getPendingAttempt(disputeId: string): Promise + getLatestAttempt(disputeId: string): Promise + listAttempts(disputeId: string): Promise + createAttempt(input: CreateAttemptRow): Promise + updateAttempt( + attemptId: string, + patch: { + status?: ResolutionAttemptRecord['status'] + txHash?: string | null + ledger?: number | null + errorCode?: string | null + errorMessage?: string | null + submittedAt?: string | null + confirmedAt?: string | null + failedAt?: string | null + } + ): Promise + confirmResolution(input: ConfirmResolutionRow): Promise + appendAudit(input: { + disputeId: string | null + contractId: string + actorUserId: string | null + actorWallet: string | null + action: DisputeAuditAction + metadata?: Record + }): Promise + listAudit(disputeId: string, limit: number): Promise + linkAttemptToDispute(disputeId: string, attemptId: string): Promise +} + +export class SqlDisputeRepository implements DisputeRepository { + isAvailable(): boolean { + return Boolean(process.env.DATABASE_URL) + } + + async findUserByWallet(walletAddress: string): Promise { + const rows = (await sql` + SELECT id, wallet_address, role::text AS role + FROM users + WHERE lower(wallet_address) = lower(${walletAddress}) + LIMIT 1 + `) as Row[] + return rows[0] ? toActor(rows[0]) : null + } + + async getContract(contractId: string): Promise { + const rows = (await sql` + SELECT id, client_id, freelancer_id, status, escrow_status, escrow_address, + arbiter_address, designated_resolver_id, active_dispute_id, + total_amount, currency + FROM contracts + WHERE id = ${contractId} + LIMIT 1 + `) as Row[] + return rows[0] ? mapContract(rows[0]) : null + } + + async getMilestone(milestoneId: string): Promise { + const rows = (await sql` + SELECT id, contract_id, status, amount + FROM milestones + WHERE id = ${milestoneId} + LIMIT 1 + `) as Row[] + const row = rows[0] + if (!row) return null + return { + id: str(row.id), + contractId: strOrNull(row.contract_id), + status: str(row.status), + amount: str(row.amount), + } + } + + async getDispute(disputeId: string): Promise { + const rows = (await sql` + SELECT id, contract_id, milestone_id, raised_by, raised_by_user_id, reason, + desired_outcome, status, resolver_id, resolution_notes, + resolution_metadata, client_refund_amount, freelancer_payout_amount, + resolved_at, creation_idempotency_key, last_resolution_attempt_id, + created_at, updated_at + FROM disputes + WHERE id = ${disputeId} + LIMIT 1 + `) as Row[] + return rows[0] ? mapDispute(rows[0]) : null + } + + async getDisputeByCreationKey( + contractId: string, + key: string + ): Promise { + const rows = (await sql` + SELECT id, contract_id, milestone_id, raised_by, raised_by_user_id, reason, + desired_outcome, status, resolver_id, resolution_notes, + resolution_metadata, client_refund_amount, freelancer_payout_amount, + resolved_at, creation_idempotency_key, last_resolution_attempt_id, + created_at, updated_at + FROM disputes + WHERE contract_id = ${contractId} AND creation_idempotency_key = ${key} + LIMIT 1 + `) as Row[] + return rows[0] ? mapDispute(rows[0]) : null + } + + async getActiveDisputeForContract(contractId: string): Promise { + const rows = (await sql` + SELECT id, contract_id, milestone_id, raised_by, raised_by_user_id, reason, + desired_outcome, status, resolver_id, resolution_notes, + resolution_metadata, client_refund_amount, freelancer_payout_amount, + resolved_at, creation_idempotency_key, last_resolution_attempt_id, + created_at, updated_at + FROM disputes + WHERE contract_id = ${contractId} + AND status IN ('open', 'under_review', 'escalated') + ORDER BY created_at DESC + LIMIT 1 + `) as Row[] + return rows[0] ? mapDispute(rows[0]) : null + } + + async createDisputeAtomic( + input: CreateDisputeRow + ): Promise<{ dispute: DisputeRecord; contractStatus: ContractRecord['status'] } | null> { + const rows = (await sql` + WITH inserted AS ( + INSERT INTO disputes ( + contract_id, milestone_id, raised_by, raised_by_user_id, reason, + desired_outcome, evidence, status, creation_idempotency_key + ) + SELECT + ${input.contractId}::uuid, + ${input.milestoneId}::uuid, + ${input.raisedBy}::dispute_raised_by, + ${input.raisedByUserId}::uuid, + ${input.reason}, + ${input.desiredOutcome}, + ${JSON.stringify(input.evidence)}::jsonb, + 'open', + ${input.idempotencyKey} + WHERE NOT EXISTS ( + SELECT 1 FROM disputes d + WHERE d.contract_id = ${input.contractId}::uuid + AND d.status IN ('open', 'under_review', 'escalated') + ) + RETURNING * + ), + updated_contract AS ( + UPDATE contracts c + SET status = 'disputed', + active_dispute_id = (SELECT id FROM inserted), + updated_at = NOW() + WHERE c.id = ${input.contractId}::uuid + AND EXISTS (SELECT 1 FROM inserted) + RETURNING c.status + ), + audit AS ( + INSERT INTO dispute_audit_events ( + dispute_id, contract_id, actor_user_id, actor_wallet, action, metadata + ) + SELECT + i.id, + ${input.contractId}::uuid, + ${input.raisedByUserId}::uuid, + ${input.actorWallet}, + 'dispute_created', + ${JSON.stringify({ + reason: input.reason, + milestoneId: input.milestoneId, + desiredOutcome: input.desiredOutcome, + })}::jsonb + FROM inserted i + RETURNING id + ) + SELECT + (SELECT to_jsonb(d) FROM inserted d) AS dispute, + (SELECT to_jsonb(c) FROM updated_contract c) AS contract + `) as Row[] + + const row = rows[0] + const disputeRow = row?.dispute as Row | null | undefined + if (!disputeRow) return null + const contractRow = row?.contract as Row | null | undefined + return { + dispute: mapDispute(disputeRow), + contractStatus: (contractRow?.status as ContractRecord['status']) ?? 'disputed', + } + } + + async listEvidence(disputeId: string): Promise { + const rows = (await sql` + SELECT id, dispute_id, milestone_id, submitted_by_user_id, evidence_type, + reference_url, label, description, content_hash, created_at + FROM dispute_evidence_items + WHERE dispute_id = ${disputeId} + ORDER BY created_at ASC + `) as Row[] + return rows.map(mapEvidence) + } + + async getEvidenceByHash( + disputeId: string, + contentHash: string + ): Promise { + const rows = (await sql` + SELECT id, dispute_id, milestone_id, submitted_by_user_id, evidence_type, + reference_url, label, description, content_hash, created_at + FROM dispute_evidence_items + WHERE dispute_id = ${disputeId} AND content_hash = ${contentHash} + LIMIT 1 + `) as Row[] + return rows[0] ? mapEvidence(rows[0]) : null + } + + async insertEvidence(input: { + disputeId: string + milestoneId: string | null + submittedByUserId: string + evidenceType: EvidenceType + referenceUrl: string + label: string | null + description: string | null + contentHash: string + actorWallet: string + contractId: string + }): Promise { + const rows = (await sql` + WITH inserted AS ( + INSERT INTO dispute_evidence_items ( + dispute_id, milestone_id, submitted_by_user_id, evidence_type, + reference_url, label, description, content_hash + ) + VALUES ( + ${input.disputeId}::uuid, + ${input.milestoneId}::uuid, + ${input.submittedByUserId}::uuid, + ${input.evidenceType}, + ${input.referenceUrl}, + ${input.label}, + ${input.description}, + ${input.contentHash} + ) + ON CONFLICT (dispute_id, content_hash) DO NOTHING + RETURNING * + ), + audit AS ( + INSERT INTO dispute_audit_events ( + dispute_id, contract_id, actor_user_id, actor_wallet, action, metadata + ) + SELECT + i.dispute_id, + ${input.contractId}::uuid, + ${input.submittedByUserId}::uuid, + ${input.actorWallet}, + 'evidence_submitted', + ${JSON.stringify({ + evidenceId: input.contentHash, + evidenceType: input.evidenceType, + reference: input.referenceUrl, + })}::jsonb + FROM inserted i + RETURNING id + ) + SELECT (SELECT to_jsonb(e) FROM inserted e) AS evidence + `) as Row[] + + const evidenceRow = rows[0]?.evidence as Row | null | undefined + return evidenceRow ? mapEvidence(evidenceRow) : null + } + + async getAttempt(attemptId: string): Promise { + const rows = (await sql` + SELECT * FROM dispute_resolution_attempts WHERE id = ${attemptId} LIMIT 1 + `) as Row[] + return rows[0] ? mapAttempt(rows[0]) : null + } + + async getAttemptByKey( + disputeId: string, + key: string + ): Promise { + const rows = (await sql` + SELECT * FROM dispute_resolution_attempts + WHERE dispute_id = ${disputeId} AND idempotency_key = ${key} + LIMIT 1 + `) as Row[] + return rows[0] ? mapAttempt(rows[0]) : null + } + + async getPendingAttempt(disputeId: string): Promise { + const rows = (await sql` + SELECT * FROM dispute_resolution_attempts + WHERE dispute_id = ${disputeId} AND status = 'pending' + ORDER BY created_at DESC + LIMIT 1 + `) as Row[] + return rows[0] ? mapAttempt(rows[0]) : null + } + + async getLatestAttempt(disputeId: string): Promise { + const rows = (await sql` + SELECT * FROM dispute_resolution_attempts + WHERE dispute_id = ${disputeId} + ORDER BY created_at DESC + LIMIT 1 + `) as Row[] + return rows[0] ? mapAttempt(rows[0]) : null + } + + async listAttempts(disputeId: string): Promise { + const rows = (await sql` + SELECT * FROM dispute_resolution_attempts + WHERE dispute_id = ${disputeId} + ORDER BY created_at DESC + LIMIT 25 + `) as Row[] + return rows.map(mapAttempt) + } + + async createAttempt(input: CreateAttemptRow): Promise { + try { + const rows = (await sql` + INSERT INTO dispute_resolution_attempts ( + dispute_id, requested_by_user_id, outcome, reasons, metadata, + onchain, idempotency_key, retry_of, submitted_at + ) + VALUES ( + ${input.disputeId}::uuid, + ${input.requestedByUserId}::uuid, + ${input.outcome}::dispute_status, + ${input.reasons}, + ${JSON.stringify(input.metadata)}::jsonb, + ${input.onchain}, + ${input.idempotencyKey}, + ${input.retryOf}::uuid, + NOW() + ) + RETURNING * + `) as Row[] + return mapAttempt(rows[0]) + } catch (err) { + if (isUniqueViolation(err)) { + throw new DisputeConflictError( + 'Another resolution attempt is already in progress for this dispute', + 'RESOLUTION_IN_PROGRESS' + ) + } + throw err + } + } + + async updateAttempt( + attemptId: string, + patch: { + status?: ResolutionAttemptRecord['status'] + txHash?: string | null + ledger?: number | null + errorCode?: string | null + errorMessage?: string | null + submittedAt?: string | null + confirmedAt?: string | null + failedAt?: string | null + } + ): Promise { + const rows = (await sql` + UPDATE dispute_resolution_attempts + SET status = COALESCE(${patch.status ?? null}, status), + tx_hash = COALESCE(${patch.txHash ?? null}, tx_hash), + ledger = COALESCE(${patch.ledger ?? null}, ledger), + error_code = COALESCE(${patch.errorCode ?? null}, error_code), + error_message = COALESCE(${patch.errorMessage ?? null}, error_message), + submitted_at = COALESCE(${patch.submittedAt ?? null}::timestamptz, submitted_at), + confirmed_at = COALESCE(${patch.confirmedAt ?? null}::timestamptz, confirmed_at), + failed_at = COALESCE(${patch.failedAt ?? null}::timestamptz, failed_at), + updated_at = NOW() + WHERE id = ${attemptId} + RETURNING * + `) as Row[] + return rows[0] ? mapAttempt(rows[0]) : null + } + + async confirmResolution( + input: ConfirmResolutionRow + ): Promise { + const rows = (await sql` + WITH resolved AS ( + UPDATE disputes d + SET status = ${input.outcome}::dispute_status, + resolver_id = ${input.resolverId}::uuid, + resolution_notes = ${input.reasons}, + resolution_metadata = ${JSON.stringify(input.metadata)}::jsonb, + client_refund_amount = ${input.clientRefundAmount}, + freelancer_payout_amount = ${input.freelancerPayoutAmount}, + resolved_at = NOW(), + updated_at = NOW(), + last_resolution_attempt_id = ${input.attemptId}::uuid + WHERE d.id = ${input.disputeId}::uuid + AND d.status IN ('open', 'under_review', 'escalated') + RETURNING d.* + ), + confirmed_attempt AS ( + UPDATE dispute_resolution_attempts a + SET status = 'confirmed', + tx_hash = COALESCE(${input.txHash}, a.tx_hash), + ledger = COALESCE(${input.ledger}, a.ledger), + confirmed_at = NOW(), + updated_at = NOW() + WHERE a.id = ${input.attemptId}::uuid + AND a.status = 'pending' + AND EXISTS (SELECT 1 FROM resolved) + RETURNING a.* + ), + updated_contract AS ( + UPDATE contracts c + SET status = ${input.contractStatus}::contract_status, + active_dispute_id = NULL, + completed_at = CASE WHEN ${input.contractStatus} = 'completed' THEN NOW() ELSE c.completed_at END, + cancelled_at = CASE WHEN ${input.contractStatus} = 'cancelled' THEN NOW() ELSE c.cancelled_at END, + updated_at = NOW() + WHERE c.id = ${input.contractId}::uuid + AND EXISTS (SELECT 1 FROM resolved) + RETURNING c.status + ), + audit AS ( + INSERT INTO dispute_audit_events ( + dispute_id, contract_id, actor_user_id, actor_wallet, action, metadata + ) + SELECT + ${input.disputeId}::uuid, + ${input.contractId}::uuid, + ${input.resolverId}::uuid, + ${input.actorWallet}, + 'resolution_confirmed', + ${JSON.stringify({ + attemptId: input.attemptId, + outcome: input.outcome, + txHash: input.txHash, + ledger: input.ledger, + onchain: input.txHash !== null, + })}::jsonb + WHERE EXISTS (SELECT 1 FROM resolved) + RETURNING * + ) + SELECT + (SELECT to_jsonb(a) FROM confirmed_attempt a) AS attempt, + (SELECT to_jsonb(d) FROM resolved d) AS dispute, + (SELECT to_jsonb(c) FROM updated_contract c) AS contract, + (SELECT to_jsonb(au) FROM audit au) AS audit + `) as Row[] + + const row = rows[0] + const attemptRow = row?.attempt as Row | null | undefined + const disputeRow = row?.dispute as Row | null | undefined + if (!attemptRow || !disputeRow) return null + + const contractRow = row?.contract as Row | null | undefined + const auditRow = row?.audit as Row | null | undefined + + return { + attempt: mapAttempt(attemptRow), + dispute: mapDispute(disputeRow), + contractStatus: (contractRow?.status as ContractRecord['status']) ?? input.contractStatus, + audit: auditRow ? mapAudit(auditRow) : null, + } + } + + async appendAudit(input: { + disputeId: string | null + contractId: string + actorUserId: string | null + actorWallet: string | null + action: DisputeAuditAction + metadata?: Record + }): Promise { + const rows = (await sql` + INSERT INTO dispute_audit_events ( + dispute_id, contract_id, actor_user_id, actor_wallet, action, metadata + ) + VALUES ( + ${input.disputeId}::uuid, + ${input.contractId}::uuid, + ${input.actorUserId}::uuid, + ${input.actorWallet}, + ${input.action}, + ${JSON.stringify(input.metadata ?? {})}::jsonb + ) + RETURNING * + `) as Row[] + return rows[0] ? mapAudit(rows[0]) : null + } + + async listAudit(disputeId: string, limit: number): Promise { + const rows = (await sql` + SELECT * FROM dispute_audit_events + WHERE dispute_id = ${disputeId} + ORDER BY created_at ASC + LIMIT ${limit} + `) as Row[] + return rows.map(mapAudit) + } + + async linkAttemptToDispute(disputeId: string, attemptId: string): Promise { + await sql` + UPDATE disputes + SET last_resolution_attempt_id = ${attemptId}::uuid, updated_at = NOW() + WHERE id = ${disputeId}::uuid + ` + } +} + +function isUniqueViolation(error: unknown): boolean { + const err = error as { code?: string; message?: string } + return err?.code === '23505' || /duplicate key value/i.test(err?.message ?? '') +} + +export const disputeRepository = new SqlDisputeRepository() + +/** Exported for tests/documentation: the active-status list used in SQL. */ +export const ACTIVE_STATUSES: readonly string[] = ACTIVE_DISPUTE_STATUSES diff --git a/lib/disputes/service.ts b/lib/disputes/service.ts new file mode 100644 index 0000000..bbe86d0 --- /dev/null +++ b/lib/disputes/service.ts @@ -0,0 +1,917 @@ +/** + * Dispute Resolution Workflow — Service + * + * Orchestrates the dispute lifecycle: + * create → evidence → resolve (on-chain) → confirm/fail with retry support. + * + * Invariants enforced here: + * • Actors are resolved from the authenticated wallet only. + * • Contract/dispute state is loaded from the database, never trusted from + * the request body. + * • A dispute is never marked resolved until the blockchain transaction has + * been verified; `pending` and `failed` attempts are stored separately. + * • Every lifecycle event is appended to the immutable audit trail. + * • Duplicate requests replay deterministically via idempotency keys, and + * concurrent resolutions are rejected by the repository's unique indexes. + */ + +import { createHash } from 'crypto' + +import { + DisputeConflictError, + DisputeError, + DisputeIneligibleError, + DisputeNotFoundError, + DisputeValidationError, + type ActiveDisputeStatus, + type ContractRecord, + type CreateDisputeInput, + type CreateDisputeResult, + type DisputeActor, + type DisputeAuditAction, + type DisputeOutcome, + type DisputeRecord, + type EvidenceRecord, + type EvidenceReferenceInput, + type GetDisputeResult, + type ResolutionAttemptRecord, + type ResolutionState, + type ResolveDisputeInput, + type ResolveDisputeResult, + type SubmitEvidenceInput, + type SubmitEvidenceResult, +} from './types' +import { + ACTIVE_DISPUTE_STATUSES, +} from './types' +import { + assertCanCreateDispute, + assertCanResolveDispute, + assertCanSubmitEvidence, + assertCanViewDispute, + assertOutcomeSupportedOnChain, +} from './authorization' +import { assertSplitAmounts } from './validation' +import { disputeRepository, type DisputeRepository } from './repository' +import { + sorobanDisputeChainGateway, + type ChainResolutionSubmission, + type DisputeChainGateway, +} from './blockchain' + +const CONTRACT_OUTCOME_STATUS: Record = { + resolved_client: 'cancelled', + resolved_freelancer: 'completed', + resolved_split: 'completed', + withdrawn: 'active', +} + +/** Escrow contract statuses that prove funds are actually locked. */ +const DISPUTABLE_ESCROW_STATUSES = ['funded', 'partially_released'] + +/** Milestone states the escrow contract allows a dispute to be raised from. */ +const DISPUTABLE_MILESTONE_STATUSES = ['submitted', 'approved', 'expired', 'extended'] + +export function evidenceFingerprint(reference: EvidenceReferenceInput): string { + return createHash('sha256') + .update(`${reference.type}|${reference.url}|${reference.label ?? ''}`) + .digest('hex') +} + +function isActiveStatus(status: string): status is ActiveDisputeStatus { + return (ACTIVE_DISPUTE_STATUSES as readonly string[]).includes(status) +} + +export class DisputeWorkflowService { + constructor( + private readonly repo: DisputeRepository = disputeRepository, + private readonly chain: DisputeChainGateway = sorobanDisputeChainGateway + ) {} + + // ========================================================================= + // POST /api/contracts/:id/disputes + // ========================================================================= + + async createDispute(input: CreateDisputeInput): Promise { + this.assertStorageAvailable() + + const contract = await this.requireContract(input.contractId) + const actor = await this.requireActor(input.actorWalletAddress) + + // Replay of an identical request must return the original dispute. + const replay = await this.repo.getDisputeByCreationKey( + contract.id, + input.idempotencyKey + ) + if (replay) { + return { dispute: replay, contractStatus: contract.status, replayed: true } + } + + try { + assertCanCreateDispute(actor, contract) + } catch (err) { + await this.safeAudit({ + disputeId: contract.activeDisputeId, + contractId: contract.id, + actorUserId: actor.userId, + actorWallet: actor.walletAddress, + action: 'authorization_denied', + metadata: { operation: 'dispute_creation' }, + }) + throw err + } + + // Duplicate detection comes first: a contract in 'disputed' state is + // expected to have an active dispute, and callers need the existing id. + const activeDispute = await this.repo.getActiveDisputeForContract(contract.id) + if (activeDispute) { + throw new DisputeConflictError( + 'This contract already has an active dispute', + 'DISPUTE_ALREADY_EXISTS', + { existingDisputeId: activeDispute.id } + ) + } + + if (contract.status !== 'active' && contract.status !== 'paused') { + throw new DisputeIneligibleError( + `A dispute cannot be opened while the contract status is '${contract.status}'`, + { contractStatus: contract.status } + ) + } + if (!DISPUTABLE_ESCROW_STATUSES.includes(contract.escrowStatus)) { + throw new DisputeIneligibleError( + `A dispute requires funded escrow (current escrow status: '${contract.escrowStatus}')`, + { escrowStatus: contract.escrowStatus } + ) + } + + if (input.milestoneId) { + const milestone = await this.repo.getMilestone(input.milestoneId) + if (!milestone) throw new DisputeNotFoundError('milestone', input.milestoneId) + if (milestone.contractId && milestone.contractId !== contract.id) { + throw new DisputeValidationError('milestoneId does not belong to this contract') + } + if (!DISPUTABLE_MILESTONE_STATUSES.includes(milestone.status)) { + throw new DisputeIneligibleError( + `The milestone cannot be disputed from status '${milestone.status}'`, + { milestoneStatus: milestone.status } + ) + } + } else if (contract.escrowAddress) { + // The escrow contract resolves disputes per milestone; without one there + // is nothing the arbiter can settle on-chain. + throw new DisputeValidationError( + 'milestoneId is required to dispute an on-chain escrowed contract' + ) + } + + const evidencePayload = (input.evidence ?? []).map((reference) => ({ + type: reference.type, + url: reference.url, + label: reference.label ?? null, + hash: evidenceFingerprint(reference), + })) + + const created = await this.repo.createDisputeAtomic({ + contractId: contract.id, + milestoneId: input.milestoneId ?? null, + raisedBy: + actor.userId === contract.clientId + ? 'client' + : actor.userId === contract.freelancerId + ? 'freelancer' + : 'admin', + raisedByUserId: actor.userId, + reason: input.reason, + desiredOutcome: input.desiredOutcome ?? null, + idempotencyKey: input.idempotencyKey, + evidence: evidencePayload, + actorWallet: actor.walletAddress, + }) + + if (!created) { + // Lost a race against a concurrent creation (or the contract changed). + const raced = await this.repo.getActiveDisputeForContract(contract.id) + if (raced) { + throw new DisputeConflictError( + 'This contract already has an active dispute', + 'DISPUTE_ALREADY_EXISTS', + { existingDisputeId: raced.id } + ) + } + throw new DisputeIneligibleError( + 'The contract is no longer eligible for a dispute' + ) + } + + return { + dispute: created.dispute, + contractStatus: created.contractStatus, + replayed: false, + } + } + + // ========================================================================= + // POST /api/disputes/:id/evidence + // ========================================================================= + + async submitEvidence(input: SubmitEvidenceInput): Promise { + this.assertStorageAvailable() + + const dispute = await this.requireDispute(input.disputeId) + const contract = await this.requireContract(dispute.contractId) + const actor = await this.requireActor(input.actorWalletAddress) + + try { + assertCanSubmitEvidence(actor, contract) + } catch (err) { + await this.safeAudit({ + disputeId: dispute.id, + contractId: contract.id, + actorUserId: actor.userId, + actorWallet: actor.walletAddress, + action: 'authorization_denied', + metadata: { operation: 'evidence_submission' }, + }) + throw err + } + + if (!isActiveStatus(dispute.status)) { + throw new DisputeConflictError( + 'Evidence can no longer be submitted to a closed dispute', + 'DISPUTE_CLOSED' + ) + } + + const inserted: EvidenceRecord[] = [] + const duplicates: string[] = [] + + for (const reference of input.references) { + const contentHash = evidenceFingerprint(reference) + const existing = await this.repo.getEvidenceByHash(dispute.id, contentHash) + if (existing) { + duplicates.push(reference.url) + continue + } + + const record = await this.repo.insertEvidence({ + disputeId: dispute.id, + milestoneId: dispute.milestoneId, + submittedByUserId: actor.userId, + evidenceType: reference.type, + referenceUrl: reference.url, + label: reference.label ?? null, + description: reference.description ?? input.description ?? null, + contentHash, + actorWallet: actor.walletAddress, + contractId: contract.id, + }) + + if (record) inserted.push(record) + else duplicates.push(reference.url) + } + + return { evidence: inserted, duplicates } + } + + // ========================================================================= + // GET /api/disputes/:id + // ========================================================================= + + async getDispute(disputeId: string, actorWalletAddress: string): Promise { + this.assertStorageAvailable() + + const dispute = await this.requireDispute(disputeId) + const contract = await this.requireContract(dispute.contractId) + const actor = await this.requireActor(actorWalletAddress) + + assertCanViewDispute(actor, contract, dispute) + + const [evidence, attempts, auditTrail] = await Promise.all([ + this.repo.listEvidence(dispute.id), + this.repo.listAttempts(dispute.id), + this.repo.listAudit(dispute.id, 100), + ]) + + return { + dispute, + evidence, + resolutionAttempt: attempts[0] ?? null, + attempts, + auditTrail, + } + } + + // ========================================================================= + // POST /api/disputes/:id/resolve + // ========================================================================= + + async resolveDispute(input: ResolveDisputeInput): Promise { + this.assertStorageAvailable() + + const dispute = await this.requireDispute(input.disputeId) + const contract = await this.requireContract(dispute.contractId) + const actor = await this.requireActor(input.actorWalletAddress) + + try { + assertCanResolveDispute(actor, contract) + } catch (err) { + await this.safeAudit({ + disputeId: dispute.id, + contractId: contract.id, + actorUserId: actor.userId, + actorWallet: actor.walletAddress, + action: 'authorization_denied', + metadata: { operation: 'dispute_resolution' }, + }) + throw err + } + + // --- Idempotent replay of a previous attempt ------------------------- + const existingAttempt = await this.repo.getAttemptByKey( + dispute.id, + input.idempotencyKey + ) + if (existingAttempt) { + this.assertSameResolutionPayload(existingAttempt, input) + if (existingAttempt.status === 'confirmed') { + return { + state: 'confirmed', + dispute, + attempt: existingAttempt, + contractStatus: contract.status, + replayed: true, + retryable: false, + } + } + if (existingAttempt.status === 'pending') { + return { + state: 'pending', + dispute, + attempt: existingAttempt, + contractStatus: contract.status, + replayed: true, + retryable: true, + } + } + // A failed attempt replayed with the same key is a retry. + return this.retryAttempt(existingAttempt, dispute, contract, actor) + } + + // --- A dispute can only be resolved once ----------------------------- + if (!isActiveStatus(dispute.status)) { + throw new DisputeConflictError( + 'This dispute has already been resolved', + 'RESOLUTION_ALREADY_FINALISED', + { disputeStatus: dispute.status, resolvedAt: dispute.resolvedAt } + ) + } + + // --- Explicit retry of a specific failed attempt --------------------- + if (input.retryAttemptId) { + const target = await this.repo.getAttempt(input.retryAttemptId) + if (!target || target.disputeId !== dispute.id) { + throw new DisputeNotFoundError('dispute', input.retryAttemptId) + } + if (target.status !== 'failed') { + throw new DisputeConflictError( + 'Only failed resolution attempts can be retried', + 'RESOLUTION_IN_PROGRESS', + { attemptStatus: target.status } + ) + } + return this.retryAttempt( + target, + dispute, + contract, + actor, + input.idempotencyKey, + input + ) + } + + // --- Concurrent resolution guard ------------------------------------- + const pending = await this.repo.getPendingAttempt(dispute.id) + if (pending) { + const state = await this.reconcilePendingAttempt(pending, dispute, contract, actor) + if (state) return state + throw new DisputeConflictError( + 'A resolution for this dispute is already in progress', + 'RESOLUTION_IN_PROGRESS', + { attemptId: pending.id, txHash: pending.txHash } + ) + } + + // --- Validate the requested outcome ---------------------------------- + assertOutcomeSupportedOnChain(input.outcome, contract) + assertSplitAmounts( + input.outcome, + contract.totalAmount, + input.clientRefundAmount, + input.freelancerPayoutAmount + ) + + const onchain = Boolean(contract.escrowAddress) && input.outcome !== 'withdrawn' + if (onchain && !dispute.milestoneId) { + throw new DisputeValidationError( + 'The escrow contract can only settle milestone-scoped disputes; milestoneId is missing' + ) + } + + // Split amounts are part of the immutable resolution record. They live in + // the attempt metadata so the audit trail and the dispute row agree. + const resolutionMetadata: Record = { + ...input.metadata, + ...(input.outcome === 'resolved_split' + ? { + clientRefundAmount: input.clientRefundAmount ?? null, + freelancerPayoutAmount: input.freelancerPayoutAmount ?? null, + } + : {}), + } + + const attempt = await this.repo.createAttempt({ + disputeId: dispute.id, + requestedByUserId: actor.userId, + outcome: input.outcome, + reasons: input.reasons, + metadata: resolutionMetadata, + onchain, + idempotencyKey: input.idempotencyKey, + retryOf: null, + }) + + await this.repo.linkAttemptToDispute(dispute.id, attempt.id) + await this.safeAudit({ + disputeId: dispute.id, + contractId: contract.id, + actorUserId: actor.userId, + actorWallet: actor.walletAddress, + action: 'resolution_requested', + metadata: { + attemptId: attempt.id, + outcome: input.outcome, + onchain, + txHash: null, + }, + }) + + return this.executeAttempt(attempt, dispute, contract, actor, input) + } + + /** + * Reconcile a pending resolution against the chain. Used by the retry flow + * and exposed to callers so a crashed/timeout resolution can be recovered + * without losing the dispute record. + */ + async reconcileResolution( + disputeId: string, + actorWalletAddress: string + ): Promise { + this.assertStorageAvailable() + + const dispute = await this.requireDispute(disputeId) + const contract = await this.requireContract(dispute.contractId) + const actor = await this.requireActor(actorWalletAddress) + assertCanResolveDispute(actor, contract) + + const pending = await this.repo.getPendingAttempt(dispute.id) + if (!pending) return null + return this.reconcilePendingAttempt(pending, dispute, contract, actor) + } + + // ========================================================================= + // Internals + // ========================================================================= + + private assertSameResolutionPayload( + attempt: ResolutionAttemptRecord, + input: ResolveDisputeInput + ): void { + if (attempt.outcome !== input.outcome || attempt.reasons !== input.reasons) { + throw new DisputeConflictError( + 'This idempotency key was already used with a different resolution payload', + 'IDEMPOTENCY_KEY_REUSED', + { attemptId: attempt.id } + ) + } + } + + private async executeAttempt( + attempt: ResolutionAttemptRecord, + dispute: DisputeRecord, + contract: ContractRecord, + actor: DisputeActor, + input: ResolveDisputeInput + ): Promise { + // Withdrawals are an off-chain state change: no funds move. + if (!attempt.onchain) { + return this.confirmAttempt(attempt, dispute, contract, actor, null, null) + } + + let submission: ChainResolutionSubmission + try { + submission = await this.chain.submitResolution({ + contractAddress: contract.escrowAddress as string, + milestoneId: dispute.milestoneId as string, + releaseToFreelancer: input.outcome === 'resolved_freelancer', + disputeId: dispute.id, + }) + } catch (err) { + const code = err instanceof DisputeError ? err.code : 'BLOCKCHAIN_UNAVAILABLE' + const message = + err instanceof Error ? err.message : 'Dispute resolution could not be submitted' + return this.failAttempt(attempt, dispute, contract, actor, { + code, + message, + retryable: true, + }) + } + + if (submission.state === 'confirmed') { + return this.confirmAttempt( + attempt, + dispute, + contract, + actor, + submission.txHash, + submission.ledger ?? null + ) + } + + if (submission.state === 'failed') { + return this.failAttempt(attempt, dispute, contract, actor, { + code: submission.errorCode ?? 'BLOCKCHAIN_RESOLUTION_FAILED', + message: submission.errorMessage ?? 'The escrow contract rejected the resolution', + retryable: false, + txHash: submission.txHash, + }) + } + + // --- Pending: the transaction is on its way but not yet verified ------ + const updated = await this.repo.updateAttempt(attempt.id, { + status: 'pending', + txHash: submission.txHash, + ledger: submission.ledger ?? null, + }) + + await this.safeAudit({ + disputeId: dispute.id, + contractId: contract.id, + actorUserId: actor.userId, + actorWallet: actor.walletAddress, + action: 'resolution_pending', + metadata: { + attemptId: attempt.id, + outcome: attempt.outcome, + txHash: submission.txHash, + }, + }) + + return { + state: 'pending', + dispute, + attempt: updated ?? attempt, + contractStatus: contract.status, + replayed: false, + retryable: true, + } + } + + private async confirmAttempt( + attempt: ResolutionAttemptRecord, + dispute: DisputeRecord, + contract: ContractRecord, + actor: DisputeActor, + txHash: string | null, + ledger: number | null + ): Promise { + const contractStatus = CONTRACT_OUTCOME_STATUS[attempt.outcome] + + const confirmed = await this.repo.confirmResolution({ + disputeId: dispute.id, + contractId: contract.id, + attemptId: attempt.id, + resolverId: actor.userId, + outcome: attempt.outcome, + reasons: attempt.reasons, + metadata: attempt.metadata, + txHash, + ledger, + contractStatus, + clientRefundAmount: + attempt.outcome === 'resolved_split' + ? (attempt.metadata.clientRefundAmount as string | null) ?? null + : null, + freelancerPayoutAmount: + attempt.outcome === 'resolved_split' + ? (attempt.metadata.freelancerPayoutAmount as string | null) ?? null + : null, + actorWallet: actor.walletAddress, + }) + + if (!confirmed) { + // Another request resolved the dispute first. The on-chain transaction + // (if any) already exists, so this must surface as a conflict, never as + // a success. + const latest = await this.repo.getDispute(dispute.id) + const failed = await this.repo.updateAttempt(attempt.id, { + status: 'failed', + errorCode: 'CONCURRENT_RESOLUTION', + errorMessage: 'Dispute was resolved by a concurrent request', + failedAt: new Date().toISOString(), + }) + await this.safeAudit({ + disputeId: dispute.id, + contractId: contract.id, + actorUserId: actor.userId, + actorWallet: actor.walletAddress, + action: 'resolution_failed', + metadata: { attemptId: attempt.id, errorCode: 'CONCURRENT_RESOLUTION' }, + }) + throw new DisputeConflictError( + 'This dispute was already resolved by another request', + 'RESOLUTION_ALREADY_FINALISED', + { + disputeStatus: latest?.status ?? dispute.status, + attempt: failed?.id ?? attempt.id, + txHash, + } + ) + } + + return { + state: 'confirmed', + dispute: confirmed.dispute, + attempt: confirmed.attempt, + contractStatus: confirmed.contractStatus, + replayed: false, + retryable: false, + } + } + + private async failAttempt( + attempt: ResolutionAttemptRecord, + dispute: DisputeRecord, + contract: ContractRecord, + actor: DisputeActor, + failure: { + code: string + message: string + retryable: boolean + txHash?: string | null + } + ): Promise { + const updated = await this.repo.updateAttempt(attempt.id, { + status: 'failed', + errorCode: failure.code, + errorMessage: failure.message, + failedAt: new Date().toISOString(), + txHash: failure.txHash ?? null, + }) + + await this.safeAudit({ + disputeId: dispute.id, + contractId: contract.id, + actorUserId: actor.userId, + actorWallet: actor.walletAddress, + action: 'resolution_failed', + metadata: { + attemptId: attempt.id, + outcome: attempt.outcome, + errorCode: failure.code, + retryable: failure.retryable, + txHash: failure.txHash ?? null, + }, + }) + + return { + state: 'failed', + dispute, + attempt: updated ?? attempt, + contractStatus: contract.status, + replayed: false, + retryable: failure.retryable, + } + } + + private async retryAttempt( + failed: ResolutionAttemptRecord, + dispute: DisputeRecord, + contract: ContractRecord, + actor: DisputeActor, + idempotencyKey?: string, + override?: ResolveDisputeInput + ): Promise { + if (!isActiveStatus(dispute.status)) { + throw new DisputeConflictError( + 'This dispute has already been resolved', + 'RESOLUTION_ALREADY_FINALISED', + { disputeStatus: dispute.status } + ) + } + + const key = idempotencyKey ?? `${failed.idempotencyKey}.retry` + if (key === failed.idempotencyKey) { + // Reuse the failed attempt row: reset it to pending and resubmit. This + // keeps the idempotency key → attempt relationship stable. + const reset = await this.repo.updateAttempt(failed.id, { + status: 'pending', + errorCode: null, + errorMessage: null, + txHash: null, + failedAt: null, + submittedAt: new Date().toISOString(), + }) + await this.safeAudit({ + disputeId: dispute.id, + contractId: contract.id, + actorUserId: actor.userId, + actorWallet: actor.walletAddress, + action: 'resolution_retried', + metadata: { attemptId: failed.id, retryOf: failed.id, txHash: failed.txHash }, + }) + return this.executeAttempt( + reset ?? failed, + dispute, + contract, + actor, + override ?? this.attemptToInput(failed, dispute.id, actor.walletAddress) + ) + } + + const attempt = await this.repo.createAttempt({ + disputeId: dispute.id, + requestedByUserId: actor.userId, + outcome: failed.outcome, + reasons: failed.reasons, + metadata: failed.metadata, + onchain: failed.onchain, + idempotencyKey: key, + retryOf: failed.id, + }) + + await this.repo.linkAttemptToDispute(dispute.id, attempt.id) + await this.safeAudit({ + disputeId: dispute.id, + contractId: contract.id, + actorUserId: actor.userId, + actorWallet: actor.walletAddress, + action: 'resolution_retried', + metadata: { attemptId: attempt.id, retryOf: failed.id, txHash: failed.txHash }, + }) + + return this.executeAttempt( + attempt, + dispute, + contract, + actor, + override ?? this.attemptToInput(failed, dispute.id, actor.walletAddress) + ) + } + + private attemptToInput( + attempt: ResolutionAttemptRecord, + disputeId: string, + actorWalletAddress: string + ): ResolveDisputeInput { + return { + disputeId, + actorWalletAddress, + outcome: attempt.outcome, + reasons: attempt.reasons, + metadata: attempt.metadata, + idempotencyKey: attempt.idempotencyKey, + } + } + + private async reconcilePendingAttempt( + pending: ResolutionAttemptRecord, + dispute: DisputeRecord, + contract: ContractRecord, + actor: DisputeActor + ): Promise { + const txHash = pending.txHash + + if (!pending.onchain) { + // A withdrawal attempt never stays pending; treat it as recoverable. + const failed = await this.repo.updateAttempt(pending.id, { + status: 'failed', + errorCode: 'RECOVERY_REQUIRED', + errorMessage: 'Resolution attempt was left pending without a transaction', + failedAt: new Date().toISOString(), + }) + if (!failed) return null + return { + state: 'failed', + dispute, + attempt: failed, + contractStatus: contract.status, + replayed: true, + retryable: true, + } + } + + if (!txHash) { + // The submission is still in flight and has no hash yet. Never touch the + // attempt: the caller must treat this as RESOLUTION_IN_PROGRESS. + return null + } + + const status = await this.chain.verifyResolution( + txHash, + contract.escrowAddress ?? undefined + ) + + if (status === 'confirmed') { + return this.confirmAttempt( + pending, + dispute, + contract, + actor, + txHash, + pending.ledger + ) + } + + if (status === 'failed') { + return this.failAttempt(pending, dispute, contract, actor, { + code: 'CONTRACT_REVERTED', + message: 'The resolution transaction was reverted on-chain', + retryable: false, + txHash: pending.txHash, + }) + } + + return { + state: 'pending', + dispute, + attempt: pending, + contractStatus: contract.status, + replayed: true, + retryable: true, + } + } + + private async requireActor(walletAddress: string): Promise { + const wallet = walletAddress?.trim() + if (!wallet) { + throw new DisputeError('Authentication required', 'AUTH_REQUIRED', 401) + } + const actor = await this.repo.findUserByWallet(wallet) + if (!actor) { + throw new DisputeError( + 'Authenticated wallet has no platform account', + 'USER_NOT_FOUND', + 401 + ) + } + return actor + } + + private async requireContract(contractId: string): Promise { + const contract = await this.repo.getContract(contractId) + if (!contract) throw new DisputeNotFoundError('contract', contractId) + return contract + } + + private async requireDispute(disputeId: string): Promise { + const dispute = await this.repo.getDispute(disputeId) + if (!dispute) throw new DisputeNotFoundError('dispute', disputeId) + return dispute + } + + private assertStorageAvailable(): void { + if (!this.repo.isAvailable()) { + throw new DisputeError( + 'Dispute storage is not configured', + 'SERVICE_UNAVAILABLE', + 503 + ) + } + } + + private async safeAudit(input: { + disputeId: string | null + contractId: string + actorUserId: string | null + actorWallet: string | null + action: DisputeAuditAction + metadata?: Record + }): Promise { + try { + await this.repo.appendAudit(input) + } catch (err) { + // Audit failures must never lose the primary operation, but they are + // logged (without evidence contents or secrets) for alerting. + console.error('[disputes] Failed to append audit event', input.action, { + disputeId: input.disputeId, + error: err instanceof Error ? err.message : 'unknown', + }) + } + } +} + +export const disputeWorkflowService = new DisputeWorkflowService() + +export type { ResolutionState } diff --git a/lib/disputes/types.ts b/lib/disputes/types.ts new file mode 100644 index 0000000..6e8d0ea --- /dev/null +++ b/lib/disputes/types.ts @@ -0,0 +1,323 @@ +/** + * Dispute Resolution Workflow — Domain Types + * + * These types mirror the canonical (UUID) schema managed by + * lib/db/migrations/ and are shared by the repository, service, blockchain + * gateway and HTTP layer. No Next.js or SQL imports live here so the module + * stays trivially unit-testable. + */ + +// --------------------------------------------------------------------------- +// Enums / unions +// --------------------------------------------------------------------------- + +export const DISPUTE_OUTCOMES = [ + 'resolved_client', + 'resolved_freelancer', + 'resolved_split', + 'withdrawn', +] as const +export type DisputeOutcome = (typeof DISPUTE_OUTCOMES)[number] + +export const ACTIVE_DISPUTE_STATUSES = ['open', 'under_review', 'escalated'] as const +export type ActiveDisputeStatus = (typeof ACTIVE_DISPUTE_STATUSES)[number] + +export type DisputeStatus = ActiveDisputeStatus | DisputeOutcome + +export type ResolutionAttemptStatus = 'pending' | 'confirmed' | 'failed' + +export type ContractStatus = + | 'pending' + | 'active' + | 'paused' + | 'completed' + | 'cancelled' + | 'disputed' + +export type EscrowStatus = + | 'unfunded' + | 'funded' + | 'partially_released' + | 'fully_released' + | 'refunded' + +export type EvidenceType = 'url' | 'ipfs' | 'document' | 'transaction' | 'other' + +export const EVIDENCE_TYPES: readonly EvidenceType[] = [ + 'url', + 'ipfs', + 'document', + 'transaction', + 'other', +] + +export const DISPUTE_AUDIT_ACTIONS = [ + 'dispute_created', + 'evidence_submitted', + 'authorization_denied', + 'resolution_requested', + 'resolution_pending', + 'resolution_confirmed', + 'resolution_failed', + 'resolution_retried', +] as const +export type DisputeAuditAction = (typeof DISPUTE_AUDIT_ACTIONS)[number] + +// --------------------------------------------------------------------------- +// Domain records +// --------------------------------------------------------------------------- + +export interface DisputeActor { + userId: string + walletAddress: string + role: string +} + +export interface ContractRecord { + id: string + clientId: string + freelancerId: string + status: ContractStatus + escrowStatus: EscrowStatus + escrowAddress: string | null + arbiterAddress: string | null + designatedResolverId: string | null + activeDisputeId: string | null + totalAmount: string + currency: string +} + +export interface DisputeRecord { + id: string + contractId: string + milestoneId: string | null + raisedBy: 'client' | 'freelancer' | 'admin' + raisedByUserId: string + reason: string + desiredOutcome: string | null + status: DisputeStatus + resolverId: string | null + resolutionNotes: string | null + resolutionMetadata: Record + clientRefundAmount: string | null + freelancerPayoutAmount: string | null + resolvedAt: string | null + creationIdempotencyKey: string | null + lastResolutionAttemptId: string | null + createdAt: string + updatedAt: string +} + +export interface MilestoneRecord { + id: string + contractId: string | null + status: string + amount: string +} + +export interface EvidenceRecord { + id: string + disputeId: string + milestoneId: string | null + submittedByUserId: string + evidenceType: EvidenceType + referenceUrl: string + label: string | null + description: string | null + contentHash: string + createdAt: string +} + +export interface ResolutionAttemptRecord { + id: string + disputeId: string + requestedByUserId: string + outcome: DisputeOutcome + reasons: string + metadata: Record + status: ResolutionAttemptStatus + onchain: boolean + txHash: string | null + ledger: number | null + errorCode: string | null + errorMessage: string | null + retryOf: string | null + idempotencyKey: string + submittedAt: string | null + confirmedAt: string | null + failedAt: string | null + createdAt: string + updatedAt: string +} + +export interface AuditEventRecord { + id: string + disputeId: string + contractId: string + actorUserId: string | null + actorWallet: string | null + action: DisputeAuditAction + metadata: Record + createdAt: string +} + +// --------------------------------------------------------------------------- +// Service inputs / outputs +// --------------------------------------------------------------------------- + +export interface EvidenceReferenceInput { + type: EvidenceType + url: string + label?: string + description?: string +} + +export interface CreateDisputeInput { + contractId: string + actorWalletAddress: string + reason: string + desiredOutcome?: string + milestoneId?: string + evidence?: EvidenceReferenceInput[] + idempotencyKey: string +} + +export interface CreateDisputeResult { + dispute: DisputeRecord + contractStatus: ContractStatus + /** true when the request replayed an existing dispute with the same key */ + replayed: boolean +} + +export interface SubmitEvidenceInput { + disputeId: string + actorWalletAddress: string + references: EvidenceReferenceInput[] + description?: string + idempotencyKey: string +} + +export interface SubmitEvidenceResult { + evidence: EvidenceRecord[] + /** Evidence references that already existed and were not inserted again */ + duplicates: string[] +} + +export interface GetDisputeResult { + dispute: DisputeRecord + evidence: EvidenceRecord[] + resolutionAttempt: ResolutionAttemptRecord | null + attempts: ResolutionAttemptRecord[] + auditTrail: AuditEventRecord[] +} + +export interface ResolveDisputeInput { + disputeId: string + actorWalletAddress: string + outcome: DisputeOutcome + reasons: string + metadata: Record + clientRefundAmount?: string + freelancerPayoutAmount?: string + idempotencyKey: string + /** Retry a previously failed on-chain resolution attempt. */ + retryAttemptId?: string +} + +export type ResolutionState = 'confirmed' | 'pending' | 'failed' + +export interface ResolveDisputeResult { + state: ResolutionState + dispute: DisputeRecord + attempt: ResolutionAttemptRecord + contractStatus: ContractStatus | null + replayed: boolean + /** true when a failed attempt may be retried with the same idempotency key */ + retryable: boolean +} + +// --------------------------------------------------------------------------- +// Errors +// --------------------------------------------------------------------------- + +export class DisputeError extends Error { + readonly code: string + readonly status: number + readonly details?: Record + + constructor( + message: string, + code: string, + status: number, + details?: Record + ) { + super(message) + this.name = 'DisputeError' + this.code = code + this.status = status + this.details = details + } +} + +export class DisputeValidationError extends DisputeError { + constructor(message: string, details?: Record) { + super(message, 'DISPUTE_VALIDATION_ERROR', 422, details) + this.name = 'DisputeValidationError' + } +} + +export class DisputeNotFoundError extends DisputeError { + constructor(resource: 'contract' | 'dispute' | 'milestone', id: string) { + super(`${resource} not found: ${id}`, `${resource.toUpperCase()}_NOT_FOUND`, 404) + this.name = 'DisputeNotFoundError' + } +} + +export class DisputeForbiddenError extends DisputeError { + constructor(message = 'You are not authorised to perform this action') { + super(message, 'DISPUTE_FORBIDDEN', 403) + this.name = 'DisputeForbiddenError' + } +} + +export class DisputeConflictError extends DisputeError { + constructor( + message: string, + code: + | 'DISPUTE_ALREADY_EXISTS' + | 'RESOLUTION_ALREADY_FINALISED' + | 'RESOLUTION_IN_PROGRESS' + | 'IDEMPOTENCY_KEY_REUSED' + | 'DISPUTE_CLOSED', + details?: Record + ) { + super(message, code, 409, details) + this.name = 'DisputeConflictError' + } +} + +export class DisputeIneligibleError extends DisputeError { + constructor(message: string, details?: Record) { + super(message, 'DISPUTE_INELIGIBLE', 409, details) + this.name = 'DisputeIneligibleError' + } +} + +export class DisputeChainError extends DisputeError { + readonly retryable: boolean + + constructor( + message: string, + code: 'BLOCKCHAIN_UNAVAILABLE' | 'BLOCKCHAIN_RESOLUTION_FAILED' | 'BLOCKCHAIN_NOT_CONFIGURED', + retryable: boolean + ) { + super(message, code, code === 'BLOCKCHAIN_UNAVAILABLE' ? 503 : 502, { retryable }) + this.name = 'DisputeChainError' + this.retryable = retryable + } +} + +/** Maps a domain error to an HTTP status, defaulting to 500. */ +export function disputeErrorToStatus(error: unknown): number { + return error instanceof DisputeError ? error.status : 500 +} diff --git a/lib/disputes/validation.ts b/lib/disputes/validation.ts new file mode 100644 index 0000000..cb1c4ce --- /dev/null +++ b/lib/disputes/validation.ts @@ -0,0 +1,273 @@ +/** + * Dispute Resolution Workflow — Input validation + * + * Request bodies are untrusted. Every field is validated here before the + * service touches the database or the blockchain. Validation failures surface + * as DisputeValidationError (HTTP 422) with a field-level `details` payload. + */ + +import { + DISPUTE_OUTCOMES, + EVIDENCE_TYPES, + DisputeValidationError, + type DisputeOutcome, + type EvidenceReferenceInput, + type EvidenceType, +} from './types' + +const IDEMPOTENCY_KEY_RE = /^[A-Za-z0-9_.:-]{8,128}$/ +const MIN_REASON_LENGTH = 10 +const MAX_REASON_LENGTH = 5000 +const MAX_REFERENCE_LENGTH = 2048 +const MAX_METADATA_BYTES = 16 * 1024 + +export interface ParsedCreateDispute { + reason: string + desiredOutcome?: string + milestoneId?: string + evidence: EvidenceReferenceInput[] + idempotencyKey: string +} + +export interface ParsedSubmitEvidence { + references: EvidenceReferenceInput[] + description?: string + idempotencyKey: string +} + +export interface ParsedResolveDispute { + outcome: DisputeOutcome + reasons: string + metadata: Record + clientRefundAmount?: string + freelancerPayoutAmount?: string + idempotencyKey: string + retryAttemptId?: string +} + +function asObject(value: unknown): Record { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new DisputeValidationError('Request body must be a JSON object') + } + return value as Record +} + +function requiredString( + value: unknown, + field: string, + { min = 1, max = MAX_REASON_LENGTH }: { min?: number; max?: number } = {} +): string { + if (typeof value !== 'string') { + throw new DisputeValidationError(`${field} is required and must be a string`, { + field, + }) + } + const trimmed = value.trim() + if (trimmed.length < min) { + throw new DisputeValidationError( + `${field} must be at least ${min} characters long`, + { field } + ) + } + if (trimmed.length > max) { + throw new DisputeValidationError( + `${field} must be at most ${max} characters long`, + { field } + ) + } + return trimmed +} + +function optionalString(value: unknown, field: string, max = MAX_REASON_LENGTH) { + if (value === undefined || value === null || value === '') return undefined + return requiredString(value, field, { max }) +} + +/** Idempotency keys come from the `Idempotency-Key` header or the body. */ +export function parseIdempotencyKey( + headerValue: string | null | undefined, + bodyValue: unknown +): string { + const candidate = + typeof headerValue === 'string' && headerValue.trim() + ? headerValue.trim() + : typeof bodyValue === 'string' + ? bodyValue.trim() + : '' + + if (!candidate) { + throw new DisputeValidationError( + 'An Idempotency-Key header (or idempotencyKey body field) is required', + { field: 'idempotencyKey' } + ) + } + if (!IDEMPOTENCY_KEY_RE.test(candidate)) { + throw new DisputeValidationError( + 'Idempotency-Key must be 8-128 characters of letters, digits, ".", ":", "_" or "-"', + { field: 'idempotencyKey' } + ) + } + return candidate +} + +function parseEvidenceReference(value: unknown, index: number): EvidenceReferenceInput { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new DisputeValidationError(`evidence[${index}] must be an object`, { + field: `evidence[${index}]`, + }) + } + const entry = value as Record + const type = entry.type ?? 'url' + if (typeof type !== 'string' || !EVIDENCE_TYPES.includes(type as EvidenceType)) { + throw new DisputeValidationError( + `evidence[${index}].type must be one of: ${EVIDENCE_TYPES.join(', ')}`, + { field: `evidence[${index}].type` } + ) + } + const url = requiredString(entry.url, `evidence[${index}].url`, { + max: MAX_REFERENCE_LENGTH, + }) + if (/[\u0000-\u001f]/.test(url)) { + throw new DisputeValidationError(`evidence[${index}].url contains control characters`, { + field: `evidence[${index}].url`, + }) + } + return { + type: type as EvidenceType, + url, + label: optionalString(entry.label, `evidence[${index}].label`, 200), + description: optionalString(entry.description, `evidence[${index}].description`, 2000), + } +} + +function parseEvidenceList(value: unknown, field = 'evidence'): EvidenceReferenceInput[] { + if (value === undefined || value === null) return [] + if (!Array.isArray(value)) { + throw new DisputeValidationError(`${field} must be an array`, { field }) + } + if (value.length > 20) { + throw new DisputeValidationError(`${field} may contain at most 20 references`, { + field, + }) + } + return value.map((entry, index) => parseEvidenceReference(entry, index)) +} + +export function parseCreateDisputeInput( + raw: unknown, + headerKey?: string | null +): ParsedCreateDispute { + const body = asObject(raw) + return { + reason: requiredString(body.reason, 'reason', { min: MIN_REASON_LENGTH }), + desiredOutcome: optionalString(body.desiredOutcome, 'desiredOutcome', 2000), + milestoneId: optionalString(body.milestoneId, 'milestoneId', 100), + evidence: parseEvidenceList(body.evidence), + idempotencyKey: parseIdempotencyKey(headerKey, body.idempotencyKey), + } +} + +export function parseSubmitEvidenceInput( + raw: unknown, + headerKey?: string | null +): ParsedSubmitEvidence { + const body = asObject(raw) + const references = parseEvidenceList(body.references ?? body.evidence, 'references') + const description = optionalString(body.description, 'description', 2000) + + if (references.length === 0 && !description) { + throw new DisputeValidationError( + 'Provide at least one evidence reference or a description', + { field: 'references' } + ) + } + + return { + references, + description, + idempotencyKey: parseIdempotencyKey(headerKey, body.idempotencyKey), + } +} + +export function parseResolveDisputeInput( + raw: unknown, + headerKey?: string | null +): ParsedResolveDispute { + const body = asObject(raw) + const outcome = body.outcome + if (typeof outcome !== 'string' || !DISPUTE_OUTCOMES.includes(outcome as DisputeOutcome)) { + throw new DisputeValidationError( + `outcome must be one of: ${DISPUTE_OUTCOMES.join(', ')}`, + { field: 'outcome' } + ) + } + + const metadata = body.metadata + if (metadata !== undefined && metadata !== null) { + if (typeof metadata !== 'object' || Array.isArray(metadata)) { + throw new DisputeValidationError('metadata must be a JSON object', { + field: 'metadata', + }) + } + if (Buffer.byteLength(JSON.stringify(metadata)) > MAX_METADATA_BYTES) { + throw new DisputeValidationError('metadata exceeds the 16 KB limit', { + field: 'metadata', + }) + } + } + + return { + outcome: outcome as DisputeOutcome, + reasons: requiredString(body.reasons ?? body.resolutionNotes, 'reasons', { + min: MIN_REASON_LENGTH, + }), + metadata: (metadata as Record) ?? {}, + clientRefundAmount: optionalString(body.clientRefundAmount, 'clientRefundAmount', 32), + freelancerPayoutAmount: optionalString( + body.freelancerPayoutAmount, + 'freelancerPayoutAmount', + 32 + ), + idempotencyKey: parseIdempotencyKey(headerKey, body.idempotencyKey), + retryAttemptId: optionalString(body.retryAttemptId, 'retryAttemptId', 100), + } +} + +/** Amounts are NUMERIC(18,6) strings; compare exactly in base units. */ +export function toBaseUnits(value: string, field: string): bigint { + if (!/^\d+(\.\d{1,6})?$/.test(value.trim())) { + throw new DisputeValidationError( + `${field} must be a positive decimal string with at most 6 decimal places`, + { field } + ) + } + const [whole, fraction = ''] = value.trim().split('.') + return BigInt(whole) * BigInt(1_000_000) + BigInt((fraction + '000000').slice(0, 6)) +} + +export function assertSplitAmounts( + outcome: DisputeOutcome, + contractTotal: string, + clientRefundAmount?: string, + freelancerPayoutAmount?: string +): void { + if (outcome !== 'resolved_split') return + + if (!clientRefundAmount || !freelancerPayoutAmount) { + throw new DisputeValidationError( + 'clientRefundAmount and freelancerPayoutAmount are required for a split resolution', + { field: 'clientRefundAmount' } + ) + } + + const total = toBaseUnits(contractTotal, 'contractTotal') + const refund = toBaseUnits(clientRefundAmount, 'clientRefundAmount') + const payout = toBaseUnits(freelancerPayoutAmount, 'freelancerPayoutAmount') + + if (refund + payout !== total) { + throw new DisputeValidationError( + 'Split amounts must add up to the contract total', + { field: 'clientRefundAmount' } + ) + } +} diff --git a/lib/soroban/sdk/args.ts b/lib/soroban/sdk/args.ts index f040659..98f961f 100644 --- a/lib/soroban/sdk/args.ts +++ b/lib/soroban/sdk/args.ts @@ -11,6 +11,10 @@ export function encodeU32(value: number): xdr.ScVal { return nativeToScVal(value, { type: 'u32' }) } +export function encodeBool(value: boolean): xdr.ScVal { + return nativeToScVal(value, { type: 'bool' }) +} + export function encodeI128(value: number): xdr.ScVal { return nativeToScVal(BigInt(value), { type: 'i128' }) } diff --git a/lib/soroban/sdk/client.ts b/lib/soroban/sdk/client.ts index d7941f7..e2d34f9 100644 --- a/lib/soroban/sdk/client.ts +++ b/lib/soroban/sdk/client.ts @@ -11,7 +11,14 @@ import { xdr, type Transaction, } from '@stellar/stellar-sdk' -import { assertMilestoneId, assertSafeAmount, encodeAddress, encodeMilestones, encodeU32 } from './args' +import { + assertMilestoneId, + assertSafeAmount, + encodeAddress, + encodeBool, + encodeMilestones, + encodeU32, +} from './args' import { parseContractError, parseContractEvents, parseDiagnosticEvents } from './parse' import { SorobanSdkError, @@ -119,6 +126,37 @@ export class SorobanContractClient { ]) } + /** + * Arbiter-only: settle a disputed milestone on-chain. + * `release_to_freelancer === true` pays the freelancer, otherwise the client + * is refunded (the escrow contract is binary — no split outcome). + */ + async resolveDispute( + escrowId: string, + milestoneId: string, + releaseToFreelancer: boolean + ): Promise { + assertContractId(escrowId, 'escrowId') + return this.invoke(escrowId, 'resolve_dispute', [ + encodeU32(assertMilestoneId(milestoneId)), + encodeBool(releaseToFreelancer), + ]) + } + + /** Re-fetch a submitted transaction to confirm its final on-chain status. */ + async getTransactionStatus( + hash: string + ): Promise<'confirmed' | 'failed' | 'pending' | 'unknown'> { + try { + const response = await this.server.getTransaction(hash) + if (response.status === 'SUCCESS') return 'confirmed' + if (response.status === 'FAILED') return 'failed' + return 'pending' + } catch { + return 'unknown' + } + } + async releasePayment(escrowId: string, milestoneId: string): Promise { assertContractId(escrowId, 'escrowId') return this.invoke(escrowId, 'release', [