fix: harden profile updates and localize public errors in Persian

Preserve actor and user profile fields during partial updates and validate supported personal data.

Add Persian HTTP error handling, validation translations, regression tests, and audit documentation.
This commit is contained in:
SepehrYahyaee
2026-11-04 12:03:04 +03:30
parent 255998097d
commit 2056412efe
16 changed files with 1627 additions and 205 deletions
+216
View File
@@ -0,0 +1,216 @@
import {
BadRequestException,
ForbiddenException,
HttpException,
NotFoundException,
} from "@nestjs/common";
import { firstValueFrom, of } from "rxjs";
import {
getPersianErrorMessage,
localizeErrorMessage,
localizeErrorPayload,
localizeFailureEnvelopes,
} from "./persian-errors";
import { PersianErrorFilter } from "./persian-error.filter";
import { PersianErrorInterceptor } from "./persian-error.interceptor";
const persian = (value: string) => {
expect(value).toMatch(/[\u0600-\u06ff]/);
expect(value).not.toMatch(/[A-Za-z]{2,}/);
};
describe("public Persian error wording", () => {
it.each([
["nationalCode must be a string", "کد ملی"],
[
"driverBirthday must be a valid ISO 8601 date string",
"تاریخ تولد راننده",
],
[
"licenseType must be one of the following values: 1, 2, 3",
"نوع گواهینامه",
],
["description must be longer than or equal to 100 characters", "۱۰۰"],
["CAR_BODY description must contain at least 100 characters", "۱۰۰"],
["latitude must not be greater than 90", "حداکثر ۹۰"],
["latitude must not be less than -90", "حداقل -۹۰"],
[
"price must be a number conforming to the specified constraints",
"قیمت قطعه",
],
[
"Guilty party OTP must be verified before running inquiries.",
"کد تأیید طرف مقصر",
],
[
"Damaged party OTP must be verified before running inquiries.",
"کد تأیید زیان‌دیده",
],
["Complete damaged-party inquiries before signing.", "پیش از امضا"],
["Request is locked by another expert", "کارشناس دیگری"],
["Only the damaged party can create the claim", "زیان‌دیده"],
[
"Unknown provider exception with credentials and stack details",
"دوباره تلاش کنید",
],
])(
"localizes %s without exposing identifiers or internal prose",
(input, expected) => {
const result = localizeErrorMessage(input);
persian(result);
if (expected === "پیش از امضا") expect(result).toContain("سپس امضا");
else expect(result).toContain(expected);
},
);
it("preserves helpful Persian messages and translates technical field names", () => {
expect(localizeErrorMessage("کد ملی راننده باید ۱۰ رقم باشد.")).toBe(
"کد ملی راننده باید ۱۰ رقم باشد.",
);
expect(localizeErrorMessage("VIN واردشده معتبر نیست.")).toBe(
"شماره شاسی واردشده معتبر نیست.",
);
persian(localizeErrorMessage("خطا: Internal server error"));
});
it.each([401, 403, 404, 409, 413, 415, 429, 500, 502, 503, 504])(
"has a readable fallback for HTTP %s",
(status) => {
persian(localizeErrorPayload(undefined, status).message);
},
);
it("retains machine codes, field paths, IDs, arrays and numeric constraints without mutating the original", () => {
const original = {
statusCode: 422,
code: "VALIDATION_ERROR",
error: "PART_NOT_ON_CLAIM",
field: "parts[0].price",
partId: 30,
minAmount: 100000,
message: ["price must be a number", "partId must be an integer number"],
validationErrors: [
{ field: "parts[0].price", message: "price must be a number" },
],
};
const result = localizeErrorPayload(original, 422);
expect(result).toMatchObject({
code: "VALIDATION_ERROR",
error: "PART_NOT_ON_CLAIM",
field: "parts[0].price",
partId: 30,
minAmount: 100000,
});
expect(result.message).toHaveLength(2);
result.message.forEach(persian);
persian(result.validationErrors[0].message);
expect(original.message[0]).toBe("price must be a number");
});
it("reads nested responses and message arrays rather than generic transport messages", () => {
expect(
getPersianErrorMessage({
message: "Request failed with status code 422",
response: {
status: 422,
data: {
message: [
"nationalCode should not be empty",
"birthday must be a valid ISO 8601 date string",
],
},
},
}),
).toContain("کد ملی");
expect(
getPersianErrorMessage({
response: { status: 400, data: "کد ملی صحیح نیست." },
}),
).toBe("کد ملی صحیح نیست.");
expect(
getPersianErrorMessage({
errors: ["نام را وارد کنید.", "کد ملی را وارد کنید."],
message: "2 errors occurred",
}),
).toBe("نام را وارد کنید.، کد ملی را وارد کنید.");
});
it.each([
{ code: "ECONNABORTED" },
{ code: "ERR_NETWORK" },
{ code: "CERT_HAS_EXPIRED" },
{ name: "NotAllowedError", code: 0, message: "Permission denied" },
{ name: "NotFoundError", code: 8, message: "No camera" },
])("handles network, TLS and browser device errors: %j", (error) =>
persian(getPersianErrorMessage(error)),
);
it("changes only failure envelopes, retaining success data, reports and statuses", async () => {
const value = {
message: "Saved",
report: "original English evidence",
status: "COMPLETED",
checks: [
{
success: false,
code: "INQUIRY_NO_MATCH",
message: "Policy not found",
},
],
};
const result = await firstValueFrom(
new PersianErrorInterceptor().intercept({} as any, {
handle: () => of(value),
}),
);
expect(result).toMatchObject({
message: "Saved",
report: value.report,
status: "COMPLETED",
checks: [{ code: "INQUIRY_NO_MATCH", success: false }],
});
persian(result.checks[0].message);
expect(localizeFailureEnvelopes(Buffer.from("original bytes"))).toEqual(
Buffer.from("original bytes"),
);
});
});
describe("global Persian HTTP error filter", () => {
const reply = jest.fn();
const response = {};
const filter = new PersianErrorFilter({
httpAdapter: { reply, isHeadersSent: () => false },
} as any);
const host = { switchToHttp: () => ({ getResponse: () => response }) } as any;
beforeEach(() => reply.mockClear());
it.each([
new BadRequestException("nationalCode should not be empty"),
new ForbiddenException("Forbidden"),
new NotFoundException("Request not found"),
new HttpException(
{
code: "PRICE_CAP_ERROR",
partId: 30,
message: "price must be a number",
},
422,
),
])("preserves exception status and localizes the HTTP body", (error) => {
filter.catch(error, host);
const [target, body, status] = reply.mock.calls[0];
expect(target).toBe(response);
expect(status).toBe(error.getStatus());
persian(body.message);
if (status === 422)
expect(body).toMatchObject({ code: "PRICE_CAP_ERROR", partId: 30 });
});
it("does not expose unexpected exception details", () => {
jest
.spyOn((filter as any).logger, "error")
.mockImplementation(() => undefined);
filter.catch(new Error("DB credentials / stack trace"), host);
expect(reply.mock.calls[0][2]).toBe(500);
expect(JSON.stringify(reply.mock.calls[0][1])).not.toContain("credentials");
});
});