Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
32bc58e
fix(images): prevent signed URLs from corrupting product photos
viniciuscbonani Oct 25, 2026
40341a6
fix(catalog): prioritize primary photos and handle failed images
viniciuscbonani Oct 25, 2026
dc13128
docs(images): record Porsche validation and recovery plan
viniciuscbonani Oct 25, 2026
16e9396
fix(products): normalize detail prices without changing currency
viniciuscbonani Oct 25, 2026
003af69
fix(frontend): preserve product price magnitude and decimal inputs
viniciuscbonani Oct 25, 2026
878ca27
docs(prices): record read-only audit and final validation
viniciuscbonani Oct 25, 2026
d4767fc
feat(processes): show scoped specialist contact after confirmation (#…
viniciuscbonani Oct 25, 2026
bca6550
feat(consultancy): collect reason and confirm persisted requests (#252)
viniciuscbonani Oct 25, 2026
9a5b7ed
docs(consultancy): record combined validation with specialist contact
viniciuscbonani Oct 25, 2026
ec6063e
docs(processes): record combined validation with consultancy requests
viniciuscbonani Oct 25, 2026
733345b
fix(consultancy): omit automatic notes from customer reasons
viniciuscbonani Oct 26, 2026
9fab6c2
docs(consultancy): add independent flow and before-after evidence
viniciuscbonani Oct 26, 2026
dca4839
docs(processes): add independent contact flow and before-after evidence
viniciuscbonani Oct 26, 2026
9d611ea
merge: sync develop into fix/product-photos-247
luizgustavo664 Oct 27, 2026
3933134
Merge pull request #256 from InteliJR/fix/product-photos-247
luizgustavo664 Oct 27, 2026
014268a
Merge pull request #259 from InteliJR/feat/specialist-contact-255
luizgustavo664 Oct 28, 2026
6616d7b
merge: sync develop into feat/consultancy-reason-252
luizgustavo664 Oct 28, 2026
890ab58
test(appointments): encerrar conversa nos cenários de conclusão da co…
luizgustavo664 Oct 28, 2026
c7bed53
Merge pull request #258 from InteliJR/feat/consultancy-reason-252
luizgustavo664 Oct 28, 2026
e4531fe
merge: sync develop into fix/product-prices-248
luizgustavo664 Oct 28, 2026
63abc17
test(products): alinhar testes de preço com o develop
luizgustavo664 Oct 28, 2026
dcede64
Merge pull request #257 from InteliJR/fix/product-prices-248
Messias-Olivindo Oct 29, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 166 additions & 0 deletions backend/scripts/audit-product-prices-248.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
/**
* Read-only audit for issue #248. Run from backend:
* npx ts-node scripts/audit-product-prices-248.ts --limit=2000
* Add --include-records to include every inspected id/type/value/currency.
*
* Loads backend/.env without replacing existing environment variables. Uses
* AUDIT_DATABASE_URL, DIRECT_URL, then DATABASE_URL. Never prints credentials.
* High prices alone do not establish that a stored price is wrong.
*/
import { Prisma, PrismaClient } from '@prisma/client';
import { existsSync } from 'node:fs';
import { resolve } from 'node:path';
import { loadEnvFile } from 'node:process';

type PriceRow = {
product_type: 'CAR' | 'BOAT' | 'AIRCRAFT';
id: string;
valor: string;
currency: string;
};

function findingsFor(row: PriceRow): string[] {
const findings: string[] = [];
const decimal = new Prisma.Decimal(row.valor);
if (!decimal.isFinite()) return ['non_finite_stored_value'];
if (decimal.lessThanOrEqualTo(0)) findings.push('non_positive_stored_value');
if (decimal.decimalPlaces() > 2)
findings.push('more_than_two_decimal_places');
if (!['BRL', 'USD'].includes(row.currency))
findings.push('unsupported_currency');

const numeric = decimal.toNumber();
if (
!Number.isFinite(numeric) ||
!new Prisma.Decimal(numeric).equals(decimal)
) {
findings.push('number_conversion_loses_precision');
}

// Reproduce Decimal's actual JSON string, including removal of trailing zeros.
const apiString = decimal.toJSON();
const legacyDetailValue = Number(
apiString.replace(/\./g, '').replace(/,/g, '.'),
);
if (!Number.isFinite(legacyDetailValue) || legacyDetailValue !== numeric) {
findings.push('legacy_detail_display_mismatch');
}
return findings;
}

async function main() {
const args = process.argv.slice(2);
if (args.includes('--help')) {
console.log(
'Usage: ts-node scripts/audit-product-prices-248.ts [--limit=2000] [--include-records]',
);
return;
}
if (
args.some(
(arg) => arg !== '--include-records' && !/^--limit=\d+$/.test(arg),
)
) {
throw new Error('INVALID_ARGUMENTS');
}
const limit = Number(
args.find((arg) => arg.startsWith('--limit='))?.slice(8) ?? 2000,
);
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 10000) {
throw new Error('INVALID_LIMIT');
}

const envPath = resolve(__dirname, '../.env');
if (existsSync(envPath)) loadEnvFile(envPath);
const source = ['AUDIT_DATABASE_URL', 'DIRECT_URL', 'DATABASE_URL'].find(
(key) => process.env[key]?.trim(),
);
if (!source) throw new Error('MISSING_DATABASE_CONFIGURATION');
const databaseUrl = new URL(process.env[source]!);
if (!['postgresql:', 'postgres:'].includes(databaseUrl.protocol)) {
throw new Error('EXPECTED_POSTGRESQL');
}
databaseUrl.searchParams.set('connection_limit', '1');
databaseUrl.searchParams.set('connect_timeout', '5');
databaseUrl.searchParams.set('pool_timeout', '5');
const prisma = new PrismaClient({
datasources: { db: { url: databaseUrl.toString() } },
log: [],
});

try {
const result = await prisma.$transaction(
async (tx) => {
await tx.$executeRaw`SET TRANSACTION READ ONLY`;
await tx.$executeRaw`SET LOCAL statement_timeout = '10s'`;
await tx.$executeRaw`SET LOCAL lock_timeout = '2s'`;
const [mode] = await tx.$queryRaw<{ read_only: string }[]>`
SELECT current_setting('transaction_read_only') AS read_only
`;
if (mode?.read_only !== 'on') throw new Error('READ_ONLY_NOT_ENFORCED');
const rows = await tx.$queryRaw<PriceRow[]>`
SELECT product_type, id, valor, currency
FROM (
SELECT 'CAR' AS product_type, id::text, valor::text, currency::text FROM "Car"
UNION ALL
SELECT 'BOAT', id::text, valor::text, currency::text FROM "Boat"
UNION ALL
SELECT 'AIRCRAFT', id::text, valor::text, currency::text FROM "Aircraft"
) AS prices
ORDER BY product_type, id
LIMIT ${limit + 1}
`;
return { rows: rows.slice(0, limit), truncated: rows.length > limit };
},
{ maxWait: 5000, timeout: 15000, isolationLevel: 'RepeatableRead' },
);

const groups: Record<string, number> = {};
const findingCounts: Record<string, number> = {};
const findings = result.rows.flatMap((row) => {
const group = `${row.product_type}/${row.currency}`;
groups[group] = (groups[group] ?? 0) + 1;
const reasons = findingsFor(row);
reasons.forEach((reason) => {
findingCounts[reason] = (findingCounts[reason] ?? 0) + 1;
});
return reasons.length ? [{ ...row, findings: reasons }] : [];
});
console.log(
JSON.stringify(
{
issue: 248,
audited_at: new Date().toISOString(),
connection_source: source,
transaction_read_only: true,
inspected: result.rows.length,
limit,
truncated: result.truncated,
groups,
finding_counts: findingCounts,
note: 'Display mismatches do not prove stored corruption. Confirm intended prices separately before any data repair.',
findings,
...(args.includes('--include-records')
? { records: result.rows }
: {}),
},
null,
2,
),
);
} finally {
await prisma.$disconnect();
}
}

main().catch((error: unknown) => {
// Database errors may contain connection details; deliberately omit messages.
const code =
error instanceof Prisma.PrismaClientKnownRequestError
? error.code
: error instanceof Error && /^[A-Z_]+$/.test(error.message)
? error.message
: 'AUDIT_FAILED';
console.error(JSON.stringify({ error: code, credentials_omitted: true }));
process.exitCode = 1;
});
91 changes: 91 additions & 0 deletions backend/src/aws/s3.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { BadRequestException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
import { S3Service } from './s3.service';

describe('S3Service product image uploads', () => {
let service: S3Service;
let send: jest.SpyInstance;

beforeEach(() => {
send = jest
.spyOn(S3Client.prototype, 'send')
.mockResolvedValue({} as never);
service = new S3Service({
getOrThrow: (name: string) =>
({
AWS_BUCKET_NAME: 'test-bucket',
AWS_REGION: 'us-east-1',
AWS_ACCESS_KEY_ID: 'test',
AWS_SECRET_ACCESS_KEY: 'test',
})[name],
get: () => undefined,
} as unknown as ConfigService);
});

afterEach(() => jest.restoreAllMocks());

it.each([
'image/jpeg',
'image/png',
'image/webp',
'image/svg+xml',
'image/vnd.microsoft.icon',
])('preserves the bytes and MIME type of a %s data URI', async (mime) => {
const bytes = Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"/>');
const key = 'cars/product/primary.jpg';
await expect(
service.uploadImageAuto(
`data:${mime};base64,${bytes.toString('base64')}`,
key,
),
).resolves.toBe(key);
const command = send.mock.calls[0][0] as PutObjectCommand;
expect(command.input).toMatchObject({
Bucket: 'test-bucket',
Key: key,
Body: bytes,
ContentType: mime,
});
});

it('continues to accept raw base64', async () => {
await service.uploadBase64Image('aW1hZ2U=', 'image.jpg');
expect(send.mock.calls[0][0].input.Body).toEqual(Buffer.from('image'));
});

it.each([
'https://example.com/image.jpg',
'https://images.example.com/cars/photo.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Signature=test',
'data:image/svg+xml;base64,???',
'data:text/plain;base64,aW1hZ2U=',
'',
'%%%',
])(
'rejects invalid base64 instead of storing corrupted bytes: %s',
async (data) => {
await expect(
service.uploadBase64Image(data, 'image.jpg'),
).rejects.toBeInstanceOf(BadRequestException);
expect(send).not.toHaveBeenCalled();
},
);

it('downloads an existing signed URL rather than decoding it as base64', async () => {
const bytes = Buffer.from('original image bytes');
const fetchMock = jest.spyOn(global, 'fetch').mockResolvedValue(
new Response(bytes, {
headers: { 'content-type': 'image/png' },
}),
);
// A URL assinada que voltou do formulário de edição era decodificada
// como base64 até o primeiro "=", gerando arquivos pequenos e inválidos.
const url = 'https://images.example.com/cars/photo.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Signature=test';
await service.uploadImageAuto(url, 'cars/product/replacement.jpg');
expect(fetchMock).toHaveBeenCalledWith(url, expect.any(Object));
expect(send.mock.calls[0][0].input).toMatchObject({
Body: bytes,
ContentType: 'image/png',
});
});
});
34 changes: 21 additions & 13 deletions backend/src/aws/s3.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { Injectable, InternalServerErrorException } from '@nestjs/common';
import {
BadRequestException,
Injectable,
InternalServerErrorException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import {
DeleteObjectCommand,
Expand Down Expand Up @@ -67,18 +71,22 @@ export class S3Service {
*/
async uploadBase64Image(base64Data: string, key: string): Promise<string> {
// Remove o prefixo "data:image/...;base64," se existir
const base64Match = base64Data.match(/^data:image\/(\w+);base64,(.+)$/);
let buffer: Buffer;
let contentType = 'image/jpeg'; // default

if (base64Match) {
const imageType = base64Match[1]; // jpeg, png, etc
const base64Content = base64Match[2];
buffer = Buffer.from(base64Content, 'base64');
contentType = `image/${imageType}`;
} else {
// Assume que já é base64 puro
buffer = Buffer.from(base64Data, 'base64');
const base64Match = base64Data.match(
/^data:(image\/[a-z0-9.+-]+);base64,([\s\S]+)$/i,
);
const contentType = base64Match?.[1].toLowerCase() ?? 'image/jpeg';
const payload = (base64Match?.[2] ?? base64Data).replace(/\s/g, '');
const buffer = Buffer.from(payload, 'base64');

// Buffer.from ignora caracteres inválidos: uma URL ou data URI malformada
// virava um objeto corrompido, mas o upload parecia ter dado certo.
if (
!/^[a-z0-9+/]+={0,2}$/i.test(payload) ||
buffer.length === 0 ||
buffer.toString('base64').replace(/=+$/, '') !==
payload.replace(/=+$/, '')
) {
throw new BadRequestException('Imagem base64 inválida.');
}

const command = new PutObjectCommand({
Expand Down
8 changes: 6 additions & 2 deletions backend/src/features/aircrafts/aircrafts.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,10 +278,14 @@ export class AircraftsService {
image_url: await this.s3Service.getSignedUrl(image.image_url),
})),
);
return { ...aircraft, images: imagesWithUrls };
return {
...aircraft,
valor: aircraft.valor.toNumber(),
images: imagesWithUrls,
};
}

return { ...aircraft };
return { ...aircraft, valor: aircraft.valor.toNumber() };
}

// update(id: string, updateAircraftDto: UpdateAircraftDto) {
Expand Down
Loading
Loading