diff --git a/Dockerfile b/Dockerfile index 65339ae..8c5caf9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,8 @@ # Use the official Node.js image as the base image FROM docker.arvancloud.ir/node:20-alpine +RUN apk add --no-cache ffmpeg + WORKDIR /app COPY package*.json ./ diff --git a/docs/qa-remediation-2026-11-22-verification.json b/docs/qa-remediation-2026-11-22-verification.json new file mode 100644 index 0000000..6732b72 --- /dev/null +++ b/docs/qa-remediation-2026-11-22-verification.json @@ -0,0 +1,85 @@ +{ + "date": "2026-11-22", + "environment": "isolated local MongoDB, synthetic accounts and generated media; external providers mocked", + "httpFlowMatrix": { + "v1-CAR_BODY": { + "status": "COMPLETED" + }, + "v1-THIRD_PARTY": { + "status": "COMPLETED" + }, + "v2-CAR_BODY": { + "status": "COMPLETED" + }, + "v2-THIRD_PARTY": { + "status": "COMPLETED" + }, + "v3-CAR_BODY": { + "status": "COMPLETED" + }, + "v3-THIRD_PARTY": { + "status": "COMPLETED" + }, + "v4-CAR_BODY": { + "status": "COMPLETED" + }, + "v4-THIRD_PARTY": { + "status": "COMPLETED" + }, + "v5-CAR_BODY": { + "status": "COMPLETED" + }, + "v5-THIRD_PARTY": { + "status": "COMPLETED" + }, + "v6-CAR_BODY": { + "status": "COMPLETED" + }, + "v6-THIRD_PARTY": { + "status": "COMPLETED" + } + }, + "negativeControls": { + "malformedId": 400, + "createRace": { + "success": 1, + "conflict": 5 + }, + "invalidMedia": 400, + "invalidEnums": 400, + "foreignFieldMutation": 403 + }, + "signedMedia": { + "expertCapture": 200, + "ownerDocument": true, + "blameEvidence": true, + "bareFile": 401, + "duplicateSignature": 401 + }, + "browserChecks": [ + "v6 login retains blame context", + "five formerly denied versioned routes render", + "repair-only objection form renders", + "Persian-locale expert assessment renders", + "written blame resend submits without an image", + "instruction-only claim resend acknowledgment reaches expert queue" + ], + "historicalRepair": { + "dryRunMatched": 2, + "applied": 2, + "signedControlUnchanged": true, + "pricedControlUnchanged": true + }, + "automatedChecks": { + "apiSuites": 111, + "apiTestsPassed": 1070, + "httpE2ePassed": 26, + "httpE2eSkipped": 4, + "userUiSuite": "passed", + "expertUiSuite": "passed", + "apiBuild": "passed", + "userUiBuild": "passed", + "expertUiBuild": "passed", + "uiHardeningDetectorFindings": 0 + } +} diff --git a/docs/qa-remediation-2026-11-22.md b/docs/qa-remediation-2026-11-22.md new file mode 100644 index 0000000..4bba699 --- /dev/null +++ b/docs/qa-remediation-2026-11-22.md @@ -0,0 +1,107 @@ +# QA remediation — 22 November 2026 + +Scope: the 28 distinct findings in `QA_REPORT_2026-11-22.txt`, +`QA_REPORT_2026-11-22_CONTINUED.txt`, `QA_REPORT_2026-11-22_EXTENDED.txt`, and +`qa-reports/`. The extended report repeats several continued findings; its +reconciliation supplies IDs 25–28. Changes cover `api`, `ui-user`, and +`ui-expert`. No production database changes or external provider writes were +performed. `rewrite` and `esg` are outside this change. + +## Findings and changes + +| ID | Resolution | Verification | +| --- | --- | --- | +| 1 | All V3 claim evidence/selection entry points authorize the actor against the case before changing it. | Authorization regression; real foreign-field-expert 403 and positive V3 HTTP filing/capture. | +| 2 | Reviewer assignment distinguishes initial capture from subsequent assessment after maker rejection. An assigned reviewer can acquire an assessment lock again. | HTTP V5: two reject/review cycles, rejection limit, final maker approval. | +| 3 | Both UIs spell rial amounts using locale-independent integer grouping instead of the library recursion triggered by Persian grouping. | Both UI suites; real Persian-locale expert assessment browser. | +| 4 | Added the ordinary-user V6 login page; the incoming blame token survives login redirection. | Real mobile browser link and URL assertion. | +| 5 | Labor-only lines tolerate absent prices; objection payloads omit absent optional monetary values and submission failures remain visible. | Real mobile browser protest form; UI regression suite. | +| 6 | Expired V6 ordinary-user sessions return to `/v6/login`; call-center sessions retain their expert login route. | Role-aware redirect regression. | +| 7 | Multipart nested objection rows become DTO instances and are validated explicitly at the service boundary, including deployments without a global validation pipe. | DTO tests and a real multipart objection through HTTP/MongoDB. | +| 8 | Vehicle subdocuments are serialized before merging resolved identity fields, exposing saved vehicle prices without Mongoose internals or parent documents. | HTTP detail assertions for price and absence of `_doc`/`$__parent`. | +| 9 | Unique-index conflicts during concurrent claim creation become HTTP 409 rather than 500. The database uniqueness constraint remains intact. | Real six-way creation race: one success, five HTTP 409 responses. | +| 10 | Owner claim-detail rejects malformed ObjectIds before querying MongoDB. | Real malformed-ID HTTP 400 control and explicit ID guard. | +| 11 | Upload policy verifies readable media streams and decodes content; text disguised as MP4, wrong media kinds and unreadable content cannot satisfy evidence steps. | Generated image/video/audio controls and corrupt/wrong-kind regression tests. | +| 12 | Shared description handlers enforce the declared weather, road and light enums, including expert form variants. | HTTP invalid-enum rejection without advancement, then valid filing; full API suite. | +| 13 | Expert cards recognize rejected cases and treat rejected/cancelled/stopped cases as view-only. | Expert UI status regressions. | +| 14 | Sheba masking preserves the existing prefix rather than prepending another `IR`. | Response mapping review and full API suite. | +| 15 | Car-body video instructions describe the vehicle and accident scene without requiring two vehicles. | User production build and UI source check. | +| 16 | Evidence is served through a signed, expiring read route, replacing anonymous static serving. Authorized case responses supply links usable by image/video/PDF elements. Arbitrary description text does not mint links. | Bare link 401; signed link 200; altered/expired/cross-path capability tests. See proxy requirements below. | +| 17 | Owner acceptance/rejection uses one conditional atomic update; only its winner records the decision and invokes integrations. Concurrent losing signature records are removed. Signature upload names use UUIDs. | Six-way unit and real MongoDB/HTTP race. | +| 18 | Registrar signatures accept registrar-created cases and follow the same signatures-before-accident-fields order as the shared V2 contract. | HTTP registrar CAR_BODY and THIRD_PARTY through signatures and accident fields. | +| 19 | Instruction-only claim resends display the instruction and offer acknowledgment through the existing endpoint. | Actual mobile browser acknowledgment and persisted queue transition. | +| 20 | Part resends send a stable catalog key/ID, independent of an optional English label. | Client key mapping and HTTP catalog-ID capture. | +| 21 | In-person visits have a pending status, owner instructions and a resumable expert review lock. They no longer imply completion/acceptance. Historical repair is provided separately. | HTTP visit → owner guidance → reassignment → assessment; V4/V5 visit controls; repair dry-run/apply controls. | +| 22 | Expert portfolio queries retain linked blame product type for product filters. | HTTP product counts: both products nonzero and their sum equals the total. | +| 23 | Insurer expert reports use linked blame product types. Missing types for roster-owned claims are resolved in one batch after claim scoping. | Reporting regression, including a linked blame outside the party-insurer list. | +| 24 | Satisfaction rating is written only if no rating exists, in one conditional atomic update. | Six-way concurrent rating regression and real HTTP/MongoDB race: one successful rating. | +| 25 | Versioned user route allowlists use real end anchors instead of requiring a literal `$`. | Browser assertions on five formerly denied routes. | +| 26 | Written blame resends use the text field; voice and document requests render their respective controls. The old duplicate page reuses the shared implementation. | Real browser text-only resend and successful navigation after submission. | +| 27 | Every requested replacement must have a timestamp at or after the current resend request. A partial upload cannot reuse old evidence to finish the request. | Real three-item replacement replay plus timestamp regression; original evidence stays intact. | +| 28 | Legacy top-rated-file normalization preserves root `userRating`, with a fallback for old nested records. | Reporting regression. | + +## Verification + +Sanitized results: [verification JSON](qa-remediation-2026-11-22-verification.json). + +- API: **111 suites, 1,070 tests passed** (`npm test -- --runInBand`). +- API HTTP E2E suite: **26 passed, 4 skipped** (`npm run test:e2e -- --runInBand`). + The four opt-in browser scenarios were not enabled in that runner; independent + browser replays were run separately as described above. +- Both UI regression suites passed (`npm run test:ui`). +- All three production builds passed (`npm run build` in each repository). +- Browser checks used Chromium/Brave, Persian locale, a 390×844 user viewport + and a desktop expert viewport. The UI hardening detector reported no findings + on the changed user-facing views. +- **All 12 flow/product combinations** (v1–v6 × CAR_BODY/THIRD_PARTY) reached + completed claims through filing, capture and assessment. V1/V6 included owner + acceptance; V5 included maker approval. V4/V5 also resumed after a visit. +- Additional HTTP replays used the actual updated Nest process and a disposable + local MongoDB database, synthetic users and generated media. External inquiry, + SMS, AI and Fanavaran requests were intercepted with offline provider fixtures. + These checks do not verify customer WAF/proxy configuration or real provider + acceptance. + +## Deployment requirements + +Deploy the API and both UIs together, because the pending-visit status and signed +evidence links span their contracts. + +1. **Media tools:** the API Dockerfile now installs `ffmpeg`, which includes + `ffprobe`. For deployments outside that Dockerfile, install both binaries in + the API runtime and verify that its service account can execute them. Missing + binaries will correctly reject uploads as unreadable; do not bypass validation. +2. **Evidence proxy:** remove any public Nginx `alias`/`root`/static/CDN rule that + directly exposes the API's `files` directory. Proxy `/files/*` (including its + deployed `/car-damage/api/` prefix, if applicable) to Nest, preserving the + query string and Range headers. A reverse-proxy static bypass would leave the + original anonymous-access issue unresolved. Purge previously cached public + evidence responses. Keep the existing API prefix/rewrite conventions; do not + copy a new `proxy_pass` prefix blindly. +3. **Signing secret:** all API instances serving the same files must share the + existing `JWT_SECRET`. File URLs expire after one hour; reopening/refetching + the authorized case returns fresh URLs. No additional signing secret or + public access switch is introduced. Old cached bare links require a refresh. +4. **Historical visits:** back up the database and preview the narrow repair + from the `api` directory with the intended deployment's environment: + + ```bash + node scripts/repair-premature-visit-completions.js + # After checking the matched count: + node scripts/repair-premature-visit-completions.js --apply + ``` + + Dry-run is the default. The script only changes `COMPLETED` + + `NEEDS_REVISION` records with an in-person-visit history event and no + submitted assessment, priced parts or recorded owner approvals. It unlocks + review and writes a repair history event. It does not invent an address or + change evidence, payment amounts, signatures or other completed cases. + Dry-run and apply were exercised on synthetic records, with signed/priced + controls left closed. More ambiguous old records need individual review. +5. **Historical races:** overwritten satisfaction ratings or contradictory + owner decisions already recorded before this change cannot be reliably + reconstructed automatically. Review their history and provider submission + records; the code prevents new overlapping writes but does not guess which + old decision was intended. + +No commits or pushes are included in this remediation task. diff --git a/scripts/repair-premature-visit-completions.js b/scripts/repair-premature-visit-completions.js new file mode 100644 index 0000000..e27a746 --- /dev/null +++ b/scripts/repair-premature-visit-completions.js @@ -0,0 +1,68 @@ +#!/usr/bin/env node +// Dry-run by default. Repairs only the precise historical visit-only state; +// never reopens a signed, priced or paid claim. +require("dotenv").config(); +const mongoose = require("mongoose"); +(async () => { + if (!process.env.MONGO_URI) throw new Error("MONGO_URI is required"); + await mongoose.connect(process.env.MONGO_URI, { + tls: process.env.MONGO_TLS === "true", + tlsAllowInvalidCertificates: + process.env.MONGO_TLS_ALLOW_INVALID_CERTS === "true", + }); + try { + const collection = mongoose.connection.collection("claimCases"); + const filter = { + status: "COMPLETED", + claimStatus: "NEEDS_REVISION", + "history.type": "IN_PERSON_VISIT_REQUESTED", + "evaluation.damageExpertReply.submittedAt": null, + "evaluation.damageExpertReplyFinal.submittedAt": null, + "evaluation.ownerInsurerApproval": null, + "evaluation.ownerPricedPartsApproval": null, + "evaluation.damageExpertReply.parts.0": { $exists: false }, + "evaluation.damageExpertReplyFinal.parts.0": { $exists: false }, + }; + const matched = await collection.countDocuments(filter); + if (!process.argv.includes("--apply")) { + console.log(JSON.stringify({ dryRun: true, matched })); + return; + } + const result = await collection.updateMany(filter, { + $set: { + status: "IN_PERSON_VISIT_PENDING", + "workflow.locked": false, + "workflow.currentStep": "EXPERT_DAMAGE_ASSESSMENT", + "workflow.nextStep": "EXPERT_DAMAGE_ASSESSMENT", + updatedAt: new Date(), + }, + $unset: { + "workflow.lockedBy": "", + "workflow.lockedAt": "", + "workflow.expiredAt": "", + "workflow.preLockQueueSnapshot": "", + }, + $push: { + history: { + type: "VISIT_ONLY_COMPLETION_REPAIRED", + timestamp: new Date(), + metadata: { previousStatus: "COMPLETED" }, + }, + }, + }); + console.log( + JSON.stringify({ + dryRun: false, + matched, + modified: result.modifiedCount, + }), + ); + } finally { + await mongoose.disconnect(); + } +})().catch(() => { + console.error( + "Visit-state repair failed. Check database connectivity and configuration.", + ); + process.exitCode = 1; +}); diff --git a/src/Types&Enums/claim-request-management/claim-case-status.enum.ts b/src/Types&Enums/claim-request-management/claim-case-status.enum.ts index fb6a426..0ea7e4a 100644 --- a/src/Types&Enums/claim-request-management/claim-case-status.enum.ts +++ b/src/Types&Enums/claim-request-management/claim-case-status.enum.ts @@ -16,6 +16,7 @@ export enum ClaimCaseStatus { // Expert flow WAITING_FOR_DAMAGE_EXPERT = "WAITING_FOR_DAMAGE_EXPERT", + IN_PERSON_VISIT_PENDING = "IN_PERSON_VISIT_PENDING", EXPERT_REVIEWING = "EXPERT_REVIEWING", /** * @deprecated Prefer specific post-expert statuses below. Kept for existing DB rows and reads. diff --git a/src/app.module.ts b/src/app.module.ts index 925ffd2..9d958b9 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -1,3 +1,4 @@ +import { EvidenceAccessModule } from "./evidence-access/evidence-access.module"; import { PersianErrorFilter } from "./common/errors/persian-error.filter"; import { PersianErrorInterceptor } from "./common/errors/persian-error.interceptor"; import { ManagementModule } from "./management/management.module"; @@ -8,7 +9,6 @@ import { ConfigModule, ConfigService } from "@nestjs/config"; import { HttpModule } from "@nestjs/axios"; import { UnicodeDigitsNormalizeInterceptor } from "./common/interceptors/unicode-digits-normalize.interceptor"; import { MongooseModule } from "@nestjs/mongoose"; -import { ServeStaticModule } from "@nestjs/serve-static"; import { AiModule } from "./ai/ai.module"; import { AuthModule } from "./auth/auth.module"; import { ClaimRequestManagementModule } from "./claim-request-management/claim-request-management.module"; @@ -44,14 +44,7 @@ import { createHttpModuleOptions } from "./core/config/http-proxy.factory"; AppConfigModule, DatabaseModule, CronModule, - ServeStaticModule.forRoot({ - // process.cwd() is always the project/container root (/app in Docker), - // so the volume-mounted /app/files is resolved correctly regardless of - // where the compiled dist files live (__dirname would resolve to - // /app/dist/src because TypeScript preserves the src/ prefix in outDir). - rootPath: join(process.cwd(), "files"), - serveRoot: "/files", - }), + EvidenceAccessModule, UsersModule, AuthModule, ClientModule, diff --git a/src/claim-request-management/claim-request-management.service.ts b/src/claim-request-management/claim-request-management.service.ts index 9d32df3..17b442f 100644 --- a/src/claim-request-management/claim-request-management.service.ts +++ b/src/claim-request-management/claim-request-management.service.ts @@ -1,3 +1,6 @@ +import { unlink } from "node:fs/promises"; +import { plainToInstance } from "class-transformer"; +import { validateSync } from "class-validator"; import { normalizeClaimSheba, normalizeClaimNationalCode, @@ -8416,6 +8419,9 @@ export class ClaimRequestManagementService { fanavaran, }; } catch (error) { + if ((error as {code?: number})?.code === 11000) { + throw new ConflictException('درخواست خسارت این پرونده قبلاً ثبت شده است. پرونده‌های من را باز کنید.'); + } if (error instanceof HttpException) throw error; this.logger.error( 'createClaimFromBlameV2 failed', @@ -9633,7 +9639,11 @@ export class ClaimRequestManagementService { if (!claim || !canFinalizeExpertResend(claim)) { return; } - await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { + await this.claimCaseDbService.findOneAndUpdate({ + _id: claim._id, status: ClaimCaseStatus.WAITING_FOR_USER_RESEND, + 'workflow.currentStep': ClaimWorkflowStep.USER_EXPERT_RESEND, + 'evaluation.damageExpertResend.fulfilledAt': null, + }, { $set: { status: ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT, claimStatus: ClaimStatus.PENDING, @@ -10813,6 +10823,12 @@ export class ClaimRequestManagementService { 'Only the claim owner can submit an objection', ); + // Multipart body fields are strings. This service is also called by + // mirror controllers, so normalize and validate here rather than relying + // on a global ValidationPipe (the app deliberately has none). + body = plainToInstance(UserObjectionV2Dto, body); + if (validateSync(body).length) throw new BadRequestException('اطلاعات اعتراض معتبر نیست. قطعه، توضیح اعتراض و مبالغ پیشنهادی را بررسی کنید.'); + if (claimCase.evaluation?.objection?.submittedAt) { throw new ConflictException( 'An objection has already been submitted for this claim.', @@ -11075,7 +11091,10 @@ export class ClaimRequestManagementService { createdAt: new Date(), }; - await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { + const saved = await this.claimCaseDbService.findOneAndUpdate({ + _id: claimCase._id, status: ClaimCaseStatus.COMPLETED, + 'userRating.createdAt': null, + }, { $set: { userRating }, $push: { history: { @@ -11091,6 +11110,7 @@ export class ClaimRequestManagementService { }, }); + if (!saved) throw new ConflictException("امتیاز این پرونده قبلاً ثبت شده است یا وضعیت پرونده تغییر کرده است."); return userRating; } @@ -11200,139 +11220,48 @@ export class ClaimRequestManagementService { } const signDoc = await this.claimSignDbService.create({ - fileName: signFile.filename, - userId: effectiveUserId, - path: signFile.path, + fileName: signFile.filename, userId: effectiveUserId, path: signFile.path, requestId: new Types.ObjectId(claimRequestId), } as any); - const signId = new Types.ObjectId(String((signDoc as any)._id)); const signedAt = new Date(); - const scopedApprovalPayload = { - agree, - signDetailId: signId, - signedAt, - }; - - const historyActor = { - actorId: new Types.ObjectId(effectiveUserId), - actorName: claimCase.owner?.fullName || 'User', - actorType: 'user', - }; - - /** Mixed reply: priced lines acceptance before factor uploads */ - if (isMixedPartialGate) { - if (!agree) { - await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { - $set: { - status: ClaimCaseStatus.REJECTED, - claimStatus: ClaimStatus.REJECTED, - 'evaluation.ownerPricedPartsApproval': scopedApprovalPayload, - 'workflow.nextStep': null, - }, - $push: { - history: { - type: 'OWNER_REJECTED_PRICED_PARTS_BEFORE_FACTORS', - actor: historyActor, - timestamp: signedAt, - metadata: {}, - }, - }, - }); - return { - message: - 'Your rejection has been recorded. This claim is marked rejected and will not proceed.', - claimRequestId, - status: ClaimCaseStatus.REJECTED, - claimStatus: ClaimStatus.REJECTED, - currentStep: claimCase.workflow?.currentStep, - accepted: false, - phase: 'PRICED_PARTS_FOR_FACTORS', - }; - } - - await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { - $set: { - claimStatus: ClaimStatus.NEEDS_REVISION, - 'evaluation.ownerPricedPartsApproval': scopedApprovalPayload, - 'workflow.currentStep': - ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS, - 'workflow.nextStep': ClaimWorkflowStep.EXPERT_COST_EVALUATION, - }, - $push: { - history: { - type: 'OWNER_SIGNED_PRICED_PARTS_PENDING_FACTOR_UPLOAD', - actor: historyActor, - timestamp: signedAt, - metadata: {}, - }, - }, - }); - - return { - message: - 'Priced repair lines accepted. Upload repair factor files for each factor-needed part; the claim will return to the damage expert for cost validation.', - claimRequestId, - status: claimCase.status, - claimStatus: ClaimStatus.NEEDS_REVISION, - currentStep: ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS, - accepted: true, - phase: 'PRICED_PARTS_FOR_FACTORS', - }; - } - - /** Final accept / reject (no outstanding factor gate at this step) */ - if (!agree) { - await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { - $set: { - status: ClaimCaseStatus.REJECTED, - claimStatus: ClaimStatus.REJECTED, - 'evaluation.ownerInsurerApproval': scopedApprovalPayload, - 'workflow.nextStep': null, - }, - $push: { - history: { - type: 'OWNER_REJECTED_INSURER_APPROVAL_PRICING', - actor: historyActor, - timestamp: signedAt, - metadata: {}, - }, - }, - }); - return { - message: - 'Your rejection has been recorded. This claim is marked rejected and will not proceed.', - claimRequestId, - status: ClaimCaseStatus.REJECTED, - claimStatus: ClaimStatus.REJECTED, - currentStep: claimCase.workflow?.currentStep, - accepted: false, - phase: 'FINAL_APPROVAL', - }; - } - - // Submit Fanavaran expertise when owner accepts the expert reply - const fanavaranExpertise = - await this.autoSubmitFanavaranExpertiseOnExpertReply(claimRequestId); - - await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { + const approvalField = isMixedPartialGate ? 'ownerPricedPartsApproval' : 'ownerInsurerApproval'; + const nextStatus = !agree ? ClaimCaseStatus.REJECTED : isMixedPartialGate ? claimCase.status : ClaimCaseStatus.COMPLETED; + const nextStep = agree ? (isMixedPartialGate ? ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS : ClaimWorkflowStep.CLAIM_COMPLETED) : claimCase.workflow.currentStep; + // The state change and decision are one compare-and-set. Only its winner may + // call external services; overlapping accept/reject requests cannot overwrite it. + const saved = await this.claimCaseDbService.findOneAndUpdate({ + _id: claimCase._id, status: claimCase.status, claimStatus: claimCase.claimStatus, + 'workflow.currentStep': ClaimWorkflowStep.INSURER_REVIEW, + [`evaluation.${approvalField}.signedAt`]: null, + 'evaluation.ownerInsurerApproval.signedAt': null, + }, { $set: { - status: ClaimCaseStatus.COMPLETED, - claimStatus: ClaimStatus.APPROVED, - 'evaluation.ownerInsurerApproval': scopedApprovalPayload, - 'workflow.currentStep': ClaimWorkflowStep.CLAIM_COMPLETED, - 'workflow.nextStep': ClaimWorkflowStep.CLAIM_COMPLETED, - }, - $push: { - 'workflow.completedSteps': ClaimWorkflowStep.INSURER_REVIEW, - history: { - type: 'OWNER_SIGNED_INSURER_APPROVAL', - actor: historyActor, - timestamp: signedAt, - metadata: {}, - }, + status: nextStatus, + claimStatus: !agree ? ClaimStatus.REJECTED : isMixedPartialGate ? ClaimStatus.NEEDS_REVISION : ClaimStatus.APPROVED, + [`evaluation.${approvalField}`]: { agree, signDetailId: new Types.ObjectId(String((signDoc as any)._id)), signedAt }, + 'workflow.currentStep': nextStep, + 'workflow.nextStep': !agree ? null : isMixedPartialGate ? ClaimWorkflowStep.EXPERT_COST_EVALUATION : ClaimWorkflowStep.CLAIM_COMPLETED, }, + $push: { history: { + type: isMixedPartialGate ? (agree ? 'OWNER_SIGNED_PRICED_PARTS_PENDING_FACTOR_UPLOAD' : 'OWNER_REJECTED_PRICED_PARTS_BEFORE_FACTORS') : (agree ? 'OWNER_SIGNED_INSURER_APPROVAL' : 'OWNER_REJECTED_INSURER_APPROVAL_PRICING'), + actor: { actorId: new Types.ObjectId(effectiveUserId), actorName: claimCase.owner?.fullName || 'User', actorType: 'user' }, + timestamp: signedAt, metadata: {}, + } }, + ...(!isMixedPartialGate && agree ? {$addToSet: {'workflow.completedSteps': ClaimWorkflowStep.INSURER_REVIEW}} : {}), }); - + if (!saved) { + await this.claimSignDbService.deleteById(String((signDoc as any)._id)); + await unlink(signFile.path).catch(() => undefined); + throw new ConflictException('تصمیم این پرونده قبلاً ثبت شده است یا وضعیت پرونده تغییر کرده است. پرونده را دوباره باز کنید.'); + } + if (isMixedPartialGate || !agree) return { + message: !agree ? 'عدم تأیید شما ثبت شد. پرونده رد شده است.' : 'تأیید مبالغ ثبت شد. فاکتور قطعات درخواستی را بارگذاری کنید.', + claimRequestId, status: nextStatus, + claimStatus: !agree ? ClaimStatus.REJECTED : ClaimStatus.NEEDS_REVISION, + currentStep: nextStep, accepted: agree, + phase: isMixedPartialGate ? 'PRICED_PARTS_FOR_FACTORS' : 'FINAL_APPROVAL', + }; + const fanavaranExpertise = await this.autoSubmitFanavaranExpertiseOnExpertReply(claimRequestId); const fanavaran = await this.autoSubmitToFanavaranV2OnClaimCompleted(claimRequestId); @@ -11615,6 +11544,7 @@ export class ClaimRequestManagementService { actor?: { sub: string; role?: string; username?: string }, ): Promise { try { + if (!Types.ObjectId.isValid(claimRequestId)) throw new BadRequestException("شناسه پرونده خسارت معتبر نیست."); const claim = await this.claimCaseDbService.findById(claimRequestId); if (!claim) { throw new NotFoundException('Claim request not found'); @@ -11743,7 +11673,7 @@ export class ClaimRequestManagementService { : undefined; const maskSheba = (s?: string) => - s ? s.replace(/^(.{4})(.*)(.{4})$/, 'IR$1************$3') : undefined; + s ? s.replace(/^(.{4})(.*)(.{4})$/, '$1************$3') : undefined; const maskNationalCode = (s?: string) => s ? s.replace(/^(.{2})(.*)(.{2})$/, '$1******$3') : undefined; const isExpertViewer = @@ -11829,6 +11759,7 @@ export class ClaimRequestManagementService { damagedParts, damagedPartsHistory, expertResend, + visitLocation: claim.evaluation?.visitLocation, fanavaran: fanavaranClaimReferences(claim), evaluation: mappedEvaluation ? { @@ -12235,6 +12166,7 @@ export class ClaimRequestManagementService { `Claim case with ID ${claimRequestId} not found`, ); } + await this.assertActorCanViewClaimV2(claimCase, currentUserId, actor); const blame = await this.assertV3InPersonClaim(claimCase); const skipMetalPlate = !!(blame as any).isMadeByFileMaker; const isV4FileMaker = @@ -12350,6 +12282,7 @@ export class ClaimRequestManagementService { `Claim case with ID ${claimRequestId} not found`, ); } + await this.assertActorCanViewClaimV2(claimCase, currentUserId, actor); const blame = await this.assertV3InPersonClaim(claimCase); if (this.isV3InitialDocumentsPhase(claimCase)) { @@ -12382,6 +12315,7 @@ export class ClaimRequestManagementService { `Claim case with ID ${claimRequestId} not found`, ); } + await this.assertActorCanViewClaimV2(claimCase, currentUserId, actor); const blame = await this.assertV3InPersonClaim(claimCase); this.assertV3ClaimPartsPhase(blame); await this.advanceV3ClaimToOuterPartsIfReady(claimCase, blame); @@ -12415,6 +12349,7 @@ export class ClaimRequestManagementService { `Claim case with ID ${claimRequestId} not found`, ); } + await this.assertActorCanViewClaimV2(claimCase, currentUserId, actor); const blame = await this.assertV3InPersonClaim(claimCase); this.assertV3ClaimPartsPhase(blame); this.assertV3ClaimWorkflowStep( @@ -12492,7 +12427,7 @@ export class ClaimRequestManagementService { ? { shebaNumber: String(shebaNumber).replace( /^(.{4})(.*)(.{4})$/, - 'IR$1************$3', + '$1************$3', ), } : {}), @@ -12523,6 +12458,7 @@ export class ClaimRequestManagementService { `Claim case with ID ${claimRequestId} not found`, ); } + await this.assertActorCanViewClaimV2(claimCase, currentUserId, actor); const blame = await this.assertV3InPersonClaim(claimCase); const skipMetalPlate = !!(blame as any).isMadeByFileMaker; @@ -12676,6 +12612,7 @@ export class ClaimRequestManagementService { `Claim case with ID ${claimRequestId} not found`, ); } + await this.assertActorCanViewClaimV2(claimCase, currentUserId, actor); const blame = await this.assertV3InPersonClaim(claimCase); this.assertV3ClaimPartsPhase(blame); this.assertV3ClaimWorkflowStep( diff --git a/src/claim-request-management/claim-request-management.v2.controller.ts b/src/claim-request-management/claim-request-management.v2.controller.ts index 1fe6c1d..72e3383 100644 --- a/src/claim-request-management/claim-request-management.v2.controller.ts +++ b/src/claim-request-management/claim-request-management.v2.controller.ts @@ -1,3 +1,4 @@ +import { randomUUID } from "node:crypto"; import { Controller, HttpException, @@ -375,7 +376,7 @@ export class ClaimRequestManagementV2Controller { storage: diskStorage({ destination: "./files/claim-sign", filename: (req, file, callback) => { - const unique = Date.now(); + const unique = randomUUID(); const ex = extname(file.originalname); const base = file.originalname.split(/[.,\s-]/)[0] || "sign"; callback(null, `${base}-${unique}${ex}`); diff --git a/src/claim-request-management/dto/claim-details-v2.dto.ts b/src/claim-request-management/dto/claim-details-v2.dto.ts index bd7dbf9..eae2571 100644 --- a/src/claim-request-management/dto/claim-details-v2.dto.ts +++ b/src/claim-request-management/dto/claim-details-v2.dto.ts @@ -263,6 +263,9 @@ export class ClaimDetailsV2ResponseDto { }) expertResend?: ExpertResendDetailsV2Dto; + @ApiPropertyOptional() + visitLocation?: string; + @ApiPropertyOptional({ description: "Fanavaran codes and image upload receipts. Claim codes appear on COMPLETED; fileIds and attachments upload status/errors are available earlier when recorded.", diff --git a/src/claim-request-management/dto/user-objection-v2.dto.spec.ts b/src/claim-request-management/dto/user-objection-v2.dto.spec.ts new file mode 100644 index 0000000..96796fd --- /dev/null +++ b/src/claim-request-management/dto/user-objection-v2.dto.spec.ts @@ -0,0 +1,26 @@ +import { plainToInstance } from "class-transformer"; +import { validate } from "class-validator"; +import { UserObjectionV2Dto } from "./user-objection-v2.dto"; +describe("objection JSON and multipart parity", () => { + it.each([true, false])( + "validates nested entries for multipart=%s", + async (multipart) => { + const entries = [{ partId: 101, reason: "اعتراض به قیمت" }]; + const dto = plainToInstance(UserObjectionV2Dto, { + objectionParts: multipart ? JSON.stringify(entries) : entries, + }); + expect(await validate(dto)).toEqual([]); + }, + ); + it("still rejects invalid entries and malformed multipart JSON", async () => { + for (const raw of ["{", '[{"partId":"wrong"}]']) { + expect( + ( + await validate( + plainToInstance(UserObjectionV2Dto, { objectionParts: raw }), + ) + ).length, + ).toBeGreaterThan(0); + } + }); +}); diff --git a/src/claim-request-management/dto/user-objection-v2.dto.ts b/src/claim-request-management/dto/user-objection-v2.dto.ts index 029517d..4fd553f 100644 --- a/src/claim-request-management/dto/user-objection-v2.dto.ts +++ b/src/claim-request-management/dto/user-objection-v2.dto.ts @@ -1,11 +1,6 @@ import { ApiPropertyOptional } from "@nestjs/swagger"; -import { Type, Transform } from "class-transformer"; -import { - IsArray, - IsOptional, - Validate, - ValidateNested, -} from "class-validator"; +import { Type, Transform, plainToInstance } from "class-transformer"; +import { IsArray, IsOptional, Validate, ValidateNested } from "class-validator"; import { HasObjectionEntriesConstraint } from "src/common/validators/has-objection-entries.validator"; import { NewPartDto, UserObjectionPartDto } from "./user-objection.dto"; @@ -28,7 +23,10 @@ export class UserObjectionV2Dto { @Transform(({ value }) => { if (typeof value === "string") { try { - return JSON.parse(value); + const parsed = JSON.parse(value); + return Array.isArray(parsed) + ? plainToInstance(UserObjectionPartDto, parsed) + : parsed; } catch { return value; } @@ -50,7 +48,10 @@ export class UserObjectionV2Dto { @Transform(({ value }) => { if (typeof value === "string") { try { - return JSON.parse(value); + const parsed = JSON.parse(value); + return Array.isArray(parsed) + ? plainToInstance(NewPartDto, parsed) + : parsed; } catch { return value; } diff --git a/src/claim-request-management/entites/db-service/claim-sign.db.service.ts b/src/claim-request-management/entites/db-service/claim-sign.db.service.ts index 3522537..c297c8e 100644 --- a/src/claim-request-management/entites/db-service/claim-sign.db.service.ts +++ b/src/claim-request-management/entites/db-service/claim-sign.db.service.ts @@ -14,6 +14,10 @@ export class ClaimSignDbService { return await this.claimSignService.create(claimSign); } + async deleteById(id: string): Promise { + await this.claimSignService.findByIdAndDelete(id); + } + async findOne(filter: FilterQuery): Promise { return await this.claimSignService.findOne(filter); } diff --git a/src/claim-request-management/entites/schema/claim-case.evaluation.schema.ts b/src/claim-request-management/entites/schema/claim-case.evaluation.schema.ts index f9faac5..429d087 100644 --- a/src/claim-request-management/entites/schema/claim-case.evaluation.schema.ts +++ b/src/claim-request-management/entites/schema/claim-case.evaluation.schema.ts @@ -218,6 +218,8 @@ export const ClaimUserObjectionPayloadSchema = @Schema({ _id: false }) export class ClaimResendRequest { + @Prop({ type: Date }) + requestedAt?: Date; @Prop({ type: String }) resendDescription?: string; diff --git a/src/claim-request-management/expert-initiated-claim.mirror.controller.ts b/src/claim-request-management/expert-initiated-claim.mirror.controller.ts index a013d77..bb39ad2 100644 --- a/src/claim-request-management/expert-initiated-claim.mirror.controller.ts +++ b/src/claim-request-management/expert-initiated-claim.mirror.controller.ts @@ -1,3 +1,4 @@ +import { randomUUID } from "node:crypto"; import { readFile } from "node:fs/promises"; import { extname } from "node:path"; import { @@ -564,7 +565,7 @@ Returns status of each item (uploaded/captured or not). storage: diskStorage({ destination: "./files/claim-sign", filename: (req, file, callback) => { - const unique = Date.now(); + const unique = randomUUID(); const ex = extname(file.originalname); const base = file.originalname.split(/[.,\s-]/)[0] || "sign"; callback(null, `${base}-${unique}${ex}`); diff --git a/src/claim-request-management/owner-insurer-approval-no-branch.spec.ts b/src/claim-request-management/owner-insurer-approval-no-branch.spec.ts index 686f641..817ce62 100644 --- a/src/claim-request-management/owner-insurer-approval-no-branch.spec.ts +++ b/src/claim-request-management/owner-insurer-approval-no-branch.spec.ts @@ -8,7 +8,7 @@ describe("owner insurer approval without branch selection", () => { const service = Object.create( ClaimRequestManagementService.prototype, ) as ClaimRequestManagementService; - const findByIdAndUpdate = jest.fn().mockResolvedValue(undefined); + const findOneAndUpdate = jest.fn().mockResolvedValue({}); (service as any).claimCaseDbService = { findById: jest.fn().mockResolvedValue({ @@ -21,7 +21,7 @@ describe("owner insurer approval without branch selection", () => { damageExpertReply: { submittedAt: new Date(), parts: [] }, }, }), - findByIdAndUpdate, + findOneAndUpdate, }; (service as any).resolveClaimEffectiveUserId = jest .fn() @@ -48,8 +48,8 @@ describe("owner insurer approval without branch selection", () => { status: ClaimCaseStatus.REJECTED, }); - expect(findByIdAndUpdate).toHaveBeenCalledWith( - "507f1f77bcf86cd799439011", + expect(findOneAndUpdate).toHaveBeenCalledWith( + expect.objectContaining({_id: "507f1f77bcf86cd799439011", "evaluation.ownerInsurerApproval.signedAt": null}), expect.objectContaining({ $set: expect.objectContaining({ "evaluation.ownerInsurerApproval": expect.not.objectContaining({ diff --git a/src/claim-request-management/qa-concurrency-regressions.spec.ts b/src/claim-request-management/qa-concurrency-regressions.spec.ts new file mode 100644 index 0000000..a6d127d --- /dev/null +++ b/src/claim-request-management/qa-concurrency-regressions.spec.ts @@ -0,0 +1,105 @@ +import { ClaimRequestManagementService } from "./claim-request-management.service"; +const id = "507f1f77bcf86cd799439011", + uid = "507f1f77bcf86cd799439012"; +/** Simulated shared document: each conditional update is atomic, as Mongo is. */ +function serviceFor(initial: any) { + const s: any = Object.create(ClaimRequestManagementService.prototype); + const doc = { _id: id, owner: { userId: uid }, ...initial }; + s.claimCaseDbService = { + findById: jest.fn(async () => ({ + ...doc, + workflow: { ...doc.workflow }, + evaluation: { ...doc.evaluation }, + })), + findOneAndUpdate: jest.fn(async (filter, update) => { + if (filter.status !== doc.status) return null; + if (filter["userRating.createdAt"] === null && doc.userRating) + return null; + if ( + filter["evaluation.ownerInsurerApproval.signedAt"] === null && + doc.evaluation.ownerInsurerApproval + ) + return null; + for (const [k, v] of Object.entries(update.$set || {})) { + const parts = k.split("."); + let target = doc; + for (const key of parts.slice(0, -1)) target = target[key] ??= {}; + target[parts.at(-1)!] = v; + } + return doc; + }), + }; + s.resolveClaimEffectiveUserId = jest.fn(async () => uid); + s.assertEffectiveUserIsDamagedPartyOnClaim = jest.fn(async () => {}); + s.claimSignDbService = { + create: jest.fn(async () => ({ _id: "507f1f77bcf86cd799439013" })), + deleteById: jest.fn(async () => {}), + }; + s.autoSubmitFanavaranExpertiseOnExpertReply = jest.fn(async () => ({ + submitted: false, + })); + s.autoSubmitToFanavaranV2OnClaimCompleted = jest.fn(async () => ({ + submitted: false, + })); + return { s, doc }; +} +describe("one winning owner action", () => { + it("never records contradictory final decisions or duplicate integration calls", async () => { + const { s, doc } = serviceFor({ + status: "INSURER_REVIEW_AWAITING_OWNER_SIGN", + claimStatus: "APPROVED", + workflow: { currentStep: "INSURER_REVIEW" }, + evaluation: { damageExpertReply: { submittedAt: new Date(), parts: [] } }, + }); + const results = await Promise.allSettled( + [true, false, true, false, true, false].map((agree) => + s.submitOwnerInsurerApprovalSignV2( + id, + agree, + { filename: "a.jpg", path: "files/a.jpg" }, + uid, + ), + ), + ); + expect(results.filter((r) => r.status === "fulfilled")).toHaveLength(1); + expect(s.claimSignDbService.deleteById).toHaveBeenCalledTimes(5); + expect(s.autoSubmitToFanavaranV2OnClaimCompleted).toHaveBeenCalledTimes(1); + expect(doc.status).toBe("COMPLETED"); + expect(doc.evaluation.ownerInsurerApproval.agree).toBe(true); + }); + it("allows exactly one satisfaction rating under concurrent submissions", async () => { + const { s } = serviceFor({ + status: "COMPLETED", + workflow: {}, + evaluation: {}, + }); + const results = await Promise.allSettled( + [0, 1, 2, 3, 4, 5].map((n) => + s.addUserRatingV2( + id, + { progressSpeed: n, registrationEase: n, overallEvaluation: n }, + uid, + ), + ), + ); + expect(results.filter((r) => r.status === "fulfilled")).toHaveLength(1); + expect(results.filter((r) => r.status === "rejected")).toHaveLength(5); + }); + it("authorizes V3 selection before changing workflow or parts", async () => { + const { s } = serviceFor({ + status: "SELECTING_OTHER_PARTS", + workflow: {}, + evaluation: {}, + }); + s.assertActorCanViewClaimV2 = jest.fn(async () => { + throw Error("forbidden"); + }); + await expect( + s.selectOtherPartsV3(id, { otherParts: ["engine"] }, uid, { + sub: uid, + role: "field_expert", + }), + ).rejects.toThrow("forbidden"); + expect(s.claimCaseDbService.findOneAndUpdate).not.toHaveBeenCalled(); + }); +}); diff --git a/src/evidence-access/evidence-access.module.ts b/src/evidence-access/evidence-access.module.ts new file mode 100644 index 0000000..872770c --- /dev/null +++ b/src/evidence-access/evidence-access.module.ts @@ -0,0 +1,75 @@ +import { + CallHandler, + Controller, + ExecutionContext, + Get, + Injectable, + Module, + NestInterceptor, + Param, + Query, + Res, + ForbiddenException, +} from "@nestjs/common"; +import { APP_INTERCEPTOR } from "@nestjs/core"; +import { + EvidenceAccessService, + evidenceRequestScope, +} from "./evidence-access.service"; +export { EvidenceAccessService } from "./evidence-access.service"; +import { realpath } from "node:fs/promises"; +import { resolve, sep } from "node:path"; +import { Response } from "express"; +import { map, Observable } from "rxjs"; + +@Injectable() +class EvidenceLinksInterceptor implements NestInterceptor { + constructor(private readonly access: EvidenceAccessService) {} + intercept(context: ExecutionContext, next: CallHandler) { + const req = context.switchToHttp().getRequest(); + if (!req.user?.sub) return next.handle(); + return new Observable((observer) => + evidenceRequestScope.run(true, () => + next + .handle() + .pipe(map((value) => this.access.project(value))) + .subscribe(observer), + ), + ); + } +} +@Controller("files") +class EvidenceController { + constructor(private readonly access: EvidenceAccessService) {} + @Get("*path") + async read( + @Param("path") raw: string | string[], + @Query("expires") expires: string, + @Query("signature") signature: string, + @Res() res: Response, + ) { + const path = Array.isArray(raw) ? raw.join("/") : raw; + this.access.verify(path, expires, signature); + const root = await realpath(resolve("files")); + let target: string; + try { + target = await realpath(resolve(root, path)); + } catch { + res.status(404).end(); + return; + } + if (!target.startsWith(root + sep)) throw new ForbiddenException(); + res.setHeader("Cache-Control", "private, no-store"); + res.setHeader("X-Content-Type-Options", "nosniff"); + // sendFile retains Range/HEAD support needed by video players. + res.sendFile(target); + } +} +@Module({ + controllers: [EvidenceController], + providers: [ + EvidenceAccessService, + { provide: APP_INTERCEPTOR, useClass: EvidenceLinksInterceptor }, + ], +}) +export class EvidenceAccessModule {} diff --git a/src/evidence-access/evidence-access.service.ts b/src/evidence-access/evidence-access.service.ts new file mode 100644 index 0000000..0a4f446 --- /dev/null +++ b/src/evidence-access/evidence-access.service.ts @@ -0,0 +1,118 @@ +import { Injectable, UnauthorizedException } from "@nestjs/common"; +import { createHmac, timingSafeEqual } from "node:crypto"; +import { AsyncLocalStorage } from "node:async_hooks"; + +/** Short-lived read capabilities, minted only inside authenticated API responses. + * Browser image/video/PDF elements cannot attach an Authorization header. */ +@Injectable() +export class EvidenceAccessService { + private digest(path: string, expires: string): string { + const secret = process.env.JWT_SECRET; + if (!secret) throw new Error("JWT_SECRET is required for evidence access"); + return createHmac("sha256", secret) + .update(`evidence\n${path}\n${expires}`) + .digest("hex"); + } + sign(value: string): string { + const match = value.match( + /^(?:https?:\/\/[^/?#]+\/(?:[^?#]*\/)?|(?:\.?\/)?(?:[^\s/?#]+\/)*)files\/([^?#]+)(?:[?#].*)?$/, + ); + if (!match || !/\.[a-z0-9]+$/i.test(match[1])) return value; + const path = match[1]; + // Signing uses the same canonical URL path that Express decodes on read. + let decoded: string; + try { + decoded = decodeURIComponent(path); + } catch { + return value; + } + const expires = String(Math.floor(Date.now() / 1000) + 3600); + return `${value.split(/[?#]/)[0]}?expires=${expires}&signature=${this.digest(decoded, expires)}`; + } + verify(path: string, expires: string, signature: string): void { + if ( + typeof path !== "string" || + typeof expires !== "string" || + typeof signature !== "string" + ) + throw new UnauthorizedException("نشانی مدرک معتبر نیست."); + const exp = Number(expires); + if ( + !Number.isSafeInteger(exp) || + exp <= Date.now() / 1000 || + exp > Date.now() / 1000 + 3660 || + !/^[a-f0-9]{64}$/.test(signature || "") + ) + throw new UnauthorizedException( + "نشانی مدرک معتبر نیست یا منقضی شده است. پرونده را دوباره باز کنید.", + ); + if ( + !timingSafeEqual( + Buffer.from(signature, "hex"), + Buffer.from(this.digest(path, expires), "hex"), + ) + ) + throw new UnauthorizedException("دسترسی به این مدرک مجاز نیست."); + } + /** Only mirror a capability already minted by the trusted file-link builder. + * Reflected form fields or arbitrary URL-shaped text cannot mint access. */ + project(value: unknown): unknown { + const allowed = new Set(); + const walk = ( + v: unknown, + convert: (text: string, field: string) => unknown, + field = "", + ): unknown => { + if (v && typeof (v as any).toObject === "function") + return walk((v as any).toObject(), convert, field); + if (typeof v === "string") return convert(v, field); + if (Array.isArray(v)) return v.map((item) => walk(item, convert, field)); + if (v instanceof Map) + return Object.fromEntries( + [...v].map(([k, item]) => [k, walk(item, convert, String(k))]), + ); + if ( + v && + typeof v === "object" && + Object.getPrototypeOf(v) === Object.prototype + ) + return Object.fromEntries( + Object.entries(v).map(([k, item]) => [k, walk(item, convert, k)]), + ); + return v; + }; + walk(value, (text) => { + if (!text.includes("signature=")) return text; + try { + const url = new URL(text, "https://evidence.invalid"); + const path = decodeURIComponent(url.pathname.split("/files/")[1] || ""); + this.verify( + path, + url.searchParams.get("expires")!, + url.searchParams.get("signature")!, + ); + allowed.add(path); + } catch { + /* Ordinary text and untrusted links never grant access. */ + } + return text; + }); + return walk(value, (text, field) => { + if (!/(?:url|urls|path|paths|link|links)$/i.test(field)) return text; + try { + const url = new URL(text, "https://evidence.invalid"); + const path = decodeURIComponent(url.pathname.split("/files/")[1] || ""); + return allowed.has(path) ? this.sign(text) : text; + } catch { + return text; + } + }); + } +} + +export const evidenceRequestScope = new AsyncLocalStorage(); +const links = new EvidenceAccessService(); +/** Called only when constructing a link from server-owned file metadata. */ +export function signAuthorizedEvidenceLink(value: string): string { + return evidenceRequestScope.getStore() ? links.sign(value) : value; +} diff --git a/src/evidence-access/evidence-access.spec.ts b/src/evidence-access/evidence-access.spec.ts new file mode 100644 index 0000000..adb4e8a --- /dev/null +++ b/src/evidence-access/evidence-access.spec.ts @@ -0,0 +1,65 @@ +import { EvidenceAccessService } from "./evidence-access.module"; +describe("evidence read capabilities", () => { + const secret = process.env.JWT_SECRET; + beforeEach(() => { + process.env.JWT_SECRET = "test-only-evidence-key"; + }); + afterEach(() => { + if (secret == null) delete process.env.JWT_SECRET; + else process.env.JWT_SECRET = secret; + }); + it("rejects bare, expired, altered and cross-path links but accepts its own signature", () => { + const service = new EvidenceAccessService(); + const signed = new URL( + service.sign("https://example.test/car-damage/api/files/signs/a.jpg"), + ); + const exp = signed.searchParams.get("expires")!; + const sig = signed.searchParams.get("signature")!; + expect(() => service.verify("signs/a.jpg", exp, sig)).not.toThrow(); + expect(() => service.verify("signs/b.jpg", exp, sig)).toThrow(); + expect(() => service.verify("signs/a.jpg", "1", sig)).toThrow(); + expect(() => service.verify("signs/a.jpg", exp, "")).toThrow(); + expect(() => service.verify("signs/a.jpg", exp, [sig] as any)).toThrow(); + expect(() => service.verify("signs/a.jpg", exp, "0".repeat(64))).toThrow(); + }); + it("signs nested evidence without changing ordinary links, dates, or policy text", () => { + const service = new EvidenceAccessService(); + const projected: any = service.project({ + files: [ + { url: service.sign("files/car/a.jpg"), path: "files/car/a.jpg" }, + ], + reflected: { url: "files/car/private.jpg" }, + site: "https://example.test/auth", + note: "files/car/private.jpg", + description: "https://example.test/files/signs/private.png", + }); + expect(projected.files[0].url).toContain("?expires="); + expect(projected.files[0].path).toContain("?expires="); + expect(projected.reflected.url).toBe("files/car/private.jpg"); + expect(projected.site).toBe("https://example.test/auth"); + expect(projected.note).toBe("files/car/private.jpg"); + expect(projected.description).toBe( + "https://example.test/files/signs/private.png", + ); + expect(service.sign("See https://example.test/files/private.jpg")).toBe( + "See https://example.test/files/private.jpg", + ); + }); +}); + +it("mints links only while an authenticated request constructs them from stored media", () => { + const { evidenceRequestScope } = require("./evidence-access.service"); + const { buildFileLink } = require("src/helpers/urlCreator"); + const secret = process.env.JWT_SECRET; + process.env.JWT_SECRET = "qa-test-only"; + try { + expect(buildFileLink("files/car/a.jpg")).not.toContain("signature="); + expect( + evidenceRequestScope.run(true, () => buildFileLink("files/car/a.jpg")), + ).toContain("signature="); + expect(buildFileLink("files/car/a.jpg")).not.toContain("signature="); + } finally { + if (secret == null) delete process.env.JWT_SECRET; + else process.env.JWT_SECRET = secret; + } +}); diff --git a/src/expert-claim/expert-claim.service.ts b/src/expert-claim/expert-claim.service.ts index 6bef285..85619fd 100644 --- a/src/expert-claim/expert-claim.service.ts +++ b/src/expert-claim/expert-claim.service.ts @@ -1374,7 +1374,15 @@ export class ExpertClaimService { : null; const blameStatus = (reviewerBlame as any).status as string; - if (blameStatus === "WAITING_FOR_FILE_REVIEWER") { + const isReviewerCapturePhase = [ + ClaimCaseStatus.CREATED, + ClaimCaseStatus.WAITING_FOR_FILE_REVIEWER, + ClaimCaseStatus.SELECTING_OUTER_PARTS, + ClaimCaseStatus.SELECTING_OTHER_PARTS, + ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS, + ClaimCaseStatus.CAPTURING_PART_DAMAGES, + ].includes(claim.status as ClaimCaseStatus); + if (blameStatus === "WAITING_FOR_FILE_REVIEWER" && isReviewerCapturePhase) { if (assignedReviewerId && assignedReviewerId === actor.sub) { // Phase 1 is intentionally idempotent. The linked claim can still be // in a data-capture status here, so falling through to the damage @@ -1417,7 +1425,8 @@ export class ExpertClaimService { const isFactorValidationLock = claimIsAwaitingExpertFactorValidationV2(claim); const isDamageReviewLock = - claim.status === ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT; + claim.status === ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT || + claim.status === ClaimCaseStatus.IN_PERSON_VISIT_PENDING; const isExpertReviewingReentry = claim.status === ClaimCaseStatus.EXPERT_REVIEWING; const isResendPending = @@ -1612,7 +1621,7 @@ export class ExpertClaimService { assignFilter.initiatedByFieldExpertId = expertOid; assignFilter.status = claim.status; } else { - assignFilter.status = ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT; + assignFilter.status = claim.status; } const updated = await this.claimCaseDbService.findOneAndUpdate( @@ -1842,6 +1851,7 @@ export class ExpertClaimService { "workflow.currentStep": ClaimWorkflowStep.USER_EXPERT_RESEND, "workflow.nextStep": ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT, "evaluation.damageExpertResend": { + requestedAt: new Date(), resendDescription: desc || undefined, resendDocuments: uniqueDocs, resendCarParts: normalizedParts, @@ -2338,7 +2348,7 @@ export class ExpertClaimService { * - Status must be EXPERT_REVIEWING * * On success: - * - Sets status = EXPERT_REVIEWING (remains), claimStatus = NEEDS_REVISION + * - Sets status = IN_PERSON_VISIT_PENDING, claimStatus = NEEDS_REVISION * - Sets evaluation.visitLocation (optional note) * - Records history event IN_PERSON_VISIT_REQUESTED * - Unlocks the workflow so user can act @@ -2355,7 +2365,7 @@ export class ExpertClaimService { throw new NotFoundException("Claim request not found"); } - assertClaimCaseForTenant(claim, actor); + await this.assertExpertActorOnClaim(claim, actor); if (claim.status !== ClaimCaseStatus.EXPERT_REVIEWING) { throw new BadRequestException( @@ -2377,7 +2387,7 @@ export class ExpertClaimService { await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { claimStatus: ClaimStatus.NEEDS_REVISION, - status: ClaimCaseStatus.COMPLETED, + status: ClaimCaseStatus.IN_PERSON_VISIT_PENDING, "workflow.locked": false, $unset: { "workflow.lockedAt": "", @@ -2385,7 +2395,7 @@ export class ExpertClaimService { "workflow.lockedBy": "", "workflow.preLockQueueSnapshot": "", }, - ...(note ? { "evaluation.visitLocation": note } : {}), + "evaluation.visitLocation": note?.trim() || "برای ادامه ارزیابی، به شعبه رسیدگی پرونده مراجعه کنید.", ...(visitSnapshot && { "evaluation.inPersonVisitExpertProfileSnapshot": visitSnapshot, }), @@ -2415,7 +2425,7 @@ export class ExpertClaimService { return { claimRequestId, - status: ClaimCaseStatus.COMPLETED, + status: ClaimCaseStatus.IN_PERSON_VISIT_PENDING, claimStatus: ClaimStatus.NEEDS_REVISION, message: "In-person visit requested. User will be notified.", }; @@ -2635,7 +2645,7 @@ export class ExpertClaimService { { _id: { $in: blameIds.map((id) => new Types.ObjectId(id)) }, }, - { lean: true, select: "status publicId" }, + { lean: true, select: "status publicId type" }, )) as any[]) : []; const blameById = new Map( @@ -3856,7 +3866,8 @@ export class ExpertClaimService { new Map(blameLean ? [[String(claim.blameRequestId), blameLean]] : []), ); const vehiclePayload = { - ...((claim.vehicle as any) ?? {}), + ...(typeof (claim.vehicle as any)?.toObject === "function" + ? (claim.vehicle as any).toObject() : (claim.vehicle ?? {})), ...resolvedVehicle, }; diff --git a/src/expert-claim/fanavaran-stage-fields.spec.ts b/src/expert-claim/fanavaran-stage-fields.spec.ts index fb13524..d9d945e 100644 --- a/src/expert-claim/fanavaran-stage-fields.spec.ts +++ b/src/expert-claim/fanavaran-stage-fields.spec.ts @@ -173,11 +173,12 @@ describe("Expert Fanavaran stage fields", () => { management.fanavaranLookupService = { bodyPolicyById: jest.fn().mockResolvedValue({ TotalPremium: 123456 }), }; - const payload = await management.previewFanavaranSubmitV2(id, clientKey, { + const preview = await management.previewFanavaranSubmitV2(id, clientKey, { persistPayload: false, forceRefreshPolicy: false, requireClaimExpertId: false, }); + const payload = preview.payload ?? preview; expect(payload.ClaimExpertId).toBe(154); expect(payload).toMatchObject({ AccidentLocationAddress: "نشانی واقعی", diff --git a/src/expert-insurer/expert-insurer.service.ts b/src/expert-insurer/expert-insurer.service.ts index 3eb9dfa..8f30c75 100644 --- a/src/expert-insurer/expert-insurer.service.ts +++ b/src/expert-insurer/expert-insurer.service.ts @@ -166,7 +166,7 @@ export class ExpertInsurerService { carPlate: claim.vehicle?.plate, claimStatus: claim.status, rating: claim.evaluation?.rating, - userRating: claim.evaluation?.userRating, + userRating: claim.userRating ?? claim.evaluation?.userRating, damageExpertReply: claim.evaluation?.damageExpertReply, damageExpertReplyFinal: claim.evaluation?.damageExpertReplyFinal, damageExpertResend: claim.evaluation?.damageExpertResend, @@ -1065,6 +1065,19 @@ export class ExpertInsurerService { range.toDate, ); + const blameTypes = new Map(blameFiles.map((file) => [String(file._id), file.type])); + // Roster-owned claims can belong to another party insurer. Resolve only the + // missing linked types in one batch, after claims have already been scoped. + const missingBlameIds = [...new Set(claimFiles.map((file) => String(file.blameRequestId || "")))] + .filter((id) => Types.ObjectId.isValid(id) && !blameTypes.has(id)); + if (missingBlameIds.length) { + const linked = await this.blameRequestDbService.find( + {_id: {$in: missingBlameIds.map((id) => new Types.ObjectId(id))}}, + {lean: true, select: "type"}, + ); + for (const file of linked) blameTypes.set(String(file._id), file.type); + } + const blameFilesInRange = blameFiles.filter((file) => this.isInDateRange(file?.createdAt, range.fromDate, range.toDate), ); @@ -1098,7 +1111,8 @@ export class ExpertInsurerService { .filter((expertId): expertId is string => !!expertId) .filter((expertId) => rosterById.has(expertId)); const fileType = String( - file?.snapshot?.accident?.type ?? + blameTypes.get(String(file.blameRequestId)) ?? + file?.snapshot?.accident?.type ?? file?.blameFile?.type ?? BlameRequestType.THIRD_PARTY, ); diff --git a/src/expert-insurer/qa-reporting-regressions.spec.ts b/src/expert-insurer/qa-reporting-regressions.spec.ts new file mode 100644 index 0000000..6d15fdf --- /dev/null +++ b/src/expert-insurer/qa-reporting-regressions.spec.ts @@ -0,0 +1,61 @@ +import { ExpertInsurerService } from "./expert-insurer.service"; +import { Types } from "mongoose"; + +describe("QA reporting regressions", () => { + it("classifies a roster-owned claim by its linked blame even when that blame is outside the party-insurer list", async () => { + const s: any = Object.create(ExpertInsurerService.prototype); + const clientKey = String(new Types.ObjectId()), + expertId = new Types.ObjectId(), + blameId = new Types.ObjectId(); + s.expertDbService = { findAll: jest.fn().mockResolvedValue([]) }; + s.damageExpertDbService = { + findAll: jest + .fn() + .mockResolvedValue([ + { _id: expertId, firstName: "QA", lastName: "Expert" }, + ]), + }; + s.fieldExpertDbService = { findAll: jest.fn().mockResolvedValue([]) }; + s.getClientBlameFiles = jest.fn().mockResolvedValue([]); + s.getClientClaimFiles = jest + .fn() + .mockResolvedValue([ + { + _id: new Types.ObjectId(), + blameRequestId: blameId, + createdAt: new Date(), + }, + ]); + s.expertFileActivityDbService = { + findByTenant: jest.fn().mockResolvedValue([]), + }; + s.claimDamageExpertActorId = jest.fn().mockReturnValue(String(expertId)); + s.blameRequestDbService = { + find: jest.fn().mockResolvedValue([{ _id: blameId, type: "CAR_BODY" }]), + }; + const result = await s.buildExpertReportRows({ clientKey }); + expect(result.experts[0]).toMatchObject({ + totalFiles: 1, + carBodyFiles: 1, + thirdPartyFiles: 0, + }); + expect(s.blameRequestDbService.find).toHaveBeenCalledWith( + { _id: { $in: [blameId] } }, + { lean: true, select: "type" }, + ); + }); + it("preserves current root user ratings and falls back to legacy nested ratings", () => { + const s: any = Object.create(ExpertInsurerService.prototype); + const current = { overallEvaluation: 5 }, + legacy = { overallEvaluation: 1 }; + expect( + s.normalizeClaimCase({ + userRating: current, + evaluation: { userRating: legacy }, + }).userRating, + ).toBe(current); + expect( + s.normalizeClaimCase({ evaluation: { userRating: legacy } }).userRating, + ).toBe(legacy); + }); +}); diff --git a/src/helpers/claim-details-v2-owner-guidance.ts b/src/helpers/claim-details-v2-owner-guidance.ts index ba7ce96..e1e971e 100644 --- a/src/helpers/claim-details-v2-owner-guidance.ts +++ b/src/helpers/claim-details-v2-owner-guidance.ts @@ -103,6 +103,12 @@ export function buildClaimDetailsV2OwnerGuidance( const objectionAllowed = ownerMaySubmitObjectionForClaimDetails(claim); const objectionHint = objectionHintWhen(objectionAllowed); + if (claim.status === ClaimCaseStatus.IN_PERSON_VISIT_PENDING) return { + phaseKey: "IN_PERSON_VISIT_PENDING", headline: "مراجعه حضوری درخواست شده است", + detail: claim.evaluation?.visitLocation || "برای ادامه ارزیابی، به شعبه رسیدگی پرونده مراجعه کنید.", + nextActions: [], objectionAllowed: false, + }; + if (claim.status === ClaimCaseStatus.COMPLETED) { return { phaseKey: "COMPLETED", diff --git a/src/helpers/claim-expert-resend.spec.ts b/src/helpers/claim-expert-resend.spec.ts new file mode 100644 index 0000000..f36e162 --- /dev/null +++ b/src/helpers/claim-expert-resend.spec.ts @@ -0,0 +1,58 @@ +import { canFinalizeExpertResend } from "./claim-expert-resend"; +describe("current resend evidence", () => { + it("requires every replacement to be newer than this request, without discarding original evidence", () => { + const c: any = { + status: "WAITING_FOR_USER_RESEND", + workflow: { currentStep: "USER_EXPERT_RESEND" }, + evaluation: { + damageExpertResend: { + requestedAt: new Date("2026-11-22T10:00:00Z"), + resendDocuments: [ + "damaged_driving_license_front", + "damaged_car_card_front", + ], + resendCarParts: [{ id: 101, name: "101", catalogKey: "101" }], + }, + }, + damage: { + selectedParts: [ + { id: 101, name: "101", catalogKey: "101", label_fa: "سپر" }, + ], + }, + requiredDocuments: { + damaged_driving_license_front: { + uploaded: true, + uploadedAt: new Date("2026-11-21"), + }, + damaged_car_card_front: { + uploaded: true, + uploadedAt: new Date("2026-11-21"), + }, + }, + media: { + damagedParts: [ + { + id: 101, + name: "101", + catalogKey: "101", + path: "files/old.jpg", + capturedAt: new Date("2026-11-21"), + }, + ], + }, + }; + expect(canFinalizeExpertResend(c)).toBe(false); + c.requiredDocuments.damaged_driving_license_front.uploadedAt = new Date( + "2026-11-22T10:01:00Z", + ); + expect(canFinalizeExpertResend(c)).toBe(false); + c.requiredDocuments.damaged_car_card_front.uploadedAt = new Date( + "2026-11-22T10:02:00Z", + ); + expect(canFinalizeExpertResend(c)).toBe(false); + c.media.damagedParts[0].capturedAt = new Date("2026-11-22T10:03:00Z"); + expect(canFinalizeExpertResend(c)).toBe(true); + c.evaluation.damageExpertResend.fulfilledAt = new Date(); + expect(canFinalizeExpertResend(c)).toBe(false); + }); +}); diff --git a/src/helpers/claim-expert-resend.ts b/src/helpers/claim-expert-resend.ts index 4511ac4..a6bedfd 100644 --- a/src/helpers/claim-expert-resend.ts +++ b/src/helpers/claim-expert-resend.ts @@ -260,28 +260,18 @@ export function canFinalizeExpertResend(claim: any): boolean { claim?.damage?.selectedParts, ); - console.log("[canFinalizeExpertResend]", { - docKeys, - partKeys, - docResults: docKeys.map((k) => ({ - k, - uploaded: isRequiredDocumentUploaded(claim, k), - })), - partResults: partKeys.map((k) => ({ - k, - captured: hasDamagedPartCapture(claim, k), - })), - }); - if (docKeys.length === 0 && partKeys.length === 0) { return String(r.resendDescription || "").trim() !== ""; } for (const k of docKeys) { - if (!isRequiredDocumentUploaded(claim, k)) return false; + const entry = getRequiredDocEntry(claim, k) as {uploadedAt?: Date}; + if (!isRequiredDocumentUploaded(claim, k) || !isCurrentResendEvidence(claim, entry?.uploadedAt)) return false; } for (const k of partKeys) { - if (!hasDamagedPartCapture(claim, k)) return false; + const norm = normalizeDamageSelectedParts(claim?.damage?.selectedParts, carType, claim?.damage?.selectedOuterParts); + const capture = getDamagedPartCaptureBlob(claim?.media?.damagedParts, k, norm) as {capturedAt?: Date}; + if (!hasDamagedPartCapture(claim, k) || !isCurrentResendEvidence(claim, capture?.capturedAt)) return false; } return true; } @@ -334,3 +324,14 @@ export function partKeyAllowedForExpertResend( return directMatch || (resolvedKey != null && allowedKeys.has(resolvedKey)); } + +/** Legacy pending resends use their recorded request event as the cutoff. */ +export function isCurrentResendEvidence(claim: any, uploadedAt: unknown): boolean { + const requestedAt = claim?.evaluation?.damageExpertResend?.requestedAt ?? + [...(claim?.history ?? [])].reverse().find((h: any) => h.type === 'EXPERT_RESEND_REQUESTED')?.timestamp; + // Old rows without a cutoff must receive fresh uploads rather than implicitly + // satisfying a replacement request using evidence from initial submission. + const cutoff = new Date(requestedAt ?? claim?.updatedAt ?? 0).getTime(); + const received = new Date(uploadedAt as string).getTime(); + return Number.isFinite(received) && received >= cutoff; +} diff --git a/src/helpers/unified-file-status.spec.ts b/src/helpers/unified-file-status.spec.ts index 0b54551..4ca323b 100644 --- a/src/helpers/unified-file-status.spec.ts +++ b/src/helpers/unified-file-status.spec.ts @@ -44,3 +44,7 @@ describe("resolveUnifiedFileStatus", () => { expect(counts.IN_PROGRESS).toBe(2); }); }); + +it("keeps a pending in-person review out of completed/user-capture buckets", () => { + expect(resolveUnifiedFileStatus({blameStatus: CaseStatus.COMPLETED, claimStatus: ClaimCaseStatus.IN_PERSON_VISIT_PENDING})).toBe("EXPERT_REVIEWING"); +}); diff --git a/src/helpers/unified-file-status.ts b/src/helpers/unified-file-status.ts index a1803f4..8623c5b 100644 --- a/src/helpers/unified-file-status.ts +++ b/src/helpers/unified-file-status.ts @@ -172,7 +172,7 @@ export function resolveUnifiedFileStatus( return "WAITING_FOR_DOCUMENT_RESEND"; } - if (claim === ClaimCaseStatus.EXPERT_REVIEWING) return "EXPERT_REVIEWING"; + if (claim === ClaimCaseStatus.EXPERT_REVIEWING || claim === ClaimCaseStatus.IN_PERSON_VISIT_PENDING) return "EXPERT_REVIEWING"; if (claim === ClaimCaseStatus.EXPERT_VALIDATING_REPAIR_FACTORS) { return "EXPERT_VALIDATING_FACTORS"; } diff --git a/src/helpers/urlCreator.ts b/src/helpers/urlCreator.ts index a1cf24b..3da10be 100644 --- a/src/helpers/urlCreator.ts +++ b/src/helpers/urlCreator.ts @@ -1,3 +1,5 @@ +import { signAuthorizedEvidenceLink } from "src/evidence-access/evidence-access.service"; + type StoredFileCapture = { url?: string; path?: string; @@ -41,9 +43,9 @@ export function buildFileLink(path: string): string { const baseUrl = (process.env.URL ?? "").replace(/\/+$/, ""); if (process.env.NODE_ENV === "local") { - return `${baseUrl}/${relative}`; + return signAuthorizedEvidenceLink(`${baseUrl}/${relative}`); } - return `${baseUrl}/api/${relative}`; + return signAuthorizedEvidenceLink(`${baseUrl}/api/${relative}`); } /** diff --git a/src/media-policy/media-policy.service.ts b/src/media-policy/media-policy.service.ts index e0b4563..f4c4337 100644 --- a/src/media-policy/media-policy.service.ts +++ b/src/media-policy/media-policy.service.ts @@ -1,3 +1,4 @@ +import { validateMedia } from "./validate-media"; import { BadRequestException, Injectable, Logger } from "@nestjs/common"; import { InjectModel } from "@nestjs/mongoose"; import { Model, Types } from "mongoose"; @@ -106,7 +107,7 @@ export class MediaPolicyService { kind: MediaKind, ): Promise { const limits = await this.clientService.getMediaLimits(clientId, kind); - const violation = this.checkLimits(file, limits, kind); + const violation = this.checkLimits(file, limits, kind) ?? await this.contentViolation(file, kind); if (!violation) return; await this.tryDelete(file?.path); @@ -133,7 +134,7 @@ export class MediaPolicyService { const kind = fieldKindMap[field]; if (!kind) continue; const limits = await getLimits(kind); - const violation = this.checkLimits(file, limits, kind, field); + const violation = this.checkLimits(file, limits, kind, field) ?? await this.contentViolation(file, kind); if (!violation) continue; // The request is being rejected — clean up all uploaded files so we @@ -143,6 +144,16 @@ export class MediaPolicyService { } } + private async contentViolation(file: NonNullable, kind: MediaKind) { + try { + if (!file.path) throw new Error('Missing file'); + await validateMedia(file.path, kind); + return null; + } catch { + return {code: 'MEDIA_CONTENT_INVALID', kind, message: 'محتوای فایل قابل خواندن نیست یا با نوع مدرک مطابقت ندارد. فایل سالم و مناسب را دوباره انتخاب کنید.'}; + } + } + private checkLimits( file: NonNullable, { minBytes, maxBytes }: MediaLimits, diff --git a/src/media-policy/validate-media.spec.ts b/src/media-policy/validate-media.spec.ts new file mode 100644 index 0000000..d685785 --- /dev/null +++ b/src/media-policy/validate-media.spec.ts @@ -0,0 +1,68 @@ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { mkdtemp, writeFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { validateMedia } from "./validate-media"; +describe("uploaded media content", () => { + it("rejects text spoofed as mp4 and accepts valid document PDFs", async () => { + const dir = await mkdtemp(join(tmpdir(), "media-test-")); + try { + const path = join(dir, "spoof.mp4"); + await writeFile(path, "This is not a video."); + await expect(validateMedia(path, "video")).rejects.toThrow(); + const pdf = join(dir, "document.pdf"); + await writeFile(pdf, "%PDF-1.4\n1 0 obj\n<<>>\nendobj\n%%EOF"); + await expect(validateMedia(pdf, "image")).resolves.toBeUndefined(); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +}); + +it("accepts real images, videos and audio but rejects a still image posing as a video", async () => { + const dir = await mkdtemp(join(tmpdir(), "media-content-")); + const run = promisify(execFile); + try { + const image = join(dir, "photo.png"), + video = join(dir, "clip.mp4"), + audio = join(dir, "voice.wav"); + await run("ffmpeg", [ + "-v", + "error", + "-f", + "lavfi", + "-i", + "color=s=32x32", + "-frames:v", + "1", + image, + ]); + await run("ffmpeg", [ + "-v", + "error", + "-f", + "lavfi", + "-i", + "color=s=32x32:d=0.2", + video, + ]); + await run("ffmpeg", [ + "-v", + "error", + "-f", + "lavfi", + "-i", + "sine=duration=0.2", + audio, + ]); + await expect(validateMedia(image, "image")).resolves.toBeUndefined(); + await expect(validateMedia(video, "video")).resolves.toBeUndefined(); + await expect(validateMedia(audio, "voice")).resolves.toBeUndefined(); + await expect(validateMedia(image, "video")).rejects.toThrow(); + await expect(validateMedia(video, "image")).rejects.toThrow(); + await expect(validateMedia(image, "voice")).rejects.toThrow(); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/src/media-policy/validate-media.ts b/src/media-policy/validate-media.ts new file mode 100644 index 0000000..3f8817d --- /dev/null +++ b/src/media-policy/validate-media.ts @@ -0,0 +1,76 @@ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { readFile } from "node:fs/promises"; +import type { MediaKind } from "src/client/client.service"; +const run = promisify(execFile); +/** Inspect bytes/streams, never the user-controlled filename or Content-Type. */ +export async function validateMedia( + path: string, + kind: MediaKind, +): Promise { + if (kind === "image" || kind === "chassisNumber" || kind === "carPlate") { + const bytes = await readFile(path); + // Documents also accept PDFs. Require both the header and end marker. + if (bytes.subarray(0, 5).toString() === "%PDF-") { + if (!bytes.subarray(-2048).includes(Buffer.from("%%EOF"))) + throw new Error("Invalid PDF"); + return; + } + } + const { stdout } = await run( + "ffprobe", + [ + "-v", + "error", + "-protocol_whitelist", + "file,pipe", + "-show_streams", + "-show_format", + "-of", + "json", + path, + ], + { timeout: 15000, maxBuffer: 1024 * 1024 }, + ); + const metadata = JSON.parse(stdout); + const imageFormat = String(metadata.format?.format_name || "") + .split(",") + .some((f: string) => + /^(?:image2|image2pipe|.*_pipe|gif|apng|ico|heif)$/.test(f), + ); + if ( + (kind === "video" && imageFormat) || + ((kind === "image" || kind === "chassisNumber" || kind === "carPlate") && + !imageFormat) + ) + throw new Error("Wrong media container"); + const streams = metadata.streams as Array<{ + codec_type?: string; + width?: number; + height?: number; + }>; + const type = kind === "voice" ? "audio" : "video"; + if (!streams?.some((s) => s.codec_type === type)) + throw new Error("Missing media stream"); + if (type === "video" && !streams.some((s) => s.width > 0 && s.height > 0)) + throw new Error("Invalid dimensions"); + await run( + "ffmpeg", + [ + "-v", + "error", + "-protocol_whitelist", + "file,pipe", + "-nostdin", + "-i", + path, + "-map", + `0:${type === "audio" ? "a" : "v"}:0`, + ...(type === "audio" ? ["-t", "0.1"] : ["-frames:v", "1"]), + "-f", + "null", + "-", + ], + { timeout: 15000, maxBuffer: 1024 * 1024 }, + ); +} diff --git a/src/request-management/call-center-v6-workflow.spec.ts b/src/request-management/call-center-v6-workflow.spec.ts index 682ee4b..f1a62f7 100644 --- a/src/request-management/call-center-v6-workflow.spec.ts +++ b/src/request-management/call-center-v6-workflow.spec.ts @@ -234,9 +234,9 @@ describe("V6 call-center workflow", () => { Object.assign(body, { accidentDate: "1405/08/18", accidentTime: "12:00", - weatherCondition: 1, - roadCondition: 1, - lightCondition: 1, + weatherCondition: "صاف", + roadCondition: "خشک", + lightCondition: "روز", }); await service.addDescriptionV2(id, body, first); if (type === Kind.THIRD_PARTY) { diff --git a/src/request-management/file-reviewer-blame-v4.controller.ts b/src/request-management/file-reviewer-blame-v4.controller.ts index b5a71ea..bb56074 100644 --- a/src/request-management/file-reviewer-blame-v4.controller.ts +++ b/src/request-management/file-reviewer-blame-v4.controller.ts @@ -1,3 +1,4 @@ +import { randomUUID } from "node:crypto"; import { extname } from "node:path"; import { BadRequestException, @@ -382,7 +383,7 @@ export class FileReviewerBlameV4Controller { storage: diskStorage({ destination: "./files/claim-sign", filename: (req, file, callback) => { - const unique = Date.now(); + const unique = randomUUID(); const ex = extname(file.originalname); const base = file.originalname.split(/[.,\s-]/)[0] || "sign"; callback(null, `${base}-${unique}${ex}`); diff --git a/src/request-management/file-reviewer-blame-v5.controller.ts b/src/request-management/file-reviewer-blame-v5.controller.ts index 329eaf1..ddaef5f 100644 --- a/src/request-management/file-reviewer-blame-v5.controller.ts +++ b/src/request-management/file-reviewer-blame-v5.controller.ts @@ -1,3 +1,4 @@ +import { randomUUID } from "node:crypto"; import { extname } from "node:path"; import { Body, @@ -380,7 +381,7 @@ export class FileReviewerBlameV5Controller { storage: diskStorage({ destination: "./files/claim-sign", filename: (req, file, callback) => { - const unique = Date.now(); + const unique = randomUUID(); const ex = extname(file.originalname); const base = file.originalname.split(/[.,\s-]/)[0] || "sign"; callback(null, `${base}-${unique}${ex}`); diff --git a/src/request-management/registrar-blame.mirror.controller.ts b/src/request-management/registrar-blame.mirror.controller.ts index 02b7a4b..765ecfa 100644 --- a/src/request-management/registrar-blame.mirror.controller.ts +++ b/src/request-management/registrar-blame.mirror.controller.ts @@ -393,18 +393,6 @@ export class RegistrarBlameMirrorController { @CurrentUser() registrar: any, @UploadedFile() sign: Express.Multer.File, ) { - // Guard: accident fields must be filled before signing to prevent the - // double-sign bug where add-accident-fields re-enters WAITING_FOR_SIGNATURES. - const requestData = await this.requestManagementService.getBlameRequestV2( - requestId, - registrar, - ); - if (!(requestData?.expert?.decision as any)?.fields?.accidentWay) { - throw new BadRequestException( - "Accident fields (accidentWay, accidentReason, accidentType) must be submitted via add-accident-fields before signing.", - ); - } - await this.mediaPolicyService.assertForBlame(sign, requestId, "image"); const partyRole = body?.partyRole === "SECOND" ? PartyRole.SECOND : PartyRole.FIRST; diff --git a/src/request-management/request-management.service.ts b/src/request-management/request-management.service.ts index 2f23fe2..af880f2 100644 --- a/src/request-management/request-management.service.ts +++ b/src/request-management/request-management.service.ts @@ -1,3 +1,4 @@ +import { WeatherCondition, RoadCondition, LightCondition } from "src/Types&Enums/blame-request-management/accident-conditions.enum"; import { UserClaimBranchService, userClaimBranchContext, usesUserClaimBranch } from "src/client/user-claim-branch.service"; import { normalizeAccidentLocation } from "./accident-location"; import { @@ -215,6 +216,13 @@ export class RequestManagementService { } /** Keep eligibility rejections distinct from an unavailable CAR_BODY provider. */ + private assertAccidentConditions(body: {weatherCondition?: unknown; roadCondition?: unknown; lightCondition?: unknown}): void { + for (const [value, choices] of [[body.weatherCondition, WeatherCondition], [body.roadCondition, RoadCondition], [body.lightCondition, LightCondition]] as const) { + if (value != null && !Object.values(choices).includes(value as never)) + throw new BadRequestException("شرایط آب‌وهوا، راه یا روشنایی حادثه معتبر نیست. گزینه‌های فرم را دوباره انتخاب کنید."); + } + } + private assertCarBodyDescriptionMinimum( requestType: BlameRequestType | string | undefined, description: unknown, @@ -2910,6 +2918,7 @@ export class RequestManagementService { ); this.assertCarBodyDescriptionMinimum(req.type, body.desc); + this.assertAccidentConditions(body as DescriptionDto); // Set userId for party if not already set (important for second party) if (!party.person) party.person = {} as any; @@ -5075,6 +5084,7 @@ export class RequestManagementService { formData?.expertDescription?.desc, ); + this.assertAccidentConditions(formData?.expertDescription ?? {}); const firstPartyUserId = await this.getOrCreateUserByPhoneNumber( formData.firstPartyPhoneNumber, ); @@ -5399,6 +5409,7 @@ export class RequestManagementService { throw new BadRequestException("expertDescription.desc is required."); } + this.assertAccidentConditions(formData?.expertDescription ?? {}); const firstPartyUserId = await this.getOrCreateUserByPhoneNumber( formData.firstPartyPhoneNumber, ); @@ -5846,7 +5857,7 @@ export class RequestManagementService { const req = await this.blameRequestDbService.findById(requestId); if (!req) throw new NotFoundException("Request not found"); if ( - !req.expertInitiated || + (!req.expertInitiated && !req.registrarInitiated) || req.creationMethod !== CreationMethod.IN_PERSON ) { throw new BadRequestException( @@ -5889,7 +5900,7 @@ export class RequestManagementService { const signatureData = { fileId: String((signDoc as any)._id), fileName: signFile.filename, - fileUrl: signFile.path, + fileUrl: buildFileLink(signFile.path), }; const updatePayload: any = { $set: { @@ -6578,7 +6589,7 @@ export class RequestManagementService { const signatureData = { fileId: String((signDoc as any)._id), fileName: signFile.filename, - fileUrl: signFile.path, + fileUrl: buildFileLink(signFile.path), }; const confirmationPayload = { @@ -8203,7 +8214,7 @@ export class RequestManagementService { const signatureData = { fileId: String((signDoc as any)._id), fileName: signFile.filename, - fileUrl: signFile.path, + fileUrl: buildFileLink(signFile.path), }; await this.blameRequestDbService.findByIdAndUpdate(requestId, { @@ -8700,6 +8711,7 @@ export class RequestManagementService { const role = this.resolvePartyRoleV3(req, partyRole); this.assertBlameV3PartyDetailPhase(req, role); this.assertCarBodyDescriptionMinimum(req.type, body.desc); + this.assertAccidentConditions(body as DescriptionDto); // accidentDate and accidentTime are only required for the first (guilty) // party — the second (damaged) party can skip them. @@ -8724,8 +8736,6 @@ export class RequestManagementService { const idx = this.getPartyIndex(req, role); if (idx === -1) throw new BadRequestException(`${role} party not found`); - this.assertCarBodyDescriptionMinimum(req.type, body.desc); - const party = req.parties[idx]; if (req.type === BlameRequestType.CAR_BODY && role === PartyRole.FIRST) { await this.validateCarBodyAccidentCoverage(party, body.accidentDate);