Реализовать лабораторную 4: вложения в S3 и согласованность с БД
- приватный bucket SeaweedFS за S3-шлюзом, отдельные identities admin/api/reconciler, анонимный доступ запрещён - потоковый upload с проверкой PNG/JPEG (CRC, распаковка со сверкой объёма, лимит пикселей до распаковки) без буферизации тела - скачивание через авторизованный API; компенсация неудачной загрузки: сначала pending-строка, затем объект - reconciler БД ↔ S3 с grace period: stale_pending, orphan_object, missing_object, size/checksum mismatch, обратимый карантин lost - сценарии отказов S3, замер памяти загрузок, трек 2, evidence и REPORT.md
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
// Вложения: потоковая загрузка PNG/JPEG в приватный S3, метаданные в PostgreSQL, скачивание только через API.
|
||||
//
|
||||
// Согласованность двух хранилищ без распределённой транзакции:
|
||||
// 1. INSERT строки pending (запись-намерение с ключом объекта) — COMMIT;
|
||||
// 2. поток байтов: клиент → проверка формата + SHA-256 → S3 PUT;
|
||||
// 3. UPDATE pending → ready — только после этого 201.
|
||||
// Ошибка на шаге 2–3 → компенсация (удалить объект, затем строку). Если процесс умер и компенсации не было,
|
||||
// остаются pending-строка и, возможно, объект: их удаляет reconciler после grace period (src/reconcile.ts).
|
||||
// Объект без строки появиться не может: строка всегда создаётся раньше объекта.
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { Transform } from 'node:stream';
|
||||
import type { Ctx, Result } from '../http/context.ts';
|
||||
import { badRequest, notFound, tooLarge, unavailable, unsupported } from '../http/errors.ts';
|
||||
import { isText, mediaType, uuidParam } from '../http/request.ts';
|
||||
import { requireMember } from './chats.ts';
|
||||
import { imageValidator, type Dimensions } from './images.ts';
|
||||
import type { User } from './model.ts';
|
||||
import { authenticate } from './sessions.ts';
|
||||
|
||||
const FORBIDDEN_IN_FILENAME = /[/\\\p{Cc}]/u; // разделители путей, NUL и управляющие символы C0/C1
|
||||
const VARIANTS = ['thumbnail', 'crop', 'optimized']; // имена контракта; в lab4 вариантов ещё нет
|
||||
const columns = `a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256,
|
||||
rfc3339(a.created_at) AS created_at, rfc3339(a.updated_at) AS updated_at`;
|
||||
|
||||
type Row = Record<string, unknown> & { object_key?: string };
|
||||
|
||||
// Ключ объекта в S3 наружу не отдаётся. В lab4 через API видны только ready-вложения без вариантов.
|
||||
const view = ({ object_key: _, ...row }: Row) => ({ ...row, status: 'ready', variants: [], error_code: null });
|
||||
|
||||
// POST /api/v1/chats/{chat_id}/attachments?filename=… — сырые байты одного PNG/JPEG.
|
||||
// Все лимиты проверяются до чтения тела; тело не буферизуется целиком ни в памяти, ни на диске API.
|
||||
export async function uploadAttachment(c: Ctx): Promise<Result> {
|
||||
const user = await authenticate(c);
|
||||
const chatId = await requireMember(c, user);
|
||||
const filename = c.url.searchParams.get('filename');
|
||||
if (!isText(filename, 1, 255) || FORBIDDEN_IN_FILENAME.test(filename)) {
|
||||
throw badRequest('filename: 1–255 символов, без / \\ и управляющих символов');
|
||||
}
|
||||
const type = mediaType(c.req);
|
||||
if (type !== 'image/png' && type !== 'image/jpeg') throw unsupported('Ожидается image/png или image/jpeg');
|
||||
const declared = c.req.headers['content-length'];
|
||||
if (declared === undefined || !/^\d+$/.test(declared)) throw badRequest('Нужен Content-Length: файл передаётся потоком в S3');
|
||||
const length = Number(declared);
|
||||
if (length > c.config.maxUploadBytes) throw tooLarge(`Файл больше ${c.config.maxUploadBytes} байт`);
|
||||
if (length === 0) throw unsupported('Пустое тело не является изображением');
|
||||
|
||||
const id = randomUUID();
|
||||
const key = `originals/${id}`; // filename только для отображения и в ключ не попадает
|
||||
await c.db.query(`INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, object_key)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)`, [id, chatId, user.id, filename, type, key]);
|
||||
try {
|
||||
const { sha256, width, height } = await store(c, key, type, length);
|
||||
const r = await c.db.query(`UPDATE attachments AS a SET state = 'ready', size_bytes = $2, sha256 = $3, width = $4, height = $5,
|
||||
updated_at = clock_timestamp() WHERE a.id = $1 AND a.state = 'pending' RETURNING ${columns}`, [id, length, sha256, width, height]);
|
||||
if (!r.rowCount) throw unavailable('Загрузка не завершилась вовремя'); // строку уже убрал reconciler
|
||||
return [201, view(r.rows[0])];
|
||||
} catch (err) {
|
||||
void discard(c, id, key); // в фоне: при зависшем S3 клиент не ждёт ещё и DELETE
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// Клиент → проверка + SHA-256 → S3. Обратное давление: пока S3 не принял кусок, следующий не читается из сокета,
|
||||
// поэтому память на загрузку не зависит от размера файла. Последний кусок уходит в S3 только после полной
|
||||
// проверки файла: S3 не получит все Content-Length байт невалидного изображения, и объект не создастся.
|
||||
async function store(c: Ctx, key: string, type: 'image/png' | 'image/jpeg', length: number) {
|
||||
const check = imageValidator(type, c.config.maxImagePixels);
|
||||
const hash = createHash('sha256');
|
||||
const abort = new AbortController();
|
||||
let received = 0;
|
||||
let dims: Dimensions | undefined;
|
||||
let failure: unknown;
|
||||
const fail = (err: unknown) => {
|
||||
failure ??= err;
|
||||
abort.abort();
|
||||
};
|
||||
const body = new Transform({
|
||||
transform(chunk: Buffer, _encoding, done) {
|
||||
received += chunk.length;
|
||||
hash.update(chunk);
|
||||
check.write(chunk)
|
||||
.then(async () => { if (received === length) dims = await check.end(); })
|
||||
.then(() => done(null, chunk), done);
|
||||
},
|
||||
});
|
||||
body.on('error', fail);
|
||||
c.req.on('close', () => { if (!c.req.complete) fail(badRequest('Загрузка прервана клиентом')); });
|
||||
c.req.pipe(body);
|
||||
try {
|
||||
await c.s3.put(key, body, length, type, abort.signal);
|
||||
if (failure) throw failure;
|
||||
if (!dims) throw new Error('S3 принял объект до конца проверки');
|
||||
return { sha256: hash.digest('hex'), ...dims };
|
||||
} catch (err) {
|
||||
// Остаток тела читаем и выбрасываем: иначе ответ с ошибкой не дойдёт до клиента, который ещё отправляет файл.
|
||||
c.req.unpipe(body);
|
||||
c.req.resume();
|
||||
body.destroy();
|
||||
check.close();
|
||||
throw failure ?? err;
|
||||
}
|
||||
}
|
||||
|
||||
// Компенсация неудачной загрузки: сначала pending-строка, затем объект. Если строка уже ready (COMMIT прошёл,
|
||||
// а до API дошла ошибка), объект принадлежит готовому вложению и не удаляется. Сбой здесь не теряет учёт:
|
||||
// останется pending-строка или объект без строки, их подберёт reconciler.
|
||||
async function discard(c: Ctx, id: string, key: string): Promise<void> {
|
||||
try {
|
||||
const deleted = await c.db.query(`DELETE FROM attachments WHERE id = $1 AND state = 'pending'`, [id]);
|
||||
if (!deleted.rowCount && (await c.db.query('SELECT 1 FROM attachments WHERE id = $1', [id])).rowCount) return;
|
||||
await c.s3.remove(key);
|
||||
} catch (err) {
|
||||
console.error(`компенсация вложения ${id} не завершена, остаток уберёт reconciler: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Вложение доступно только участникам его чата; постороннему — тот же 404, что и для несуществующего.
|
||||
async function findReady(c: Ctx, user: User): Promise<Row & { object_key: string }> {
|
||||
const r = await c.db.query(`SELECT ${columns}, a.object_key FROM attachments a
|
||||
JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2
|
||||
WHERE a.id = $1 AND a.state = 'ready'`, [uuidParam(c, 'attachment_id'), user.id]);
|
||||
if (!r.rowCount) throw notFound();
|
||||
return r.rows[0];
|
||||
}
|
||||
|
||||
// GET /api/v1/attachments/{attachment_id}
|
||||
export async function getAttachment(c: Ctx): Promise<Result> {
|
||||
return [200, view(await findReady(c, await authenticate(c)))];
|
||||
}
|
||||
|
||||
// GET /api/v1/attachments/{attachment_id}/content[?variant=original] — байты потоком из S3, без redirect.
|
||||
export async function downloadAttachment(c: Ctx): Promise<Result> {
|
||||
const user = await authenticate(c);
|
||||
const variant = c.url.searchParams.get('variant');
|
||||
if (variant !== null && variant !== 'original' && !VARIANTS.includes(variant)) throw badRequest('Неизвестный variant');
|
||||
const row = await findReady(c, user);
|
||||
if (variant !== null && variant !== 'original') throw notFound(); // вариантов у ready-объекта lab4 нет
|
||||
const body = await c.s3.get(row.object_key);
|
||||
if (!body) {
|
||||
console.error(`объект вложения ${row.id} отсутствует в S3`); // reconciler пометит его lost
|
||||
throw notFound();
|
||||
}
|
||||
return [200, body, {
|
||||
'Content-Type': row.content_type as string,
|
||||
'Content-Length': row.size_bytes as number,
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
}];
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// Чаты: создание, список чатов пользователя, один чат, проверка членства.
|
||||
import type { Ctx, Result } from '../http/context.ts';
|
||||
import { badRequest, notFound } from '../http/errors.ts';
|
||||
import { afterCursor, limitOf, page } from '../http/pagination.ts';
|
||||
import { UUID, isText, jsonObject, readJson, uuidParam } from '../http/request.ts';
|
||||
import { authenticate } from './sessions.ts';
|
||||
import type { User } from './model.ts';
|
||||
|
||||
// Чаты, где состоит пользователь $1; member_ids в порядке, заданном при создании.
|
||||
const chatSelect = `SELECT c.id, c.title, rfc3339(c.created_at) AS created_at,
|
||||
(SELECT array_agg(m.user_id::text ORDER BY m.position) FROM chat_members m WHERE m.chat_id = c.id) AS member_ids
|
||||
FROM chats c JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1 `;
|
||||
|
||||
// chat_id из пути, если пользователь — участник. Постороннему тот же 404, что и для несуществующего чата.
|
||||
export async function requireMember(c: Ctx, user: User): Promise<string> {
|
||||
const chatId = uuidParam(c, 'chat_id');
|
||||
const r = await c.db.query({
|
||||
name: 'member',
|
||||
text: 'SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2',
|
||||
values: [chatId, user.id],
|
||||
});
|
||||
if (!r.rowCount) throw notFound();
|
||||
return chatId;
|
||||
}
|
||||
|
||||
// POST /api/v1/chats: участники фиксируются при создании и обязательно включают создателя.
|
||||
export async function createChat(c: Ctx): Promise<Result> {
|
||||
const user = await authenticate(c);
|
||||
const b = jsonObject(await readJson(c.req), ['title', 'member_ids']);
|
||||
const ids = b.member_ids;
|
||||
if (!isText(b.title, 1, 100) || !Array.isArray(ids) || ids.length < 1 || ids.length > 100
|
||||
|| !ids.every((id) => typeof id === 'string' && UUID.test(id))) {
|
||||
throw badRequest('Неверные title или member_ids');
|
||||
}
|
||||
const members = ids.map((id: string) => id.toLowerCase());
|
||||
if (new Set(members).size !== members.length || !members.includes(user.id)) {
|
||||
throw badRequest('member_ids должны быть уникальны и включать создателя');
|
||||
}
|
||||
try {
|
||||
// Один оператор = одна транзакция: при неизвестном участнике сработает FK и не создастся ничего.
|
||||
const r = await c.db.query(`WITH c AS (INSERT INTO chats (title) VALUES ($1) RETURNING id, title, created_at),
|
||||
m AS (INSERT INTO chat_members (chat_id, user_id, position)
|
||||
SELECT c.id, t.u::uuid, t.o FROM c, unnest($2::text[]) WITH ORDINALITY AS t(u, o))
|
||||
SELECT id, title, rfc3339(created_at) AS created_at FROM c`, [b.title, members]);
|
||||
return [201, { ...r.rows[0], member_ids: members }];
|
||||
} catch (err) {
|
||||
if ((err as { code?: string }).code === '23503') throw badRequest('Неизвестный участник'); // foreign_key_violation
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// GET /api/v1/chats: только чаты текущего пользователя, cursor привязан к пользователю.
|
||||
export async function listChats(c: Ctx): Promise<Result> {
|
||||
const user = await authenticate(c);
|
||||
const limit = limitOf(c.url);
|
||||
const [ts, id] = afterCursor(c.url, 'c', user.id);
|
||||
const r = await c.db.query(chatSelect + 'WHERE (c.created_at, c.id) > ($2, $3::uuid) ORDER BY c.created_at, c.id LIMIT $4',
|
||||
[user.id, ts, id, limit + 1]);
|
||||
return [200, page(r.rows, limit, 'c', user.id)];
|
||||
}
|
||||
|
||||
// GET /api/v1/chats/{chat_id}
|
||||
export async function getChat(c: Ctx): Promise<Result> {
|
||||
const user = await authenticate(c);
|
||||
const r = await c.db.query(chatSelect + 'WHERE c.id = $2', [user.id, uuidParam(c, 'chat_id')]);
|
||||
if (!r.rowCount) throw notFound();
|
||||
return [200, r.rows[0]];
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
// Потоковая проверка PNG/JPEG по содержимому: без декодирования пикселей и без буферизации файла.
|
||||
// Размеры берутся из заголовка (IHDR / SOF) и проверяются ДО распаковки данных, поэтому «бомба» отсекается сразу.
|
||||
// PNG: сигнатура, порядок chunk-ов, CRC каждого chunk, поток zlib распаковывается с подсчётом байтов
|
||||
// (вывод выбрасывается) и сверяется с объёмом, который следует из размеров и формата пикселя.
|
||||
// JPEG: структура маркеров, ровно один SOF до первого SOS, обязательный EOI; энтропийные данные не декодируются.
|
||||
// Обработанный кусок можно сразу передавать дальше: состояние проверки — несколько чисел и ≤ 13 байт хвоста.
|
||||
import { finished } from 'node:stream/promises';
|
||||
import { createInflate, crc32 } from 'node:zlib';
|
||||
import { tooLarge, unsupported } from '../http/errors.ts';
|
||||
|
||||
export type Dimensions = { width: number; height: number };
|
||||
|
||||
export type ImageValidator = {
|
||||
write(chunk: Buffer): Promise<void>;
|
||||
end(): Promise<Dimensions>; // весь файл получен; бросает 415, если он обрезан
|
||||
close(): void; // освободить ресурсы при обрыве загрузки
|
||||
};
|
||||
|
||||
const broken = (why: string) => unsupported(`Содержимое не является корректным изображением: ${why}`);
|
||||
|
||||
export function imageValidator(type: 'image/png' | 'image/jpeg', maxPixels: number): ImageValidator {
|
||||
return type === 'image/png' ? png(maxPixels) : jpeg(maxPixels);
|
||||
}
|
||||
|
||||
function checkPixels(width: number, height: number, maxPixels: number): void {
|
||||
if (width * height > maxPixels) throw tooLarge(`Изображение больше ${maxPixels} пикселей`);
|
||||
}
|
||||
|
||||
const SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
const CHANNELS: Record<number, number> = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 };
|
||||
const DEPTHS: Record<number, number[]> = { 0: [1, 2, 4, 8, 16], 2: [8, 16], 3: [1, 2, 4, 8], 4: [8, 16], 6: [8, 16] };
|
||||
const ADAM7 = [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]];
|
||||
|
||||
// Объём распакованных данных PNG: в каждой строке байт фильтра + пиксели; при interlace — сумма 7 проходов Adam7.
|
||||
function rawSize(width: number, height: number, bits: number, interlaced: boolean): number {
|
||||
const row = (w: number) => 1 + Math.ceil((w * bits) / 8);
|
||||
if (!interlaced) return height * row(width);
|
||||
let total = 0;
|
||||
for (const [x0, y0, dx, dy] of ADAM7) {
|
||||
const w = Math.ceil((width - x0) / dx);
|
||||
const h = Math.ceil((height - y0) / dy);
|
||||
if (w > 0 && h > 0) total += h * row(w);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
function png(maxPixels: number): ImageValidator {
|
||||
let carry = Buffer.alloc(0);
|
||||
let state: 'signature' | 'header' | 'data' | 'crc' | 'done' = 'signature';
|
||||
let type = '';
|
||||
let left = 0;
|
||||
let crc = 0;
|
||||
let ihdr = Buffer.alloc(0);
|
||||
let dims: Dimensions | null = null;
|
||||
let color = 0;
|
||||
let palette = false;
|
||||
let idat: 'none' | 'open' | 'closed' = 'none';
|
||||
let expected = 0;
|
||||
let inflated = 0;
|
||||
|
||||
const inflate = createInflate();
|
||||
let zerr: Error | null = null;
|
||||
let wake: (() => void) | null = null;
|
||||
inflate.on('data', (d: Buffer) => { inflated += d.length; });
|
||||
// При ошибке zlib callback write не вызывается: будим ожидающего вручную.
|
||||
inflate.on('error', (e) => { zerr = e; wake?.(); });
|
||||
const feed = (data: Buffer) => zerr ? Promise.resolve() : new Promise<void>((resolve) => {
|
||||
wake = resolve;
|
||||
inflate.write(data, () => resolve());
|
||||
});
|
||||
|
||||
function startChunk(len: number) {
|
||||
if (!/^[A-Za-z]{4}$/.test(type) || len > 0x7fffffff) throw broken('неверный заголовок chunk');
|
||||
if (!dims && type !== 'IHDR') throw broken('первым должен быть IHDR');
|
||||
if (dims && type === 'IHDR') throw broken('повторный IHDR');
|
||||
if (type === 'IHDR' && len !== 13) throw broken('неверная длина IHDR');
|
||||
// Неизвестный критический chunk (заглавная первая буква) декодер обязан отвергнуть.
|
||||
if (/^[A-Z]/.test(type) && !['IHDR', 'PLTE', 'IDAT', 'IEND'].includes(type)) throw broken(`неизвестный chunk ${type}`);
|
||||
if (type === 'IDAT') {
|
||||
if (idat === 'closed') throw broken('IDAT идут не подряд');
|
||||
if (color === 3 && !palette) throw broken('нет палитры PLTE');
|
||||
idat = 'open';
|
||||
} else if (idat === 'open') {
|
||||
idat = 'closed';
|
||||
}
|
||||
if (type === 'PLTE') palette = true;
|
||||
if (type === 'IEND' && (len !== 0 || idat === 'none')) throw broken('неверный IEND');
|
||||
}
|
||||
|
||||
function endChunk() {
|
||||
if (type === 'IHDR') {
|
||||
const width = ihdr.readUInt32BE(0);
|
||||
const height = ihdr.readUInt32BE(4);
|
||||
const depth = ihdr[8];
|
||||
color = ihdr[9];
|
||||
if (!width || !height || width > 0x7fffffff || height > 0x7fffffff) throw broken('неверные размеры');
|
||||
if (!DEPTHS[color]?.includes(depth) || ihdr[10] !== 0 || ihdr[11] !== 0 || ihdr[12] > 1) throw broken('неверные параметры IHDR');
|
||||
checkPixels(width, height, maxPixels); // до первого байта IDAT
|
||||
dims = { width, height };
|
||||
expected = rawSize(width, height, CHANNELS[color] * depth, ihdr[12] === 1);
|
||||
}
|
||||
state = type === 'IEND' ? 'done' : 'header';
|
||||
}
|
||||
|
||||
async function write(chunk: Buffer) {
|
||||
const buf = carry.length ? Buffer.concat([carry, chunk]) : chunk;
|
||||
let pos = 0;
|
||||
while (pos < buf.length) {
|
||||
const avail = buf.length - pos;
|
||||
if (state === 'signature') {
|
||||
if (avail < 8) break;
|
||||
if (!buf.subarray(pos, pos + 8).equals(SIGNATURE)) throw broken('нет сигнатуры PNG');
|
||||
pos += 8;
|
||||
state = 'header';
|
||||
} else if (state === 'header') {
|
||||
if (avail < 8) break;
|
||||
left = buf.readUInt32BE(pos);
|
||||
type = buf.toString('latin1', pos + 4, pos + 8);
|
||||
startChunk(left);
|
||||
crc = crc32(buf.subarray(pos + 4, pos + 8));
|
||||
pos += 8;
|
||||
state = left ? 'data' : 'crc';
|
||||
} else if (state === 'data') {
|
||||
const part = buf.subarray(pos, pos + Math.min(left, avail));
|
||||
crc = crc32(part, crc);
|
||||
if (type === 'IHDR') ihdr = Buffer.concat([ihdr, part]);
|
||||
if (type === 'IDAT') {
|
||||
await feed(part);
|
||||
if (zerr) throw broken('повреждён поток zlib');
|
||||
if (inflated > expected) throw broken('данных больше, чем пикселей');
|
||||
}
|
||||
left -= part.length;
|
||||
pos += part.length;
|
||||
if (!left) state = 'crc';
|
||||
} else if (state === 'crc') {
|
||||
if (avail < 4) break;
|
||||
if (buf.readUInt32BE(pos) !== crc) throw broken(`неверная CRC chunk ${type}`);
|
||||
pos += 4;
|
||||
endChunk();
|
||||
} else {
|
||||
throw broken('данные после IEND');
|
||||
}
|
||||
}
|
||||
carry = Buffer.from(buf.subarray(pos));
|
||||
}
|
||||
|
||||
return {
|
||||
async write(chunk) {
|
||||
try {
|
||||
await write(chunk);
|
||||
} catch (err) {
|
||||
inflate.destroy();
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
async end() {
|
||||
if (state !== 'done') throw broken('файл обрезан');
|
||||
inflate.end();
|
||||
try {
|
||||
await finished(inflate);
|
||||
} catch {
|
||||
throw broken('поток zlib не завершён');
|
||||
}
|
||||
if (inflated !== expected) throw broken('объём данных не совпадает с размерами');
|
||||
return dims!;
|
||||
},
|
||||
close: () => inflate.destroy(),
|
||||
};
|
||||
}
|
||||
|
||||
// SOF0–SOF15 кроме DHT (C4), JPG (C8), DAC (CC): в них ширина и высота кадра.
|
||||
const SOF = new Set([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf]);
|
||||
const SOS = 0xda;
|
||||
|
||||
function jpeg(maxPixels: number): ImageValidator {
|
||||
let carry = Buffer.alloc(0);
|
||||
let state: 'soi' | 'marker' | 'length' | 'payload' | 'scan' | 'done' = 'soi';
|
||||
let marker = 0;
|
||||
let left = 0;
|
||||
let head = Buffer.alloc(0); // начало SOF: точность, высота, ширина
|
||||
let dims: Dimensions | null = null;
|
||||
let scanned = false;
|
||||
|
||||
function write(chunk: Buffer) {
|
||||
const buf = carry.length ? Buffer.concat([carry, chunk]) : chunk;
|
||||
let pos = 0;
|
||||
loop: while (pos < buf.length) {
|
||||
const avail = buf.length - pos;
|
||||
switch (state) {
|
||||
case 'soi':
|
||||
if (avail < 2) break loop;
|
||||
if (buf[pos] !== 0xff || buf[pos + 1] !== 0xd8) throw broken('нет сигнатуры JPEG');
|
||||
pos += 2;
|
||||
state = 'marker';
|
||||
break;
|
||||
case 'marker': {
|
||||
if (avail < 2) break loop;
|
||||
if (buf[pos] !== 0xff) throw broken('ожидался маркер');
|
||||
const code = buf[pos + 1];
|
||||
if (code === 0xff) { // байты-заполнители 0xFF перед маркером
|
||||
pos += 1;
|
||||
break;
|
||||
}
|
||||
pos += 2;
|
||||
if (code === 0xd9) {
|
||||
if (!scanned) throw broken('EOI до данных изображения');
|
||||
state = 'done';
|
||||
} else if (code === 0x00 || code === 0xd8 || (code >= 0xd0 && code <= 0xd7)) {
|
||||
throw broken('неожиданный маркер');
|
||||
} else if (code !== 0x01) { // TEM не имеет длины
|
||||
marker = code;
|
||||
state = 'length';
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'length': {
|
||||
if (avail < 2) break loop;
|
||||
left = buf.readUInt16BE(pos) - 2;
|
||||
pos += 2;
|
||||
if (left < 0) throw broken('неверная длина сегмента');
|
||||
if (SOF.has(marker) && (dims || left < 6)) throw broken('неверный SOF');
|
||||
if (marker === SOS && !dims) throw broken('SOS до SOF');
|
||||
head = Buffer.alloc(0);
|
||||
state = 'payload';
|
||||
break;
|
||||
}
|
||||
case 'payload': {
|
||||
const n = Math.min(left, avail);
|
||||
if (SOF.has(marker) && head.length < 5) head = Buffer.concat([head, buf.subarray(pos, pos + Math.min(n, 5 - head.length))]);
|
||||
pos += n;
|
||||
left -= n;
|
||||
if (left) break;
|
||||
if (SOF.has(marker)) {
|
||||
const height = head.readUInt16BE(1);
|
||||
const width = head.readUInt16BE(3);
|
||||
if (!width || !height) throw broken('нулевые размеры');
|
||||
checkPixels(width, height, maxPixels); // до энтропийных данных
|
||||
dims = { width, height };
|
||||
}
|
||||
scanned ||= marker === SOS;
|
||||
state = marker === SOS ? 'scan' : 'marker';
|
||||
break;
|
||||
}
|
||||
case 'scan': {
|
||||
// Внутри энтропийных данных 0xFF допустим только как FF00 (stuffing) и RSTn; иначе начинается маркер.
|
||||
const ff = buf.indexOf(0xff, pos);
|
||||
if (ff < 0) {
|
||||
pos = buf.length;
|
||||
} else if (ff + 1 >= buf.length) {
|
||||
pos = ff;
|
||||
break loop;
|
||||
} else {
|
||||
const next = buf[ff + 1];
|
||||
if (next === 0x00 || (next >= 0xd0 && next <= 0xd7)) pos = ff + 2;
|
||||
else if (next === 0xff) pos = ff + 1;
|
||||
else {
|
||||
pos = ff;
|
||||
state = 'marker';
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'done': // данные после EOI (MPF, «живые» фото) — нормальная практика камер
|
||||
pos = buf.length;
|
||||
break;
|
||||
}
|
||||
}
|
||||
carry = Buffer.from(buf.subarray(pos));
|
||||
}
|
||||
|
||||
return {
|
||||
write: async (chunk) => write(chunk),
|
||||
async end() {
|
||||
if (state !== 'done') throw broken('нет EOI: файл обрезан');
|
||||
return dims!;
|
||||
},
|
||||
close: () => {},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// Сообщения: идемпотентная отправка и история чата.
|
||||
import type { Ctx, Result } from '../http/context.ts';
|
||||
import { badRequest, conflict, notFound } from '../http/errors.ts';
|
||||
import { afterCursor, limitOf, page } from '../http/pagination.ts';
|
||||
import { UUID, isText, jsonObject, readJson } from '../http/request.ts';
|
||||
import { requireMember } from './chats.ts';
|
||||
import { authenticate, sha256 } from './sessions.ts';
|
||||
|
||||
const IDEMPOTENCY_KEY = /^[A-Za-z0-9._:-]{1,128}$/;
|
||||
// attachment_ids в порядке, заданном отправителем; text[] драйвер pg возвращает как массив строк.
|
||||
const attachmentIds = (m: string) =>
|
||||
`ARRAY(SELECT ma.attachment_id::text FROM message_attachments ma WHERE ma.message_id = ${m}.id ORDER BY ma.position) AS attachment_ids`;
|
||||
const messageColumns = `id, chat_id, sender_id, text, rfc3339(created_at) AS created_at, ${attachmentIds('messages')}`;
|
||||
|
||||
// POST /api/v1/chats/{chat_id}/messages с обязательным Idempotency-Key.
|
||||
// Область ключа: пользователь + метод + путь чата + ключ.
|
||||
// Ключ и сообщение вставляются ОДНИМ оператором, поэтому фиксируются атомарно: при ошибке БД нет ни того,
|
||||
// ни другого, и клиент может безопасно повторить запрос с тем же ключом.
|
||||
// Одновременный дубль (с любой реплики) ждёт на первичном ключе idempotency_keys, пока первая транзакция
|
||||
// не зафиксируется, затем получает ON CONFLICT DO NOTHING и отдаёт сохранённый результат.
|
||||
export async function sendMessage(c: Ctx): Promise<Result> {
|
||||
const user = await authenticate(c);
|
||||
const chatId = await requireMember(c, user); // повтор тоже заново проверяет сессию и доступ
|
||||
const key = c.req.headers['idempotency-key'];
|
||||
if (typeof key !== 'string' || !IDEMPOTENCY_KEY.test(key)) throw badRequest('Нужен Idempotency-Key [A-Za-z0-9._:-]{1,128}');
|
||||
// sender_id в теле не принимается: отправитель — из сессии.
|
||||
const b = jsonObject(await readJson(c.req), ['text', 'attachment_ids']);
|
||||
const ids = attachmentList(b.attachment_ids);
|
||||
const text = b.text;
|
||||
// С вложениями текст может быть пустым; без вложений — 1–4000 символов, не только пробелы.
|
||||
if (typeof text !== 'string' || [...text].length > 4000 || (!ids.length && !isText(text, 1, 4000))) {
|
||||
throw badRequest('text: до 4000 символов; пустой текст допустим только с вложениями');
|
||||
}
|
||||
if (ids.length) await requireReadyAttachments(c, chatId, ids);
|
||||
|
||||
const path = `/api/v1/chats/${chatId}/messages`;
|
||||
// Каноническое тело: порядок ключей JSON не важен, отсутствующий attachment_ids = [].
|
||||
// Без вложений hash тот же, что в lab3 (32 байта); с вложениями 64 байта — с текстовым не совпадёт.
|
||||
const hash = ids.length ? Buffer.concat([sha256(text), sha256(ids.join(','))]) : sha256(text);
|
||||
let inserted;
|
||||
try {
|
||||
inserted = await c.db.query({
|
||||
name: 'send',
|
||||
text: `WITH k AS (
|
||||
INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, message_id)
|
||||
VALUES ($1, 'POST', $2, $3, $4, gen_random_uuid()) ON CONFLICT DO NOTHING RETURNING message_id),
|
||||
m AS (INSERT INTO messages (id, chat_id, sender_id, text) SELECT message_id, $5, $1, $6 FROM k
|
||||
RETURNING id, chat_id, sender_id, text, rfc3339(created_at) AS created_at),
|
||||
a AS (INSERT INTO message_attachments (message_id, chat_id, attachment_id, position)
|
||||
SELECT m.id, m.chat_id, t.id, t.ord FROM m, unnest($7::uuid[]) WITH ORDINALITY AS t(id, ord))
|
||||
SELECT * FROM m`,
|
||||
values: [user.id, path, key, hash, chatId, text, ids],
|
||||
});
|
||||
} catch (err) {
|
||||
// Составной FK (chat_id, attachment_id): вложение другого чата не прикрепить даже в обход проверки выше.
|
||||
if ((err as { code?: string }).code === '23503') throw notFound();
|
||||
throw err;
|
||||
}
|
||||
if (inserted.rowCount) return [201, { ...inserted.rows[0], attachment_ids: ids }];
|
||||
|
||||
// Ключ уже использован: тот же body → тот же 201 и то же сообщение, другой body → 409.
|
||||
const stored = await c.db.query(`SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, rfc3339(m.created_at) AS created_at,
|
||||
${attachmentIds('m')}
|
||||
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.user_id = $1 AND k.method = 'POST' AND k.path = $2 AND k.key = $3`, [user.id, path, key]);
|
||||
const { request_hash, ...message } = stored.rows[0];
|
||||
if (!hash.equals(request_hash)) throw conflict('Idempotency-Key уже использован с другим телом');
|
||||
return [201, message];
|
||||
}
|
||||
|
||||
// GET /api/v1/chats/{chat_id}/messages: история по возрастанию (created_at, id), limit 1–100.
|
||||
export async function listMessages(c: Ctx): Promise<Result> {
|
||||
const user = await authenticate(c);
|
||||
const chatId = await requireMember(c, user);
|
||||
const limit = limitOf(c.url);
|
||||
const [ts, id] = afterCursor(c.url, 'm', chatId);
|
||||
const r = await c.db.query({
|
||||
name: 'history',
|
||||
text: `SELECT ${messageColumns} FROM messages WHERE chat_id = $1 AND (created_at, id) > ($2, $3::uuid)
|
||||
ORDER BY created_at, id LIMIT $4`,
|
||||
values: [chatId, ts, id, limit + 1],
|
||||
});
|
||||
return [200, page(r.rows, limit, 'm', chatId)];
|
||||
}
|
||||
|
||||
// attachment_ids: 0–10 уникальных UUID (в нижнем регистре), по умолчанию [].
|
||||
function attachmentList(value: unknown): string[] {
|
||||
if (value === undefined) return [];
|
||||
if (!Array.isArray(value) || value.length > 10 || !value.every((id) => typeof id === 'string' && UUID.test(id))) {
|
||||
throw badRequest('attachment_ids: до 10 UUID');
|
||||
}
|
||||
const ids = value.map((id: string) => id.toLowerCase());
|
||||
if (new Set(ids).size !== ids.length) throw badRequest('attachment_ids должны быть уникальны');
|
||||
return ids;
|
||||
}
|
||||
|
||||
// Все вложения из этого чата и готовы. Чужое или неизвестное — 404, как и чужой чат.
|
||||
async function requireReadyAttachments(c: Ctx, chatId: string, ids: string[]): Promise<void> {
|
||||
const r = await c.db.query(`SELECT count(*)::int AS n FROM attachments WHERE id = ANY($1::uuid[]) AND chat_id = $2 AND state = 'ready'`,
|
||||
[ids, chatId]);
|
||||
if (r.rows[0].n !== ids.length) throw notFound();
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// Общая модель пользователя для модулей users и sessions.
|
||||
|
||||
export type User = { id: string; username: string; display_name: string; created_at: string };
|
||||
|
||||
export const USERNAME = /^[a-z0-9_]{3,32}$/;
|
||||
|
||||
// Время форматирует PostgreSQL: Date в JS потерял бы микросекунды, на которых держится cursor.
|
||||
export const userColumns = 'u.id, u.username, u.display_name, rfc3339(u.created_at) AS created_at';
|
||||
@@ -0,0 +1,29 @@
|
||||
// Хеширование паролей: scrypt из node:crypto (N=2^14, r=8, p=1, 16 MiB на хеш).
|
||||
// Формат хранения: scrypt$N$r$p$соль$хеш (base64), параметры читаются из записи при проверке.
|
||||
import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto';
|
||||
|
||||
const N = 16384;
|
||||
const R = 8;
|
||||
const P = 1;
|
||||
|
||||
function scryptKey(password: string, salt: Buffer, n: number, r: number, p: number): Promise<Buffer> {
|
||||
return new Promise((resolve, reject) =>
|
||||
scrypt(password, salt, 32, { N: n, r, p, maxmem: 64 << 20 }, (err, key) => (err ? reject(err) : resolve(key))));
|
||||
}
|
||||
|
||||
export async function hashPassword(password: string): Promise<string> {
|
||||
const salt = randomBytes(16);
|
||||
const key = await scryptKey(password, salt, N, R, P);
|
||||
return ['scrypt', N, R, P, salt.toString('base64'), key.toString('base64')].join('$');
|
||||
}
|
||||
|
||||
export async function checkPassword(password: string, encoded: string): Promise<boolean> {
|
||||
const [alg, n, r, p, salt, hash] = encoded.split('$');
|
||||
if (alg !== 'scrypt') return false;
|
||||
const got = await scryptKey(password, Buffer.from(salt, 'base64'), Number(n), Number(r), Number(p));
|
||||
return timingSafeEqual(got, Buffer.from(hash, 'base64'));
|
||||
}
|
||||
|
||||
// Хеш-пустышка: вход несуществующего пользователя стоит столько же, сколько неверный пароль,
|
||||
// поэтому по времени ответа нельзя узнать, существует ли username.
|
||||
export const dummyHash = hashPassword('dummy-password-for-timing');
|
||||
@@ -0,0 +1,62 @@
|
||||
// Сессии: вход по Basic, выход, проверка Bearer-токена.
|
||||
// В БД хранится только sha256(токена): дамп базы не даёт рабочих токенов.
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import type { Ctx, Result } from '../http/context.ts';
|
||||
import { HttpError, unauthorized } from '../http/errors.ts';
|
||||
import { isText, requireEmptyBody } from '../http/request.ts';
|
||||
import { checkPassword, dummyHash } from './passwords.ts';
|
||||
import { USERNAME, userColumns, type User } from './model.ts';
|
||||
|
||||
export const sha256 = (s: string) => createHash('sha256').update(s).digest();
|
||||
|
||||
function bearerToken(c: Ctx): string | null {
|
||||
return /^Bearer +(\S+)$/i.exec(c.req.headers.authorization ?? '')?.[1] ?? null;
|
||||
}
|
||||
|
||||
// Текущий пользователь по Bearer-сессии. Basic и X-User-Id на бизнес-эндпоинтах не аутентифицируют.
|
||||
// Запрос именованный: pg готовит его один раз на соединение (улучшение из трека 1).
|
||||
export async function authenticate(c: Ctx): Promise<User> {
|
||||
const token = bearerToken(c);
|
||||
if (!token) throw unauthorized();
|
||||
const r = await c.db.query<User>({
|
||||
name: 'auth',
|
||||
text: `SELECT ${userColumns} FROM sessions s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1 AND s.expires_at > now()`,
|
||||
values: [sha256(token)],
|
||||
});
|
||||
if (!r.rowCount) throw unauthorized();
|
||||
return r.rows[0];
|
||||
}
|
||||
|
||||
// POST /api/v1/auth/sessions: Basic username:password → новый Bearer-токен.
|
||||
export async function createSession(c: Ctx): Promise<Result> {
|
||||
await requireEmptyBody(c.req); // контракт: только заголовок Basic, без JSON-тела
|
||||
const deny = new HttpError(401, 'unauthorized', 'Неверные учётные данные'); // одинаковый ответ на любую ошибку входа
|
||||
const m = /^Basic +([A-Za-z0-9+/]+=*)$/i.exec(c.req.headers.authorization ?? '');
|
||||
if (!m) throw deny;
|
||||
const decoded = Buffer.from(m[1], 'base64').toString('utf8');
|
||||
const colon = decoded.indexOf(':'); // в username двоеточия нет, в пароле может быть
|
||||
const username = decoded.slice(0, colon);
|
||||
const password = decoded.slice(colon + 1);
|
||||
if (colon < 0 || !USERNAME.test(username)) throw deny;
|
||||
|
||||
const r = await c.db.query<User & { password_hash: string }>(
|
||||
`SELECT ${userColumns}, u.password_hash FROM users u WHERE u.username = $1`, [username]);
|
||||
const row = r.rows[0];
|
||||
const valid = await checkPassword(password, row?.password_hash ?? await dummyHash);
|
||||
if (!row || !valid || !isText(password, 12, 128)) throw deny;
|
||||
|
||||
const token = randomBytes(32).toString('base64url'); // 256 бит энтропии
|
||||
const s = await c.db.query(
|
||||
`INSERT INTO sessions (token_hash, user_id, expires_at) VALUES ($1, $2, now() + make_interval(secs => $3))
|
||||
RETURNING rfc3339(expires_at) AS expires_at`, [sha256(token), row.id, c.config.sessionTtlSeconds]);
|
||||
const { password_hash: _, ...user } = row;
|
||||
return [201, { token, token_type: 'Bearer', expires_at: s.rows[0].expires_at, user }];
|
||||
}
|
||||
|
||||
// DELETE /api/v1/auth/sessions/current: отзыв текущего токена.
|
||||
export async function deleteSession(c: Ctx): Promise<Result> {
|
||||
await authenticate(c);
|
||||
await c.db.query('DELETE FROM sessions WHERE token_hash = $1', [sha256(bearerToken(c)!)]);
|
||||
return [204];
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// Пользователи: регистрация и профиль текущего пользователя.
|
||||
import type { Ctx, Result } from '../http/context.ts';
|
||||
import { badRequest, conflict } from '../http/errors.ts';
|
||||
import { isText, jsonObject, readJson } from '../http/request.ts';
|
||||
import { hashPassword } from './passwords.ts';
|
||||
import { USERNAME, userColumns, type User } from './model.ts';
|
||||
import { authenticate } from './sessions.ts';
|
||||
|
||||
// POST /api/v1/users: публичная регистрация. Пароль и его хеш в ответ не попадают.
|
||||
export async function createUser(c: Ctx): Promise<Result> {
|
||||
const b = jsonObject(await readJson(c.req), ['username', 'display_name', 'password']);
|
||||
if (typeof b.username !== 'string' || !USERNAME.test(b.username) || !isText(b.display_name, 1, 100) || !isText(b.password, 12, 128)) {
|
||||
throw badRequest('Неверные username, display_name или password');
|
||||
}
|
||||
try {
|
||||
const r = await c.db.query<User>(
|
||||
`INSERT INTO users AS u (username, display_name, password_hash) VALUES ($1, $2, $3) RETURNING ${userColumns}`,
|
||||
[b.username, b.display_name, await hashPassword(b.password)]);
|
||||
return [201, r.rows[0]];
|
||||
} catch (err) {
|
||||
if ((err as { code?: string }).code === '23505') throw conflict('Username уже занят'); // unique_violation
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// GET /api/v1/users/me
|
||||
export async function me(c: Ctx): Promise<Result> {
|
||||
return [200, await authenticate(c)];
|
||||
}
|
||||
Reference in New Issue
Block a user