@open-mercato/core 0.10.1-develop.7841.1.af87ac614d → 0.10.1-develop.7857.1.259928eb85
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/dist/modules/api_keys/api/keys/route.js +15 -1
- package/dist/modules/api_keys/api/keys/route.js.map +2 -2
- package/dist/modules/attachments/api/file/[id]/route.js +6 -1
- package/dist/modules/attachments/api/file/[id]/route.js.map +2 -2
- package/dist/modules/attachments/api/image/[id]/[[...slug]]/route.js +6 -1
- package/dist/modules/attachments/api/image/[id]/[[...slug]]/route.js.map +2 -2
- package/dist/modules/attachments/api/library/[id]/route.js +16 -1
- package/dist/modules/attachments/api/library/[id]/route.js.map +2 -2
- package/dist/modules/attachments/api/route.js +11 -3
- package/dist/modules/attachments/api/route.js.map +2 -2
- package/dist/modules/attachments/cli.js +2 -0
- package/dist/modules/attachments/cli.js.map +2 -2
- package/dist/modules/attachments/data/validators.js +11 -0
- package/dist/modules/attachments/data/validators.js.map +2 -2
- package/dist/modules/attachments/index.js +10 -0
- package/dist/modules/attachments/index.js.map +2 -2
- package/dist/modules/attachments/lib/access-query.js +5 -1
- package/dist/modules/attachments/lib/access-query.js.map +2 -2
- package/dist/modules/attachments/lib/createFromBuffer.js +2 -0
- package/dist/modules/attachments/lib/createFromBuffer.js.map +2 -2
- package/dist/modules/attachments/lib/drivers/driverFactory.js +54 -33
- package/dist/modules/attachments/lib/drivers/driverFactory.js.map +2 -2
- package/dist/modules/attachments/lib/drivers/index.js +11 -1
- package/dist/modules/attachments/lib/drivers/index.js.map +2 -2
- package/dist/modules/attachments/lib/drivers/storageValidation.js +85 -0
- package/dist/modules/attachments/lib/drivers/storageValidation.js.map +7 -0
- package/dist/modules/attachments/lib/scoped-upload-service.js +3 -1
- package/dist/modules/attachments/lib/scoped-upload-service.js.map +2 -2
- package/dist/modules/attachments/lib/storageErrors.js +22 -0
- package/dist/modules/attachments/lib/storageErrors.js.map +7 -0
- package/dist/modules/auth/api/users/route.js +16 -1
- package/dist/modules/auth/api/users/route.js.map +2 -2
- package/dist/modules/auth/backend/users/page.js +13 -2
- package/dist/modules/auth/backend/users/page.js.map +2 -2
- package/dist/modules/catalog/commands/products.js +4 -2
- package/dist/modules/catalog/commands/products.js.map +2 -2
- package/dist/modules/customers/api/companies/[id]/route.js +4 -9
- package/dist/modules/customers/api/companies/[id]/route.js.map +2 -2
- package/dist/modules/customers/api/people/[id]/route.js +4 -9
- package/dist/modules/customers/api/people/[id]/route.js.map +2 -2
- package/dist/modules/customers/components/detail/TaskDialog.js +2 -0
- package/dist/modules/customers/components/detail/TaskDialog.js.map +2 -2
- package/dist/modules/customers/lib/todoCompatibility.js +23 -0
- package/dist/modules/customers/lib/todoCompatibility.js.map +2 -2
- package/dist/modules/directory/api/organization-branding/route.js +6 -9
- package/dist/modules/directory/api/organization-branding/route.js.map +2 -2
- package/dist/modules/directory/backend/directory/branding/page.js +15 -3
- package/dist/modules/directory/backend/directory/branding/page.js.map +2 -2
- package/dist/modules/wms/api/listEnrichers.js +3 -1
- package/dist/modules/wms/api/listEnrichers.js.map +2 -2
- package/dist/modules/wms/index.js +1 -1
- package/dist/modules/wms/index.js.map +2 -2
- package/jest.config.cjs +1 -1
- package/package.json +8 -8
- package/src/modules/api_keys/api/keys/route.ts +15 -1
- package/src/modules/api_keys/i18n/de.json +1 -0
- package/src/modules/api_keys/i18n/en.json +1 -0
- package/src/modules/api_keys/i18n/es.json +1 -0
- package/src/modules/api_keys/i18n/ko.json +1 -0
- package/src/modules/api_keys/i18n/pl.json +1 -0
- package/src/modules/attachments/api/file/[id]/route.ts +7 -1
- package/src/modules/attachments/api/image/[id]/[[...slug]]/route.ts +7 -1
- package/src/modules/attachments/api/library/[id]/route.ts +14 -1
- package/src/modules/attachments/api/route.ts +11 -3
- package/src/modules/attachments/cli.ts +2 -0
- package/src/modules/attachments/data/validators.ts +11 -0
- package/src/modules/attachments/i18n/de.json +1 -0
- package/src/modules/attachments/i18n/en.json +1 -0
- package/src/modules/attachments/i18n/es.json +1 -0
- package/src/modules/attachments/i18n/ko.json +1 -0
- package/src/modules/attachments/i18n/pl.json +1 -0
- package/src/modules/attachments/index.ts +12 -0
- package/src/modules/attachments/lib/access-query.ts +5 -1
- package/src/modules/attachments/lib/createFromBuffer.ts +2 -0
- package/src/modules/attachments/lib/drivers/driverFactory.ts +79 -55
- package/src/modules/attachments/lib/drivers/index.ts +13 -0
- package/src/modules/attachments/lib/drivers/storageValidation.ts +114 -0
- package/src/modules/attachments/lib/scoped-upload-service.ts +3 -1
- package/src/modules/attachments/lib/storageErrors.ts +21 -0
- package/src/modules/auth/api/users/route.ts +18 -1
- package/src/modules/auth/backend/users/page.tsx +14 -2
- package/src/modules/auth/i18n/de.json +1 -0
- package/src/modules/auth/i18n/en.json +1 -0
- package/src/modules/auth/i18n/es.json +1 -0
- package/src/modules/auth/i18n/ko.json +1 -0
- package/src/modules/auth/i18n/pl.json +1 -0
- package/src/modules/catalog/commands/products.ts +4 -1
- package/src/modules/customer_accounts/AGENTS.md +1 -1
- package/src/modules/customers/api/companies/[id]/route.ts +6 -13
- package/src/modules/customers/api/people/[id]/route.ts +6 -13
- package/src/modules/customers/components/detail/TaskDialog.tsx +2 -0
- package/src/modules/customers/lib/todoCompatibility.ts +28 -0
- package/src/modules/directory/api/organization-branding/route.ts +5 -8
- package/src/modules/directory/backend/directory/branding/page.tsx +15 -3
- package/src/modules/sales/AGENTS.md +3 -3
- package/src/modules/wms/api/listEnrichers.ts +5 -2
- package/src/modules/wms/index.ts +1 -1
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { attachmentErrorSchema } from "./openapi.js";
|
|
2
|
+
import { withAttachmentStorageErrors } from "@open-mercato/core/modules/attachments/lib/storageErrors";
|
|
3
|
+
import { assertAttachmentStoragePartitionExists, getAttachmentStoragePolicy } from "@open-mercato/core/modules/attachments/lib/drivers/storageValidation";
|
|
1
4
|
import { LockMode } from "@mikro-orm/core";
|
|
2
5
|
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
3
6
|
import { prepareAttachmentMutation } from "../lib/access-mutation.js";
|
|
@@ -256,7 +259,7 @@ async function listRecordAttachments(req) {
|
|
|
256
259
|
}, { headers: protectedScan ? { "Cache-Control": "private, no-store" } : void 0 });
|
|
257
260
|
}
|
|
258
261
|
const GET = withAttachmentAccessErrors(listRecordAttachments);
|
|
259
|
-
async function
|
|
262
|
+
async function uploadAttachment(req) {
|
|
260
263
|
const { t } = await resolveTranslations();
|
|
261
264
|
const auth = await getAuthFromRequest(req);
|
|
262
265
|
if (!auth || !auth.tenantId || !auth.orgId && !auth.isSuperAdmin) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
@@ -334,7 +337,7 @@ async function POST(req) {
|
|
|
334
337
|
if (uploadScope.denied) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
|
335
338
|
const orgId = uploadScope.organizationId;
|
|
336
339
|
if (!orgId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
337
|
-
await ensureDefaultPartitions(em);
|
|
340
|
+
if (getAttachmentStoragePolicy() === "legacy") await ensureDefaultPartitions(em);
|
|
338
341
|
let partitionFromField = null;
|
|
339
342
|
let fieldMaxAttachmentSizeMb = null;
|
|
340
343
|
if (fieldKey) {
|
|
@@ -407,6 +410,7 @@ async function POST(req) {
|
|
|
407
410
|
let partition = null;
|
|
408
411
|
for (const code of partitionCodeCandidates) {
|
|
409
412
|
const record = await em.findOne(AttachmentPartition, { code });
|
|
413
|
+
assertAttachmentStoragePartitionExists(Boolean(record));
|
|
410
414
|
if (record) {
|
|
411
415
|
partition = record;
|
|
412
416
|
break;
|
|
@@ -416,6 +420,7 @@ async function POST(req) {
|
|
|
416
420
|
partition = await em.findOne(AttachmentPartition, { code: defaultPartitionCode });
|
|
417
421
|
}
|
|
418
422
|
if (!partition) {
|
|
423
|
+
assertAttachmentStoragePartitionExists(false);
|
|
419
424
|
return NextResponse.json({ error: "Storage partition is not configured." }, { status: 400 });
|
|
420
425
|
}
|
|
421
426
|
await ensureAttachmentPartitionProtection(em, partition);
|
|
@@ -700,7 +705,8 @@ async function deleteAttachment(req) {
|
|
|
700
705
|
}
|
|
701
706
|
return NextResponse.json({ ok: true });
|
|
702
707
|
}
|
|
703
|
-
const
|
|
708
|
+
const POST = withAttachmentAccessErrors(withAttachmentStorageErrors(uploadAttachment));
|
|
709
|
+
const DELETE = withAttachmentAccessErrors(withAttachmentStorageErrors(deleteAttachment));
|
|
704
710
|
const openApi = {
|
|
705
711
|
summary: "Manage entity attachments",
|
|
706
712
|
description: "Upload and list attachments associated with module entities and records.",
|
|
@@ -731,6 +737,7 @@ const openApi = {
|
|
|
731
737
|
{ status: 200, description: "Attachment stored successfully", schema: uploadResponseSchema }
|
|
732
738
|
],
|
|
733
739
|
errors: [
|
|
740
|
+
{ status: 503, description: "Attachment storage configuration rejected by policy", schema: attachmentErrorSchema },
|
|
734
741
|
{ status: 400, description: "Payload validation error", schema: errorSchema },
|
|
735
742
|
{ status: 401, description: "Unauthorized", schema: errorSchema },
|
|
736
743
|
{ status: 403, description: "Attachment violates field constraints", schema: errorSchema }
|
|
@@ -745,6 +752,7 @@ const openApi = {
|
|
|
745
752
|
{ status: 404, description: "Attachment not found", schema: errorSchema }
|
|
746
753
|
],
|
|
747
754
|
errors: [
|
|
755
|
+
{ status: 503, description: "Attachment storage configuration rejected by policy", schema: attachmentErrorSchema },
|
|
748
756
|
{ status: 400, description: "Missing attachment identifier", schema: errorSchema },
|
|
749
757
|
{ status: 401, description: "Unauthorized", schema: errorSchema },
|
|
750
758
|
{ status: 403, description: "Owner policy denies access", schema: errorSchema },
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/attachments/api/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { LockMode } from '@mikro-orm/core'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { prepareAttachmentMutation } from '../lib/access-mutation'\nimport { throwAttachmentAccessError } from '../lib/access-errors'\nimport { createAttachmentAccessContext } from '../lib/access-runner'\nimport { assertAttachmentOwnerAccess, requiresAttachmentAccessScan, scanAuthorizedAttachments } from '../lib/access-query'\nimport { withAttachmentAccessErrors } from '../lib/access-errors'\nimport { NextResponse } from 'next/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { z } from 'zod'\nimport { sql } from 'kysely'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { buildAttachmentFileUrl, buildAttachmentImageUrl, slugifyAttachmentFileName } from '../lib/imageUrls'\nimport { ensureAttachmentPartitionProtection } from '../lib/access-protection'\nimport { ensureDefaultPartitions, resolveDefaultPartitionCode, sanitizePartitionCode } from '../lib/partitions'\nimport { Attachment, AttachmentPartition } from '../data/entities'\nimport { extractAttachmentContent } from '../lib/textExtraction'\nimport { requestOcrProcessing } from '../lib/ocrQueue'\nimport { StorageDriverFactory } from '../lib/drivers'\nimport { OcrService, shouldUseLlmOcr } from '../lib/ocrService'\nimport { clearAttachmentThumbnailCache } from '../lib/thumbnailCache'\nimport { lockAttachmentStorageReferences, resolveAttachmentStorageRelease } from '../lib/storageReferences'\nimport { assertAttachmentScopeInvariant } from '../lib/access'\nimport { resolveAttachmentRequestScope } from '../lib/requestScope'\nimport {\n mergeAttachmentMetadata,\n normalizeAttachmentAssignments,\n normalizeAttachmentTags,\n readAttachmentMetadata,\n upsertAssignment,\n type AttachmentAssignment,\n} from '../lib/metadata'\nimport { randomUUID } from 'crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { splitCustomFieldPayload } from '@open-mercato/shared/lib/crud/custom-fields'\nimport { emitCrudSideEffects, setCustomFieldsIfAny } from '@open-mercato/shared/lib/commands/helpers'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { attachmentCrudEvents, attachmentCrudIndexer } from '../lib/crud'\nimport { E } from '#generated/entities.ids.generated'\nimport { resolveDefaultAttachmentOcrEnabled } from '../lib/ocrConfig'\nimport {\n detectAttachmentMimeType,\n hasDangerousExecutableExtension,\n isActiveContentAttachment,\n sanitizeUploadedFileName,\n} from '../lib/security'\nimport {\n isMultipartUploadLimitError,\n isMultipartRequestWithinUploadLimit,\n parseMultipartFormDataWithinUploadLimit,\n resolveAttachmentMaxBytes,\n willExceedAttachmentTenantQuota,\n} from '../lib/upload-limits'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { AttachmentQuotaService } from '../lib/quota-service'\nimport { resolveAttachmentsUploadRateLimitConfig } from '../lib/ocrLimits'\nimport { checkRateLimit, RATE_LIMIT_ERROR_FALLBACK, RATE_LIMIT_ERROR_KEY } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport type { RateLimiterService } from '@open-mercato/shared/lib/ratelimit/service'\n\nconst logger = createLogger('attachments')\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['attachments.view'] },\n POST: { requireAuth: true, requireFeatures: ['attachments.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['attachments.manage'] },\n}\n\nconst ATTACHMENT_LIST_MAX_PAGE_SIZE = 100\n\nconst attachmentQuerySchema = z.object({\n entityId: z.string().min(1).describe('Entity identifier that owns the attachments'),\n recordId: z.string().min(1).describe('Record identifier within the entity'),\n page: z.coerce.number().min(1).optional(),\n pageSize: z.coerce.number().min(1).max(ATTACHMENT_LIST_MAX_PAGE_SIZE).optional(),\n})\n\nconst attachmentAssignmentSchema = z.object({\n type: z.string().describe('Assignment type identifier'),\n id: z.string().describe('Assignment record identifier'),\n href: z.string().nullable().optional().describe('Optional link to the related record'),\n label: z.string().nullable().optional().describe('Optional label for the assignment'),\n})\n\nconst attachmentItemSchema = z.object({\n id: z.string().describe('Attachment identifier'),\n url: z.string().describe('Public path to the stored asset'),\n fileName: z.string().describe('Original filename'),\n fileSize: z.number().int().nonnegative().describe('File size in bytes'),\n createdAt: z.string().describe('Upload timestamp (ISO 8601)'),\n mimeType: z.string().nullable().optional().describe('MIME type of the file'),\n thumbnailUrl: z.string().optional().describe('Helper route that renders a thumbnail'),\n partitionCode: z.string().optional().describe('Partition identifier'),\n tags: z.array(z.string()).optional().describe('Tags assigned to the attachment'),\n content: z.string().nullable().optional().describe('Extracted text or markdown content'),\n assignments: z.array(attachmentAssignmentSchema).optional().describe('Records that reference this attachment'),\n})\n\nconst attachmentListResponseSchema = z.object({\n items: z.array(attachmentItemSchema),\n total: z.number().int().nonnegative().optional(),\n page: z.number().int().min(1).optional(),\n pageSize: z.number().int().min(1).optional(),\n totalPages: z.number().int().min(1).optional(),\n})\n\nconst attachmentUploadBodySchema = z.object({\n entityId: z.string().min(1),\n recordId: z.string().min(1),\n fieldKey: z.string().optional(),\n file: z.string().min(1).describe('Binary file payload; supplied as multipart form-data'),\n customFields: z\n .string()\n .optional()\n .describe('JSON encoded map of custom field values collected from the upload form.'),\n})\n\nconst attachmentDeleteQuerySchema = z.object({\n id: z.string().uuid(),\n})\n\nconst uploadResponseSchema = z.object({\n ok: z.literal(true),\n item: z.object({\n id: z.string(),\n url: z.string(),\n fileName: z.string(),\n fileSize: z.number().int().nonnegative(),\n thumbnailUrl: z.string().optional(),\n content: z.string().nullable().optional(),\n tags: z.array(z.string()).optional(),\n assignments: z.array(attachmentAssignmentSchema).optional(),\n customFields: z.record(z.string(), z.unknown()).optional(),\n }),\n})\n\nconst errorSchema = z.object({\n error: z.string(),\n})\n\nconst LIBRARY_ENTITY_ID = 'attachments:library'\n\nfunction parseCustomFieldsEntry(value: FormDataEntryValue | null): Record<string, unknown> {\n if (!value) return {}\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed) return {}\n try {\n const parsed = JSON.parse(trimmed)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>\n }\n } catch {\n return {}\n }\n }\n if (typeof value === 'object' && !Array.isArray(value) && !(value instanceof File)) {\n return { ...(value as Record<string, unknown>) }\n }\n return {}\n}\n\nfunction buildFormPayload(form: FormData): Record<string, unknown> {\n const payload: Record<string, unknown> = {}\n form.forEach((value, key) => {\n if (key === 'customFields') {\n payload.customFields = parseCustomFieldsEntry(value)\n return\n }\n payload[key] = value\n })\n return payload\n}\n\nfunction parseFormTags(value: FormDataEntryValue | null): string[] {\n if (!value) return []\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed) return []\n try {\n const parsed = JSON.parse(trimmed)\n return normalizeAttachmentTags(parsed)\n } catch {\n return normalizeAttachmentTags(value)\n }\n }\n return []\n}\n\nfunction parseFormAssignments(value: FormDataEntryValue | null): AttachmentAssignment[] {\n if (!value) return []\n if (typeof value !== 'string') return []\n const trimmed = value.trim()\n if (!trimmed) return []\n try {\n const parsed = JSON.parse(trimmed)\n return normalizeAttachmentAssignments(parsed)\n } catch {\n return []\n }\n}\n\nasync function listRecordAttachments(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId || (!auth.orgId && !auth.isSuperAdmin)) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const url = new URL(req.url)\n const parsedQuery = attachmentQuerySchema.safeParse({\n entityId: url.searchParams.get('entityId') || '',\n recordId: url.searchParams.get('recordId') || '',\n page: url.searchParams.get('page') ?? undefined,\n pageSize: url.searchParams.get('pageSize') ?? undefined,\n })\n if (!parsedQuery.success) {\n return NextResponse.json({ error: 'entityId and recordId are required' }, { status: 400 })\n }\n const { entityId, recordId, page, pageSize } = parsedQuery.data\n\n const container = await createRequestContainer()\n const em = container.resolve('em') as EntityManager\n const requestScope = await resolveAttachmentRequestScope(container, auth, req)\n if (requestScope.denied) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })\n const orgId = requestScope.organizationId\n const filter: Record<string, unknown> = { entityId, recordId, tenantId: auth.tenantId! }\n if (orgId) filter.organizationId = orgId\n const orderBy: Record<string, 'ASC' | 'DESC'> = { createdAt: 'DESC', id: 'DESC' }\n const usePaging = typeof page === 'number' && typeof pageSize === 'number'\n const currentPage = usePaging ? Math.max(1, page) : null\n const currentPageSize = usePaging ? pageSize : null\n const pageOffset = usePaging ? (currentPage! - 1) * currentPageSize! : undefined\n const partitions = await em.find(AttachmentPartition, {})\n const protectedScan = requiresAttachmentAccessScan(partitions)\n const scope = { tenantId: auth.tenantId ?? null, organizationId: orgId ?? null }\n let items: Attachment[]\n let total: number | null\n if (protectedScan) {\n const scanned = await scanAuthorizedAttachments({\n auth: { ...auth, orgId }, context: createAttachmentAccessContext(container), partitions,\n offset: pageOffset, limit: currentPageSize ?? ATTACHMENT_LIST_MAX_PAGE_SIZE,\n loadBatch: (offset, limit) => findWithDecryption(em, Attachment, filter, { orderBy, offset, limit }, scope),\n })\n items = scanned.records\n total = usePaging ? scanned.total : null\n } else {\n total = usePaging ? await em.count(Attachment, filter) : null\n items = await findWithDecryption(em, Attachment, filter, {\n orderBy, ...(usePaging ? { limit: currentPageSize!, offset: pageOffset } : { limit: ATTACHMENT_LIST_MAX_PAGE_SIZE }),\n }, scope)\n }\n const totalPages = usePaging && total !== null ? Math.max(1, Math.ceil(total / currentPageSize!)) : null\n return NextResponse.json({\n items: items.map((a: any) => {\n const metadata = readAttachmentMetadata(a.storageMetadata)\n return {\n id: a.id,\n url: a.url,\n fileName: a.fileName,\n fileSize: a.fileSize,\n createdAt: a.createdAt,\n mimeType: a.mimeType ?? null,\n partitionCode: a.partitionCode,\n content: a.content ?? null,\n thumbnailUrl: buildAttachmentImageUrl(a.id, {\n width: 320,\n height: 320,\n slug: slugifyAttachmentFileName(a.fileName),\n }),\n tags: metadata.tags ?? [],\n assignments: metadata.assignments ?? [],\n }\n }),\n ...(usePaging\n ? {\n total,\n page: currentPage,\n pageSize: currentPageSize,\n totalPages,\n }\n : {}),\n }, { headers: protectedScan ? { 'Cache-Control': 'private, no-store' } : undefined })\n}\n\nexport const GET = withAttachmentAccessErrors(listRecordAttachments)\n\nexport async function POST(req: Request) {\n const { t } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId || (!auth.orgId && !auth.isSuperAdmin)) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n // A superadmin browsing with \"All organizations\" selected has no concrete\n // organization scope, but an attachment must be stored under exactly one\n // organization (the scope invariant forbids partial-null rows). Reject with a\n // clear, actionable error instead of a 401 \u2014 a 401 makes the client-side\n // fetch layer treat it as session expiry, show a misleading toast, and reset\n // the in-progress form (#3764).\n if (!auth.orgId) {\n return NextResponse.json({\n error: t('attachments.errors.selectOrganization', 'Select a specific organization before uploading an attachment.'),\n }, { status: 400 })\n }\n const tenantId = auth.tenantId\n\n const container = await createRequestContainer()\n let rateLimiterService: RateLimiterService | null = null\n try {\n rateLimiterService = container.resolve('rateLimiterService') as RateLimiterService | null\n } catch (error) {\n // Fail-open: uploads proceed when the limiter cannot be resolved (minimal/test containers).\n logger.warn('Attachment upload rate limiter unavailable; throttle skipped', { err: error })\n }\n if (rateLimiterService) {\n const principal = typeof auth.sub === 'string' && auth.sub.length > 0\n ? auth.sub\n : (typeof auth.userId === 'string' && auth.userId.length > 0 ? auth.userId : null)\n if (!principal) {\n logger.warn('Attachment upload rate limit skipped: missing authenticated principal')\n } else {\n const rateLimitResponse = await checkRateLimit(\n rateLimiterService,\n resolveAttachmentsUploadRateLimitConfig(),\n `${tenantId}:${principal}`,\n t(RATE_LIMIT_ERROR_KEY, RATE_LIMIT_ERROR_FALLBACK),\n )\n if (rateLimitResponse) return rateLimitResponse\n }\n } else {\n logger.warn('Attachment upload rate limiter not registered; throttle skipped')\n }\n\n const contentType = req.headers.get('content-type') || ''\n if (!contentType.toLowerCase().includes('multipart/form-data')) {\n return NextResponse.json({ error: 'Expected multipart/form-data' }, { status: 400 })\n }\n if (!isMultipartRequestWithinUploadLimit(req.headers.get('content-length'))) {\n return NextResponse.json({\n error: t('attachments.errors.maxUploadSize', 'Attachment exceeds the maximum upload size.'),\n }, { status: 413 })\n }\n\n let form: FormData\n try {\n form = await parseMultipartFormDataWithinUploadLimit(req)\n } catch (error) {\n if (isMultipartUploadLimitError(error)) {\n return NextResponse.json({\n error: t('attachments.errors.maxUploadSize', 'Attachment exceeds the maximum upload size.'),\n }, { status: 413 })\n }\n throw error\n }\n const formPayload = buildFormPayload(form)\n const customFieldValues = splitCustomFieldPayload(formPayload).custom\n const entityId = String(form.get('entityId') || '')\n const recordId = String(form.get('recordId') || '')\n const fieldKey = String(form.get('fieldKey') || '')\n const file = form.get('file') as unknown as File | null\n if (!entityId || !recordId || !file) return NextResponse.json({ error: 'entityId, recordId and file are required' }, { status: 400 })\n const partitionOverrideRaw = form.get('partitionCode')\n const partitionOverride =\n typeof partitionOverrideRaw === 'string' && partitionOverrideRaw.trim().length > 0\n ? sanitizePartitionCode(partitionOverrideRaw)\n : null\n const tags = parseFormTags(form.get('tags'))\n const assignmentsFromForm = parseFormAssignments(form.get('assignments'))\n\n const em = container.resolve('em') as EntityManager\n const dataEngine = container.resolve('dataEngine')\n let attachmentQuotaService: AttachmentQuotaService | null = null\n let attachmentQuotaRecoveryScheduler: ((\n payload: { reservationId: string; tenantId: string; organizationId: string },\n delayMs: number,\n ) => Promise<void>) | null = null\n try {\n attachmentQuotaService = container.resolve('attachmentQuotaService') as AttachmentQuotaService\n attachmentQuotaRecoveryScheduler = container.resolve('attachmentQuotaRecoveryScheduler') as (\n payload: { reservationId: string; tenantId: string; organizationId: string },\n delayMs: number,\n ) => Promise<void>\n } catch {\n // Legacy fallback below when the quota service is not registered in this container.\n }\n const storageDriverFactory =\n (container.resolve('storageDriverFactory') as StorageDriverFactory | null) ?? new StorageDriverFactory(em)\n const uploadScope = await resolveAttachmentRequestScope(container, auth, req)\n if (uploadScope.denied) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })\n const orgId = uploadScope.organizationId\n if (!orgId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n await ensureDefaultPartitions(em)\n // Optional per-field validations\n let partitionFromField: string | null = null\n let fieldMaxAttachmentSizeMb: number | null = null\n if (fieldKey) {\n try {\n const { CustomFieldDef } = await import('@open-mercato/core/modules/entities/data/entities')\n const def = await em.findOne(CustomFieldDef, {\n entityId,\n key: fieldKey,\n $and: [\n { $or: [ { tenantId: auth.tenantId }, { tenantId: null } ] },\n ],\n isActive: true,\n })\n const cfg = (def as any)?.configJson || {}\n const ext = (file.name || '').split('.').pop()?.toLowerCase() || ''\n if (Array.isArray(cfg.acceptExtensions) && cfg.acceptExtensions.length) {\n const allowed = new Set((cfg.acceptExtensions as any[]).map((x: any) => String(x).toLowerCase().replace(/^\\./, '')))\n if (!allowed.has(ext)) return NextResponse.json({ error: 'File type not allowed' }, { status: 400 })\n }\n if (typeof cfg.maxAttachmentSizeMb === 'number' && cfg.maxAttachmentSizeMb > 0) {\n fieldMaxAttachmentSizeMb = cfg.maxAttachmentSizeMb\n }\n if (typeof cfg.partitionCode === 'string' && cfg.partitionCode.trim().length > 0) {\n partitionFromField = sanitizePartitionCode(cfg.partitionCode)\n }\n } catch {}\n }\n if (hasDangerousExecutableExtension(file.name)) {\n return NextResponse.json({\n error: t('attachments.errors.dangerousExecutable', 'Executable file types are not allowed as attachments.'),\n }, { status: 400 })\n }\n const effectiveMaxBytes = resolveAttachmentMaxBytes(fieldMaxAttachmentSizeMb)\n if (file.size > effectiveMaxBytes) {\n return NextResponse.json({\n error: t('attachments.errors.maxUploadSize', 'Attachment exceeds the maximum upload size.'),\n }, { status: 413 })\n }\n if (!attachmentQuotaService) {\n try {\n const tenantUsageBytes = await readTenantAttachmentUsageBytes(em, tenantId)\n if (willExceedAttachmentTenantQuota(tenantUsageBytes, file.size)) {\n return NextResponse.json({\n error: t('attachments.errors.quotaExceeded', 'Attachment storage quota exceeded for this tenant.'),\n }, { status: 413 })\n }\n } catch (error) {\n logger.error('Attachment quota accounting failed', { err: error })\n return NextResponse.json({\n error: t('attachments.errors.quotaUnavailable', 'Storage quota accounting is unavailable.'),\n }, { status: 500 })\n }\n }\n const buf = Buffer.from(await file.arrayBuffer())\n const safeName = sanitizeUploadedFileName(file.name)\n const fileMimeType = detectAttachmentMimeType(buf, safeName, (file as any).type)\n if (isActiveContentAttachment(buf, safeName, fileMimeType)) {\n return NextResponse.json({ error: t('attachments.errors.activeContentBlocked', 'Active content uploads are not allowed.') }, { status: 400 })\n }\n const defaultPartitionCode = resolveDefaultPartitionCode(entityId)\n const resolvedPartitionCode = partitionOverride ?? partitionFromField ?? defaultPartitionCode\n const partitionCodeCandidates = Array.from(\n new Set(\n [partitionOverride, partitionFromField, resolvedPartitionCode].filter(\n (code): code is string => typeof code === 'string' && code.length > 0,\n ),\n ),\n )\n let partition: AttachmentPartition | null = null\n for (const code of partitionCodeCandidates) {\n const record = await em.findOne(AttachmentPartition, { code })\n if (record) {\n partition = record\n break\n }\n }\n if (!partition) {\n partition = await em.findOne(AttachmentPartition, { code: defaultPartitionCode })\n }\n if (!partition) {\n return NextResponse.json({ error: 'Storage partition is not configured.' }, { status: 400 })\n }\n await ensureAttachmentPartitionProtection(em, partition)\n const requestedPublicOverride =\n typeof partitionOverride === 'string' &&\n partitionOverride.length > 0 &&\n partition.code === partitionOverride &&\n partition.isPublic === true &&\n partition.code !== defaultPartitionCode &&\n partition.code !== partitionFromField\n if (requestedPublicOverride) {\n return NextResponse.json({ error: t('attachments.errors.publicPartitionBlocked', 'Public storage partitions cannot be selected explicitly for this upload.') }, { status: 403 })\n }\n const uploadDriver = await storageDriverFactory.resolveForPartition(partition.code, { tenantId, organizationId: orgId })\n const preparedStoragePath = attachmentQuotaService\n ? uploadDriver.prepareStoragePath?.({\n partitionCode: partition.code,\n orgId,\n tenantId,\n fileName: safeName,\n })\n : undefined\n if (attachmentQuotaService && !preparedStoragePath) {\n return NextResponse.json({\n error: t('attachments.errors.quotaRecoveryUnsupported', 'Storage driver cannot participate in quota recovery.'),\n }, { status: 500 })\n }\n let quotaReservation: { id: string; leaseToken: string; expiresAt: Date } | null = null\n if (attachmentQuotaService) {\n try {\n quotaReservation = await attachmentQuotaService.reserve({\n tenantId,\n organizationId: orgId,\n bytes: buf.length,\n source: 'attachment',\n storageDriver: uploadDriver.key,\n storagePath: preparedStoragePath!,\n partitionCode: partition.code,\n })\n if (!attachmentQuotaRecoveryScheduler) throw new Error('Attachment quota recovery is unavailable.')\n await attachmentQuotaRecoveryScheduler({\n reservationId: quotaReservation.id,\n tenantId,\n organizationId: orgId,\n }, Math.max(1_000, quotaReservation.expiresAt.getTime() - Date.now()))\n if (typeof attachmentQuotaService.beginStorage === 'function') {\n await attachmentQuotaService.beginStorage(quotaReservation.id, quotaReservation.leaseToken)\n }\n } catch (error) {\n if (quotaReservation) {\n await attachmentQuotaService.release(quotaReservation.id, quotaReservation.leaseToken).catch(() => {})\n quotaReservation = null\n }\n const code = (error as { code?: unknown })?.code\n if (code === 'quota_exceeded') {\n return NextResponse.json({\n error: t('attachments.errors.quotaExceeded', 'Attachment storage quota exceeded for this tenant.'),\n }, { status: 413 })\n }\n if (code === 'quota_target_exists') {\n return NextResponse.json({\n error: t('attachments.errors.storagePathExists', 'The target storage path already exists.'),\n }, { status: 409 })\n }\n logger.error('Attachment quota reservation failed', { err: error })\n return NextResponse.json({\n error: t('attachments.errors.quotaUnavailable', 'Storage quota accounting is unavailable.'),\n }, { status: 500 })\n }\n }\n let storedPath: string\n try {\n const stored = await uploadDriver.store({\n partitionCode: partition.code,\n orgId,\n tenantId,\n fileName: safeName,\n buffer: buf,\n storagePath: preparedStoragePath,\n })\n storedPath = stored.storagePath\n if (quotaReservation) {\n await attachmentQuotaService!.markStored(quotaReservation.id, quotaReservation.leaseToken)\n }\n } catch (error) {\n logger.error('Failed to persist file', { err: error })\n if (preparedStoragePath) {\n try {\n await (uploadDriver.deleteStrict?.(partition.code, preparedStoragePath)\n ?? uploadDriver.delete(partition.code, preparedStoragePath))\n if (quotaReservation) {\n await attachmentQuotaService!.release(quotaReservation.id, quotaReservation.leaseToken)\n }\n } catch (cleanupError) {\n logger.error('Failed to compensate attachment storage', { err: cleanupError })\n }\n }\n return NextResponse.json({ error: 'Failed to persist attachment.' }, { status: 500 })\n }\n\n const requiresOcr =\n typeof (partition as any).requiresOcr === 'boolean'\n ? Boolean((partition as any).requiresOcr)\n : resolveDefaultAttachmentOcrEnabled()\n let extractedContent: string | null = null\n const wantsLlmOcr = requiresOcr && shouldUseLlmOcr(fileMimeType, safeName)\n const ocrService = wantsLlmOcr ? new OcrService() : null\n const useLlmOcr = Boolean(wantsLlmOcr && ocrService?.available)\n\n if (requiresOcr && !useLlmOcr) {\n const { filePath: localPath, cleanup } = await uploadDriver.toLocalPath(partition.code, storedPath)\n try {\n extractedContent = await extractAttachmentContent({\n filePath: localPath,\n mimeType: fileMimeType,\n })\n } catch (error) {\n logger.error('Failed to extract attachment content', { err: error })\n } finally {\n await cleanup().catch(() => {})\n }\n }\n\n let assignments = assignmentsFromForm.slice()\n if (entityId !== LIBRARY_ENTITY_ID) {\n assignments = upsertAssignment(assignments, { type: entityId, id: recordId })\n }\n const metadata = mergeAttachmentMetadata(null, { assignments, tags })\n const attachmentId = randomUUID()\n assertAttachmentScopeInvariant({ tenantId: auth.tenantId, organizationId: orgId })\n const att = em.create(Attachment, {\n id: attachmentId,\n entityId,\n recordId,\n organizationId: orgId,\n tenantId: auth.tenantId!,\n fileName: safeName,\n mimeType: fileMimeType,\n fileSize: buf.length,\n partitionCode: partition.code,\n storageDriver: partition.storageDriver || 'local',\n storagePath: storedPath,\n url: buildAttachmentFileUrl(attachmentId),\n content: extractedContent,\n storageMetadata: metadata,\n })\n // Persist the attachment row and its custom-field values atomically so a\n // custom-field failure cannot leave behind a committed orphan attachment.\n try {\n await em.transactional(async (tx) => {\n await tx.persist(att).flush()\n if (dataEngine) {\n await setCustomFieldsIfAny({\n dataEngine,\n entityId: E.attachments.attachment,\n recordId: attachmentId,\n tenantId,\n organizationId: orgId,\n values: customFieldValues,\n })\n }\n if (quotaReservation) {\n await attachmentQuotaService!.completeAttachment(quotaReservation.id, quotaReservation.leaseToken, tx)\n }\n })\n } catch (error) {\n logger.error('Failed to persist attachment with custom attributes', { err: error })\n try {\n await (uploadDriver.deleteStrict?.(partition.code, storedPath)\n ?? uploadDriver.delete(partition.code, storedPath))\n if (quotaReservation) {\n await attachmentQuotaService!.release(quotaReservation.id, quotaReservation.leaseToken)\n }\n } catch (cleanupError) {\n logger.error('Failed to compensate attachment persistence', { err: cleanupError })\n }\n return NextResponse.json({ error: 'Failed to save attachment attributes.' }, { status: 500 })\n }\n\n if (useLlmOcr) {\n // Await so wait-queue overflow can finish the inline text fallback before\n // the response returns (background LLM OCR still schedules via setImmediate).\n try {\n await requestOcrProcessing(em, att, uploadDriver, storedPath)\n } catch (error) {\n logger.error('Failed to queue OCR processing', { err: error })\n }\n } else if (wantsLlmOcr) {\n logger.warn('OCR requested but OPENAI_API_KEY not configured, falling back to text extraction when available')\n }\n\n if (dataEngine) {\n await emitCrudSideEffects({\n dataEngine,\n action: 'created',\n entity: att,\n identifiers: {\n id: att.id,\n organizationId: att.organizationId ?? null,\n tenantId: att.tenantId ?? null,\n },\n events: attachmentCrudEvents,\n indexer: attachmentCrudIndexer,\n })\n await dataEngine.flushOrmEntityChanges()\n }\n\n return NextResponse.json({\n ok: true,\n item: {\n id: attachmentId,\n url: att.url,\n fileName: safeName,\n fileSize: buf.length,\n partitionCode: partition.code,\n thumbnailUrl: buildAttachmentImageUrl(attachmentId, {\n width: 320,\n height: 320,\n slug: slugifyAttachmentFileName(safeName),\n }),\n content: extractedContent ?? null,\n tags: metadata.tags ?? [],\n assignments: metadata.assignments ?? [],\n customFields: Object.keys(customFieldValues).length ? customFieldValues : undefined,\n },\n })\n}\n\nasync function readTenantAttachmentUsageBytes(em: EntityManager, tenantId: string): Promise<number> {\n try {\n const db = em.getKysely<any>() as any\n const row = await db\n .selectFrom('attachments')\n .select(sql<string>`sum(file_size)`.as('total_size'))\n .where('tenant_id', '=', tenantId)\n .executeTakeFirst() as { total_size: string | number | null } | undefined\n const total = row?.total_size\n if (typeof total === 'number') return Number.isFinite(total) ? total : 0\n if (typeof total === 'string') {\n const parsed = Number(total)\n return Number.isFinite(parsed) ? parsed : 0\n }\n return 0\n } catch (error) {\n throw new Error('Attachment quota accounting is unavailable.', { cause: error })\n }\n}\n\nasync function deleteAttachment(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId || (!auth.orgId && !auth.isSuperAdmin)) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const url = new URL(req.url)\n const id = url.searchParams.get('id') || ''\n if (!id) return NextResponse.json({ error: 'Attachment id is required' }, { status: 400 })\n const container = await createRequestContainer()\n const em = container.resolve('em') as EntityManager\n const dataEngine = container.resolve('dataEngine')\n const storageDriverFactory =\n (container.resolve('storageDriverFactory') as StorageDriverFactory | null) ?? new StorageDriverFactory(em)\n // Resolve the currently selected organization (#3765) so a multi-org admin who\n // switched the header org deletes within that org, not their pinned home org.\n // A superadmin browsing with \"All organizations\" selected has no concrete org,\n // so resolution returns null and the delete falls back to a tenant-only scope\n // (#3764) \u2014 letting them remove any attachment in the tenant.\n const deleteScope = await resolveAttachmentRequestScope(container, auth, req)\n if (deleteScope.denied) return NextResponse.json({ error: 'Attachment not found' }, { status: 404 })\n const orgId = deleteScope.organizationId\n const deleteFilter: Record<string, unknown> = { id, tenantId: auth.tenantId! }\n if (orgId) deleteFilter.organizationId = orgId\n const scopedAuth = { ...auth, orgId }\n const outcome = await em.transactional(async (tx) => {\n const candidate = await findOneWithDecryption(tx, Attachment, deleteFilter, undefined, {\n tenantId: auth.tenantId, organizationId: orgId,\n })\n if (!candidate) return throwAttachmentAccessError(404)\n const referenceIds = await lockAttachmentStorageReferences(tx, candidate)\n const removal = resolveAttachmentStorageRelease(referenceIds, candidate.id)\n if (!removal.removed) return throwAttachmentAccessError(404)\n const record = await findOneWithDecryption(tx, Attachment, deleteFilter, {\n lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true,\n }, { tenantId: auth.tenantId, organizationId: orgId })\n if (!record) return throwAttachmentAccessError(404)\n const guard = await prepareAttachmentMutation({ container, req, auth: scopedAuth, recordId: record.id, operation: 'delete' })\n await assertAttachmentOwnerAccess({ em: tx, context: createAttachmentAccessContext(container), auth: scopedAuth, attachment: record, action: 'delete' })\n const driver = record.storagePath ? await storageDriverFactory.resolveForPartition(record.partitionCode, {\n tenantId: record.tenantId ?? auth.tenantId!, organizationId: record.organizationId ?? orgId ?? '',\n }) : null\n tx.remove(record)\n await tx.flush()\n return { record, driver, guard, releaseStorage: removal.releaseStorage }\n })\n const { record } = outcome\n await clearAttachmentThumbnailCache(record.partitionCode, record.id).catch((error) => {\n logger.error('Failed to cleanup cached thumbnails', { err: error })\n })\n if (outcome.driver && outcome.releaseStorage) await outcome.driver.delete(record.partitionCode, record.storagePath)\n await outcome.guard.runAfterSuccess()\n if (dataEngine) {\n await emitCrudSideEffects({\n dataEngine,\n action: 'deleted',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId ?? null,\n tenantId: record.tenantId ?? null,\n },\n events: attachmentCrudEvents,\n indexer: attachmentCrudIndexer,\n })\n await dataEngine.flushOrmEntityChanges()\n }\n return NextResponse.json({ ok: true })\n}\n\nexport const DELETE = withAttachmentAccessErrors(deleteAttachment)\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Manage entity attachments',\n description: 'Upload and list attachments associated with module entities and records.',\n methods: {\n GET: {\n summary: 'List attachments for a record',\n description: 'Returns uploaded attachments for the given entity record, ordered by newest first. Without both page and pageSize, only the newest 100 attachments are returned; pass page and pageSize to page through the rest.',\n query: attachmentQuerySchema,\n responses: [\n { status: 200, description: 'Attachments found for the record', schema: attachmentListResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Missing entity or record identifiers', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 403, description: 'Owner policy denies access', schema: errorSchema },\n { status: 404, description: 'Attachment or owner is unavailable', schema: errorSchema },\n { status: 504, description: 'Owner authorization timed out', schema: errorSchema },\n ],\n },\n POST: {\n summary: 'Upload attachment',\n description: 'Uploads a new attachment using multipart form-data and stores metadata for later retrieval.',\n requestBody: {\n contentType: 'multipart/form-data',\n schema: attachmentUploadBodySchema,\n },\n responses: [\n { status: 200, description: 'Attachment stored successfully', schema: uploadResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Payload validation error', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 403, description: 'Attachment violates field constraints', schema: errorSchema },\n ],\n },\n DELETE: {\n summary: 'Delete attachment',\n description: 'Removes an uploaded attachment and deletes the stored asset.',\n query: attachmentDeleteQuerySchema,\n responses: [\n { status: 200, description: 'Attachment deleted', schema: z.object({ ok: z.literal(true) }) },\n { status: 404, description: 'Attachment not found', schema: errorSchema },\n ],\n errors: [\n { status: 400, description: 'Missing attachment identifier', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 403, description: 'Owner policy denies access', schema: errorSchema },\n { status: 404, description: 'Attachment or owner is unavailable', schema: errorSchema },\n { status: 504, description: 'Owner authorization timed out', schema: errorSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,gBAAgB;AACzB,SAAS,6BAA6B;AACtC,SAAS,iCAAiC;AAC1C,SAAS,kCAAkC;AAC3C,SAAS,qCAAqC;AAC9C,SAAS,6BAA6B,8BAA8B,iCAAiC;AACrG,SAAS,kCAAkC;AAC3C,SAAS,oBAAoB;AAC7B,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,SAAS;AAClB,SAAS,WAAW;AAEpB,SAAS,wBAAwB,yBAAyB,iCAAiC;AAC3F,SAAS,2CAA2C;AACpD,SAAS,yBAAyB,6BAA6B,6BAA6B;AAC5F,SAAS,YAAY,2BAA2B;AAChD,SAAS,gCAAgC;AACzC,SAAS,4BAA4B;AACrC,SAAS,4BAA4B;A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ACF;AAAA,IACA,QAAQ;AAAA,MACN,SAAS;AAAA,MACT,aAAa;AAAA,MACb,OAAO;AAAA,MACP,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,sBAAsB,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,IAAI,EAAE,CAAC,EAAE;AAAA,QAC5F,EAAE,QAAQ,KAAK,aAAa,wBAAwB,QAAQ,YAAY;AAAA,MAC1E;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,iCAAiC,QAAQ,YAAY;AAAA,QACjF,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,YAAY;AAAA,QAChE,EAAE,QAAQ,KAAK,aAAa,8BAA8B,QAAQ,YAAY;AAAA,QAC9E,EAAE,QAAQ,KAAK,aAAa,sCAAsC,QAAQ,YAAY;AAAA,QACtF,EAAE,QAAQ,KAAK,aAAa,iCAAiC,QAAQ,YAAY;AAAA,MACnF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
4
|
+
"sourcesContent": ["import { attachmentErrorSchema } from './openapi'\nimport { withAttachmentStorageErrors } from '@open-mercato/core/modules/attachments/lib/storageErrors'\nimport { assertAttachmentStoragePartitionExists, getAttachmentStoragePolicy } from '@open-mercato/core/modules/attachments/lib/drivers/storageValidation'\nimport { LockMode } from '@mikro-orm/core'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { prepareAttachmentMutation } from '../lib/access-mutation'\nimport { throwAttachmentAccessError } from '../lib/access-errors'\nimport { createAttachmentAccessContext } from '../lib/access-runner'\nimport { assertAttachmentOwnerAccess, requiresAttachmentAccessScan, scanAuthorizedAttachments } from '../lib/access-query'\nimport { withAttachmentAccessErrors } from '../lib/access-errors'\nimport { NextResponse } from 'next/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { z } from 'zod'\nimport { sql } from 'kysely'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { buildAttachmentFileUrl, buildAttachmentImageUrl, slugifyAttachmentFileName } from '../lib/imageUrls'\nimport { ensureAttachmentPartitionProtection } from '../lib/access-protection'\nimport { ensureDefaultPartitions, resolveDefaultPartitionCode, sanitizePartitionCode } from '../lib/partitions'\nimport { Attachment, AttachmentPartition } from '../data/entities'\nimport { extractAttachmentContent } from '../lib/textExtraction'\nimport { requestOcrProcessing } from '../lib/ocrQueue'\nimport { StorageDriverFactory } from '../lib/drivers'\nimport { OcrService, shouldUseLlmOcr } from '../lib/ocrService'\nimport { clearAttachmentThumbnailCache } from '../lib/thumbnailCache'\nimport { lockAttachmentStorageReferences, resolveAttachmentStorageRelease } from '../lib/storageReferences'\nimport { assertAttachmentScopeInvariant } from '../lib/access'\nimport { resolveAttachmentRequestScope } from '../lib/requestScope'\nimport {\n mergeAttachmentMetadata,\n normalizeAttachmentAssignments,\n normalizeAttachmentTags,\n readAttachmentMetadata,\n upsertAssignment,\n type AttachmentAssignment,\n} from '../lib/metadata'\nimport { randomUUID } from 'crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { splitCustomFieldPayload } from '@open-mercato/shared/lib/crud/custom-fields'\nimport { emitCrudSideEffects, setCustomFieldsIfAny } from '@open-mercato/shared/lib/commands/helpers'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { attachmentCrudEvents, attachmentCrudIndexer } from '../lib/crud'\nimport { E } from '#generated/entities.ids.generated'\nimport { resolveDefaultAttachmentOcrEnabled } from '../lib/ocrConfig'\nimport {\n detectAttachmentMimeType,\n hasDangerousExecutableExtension,\n isActiveContentAttachment,\n sanitizeUploadedFileName,\n} from '../lib/security'\nimport {\n isMultipartUploadLimitError,\n isMultipartRequestWithinUploadLimit,\n parseMultipartFormDataWithinUploadLimit,\n resolveAttachmentMaxBytes,\n willExceedAttachmentTenantQuota,\n} from '../lib/upload-limits'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { AttachmentQuotaService } from '../lib/quota-service'\nimport { resolveAttachmentsUploadRateLimitConfig } from '../lib/ocrLimits'\nimport { checkRateLimit, RATE_LIMIT_ERROR_FALLBACK, RATE_LIMIT_ERROR_KEY } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport type { RateLimiterService } from '@open-mercato/shared/lib/ratelimit/service'\n\nconst logger = createLogger('attachments')\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['attachments.view'] },\n POST: { requireAuth: true, requireFeatures: ['attachments.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['attachments.manage'] },\n}\n\nconst ATTACHMENT_LIST_MAX_PAGE_SIZE = 100\n\nconst attachmentQuerySchema = z.object({\n entityId: z.string().min(1).describe('Entity identifier that owns the attachments'),\n recordId: z.string().min(1).describe('Record identifier within the entity'),\n page: z.coerce.number().min(1).optional(),\n pageSize: z.coerce.number().min(1).max(ATTACHMENT_LIST_MAX_PAGE_SIZE).optional(),\n})\n\nconst attachmentAssignmentSchema = z.object({\n type: z.string().describe('Assignment type identifier'),\n id: z.string().describe('Assignment record identifier'),\n href: z.string().nullable().optional().describe('Optional link to the related record'),\n label: z.string().nullable().optional().describe('Optional label for the assignment'),\n})\n\nconst attachmentItemSchema = z.object({\n id: z.string().describe('Attachment identifier'),\n url: z.string().describe('Public path to the stored asset'),\n fileName: z.string().describe('Original filename'),\n fileSize: z.number().int().nonnegative().describe('File size in bytes'),\n createdAt: z.string().describe('Upload timestamp (ISO 8601)'),\n mimeType: z.string().nullable().optional().describe('MIME type of the file'),\n thumbnailUrl: z.string().optional().describe('Helper route that renders a thumbnail'),\n partitionCode: z.string().optional().describe('Partition identifier'),\n tags: z.array(z.string()).optional().describe('Tags assigned to the attachment'),\n content: z.string().nullable().optional().describe('Extracted text or markdown content'),\n assignments: z.array(attachmentAssignmentSchema).optional().describe('Records that reference this attachment'),\n})\n\nconst attachmentListResponseSchema = z.object({\n items: z.array(attachmentItemSchema),\n total: z.number().int().nonnegative().optional(),\n page: z.number().int().min(1).optional(),\n pageSize: z.number().int().min(1).optional(),\n totalPages: z.number().int().min(1).optional(),\n})\n\nconst attachmentUploadBodySchema = z.object({\n entityId: z.string().min(1),\n recordId: z.string().min(1),\n fieldKey: z.string().optional(),\n file: z.string().min(1).describe('Binary file payload; supplied as multipart form-data'),\n customFields: z\n .string()\n .optional()\n .describe('JSON encoded map of custom field values collected from the upload form.'),\n})\n\nconst attachmentDeleteQuerySchema = z.object({\n id: z.string().uuid(),\n})\n\nconst uploadResponseSchema = z.object({\n ok: z.literal(true),\n item: z.object({\n id: z.string(),\n url: z.string(),\n fileName: z.string(),\n fileSize: z.number().int().nonnegative(),\n thumbnailUrl: z.string().optional(),\n content: z.string().nullable().optional(),\n tags: z.array(z.string()).optional(),\n assignments: z.array(attachmentAssignmentSchema).optional(),\n customFields: z.record(z.string(), z.unknown()).optional(),\n }),\n})\n\nconst errorSchema = z.object({\n error: z.string(),\n})\n\nconst LIBRARY_ENTITY_ID = 'attachments:library'\n\nfunction parseCustomFieldsEntry(value: FormDataEntryValue | null): Record<string, unknown> {\n if (!value) return {}\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed) return {}\n try {\n const parsed = JSON.parse(trimmed)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>\n }\n } catch {\n return {}\n }\n }\n if (typeof value === 'object' && !Array.isArray(value) && !(value instanceof File)) {\n return { ...(value as Record<string, unknown>) }\n }\n return {}\n}\n\nfunction buildFormPayload(form: FormData): Record<string, unknown> {\n const payload: Record<string, unknown> = {}\n form.forEach((value, key) => {\n if (key === 'customFields') {\n payload.customFields = parseCustomFieldsEntry(value)\n return\n }\n payload[key] = value\n })\n return payload\n}\n\nfunction parseFormTags(value: FormDataEntryValue | null): string[] {\n if (!value) return []\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed) return []\n try {\n const parsed = JSON.parse(trimmed)\n return normalizeAttachmentTags(parsed)\n } catch {\n return normalizeAttachmentTags(value)\n }\n }\n return []\n}\n\nfunction parseFormAssignments(value: FormDataEntryValue | null): AttachmentAssignment[] {\n if (!value) return []\n if (typeof value !== 'string') return []\n const trimmed = value.trim()\n if (!trimmed) return []\n try {\n const parsed = JSON.parse(trimmed)\n return normalizeAttachmentAssignments(parsed)\n } catch {\n return []\n }\n}\n\nasync function listRecordAttachments(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId || (!auth.orgId && !auth.isSuperAdmin)) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const url = new URL(req.url)\n const parsedQuery = attachmentQuerySchema.safeParse({\n entityId: url.searchParams.get('entityId') || '',\n recordId: url.searchParams.get('recordId') || '',\n page: url.searchParams.get('page') ?? undefined,\n pageSize: url.searchParams.get('pageSize') ?? undefined,\n })\n if (!parsedQuery.success) {\n return NextResponse.json({ error: 'entityId and recordId are required' }, { status: 400 })\n }\n const { entityId, recordId, page, pageSize } = parsedQuery.data\n\n const container = await createRequestContainer()\n const em = container.resolve('em') as EntityManager\n const requestScope = await resolveAttachmentRequestScope(container, auth, req)\n if (requestScope.denied) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })\n const orgId = requestScope.organizationId\n const filter: Record<string, unknown> = { entityId, recordId, tenantId: auth.tenantId! }\n if (orgId) filter.organizationId = orgId\n const orderBy: Record<string, 'ASC' | 'DESC'> = { createdAt: 'DESC', id: 'DESC' }\n const usePaging = typeof page === 'number' && typeof pageSize === 'number'\n const currentPage = usePaging ? Math.max(1, page) : null\n const currentPageSize = usePaging ? pageSize : null\n const pageOffset = usePaging ? (currentPage! - 1) * currentPageSize! : undefined\n const partitions = await em.find(AttachmentPartition, {})\n const protectedScan = requiresAttachmentAccessScan(partitions)\n const scope = { tenantId: auth.tenantId ?? null, organizationId: orgId ?? null }\n let items: Attachment[]\n let total: number | null\n if (protectedScan) {\n const scanned = await scanAuthorizedAttachments({\n auth: { ...auth, orgId }, context: createAttachmentAccessContext(container), partitions,\n offset: pageOffset, limit: currentPageSize ?? ATTACHMENT_LIST_MAX_PAGE_SIZE,\n loadBatch: (offset, limit) => findWithDecryption(em, Attachment, filter, { orderBy, offset, limit }, scope),\n })\n items = scanned.records\n total = usePaging ? scanned.total : null\n } else {\n total = usePaging ? await em.count(Attachment, filter) : null\n items = await findWithDecryption(em, Attachment, filter, {\n orderBy, ...(usePaging ? { limit: currentPageSize!, offset: pageOffset } : { limit: ATTACHMENT_LIST_MAX_PAGE_SIZE }),\n }, scope)\n }\n const totalPages = usePaging && total !== null ? Math.max(1, Math.ceil(total / currentPageSize!)) : null\n return NextResponse.json({\n items: items.map((a: any) => {\n const metadata = readAttachmentMetadata(a.storageMetadata)\n return {\n id: a.id,\n url: a.url,\n fileName: a.fileName,\n fileSize: a.fileSize,\n createdAt: a.createdAt,\n mimeType: a.mimeType ?? null,\n partitionCode: a.partitionCode,\n content: a.content ?? null,\n thumbnailUrl: buildAttachmentImageUrl(a.id, {\n width: 320,\n height: 320,\n slug: slugifyAttachmentFileName(a.fileName),\n }),\n tags: metadata.tags ?? [],\n assignments: metadata.assignments ?? [],\n }\n }),\n ...(usePaging\n ? {\n total,\n page: currentPage,\n pageSize: currentPageSize,\n totalPages,\n }\n : {}),\n }, { headers: protectedScan ? { 'Cache-Control': 'private, no-store' } : undefined })\n}\n\nexport const GET = withAttachmentAccessErrors(listRecordAttachments)\n\nasync function uploadAttachment(req: Request) {\n const { t } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId || (!auth.orgId && !auth.isSuperAdmin)) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n // A superadmin browsing with \"All organizations\" selected has no concrete\n // organization scope, but an attachment must be stored under exactly one\n // organization (the scope invariant forbids partial-null rows). Reject with a\n // clear, actionable error instead of a 401 \u2014 a 401 makes the client-side\n // fetch layer treat it as session expiry, show a misleading toast, and reset\n // the in-progress form (#3764).\n if (!auth.orgId) {\n return NextResponse.json({\n error: t('attachments.errors.selectOrganization', 'Select a specific organization before uploading an attachment.'),\n }, { status: 400 })\n }\n const tenantId = auth.tenantId\n\n const container = await createRequestContainer()\n let rateLimiterService: RateLimiterService | null = null\n try {\n rateLimiterService = container.resolve('rateLimiterService') as RateLimiterService | null\n } catch (error) {\n // Fail-open: uploads proceed when the limiter cannot be resolved (minimal/test containers).\n logger.warn('Attachment upload rate limiter unavailable; throttle skipped', { err: error })\n }\n if (rateLimiterService) {\n const principal = typeof auth.sub === 'string' && auth.sub.length > 0\n ? auth.sub\n : (typeof auth.userId === 'string' && auth.userId.length > 0 ? auth.userId : null)\n if (!principal) {\n logger.warn('Attachment upload rate limit skipped: missing authenticated principal')\n } else {\n const rateLimitResponse = await checkRateLimit(\n rateLimiterService,\n resolveAttachmentsUploadRateLimitConfig(),\n `${tenantId}:${principal}`,\n t(RATE_LIMIT_ERROR_KEY, RATE_LIMIT_ERROR_FALLBACK),\n )\n if (rateLimitResponse) return rateLimitResponse\n }\n } else {\n logger.warn('Attachment upload rate limiter not registered; throttle skipped')\n }\n\n const contentType = req.headers.get('content-type') || ''\n if (!contentType.toLowerCase().includes('multipart/form-data')) {\n return NextResponse.json({ error: 'Expected multipart/form-data' }, { status: 400 })\n }\n if (!isMultipartRequestWithinUploadLimit(req.headers.get('content-length'))) {\n return NextResponse.json({\n error: t('attachments.errors.maxUploadSize', 'Attachment exceeds the maximum upload size.'),\n }, { status: 413 })\n }\n\n let form: FormData\n try {\n form = await parseMultipartFormDataWithinUploadLimit(req)\n } catch (error) {\n if (isMultipartUploadLimitError(error)) {\n return NextResponse.json({\n error: t('attachments.errors.maxUploadSize', 'Attachment exceeds the maximum upload size.'),\n }, { status: 413 })\n }\n throw error\n }\n const formPayload = buildFormPayload(form)\n const customFieldValues = splitCustomFieldPayload(formPayload).custom\n const entityId = String(form.get('entityId') || '')\n const recordId = String(form.get('recordId') || '')\n const fieldKey = String(form.get('fieldKey') || '')\n const file = form.get('file') as unknown as File | null\n if (!entityId || !recordId || !file) return NextResponse.json({ error: 'entityId, recordId and file are required' }, { status: 400 })\n const partitionOverrideRaw = form.get('partitionCode')\n const partitionOverride =\n typeof partitionOverrideRaw === 'string' && partitionOverrideRaw.trim().length > 0\n ? sanitizePartitionCode(partitionOverrideRaw)\n : null\n const tags = parseFormTags(form.get('tags'))\n const assignmentsFromForm = parseFormAssignments(form.get('assignments'))\n\n const em = container.resolve('em') as EntityManager\n const dataEngine = container.resolve('dataEngine')\n let attachmentQuotaService: AttachmentQuotaService | null = null\n let attachmentQuotaRecoveryScheduler: ((\n payload: { reservationId: string; tenantId: string; organizationId: string },\n delayMs: number,\n ) => Promise<void>) | null = null\n try {\n attachmentQuotaService = container.resolve('attachmentQuotaService') as AttachmentQuotaService\n attachmentQuotaRecoveryScheduler = container.resolve('attachmentQuotaRecoveryScheduler') as (\n payload: { reservationId: string; tenantId: string; organizationId: string },\n delayMs: number,\n ) => Promise<void>\n } catch {\n // Legacy fallback below when the quota service is not registered in this container.\n }\n const storageDriverFactory =\n (container.resolve('storageDriverFactory') as StorageDriverFactory | null) ?? new StorageDriverFactory(em)\n const uploadScope = await resolveAttachmentRequestScope(container, auth, req)\n if (uploadScope.denied) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })\n const orgId = uploadScope.organizationId\n if (!orgId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n if (getAttachmentStoragePolicy() === 'legacy') await ensureDefaultPartitions(em)\n // Optional per-field validations\n let partitionFromField: string | null = null\n let fieldMaxAttachmentSizeMb: number | null = null\n if (fieldKey) {\n try {\n const { CustomFieldDef } = await import('@open-mercato/core/modules/entities/data/entities')\n const def = await em.findOne(CustomFieldDef, {\n entityId,\n key: fieldKey,\n $and: [\n { $or: [ { tenantId: auth.tenantId }, { tenantId: null } ] },\n ],\n isActive: true,\n })\n const cfg = (def as any)?.configJson || {}\n const ext = (file.name || '').split('.').pop()?.toLowerCase() || ''\n if (Array.isArray(cfg.acceptExtensions) && cfg.acceptExtensions.length) {\n const allowed = new Set((cfg.acceptExtensions as any[]).map((x: any) => String(x).toLowerCase().replace(/^\\./, '')))\n if (!allowed.has(ext)) return NextResponse.json({ error: 'File type not allowed' }, { status: 400 })\n }\n if (typeof cfg.maxAttachmentSizeMb === 'number' && cfg.maxAttachmentSizeMb > 0) {\n fieldMaxAttachmentSizeMb = cfg.maxAttachmentSizeMb\n }\n if (typeof cfg.partitionCode === 'string' && cfg.partitionCode.trim().length > 0) {\n partitionFromField = sanitizePartitionCode(cfg.partitionCode)\n }\n } catch {}\n }\n if (hasDangerousExecutableExtension(file.name)) {\n return NextResponse.json({\n error: t('attachments.errors.dangerousExecutable', 'Executable file types are not allowed as attachments.'),\n }, { status: 400 })\n }\n const effectiveMaxBytes = resolveAttachmentMaxBytes(fieldMaxAttachmentSizeMb)\n if (file.size > effectiveMaxBytes) {\n return NextResponse.json({\n error: t('attachments.errors.maxUploadSize', 'Attachment exceeds the maximum upload size.'),\n }, { status: 413 })\n }\n if (!attachmentQuotaService) {\n try {\n const tenantUsageBytes = await readTenantAttachmentUsageBytes(em, tenantId)\n if (willExceedAttachmentTenantQuota(tenantUsageBytes, file.size)) {\n return NextResponse.json({\n error: t('attachments.errors.quotaExceeded', 'Attachment storage quota exceeded for this tenant.'),\n }, { status: 413 })\n }\n } catch (error) {\n logger.error('Attachment quota accounting failed', { err: error })\n return NextResponse.json({\n error: t('attachments.errors.quotaUnavailable', 'Storage quota accounting is unavailable.'),\n }, { status: 500 })\n }\n }\n const buf = Buffer.from(await file.arrayBuffer())\n const safeName = sanitizeUploadedFileName(file.name)\n const fileMimeType = detectAttachmentMimeType(buf, safeName, (file as any).type)\n if (isActiveContentAttachment(buf, safeName, fileMimeType)) {\n return NextResponse.json({ error: t('attachments.errors.activeContentBlocked', 'Active content uploads are not allowed.') }, { status: 400 })\n }\n const defaultPartitionCode = resolveDefaultPartitionCode(entityId)\n const resolvedPartitionCode = partitionOverride ?? partitionFromField ?? defaultPartitionCode\n const partitionCodeCandidates = Array.from(\n new Set(\n [partitionOverride, partitionFromField, resolvedPartitionCode].filter(\n (code): code is string => typeof code === 'string' && code.length > 0,\n ),\n ),\n )\n let partition: AttachmentPartition | null = null\n for (const code of partitionCodeCandidates) {\n const record = await em.findOne(AttachmentPartition, { code })\n assertAttachmentStoragePartitionExists(Boolean(record))\n if (record) {\n partition = record\n break\n }\n }\n if (!partition) {\n partition = await em.findOne(AttachmentPartition, { code: defaultPartitionCode })\n }\n if (!partition) {\n assertAttachmentStoragePartitionExists(false)\n return NextResponse.json({ error: 'Storage partition is not configured.' }, { status: 400 })\n }\n await ensureAttachmentPartitionProtection(em, partition)\n const requestedPublicOverride =\n typeof partitionOverride === 'string' &&\n partitionOverride.length > 0 &&\n partition.code === partitionOverride &&\n partition.isPublic === true &&\n partition.code !== defaultPartitionCode &&\n partition.code !== partitionFromField\n if (requestedPublicOverride) {\n return NextResponse.json({ error: t('attachments.errors.publicPartitionBlocked', 'Public storage partitions cannot be selected explicitly for this upload.') }, { status: 403 })\n }\n const uploadDriver = await storageDriverFactory.resolveForPartition(partition.code, { tenantId, organizationId: orgId })\n const preparedStoragePath = attachmentQuotaService\n ? uploadDriver.prepareStoragePath?.({\n partitionCode: partition.code,\n orgId,\n tenantId,\n fileName: safeName,\n })\n : undefined\n if (attachmentQuotaService && !preparedStoragePath) {\n return NextResponse.json({\n error: t('attachments.errors.quotaRecoveryUnsupported', 'Storage driver cannot participate in quota recovery.'),\n }, { status: 500 })\n }\n let quotaReservation: { id: string; leaseToken: string; expiresAt: Date } | null = null\n if (attachmentQuotaService) {\n try {\n quotaReservation = await attachmentQuotaService.reserve({\n tenantId,\n organizationId: orgId,\n bytes: buf.length,\n source: 'attachment',\n storageDriver: uploadDriver.key,\n storagePath: preparedStoragePath!,\n partitionCode: partition.code,\n })\n if (!attachmentQuotaRecoveryScheduler) throw new Error('Attachment quota recovery is unavailable.')\n await attachmentQuotaRecoveryScheduler({\n reservationId: quotaReservation.id,\n tenantId,\n organizationId: orgId,\n }, Math.max(1_000, quotaReservation.expiresAt.getTime() - Date.now()))\n if (typeof attachmentQuotaService.beginStorage === 'function') {\n await attachmentQuotaService.beginStorage(quotaReservation.id, quotaReservation.leaseToken)\n }\n } catch (error) {\n if (quotaReservation) {\n await attachmentQuotaService.release(quotaReservation.id, quotaReservation.leaseToken).catch(() => {})\n quotaReservation = null\n }\n const code = (error as { code?: unknown })?.code\n if (code === 'quota_exceeded') {\n return NextResponse.json({\n error: t('attachments.errors.quotaExceeded', 'Attachment storage quota exceeded for this tenant.'),\n }, { status: 413 })\n }\n if (code === 'quota_target_exists') {\n return NextResponse.json({\n error: t('attachments.errors.storagePathExists', 'The target storage path already exists.'),\n }, { status: 409 })\n }\n logger.error('Attachment quota reservation failed', { err: error })\n return NextResponse.json({\n error: t('attachments.errors.quotaUnavailable', 'Storage quota accounting is unavailable.'),\n }, { status: 500 })\n }\n }\n let storedPath: string\n try {\n const stored = await uploadDriver.store({\n partitionCode: partition.code,\n orgId,\n tenantId,\n fileName: safeName,\n buffer: buf,\n storagePath: preparedStoragePath,\n })\n storedPath = stored.storagePath\n if (quotaReservation) {\n await attachmentQuotaService!.markStored(quotaReservation.id, quotaReservation.leaseToken)\n }\n } catch (error) {\n logger.error('Failed to persist file', { err: error })\n if (preparedStoragePath) {\n try {\n await (uploadDriver.deleteStrict?.(partition.code, preparedStoragePath)\n ?? uploadDriver.delete(partition.code, preparedStoragePath))\n if (quotaReservation) {\n await attachmentQuotaService!.release(quotaReservation.id, quotaReservation.leaseToken)\n }\n } catch (cleanupError) {\n logger.error('Failed to compensate attachment storage', { err: cleanupError })\n }\n }\n return NextResponse.json({ error: 'Failed to persist attachment.' }, { status: 500 })\n }\n\n const requiresOcr =\n typeof (partition as any).requiresOcr === 'boolean'\n ? Boolean((partition as any).requiresOcr)\n : resolveDefaultAttachmentOcrEnabled()\n let extractedContent: string | null = null\n const wantsLlmOcr = requiresOcr && shouldUseLlmOcr(fileMimeType, safeName)\n const ocrService = wantsLlmOcr ? new OcrService() : null\n const useLlmOcr = Boolean(wantsLlmOcr && ocrService?.available)\n\n if (requiresOcr && !useLlmOcr) {\n const { filePath: localPath, cleanup } = await uploadDriver.toLocalPath(partition.code, storedPath)\n try {\n extractedContent = await extractAttachmentContent({\n filePath: localPath,\n mimeType: fileMimeType,\n })\n } catch (error) {\n logger.error('Failed to extract attachment content', { err: error })\n } finally {\n await cleanup().catch(() => {})\n }\n }\n\n let assignments = assignmentsFromForm.slice()\n if (entityId !== LIBRARY_ENTITY_ID) {\n assignments = upsertAssignment(assignments, { type: entityId, id: recordId })\n }\n const metadata = mergeAttachmentMetadata(null, { assignments, tags })\n const attachmentId = randomUUID()\n assertAttachmentScopeInvariant({ tenantId: auth.tenantId, organizationId: orgId })\n const att = em.create(Attachment, {\n id: attachmentId,\n entityId,\n recordId,\n organizationId: orgId,\n tenantId: auth.tenantId!,\n fileName: safeName,\n mimeType: fileMimeType,\n fileSize: buf.length,\n partitionCode: partition.code,\n storageDriver: partition.storageDriver || 'local',\n storagePath: storedPath,\n url: buildAttachmentFileUrl(attachmentId),\n content: extractedContent,\n storageMetadata: metadata,\n })\n // Persist the attachment row and its custom-field values atomically so a\n // custom-field failure cannot leave behind a committed orphan attachment.\n try {\n await em.transactional(async (tx) => {\n await tx.persist(att).flush()\n if (dataEngine) {\n await setCustomFieldsIfAny({\n dataEngine,\n entityId: E.attachments.attachment,\n recordId: attachmentId,\n tenantId,\n organizationId: orgId,\n values: customFieldValues,\n })\n }\n if (quotaReservation) {\n await attachmentQuotaService!.completeAttachment(quotaReservation.id, quotaReservation.leaseToken, tx)\n }\n })\n } catch (error) {\n logger.error('Failed to persist attachment with custom attributes', { err: error })\n try {\n await (uploadDriver.deleteStrict?.(partition.code, storedPath)\n ?? uploadDriver.delete(partition.code, storedPath))\n if (quotaReservation) {\n await attachmentQuotaService!.release(quotaReservation.id, quotaReservation.leaseToken)\n }\n } catch (cleanupError) {\n logger.error('Failed to compensate attachment persistence', { err: cleanupError })\n }\n return NextResponse.json({ error: 'Failed to save attachment attributes.' }, { status: 500 })\n }\n\n if (useLlmOcr) {\n // Await so wait-queue overflow can finish the inline text fallback before\n // the response returns (background LLM OCR still schedules via setImmediate).\n try {\n await requestOcrProcessing(em, att, uploadDriver, storedPath)\n } catch (error) {\n logger.error('Failed to queue OCR processing', { err: error })\n }\n } else if (wantsLlmOcr) {\n logger.warn('OCR requested but OPENAI_API_KEY not configured, falling back to text extraction when available')\n }\n\n if (dataEngine) {\n await emitCrudSideEffects({\n dataEngine,\n action: 'created',\n entity: att,\n identifiers: {\n id: att.id,\n organizationId: att.organizationId ?? null,\n tenantId: att.tenantId ?? null,\n },\n events: attachmentCrudEvents,\n indexer: attachmentCrudIndexer,\n })\n await dataEngine.flushOrmEntityChanges()\n }\n\n return NextResponse.json({\n ok: true,\n item: {\n id: attachmentId,\n url: att.url,\n fileName: safeName,\n fileSize: buf.length,\n partitionCode: partition.code,\n thumbnailUrl: buildAttachmentImageUrl(attachmentId, {\n width: 320,\n height: 320,\n slug: slugifyAttachmentFileName(safeName),\n }),\n content: extractedContent ?? null,\n tags: metadata.tags ?? [],\n assignments: metadata.assignments ?? [],\n customFields: Object.keys(customFieldValues).length ? customFieldValues : undefined,\n },\n })\n}\n\nasync function readTenantAttachmentUsageBytes(em: EntityManager, tenantId: string): Promise<number> {\n try {\n const db = em.getKysely<any>() as any\n const row = await db\n .selectFrom('attachments')\n .select(sql<string>`sum(file_size)`.as('total_size'))\n .where('tenant_id', '=', tenantId)\n .executeTakeFirst() as { total_size: string | number | null } | undefined\n const total = row?.total_size\n if (typeof total === 'number') return Number.isFinite(total) ? total : 0\n if (typeof total === 'string') {\n const parsed = Number(total)\n return Number.isFinite(parsed) ? parsed : 0\n }\n return 0\n } catch (error) {\n throw new Error('Attachment quota accounting is unavailable.', { cause: error })\n }\n}\n\nasync function deleteAttachment(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId || (!auth.orgId && !auth.isSuperAdmin)) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const url = new URL(req.url)\n const id = url.searchParams.get('id') || ''\n if (!id) return NextResponse.json({ error: 'Attachment id is required' }, { status: 400 })\n const container = await createRequestContainer()\n const em = container.resolve('em') as EntityManager\n const dataEngine = container.resolve('dataEngine')\n const storageDriverFactory =\n (container.resolve('storageDriverFactory') as StorageDriverFactory | null) ?? new StorageDriverFactory(em)\n // Resolve the currently selected organization (#3765) so a multi-org admin who\n // switched the header org deletes within that org, not their pinned home org.\n // A superadmin browsing with \"All organizations\" selected has no concrete org,\n // so resolution returns null and the delete falls back to a tenant-only scope\n // (#3764) \u2014 letting them remove any attachment in the tenant.\n const deleteScope = await resolveAttachmentRequestScope(container, auth, req)\n if (deleteScope.denied) return NextResponse.json({ error: 'Attachment not found' }, { status: 404 })\n const orgId = deleteScope.organizationId\n const deleteFilter: Record<string, unknown> = { id, tenantId: auth.tenantId! }\n if (orgId) deleteFilter.organizationId = orgId\n const scopedAuth = { ...auth, orgId }\n const outcome = await em.transactional(async (tx) => {\n const candidate = await findOneWithDecryption(tx, Attachment, deleteFilter, undefined, {\n tenantId: auth.tenantId, organizationId: orgId,\n })\n if (!candidate) return throwAttachmentAccessError(404)\n const referenceIds = await lockAttachmentStorageReferences(tx, candidate)\n const removal = resolveAttachmentStorageRelease(referenceIds, candidate.id)\n if (!removal.removed) return throwAttachmentAccessError(404)\n const record = await findOneWithDecryption(tx, Attachment, deleteFilter, {\n lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true,\n }, { tenantId: auth.tenantId, organizationId: orgId })\n if (!record) return throwAttachmentAccessError(404)\n const guard = await prepareAttachmentMutation({ container, req, auth: scopedAuth, recordId: record.id, operation: 'delete' })\n await assertAttachmentOwnerAccess({ em: tx, context: createAttachmentAccessContext(container), auth: scopedAuth, attachment: record, action: 'delete' })\n const driver = record.storagePath ? await storageDriverFactory.resolveForPartition(record.partitionCode, {\n tenantId: record.tenantId ?? auth.tenantId!, organizationId: record.organizationId ?? orgId ?? '',\n }) : null\n tx.remove(record)\n await tx.flush()\n return { record, driver, guard, releaseStorage: removal.releaseStorage }\n })\n const { record } = outcome\n await clearAttachmentThumbnailCache(record.partitionCode, record.id).catch((error) => {\n logger.error('Failed to cleanup cached thumbnails', { err: error })\n })\n if (outcome.driver && outcome.releaseStorage) await outcome.driver.delete(record.partitionCode, record.storagePath)\n await outcome.guard.runAfterSuccess()\n if (dataEngine) {\n await emitCrudSideEffects({\n dataEngine,\n action: 'deleted',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId ?? null,\n tenantId: record.tenantId ?? null,\n },\n events: attachmentCrudEvents,\n indexer: attachmentCrudIndexer,\n })\n await dataEngine.flushOrmEntityChanges()\n }\n return NextResponse.json({ ok: true })\n}\n\nexport const POST = withAttachmentAccessErrors(withAttachmentStorageErrors(uploadAttachment))\nexport const DELETE = withAttachmentAccessErrors(withAttachmentStorageErrors(deleteAttachment))\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Manage entity attachments',\n description: 'Upload and list attachments associated with module entities and records.',\n methods: {\n GET: {\n summary: 'List attachments for a record',\n description: 'Returns uploaded attachments for the given entity record, ordered by newest first. Without both page and pageSize, only the newest 100 attachments are returned; pass page and pageSize to page through the rest.',\n query: attachmentQuerySchema,\n responses: [\n { status: 200, description: 'Attachments found for the record', schema: attachmentListResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Missing entity or record identifiers', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 403, description: 'Owner policy denies access', schema: errorSchema },\n { status: 404, description: 'Attachment or owner is unavailable', schema: errorSchema },\n { status: 504, description: 'Owner authorization timed out', schema: errorSchema },\n ],\n },\n POST: {\n summary: 'Upload attachment',\n description: 'Uploads a new attachment using multipart form-data and stores metadata for later retrieval.',\n requestBody: {\n contentType: 'multipart/form-data',\n schema: attachmentUploadBodySchema,\n },\n responses: [\n { status: 200, description: 'Attachment stored successfully', schema: uploadResponseSchema },\n ],\n errors: [\n { status: 503, description: 'Attachment storage configuration rejected by policy', schema: attachmentErrorSchema },\n { status: 400, description: 'Payload validation error', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 403, description: 'Attachment violates field constraints', schema: errorSchema },\n ],\n },\n DELETE: {\n summary: 'Delete attachment',\n description: 'Removes an uploaded attachment and deletes the stored asset.',\n query: attachmentDeleteQuerySchema,\n responses: [\n { status: 200, description: 'Attachment deleted', schema: z.object({ ok: z.literal(true) }) },\n { status: 404, description: 'Attachment not found', schema: errorSchema },\n ],\n errors: [\n { status: 503, description: 'Attachment storage configuration rejected by policy', schema: attachmentErrorSchema },\n { status: 400, description: 'Missing attachment identifier', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 403, description: 'Owner policy denies access', schema: errorSchema },\n { status: 404, description: 'Attachment or owner is unavailable', schema: errorSchema },\n { status: 504, description: 'Owner authorization timed out', schema: errorSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,6BAA6B;AACtC,SAAS,mCAAmC;AAC5C,SAAS,wCAAwC,kCAAkC;AACnF,SAAS,gBAAgB;AACzB,SAAS,6BAA6B;AACtC,SAAS,iCAAiC;AAC1C,SAAS,kCAAkC;AAC3C,SAAS,qCAAqC;AAC9C,SAAS,6BAA6B,8BAA8B,iCAAiC;AACrG,SAAS,kCAAkC;AAC3C,SAAS,oBAAoB;AAC7B,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,SAAS;AAClB,SAAS,WAAW;AAEpB,SAAS,wBAAwB,yBAAyB,iCAAiC;AAC3F,SAAS,2CAA2C;AACpD,SAAS,yBAAyB,6BAA6B,6BAA6B;AAC5F,SAAS,YAAY,2BAA2B;AAChD,SAAS,gCAAgC;AACzC,SAAS,4BAA4B;AACrC,SAAS,4BAA4B;AACrC,SAAS,YAAY,uBAAuB;AAC5C,SAAS,qCAAqC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a,4BAA4B,QAAQ,YAAY;AAAA,QAC5E,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,YAAY;AAAA,QAChE,EAAE,QAAQ,KAAK,aAAa,yCAAyC,QAAQ,YAAY;AAAA,MAC3F;AAAA,IACF;AAAA,IACA,QAAQ;AAAA,MACN,SAAS;AAAA,MACT,aAAa;AAAA,MACb,OAAO;AAAA,MACP,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,sBAAsB,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,IAAI,EAAE,CAAC,EAAE;AAAA,QAC5F,EAAE,QAAQ,KAAK,aAAa,wBAAwB,QAAQ,YAAY;AAAA,MAC1E;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,uDAAuD,QAAQ,sBAAsB;AAAA,QACjH,EAAE,QAAQ,KAAK,aAAa,iCAAiC,QAAQ,YAAY;AAAA,QACjF,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,YAAY;AAAA,QAChE,EAAE,QAAQ,KAAK,aAAa,8BAA8B,QAAQ,YAAY;AAAA,QAC9E,EAAE,QAAQ,KAAK,aAAa,sCAAsC,QAAQ,YAAY;AAAA,QACtF,EAAE,QAAQ,KAAK,aAAa,iCAAiC,QAAQ,YAAY;AAAA,MACnF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": ["metadata", "record"]
|
|
7
7
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
|
|
2
2
|
import { Attachment } from "./data/entities.js";
|
|
3
|
+
import { isAttachmentStorageConfigurationError } from "./lib/drivers/storageValidation.js";
|
|
3
4
|
import { removeAttachmentRecord } from "./lib/storageReferences.js";
|
|
4
5
|
function parseArgs(rest) {
|
|
5
6
|
const args = {};
|
|
@@ -70,6 +71,7 @@ const deleteAttachments = {
|
|
|
70
71
|
console.log(`Not found: ${missing.join(", ")}`);
|
|
71
72
|
}
|
|
72
73
|
} catch (err) {
|
|
74
|
+
if (isAttachmentStorageConfigurationError(err)) throw err;
|
|
73
75
|
console.error("[attachments] delete command failed:", err);
|
|
74
76
|
}
|
|
75
77
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/modules/attachments/cli.ts"],
|
|
4
|
-
"sourcesContent": ["import type { ModuleCli } from '@open-mercato/shared/modules/registry'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { Attachment } from './data/entities'\nimport type { StorageDriverFactory } from './lib/drivers'\nimport { removeAttachmentRecord } from './lib/storageReferences'\n\ntype ParsedArgs = Record<string, string | boolean>\n\nfunction parseArgs(rest: string[]): ParsedArgs {\n const args: ParsedArgs = {}\n for (let i = 0; i < rest.length; i += 1) {\n const part = rest[i]\n if (!part || !part.startsWith('--')) continue\n const [rawKey, rawValue] = part.replace(/^--/, '').split('=')\n const key = rawKey.trim()\n if (!key) continue\n if (rawValue !== undefined) {\n args[key] = rawValue\n continue\n }\n const next = rest[i + 1]\n if (next && !next.startsWith('--')) {\n args[key] = next\n i += 1\n } else {\n args[key] = true\n }\n }\n return args\n}\n\nfunction coerceIdList(value?: string | boolean): string[] {\n if (typeof value !== 'string') return []\n return value\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0)\n}\n\nconst deleteAttachments: ModuleCli = {\n command: 'delete',\n async run(rest) {\n const args = parseArgs(rest)\n const ids = new Set<string>()\n coerceIdList(args.id).forEach((id) => ids.add(id))\n coerceIdList(args.ids).forEach((id) => ids.add(id))\n\n if (ids.size === 0) {\n console.error('Usage: mercato attachments delete --id <attachmentId> [--ids id1,id2] [--org <organizationId>] [--tenant <tenantId>]')\n return\n }\n const organizationId =\n typeof args.org === 'string'\n ? args.org\n : typeof args.organizationId === 'string'\n ? args.organizationId\n : undefined\n const tenantId =\n typeof args.tenant === 'string'\n ? args.tenant\n : typeof args.tenantId === 'string'\n ? args.tenantId\n : undefined\n\n try {\n const container = await createRequestContainer()\n const em = container.resolve<EntityManager>('em')\n const storageDriverFactory = container.resolve<StorageDriverFactory>('storageDriverFactory')\n const idList = Array.from(ids)\n const where: Record<string, unknown> = { id: { $in: idList } }\n if (organizationId) where.organizationId = organizationId\n if (tenantId) where.tenantId = tenantId\n const attachments = await em.find(Attachment, where)\n if (!attachments.length) {\n console.log('No attachments matched the provided filters.')\n return\n }\n const removedIds = new Set<string>()\n for (const entry of attachments) {\n const driver = await storageDriverFactory.resolveForPartition(entry.partitionCode, {\n tenantId: entry.tenantId ?? '',\n organizationId: entry.organizationId ?? '',\n })\n const removal = await removeAttachmentRecord(em, entry)\n if (!removal.removed) continue\n if (removal.releaseStorage) await driver.delete(entry.partitionCode, entry.storagePath)\n removedIds.add(entry.id)\n console.log(`Deleted attachment ${entry.id}${entry.fileName ? ` (${entry.fileName})` : ''}`)\n }\n const missing = idList.filter((id) => !removedIds.has(id))\n if (missing.length > 0) {\n console.log(`Not found: ${missing.join(', ')}`)\n }\n } catch (err) {\n console.error('[attachments] delete command failed:', err)\n }\n },\n}\n\nexport default [deleteAttachments]\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,8BAA8B;AAEvC,SAAS,kBAAkB;AAE3B,SAAS,8BAA8B;AAIvC,SAAS,UAAU,MAA4B;AAC7C,QAAM,OAAmB,CAAC;AAC1B,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK,GAAG;AACvC,UAAM,OAAO,KAAK,CAAC;AACnB,QAAI,CAAC,QAAQ,CAAC,KAAK,WAAW,IAAI,EAAG;AACrC,UAAM,CAAC,QAAQ,QAAQ,IAAI,KAAK,QAAQ,OAAO,EAAE,EAAE,MAAM,GAAG;AAC5D,UAAM,MAAM,OAAO,KAAK;AACxB,QAAI,CAAC,IAAK;AACV,QAAI,aAAa,QAAW;AAC1B,WAAK,GAAG,IAAI;AACZ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,MAAM,GAAG,KAAK,YAAY,KAAK;AACnD,UAAI,CAAC,YAAY,QAAQ;AACvB,gBAAQ,IAAI,8CAA8C;AAC1D;AAAA,MACF;AACA,YAAM,aAAa,oBAAI,IAAY;AACnC,iBAAW,SAAS,aAAa;AAC/B,cAAM,SAAS,MAAM,qBAAqB,oBAAoB,MAAM,eAAe;AAAA,UACjF,UAAU,MAAM,YAAY;AAAA,UAC5B,gBAAgB,MAAM,kBAAkB;AAAA,QAC1C,CAAC;AACD,cAAM,UAAU,MAAM,uBAAuB,IAAI,KAAK;AACtD,YAAI,CAAC,QAAQ,QAAS;AACtB,YAAI,QAAQ,eAAgB,OAAM,OAAO,OAAO,MAAM,eAAe,MAAM,WAAW;AACtF,mBAAW,IAAI,MAAM,EAAE;AACvB,gBAAQ,IAAI,sBAAsB,MAAM,EAAE,GAAG,MAAM,WAAW,KAAK,MAAM,QAAQ,MAAM,EAAE,EAAE;AAAA,MAC7F;AACA,YAAM,UAAU,OAAO,OAAO,CAAC,OAAO,CAAC,WAAW,IAAI,EAAE,CAAC;AACzD,UAAI,QAAQ,SAAS,GAAG;AACtB,gBAAQ,IAAI,cAAc,QAAQ,KAAK,IAAI,CAAC,EAAE;AAAA,MAChD;AAAA,IACF,SAAS,KAAK;AACZ,cAAQ,MAAM,wCAAwC,GAAG;AAAA,IAC3D;AAAA,EACF;AACF;AAEA,IAAO,cAAQ,CAAC,iBAAiB;",
|
|
4
|
+
"sourcesContent": ["import type { ModuleCli } from '@open-mercato/shared/modules/registry'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { Attachment } from './data/entities'\nimport type { StorageDriverFactory } from './lib/drivers'\nimport { isAttachmentStorageConfigurationError } from './lib/drivers/storageValidation'\nimport { removeAttachmentRecord } from './lib/storageReferences'\n\ntype ParsedArgs = Record<string, string | boolean>\n\nfunction parseArgs(rest: string[]): ParsedArgs {\n const args: ParsedArgs = {}\n for (let i = 0; i < rest.length; i += 1) {\n const part = rest[i]\n if (!part || !part.startsWith('--')) continue\n const [rawKey, rawValue] = part.replace(/^--/, '').split('=')\n const key = rawKey.trim()\n if (!key) continue\n if (rawValue !== undefined) {\n args[key] = rawValue\n continue\n }\n const next = rest[i + 1]\n if (next && !next.startsWith('--')) {\n args[key] = next\n i += 1\n } else {\n args[key] = true\n }\n }\n return args\n}\n\nfunction coerceIdList(value?: string | boolean): string[] {\n if (typeof value !== 'string') return []\n return value\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0)\n}\n\nconst deleteAttachments: ModuleCli = {\n command: 'delete',\n async run(rest) {\n const args = parseArgs(rest)\n const ids = new Set<string>()\n coerceIdList(args.id).forEach((id) => ids.add(id))\n coerceIdList(args.ids).forEach((id) => ids.add(id))\n\n if (ids.size === 0) {\n console.error('Usage: mercato attachments delete --id <attachmentId> [--ids id1,id2] [--org <organizationId>] [--tenant <tenantId>]')\n return\n }\n const organizationId =\n typeof args.org === 'string'\n ? args.org\n : typeof args.organizationId === 'string'\n ? args.organizationId\n : undefined\n const tenantId =\n typeof args.tenant === 'string'\n ? args.tenant\n : typeof args.tenantId === 'string'\n ? args.tenantId\n : undefined\n\n try {\n const container = await createRequestContainer()\n const em = container.resolve<EntityManager>('em')\n const storageDriverFactory = container.resolve<StorageDriverFactory>('storageDriverFactory')\n const idList = Array.from(ids)\n const where: Record<string, unknown> = { id: { $in: idList } }\n if (organizationId) where.organizationId = organizationId\n if (tenantId) where.tenantId = tenantId\n const attachments = await em.find(Attachment, where)\n if (!attachments.length) {\n console.log('No attachments matched the provided filters.')\n return\n }\n const removedIds = new Set<string>()\n for (const entry of attachments) {\n const driver = await storageDriverFactory.resolveForPartition(entry.partitionCode, {\n tenantId: entry.tenantId ?? '',\n organizationId: entry.organizationId ?? '',\n })\n const removal = await removeAttachmentRecord(em, entry)\n if (!removal.removed) continue\n if (removal.releaseStorage) await driver.delete(entry.partitionCode, entry.storagePath)\n removedIds.add(entry.id)\n console.log(`Deleted attachment ${entry.id}${entry.fileName ? ` (${entry.fileName})` : ''}`)\n }\n const missing = idList.filter((id) => !removedIds.has(id))\n if (missing.length > 0) {\n console.log(`Not found: ${missing.join(', ')}`)\n }\n } catch (err) {\n if (isAttachmentStorageConfigurationError(err)) throw err\n console.error('[attachments] delete command failed:', err)\n }\n },\n}\n\nexport default [deleteAttachments]\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,8BAA8B;AAEvC,SAAS,kBAAkB;AAE3B,SAAS,6CAA6C;AACtD,SAAS,8BAA8B;AAIvC,SAAS,UAAU,MAA4B;AAC7C,QAAM,OAAmB,CAAC;AAC1B,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK,GAAG;AACvC,UAAM,OAAO,KAAK,CAAC;AACnB,QAAI,CAAC,QAAQ,CAAC,KAAK,WAAW,IAAI,EAAG;AACrC,UAAM,CAAC,QAAQ,QAAQ,IAAI,KAAK,QAAQ,OAAO,EAAE,EAAE,MAAM,GAAG;AAC5D,UAAM,MAAM,OAAO,KAAK;AACxB,QAAI,CAAC,IAAK;AACV,QAAI,aAAa,QAAW;AAC1B,WAAK,GAAG,IAAI;AACZ;AAAA,IACF;AACA,UAAM,OAAO,KAAK,IAAI,CAAC;AACvB,QAAI,QAAQ,CAAC,KAAK,WAAW,IAAI,GAAG;AAClC,WAAK,GAAG,IAAI;AACZ,WAAK;AAAA,IACP,OAAO;AACL,WAAK,GAAG,IAAI;AAAA,IACd;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,aAAa,OAAoC;AACxD,MAAI,OAAO,UAAU,SAAU,QAAO,CAAC;AACvC,SAAO,MACJ,MAAM,GAAG,EACT,IAAI,CAAC,UAAU,MAAM,KAAK,CAAC,EAC3B,OAAO,CAAC,UAAU,MAAM,SAAS,CAAC;AACvC;AAEA,MAAM,oBAA+B;AAAA,EACnC,SAAS;AAAA,EACT,MAAM,IAAI,MAAM;AACd,UAAM,OAAO,UAAU,IAAI;AAC3B,UAA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sB,MAAM,EAAE,GAAG,MAAM,WAAW,KAAK,MAAM,QAAQ,MAAM,EAAE,EAAE;AAAA,MAC7F;AACA,YAAM,UAAU,OAAO,OAAO,CAAC,OAAO,CAAC,WAAW,IAAI,EAAE,CAAC;AACzD,UAAI,QAAQ,SAAS,GAAG;AACtB,gBAAQ,IAAI,cAAc,QAAQ,KAAK,IAAI,CAAC,EAAE;AAAA,MAChD;AAAA,IACF,SAAS,KAAK;AACZ,UAAI,sCAAsC,GAAG,EAAG,OAAM;AACtD,cAAQ,MAAM,wCAAwC,GAAG;AAAA,IAC3D;AAAA,EACF;AACF;AAEA,IAAO,cAAQ,CAAC,iBAAiB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,4 +1,13 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
const attachmentStorageConfigurationSchema = z.custom((value) => {
|
|
3
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
4
|
+
const prototype = Object.getPrototypeOf(value);
|
|
5
|
+
return prototype === Object.prototype || prototype === null;
|
|
6
|
+
});
|
|
7
|
+
const attachmentStorageScopeSchema = z.object({
|
|
8
|
+
tenantId: z.string(),
|
|
9
|
+
organizationId: z.string()
|
|
10
|
+
}).refine((scope) => Boolean(scope.tenantId.trim()) === Boolean(scope.organizationId.trim()));
|
|
2
11
|
const attachmentAccessActionSchema = z.enum(["read", "render", "metadata", "reassign", "delete", "export"]);
|
|
3
12
|
const attachmentAccessSubjectFeaturesSchema = z.array(z.string());
|
|
4
13
|
const attachmentAccessSelectorSchema = z.string().min(1).max(200).regex(/^(?:\*|[^*\s]+(?:\.\*)?)$/);
|
|
@@ -36,6 +45,8 @@ export {
|
|
|
36
45
|
attachmentAccessResolverSchema,
|
|
37
46
|
attachmentAccessSelectorSchema,
|
|
38
47
|
attachmentAccessSubjectFeaturesSchema,
|
|
48
|
+
attachmentStorageConfigurationSchema,
|
|
49
|
+
attachmentStorageScopeSchema,
|
|
39
50
|
protectedAttachmentTargetSchema
|
|
40
51
|
};
|
|
41
52
|
//# sourceMappingURL=validators.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/attachments/data/validators.ts"],
|
|
4
|
-
"sourcesContent": ["import { z } from 'zod'\nimport type { AttachmentAccessResolver } from '../lib/access-types'\n\nexport const attachmentAccessActionSchema = z.enum(['read', 'render', 'metadata', 'reassign', 'delete', 'export'])\nexport const attachmentAccessSubjectFeaturesSchema = z.array(z.string())\nexport const attachmentAccessSelectorSchema = z.string().min(1).max(200).regex(/^(?:\\*|[^*\\s]+(?:\\.\\*)?)$/)\nconst resolverIdSchema = z.string().min(3).max(200).regex(/^[a-zA-Z0-9_-]+\\.[a-zA-Z0-9_.-]+$/)\n\nexport const attachmentAccessRequirementSchema = z.object({\n resolverId: resolverIdSchema,\n targetEntity: attachmentAccessSelectorSchema,\n}).strict()\n\nexport const protectedAttachmentTargetSchema = attachmentAccessRequirementSchema.extend({\n targetPartition: attachmentAccessSelectorSchema,\n})\n\nexport const attachmentAccessResolverSchema = z.object({\n id: resolverIdSchema,\n targetPartition: attachmentAccessSelectorSchema,\n targetEntity: attachmentAccessSelectorSchema.optional(),\n actions: z.array(attachmentAccessActionSchema).min(1).optional(),\n priority: z.number().finite().optional(),\n timeoutMs: z.number().int().min(1).max(15_000).optional(),\n resolve: z.custom<AttachmentAccessResolver['resolve']>((value) => typeof value === 'function'),\n}).strict()\n\nexport const attachmentAccessRequirementsSchema = z.array(attachmentAccessRequirementSchema)\nexport const attachmentAccessDecisionSchema = z.discriminatedUnion('ok', [\n z.object({ ok: z.literal(true) }).strict(),\n z.object({\n ok: z.literal(false),\n status: z.union([z.literal(401), z.literal(403), z.literal(404), z.literal(504)]),\n reason: z.string().min(1).max(200).regex(/^[a-zA-Z0-9_.:-]+$/),\n }).strict(),\n])\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,SAAS;AAGX,MA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AAC;AAAA,IAChF,QAAQ,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,MAAM,oBAAoB;AAAA,EAC/D,CAAC,EAAE,OAAO;AACZ,CAAC;",
|
|
4
|
+
"sourcesContent": ["import { z } from 'zod'\nimport type { AttachmentAccessResolver } from '../lib/access-types'\n\nexport const attachmentStorageConfigurationSchema = z.custom<Record<string, unknown>>((value) => {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false\n const prototype = Object.getPrototypeOf(value)\n return prototype === Object.prototype || prototype === null\n})\n\nexport const attachmentStorageScopeSchema = z.object({\n tenantId: z.string(),\n organizationId: z.string(),\n}).refine((scope) => Boolean(scope.tenantId.trim()) === Boolean(scope.organizationId.trim()))\n\nexport const attachmentAccessActionSchema = z.enum(['read', 'render', 'metadata', 'reassign', 'delete', 'export'])\nexport const attachmentAccessSubjectFeaturesSchema = z.array(z.string())\nexport const attachmentAccessSelectorSchema = z.string().min(1).max(200).regex(/^(?:\\*|[^*\\s]+(?:\\.\\*)?)$/)\nconst resolverIdSchema = z.string().min(3).max(200).regex(/^[a-zA-Z0-9_-]+\\.[a-zA-Z0-9_.-]+$/)\n\nexport const attachmentAccessRequirementSchema = z.object({\n resolverId: resolverIdSchema,\n targetEntity: attachmentAccessSelectorSchema,\n}).strict()\n\nexport const protectedAttachmentTargetSchema = attachmentAccessRequirementSchema.extend({\n targetPartition: attachmentAccessSelectorSchema,\n})\n\nexport const attachmentAccessResolverSchema = z.object({\n id: resolverIdSchema,\n targetPartition: attachmentAccessSelectorSchema,\n targetEntity: attachmentAccessSelectorSchema.optional(),\n actions: z.array(attachmentAccessActionSchema).min(1).optional(),\n priority: z.number().finite().optional(),\n timeoutMs: z.number().int().min(1).max(15_000).optional(),\n resolve: z.custom<AttachmentAccessResolver['resolve']>((value) => typeof value === 'function'),\n}).strict()\n\nexport const attachmentAccessRequirementsSchema = z.array(attachmentAccessRequirementSchema)\nexport const attachmentAccessDecisionSchema = z.discriminatedUnion('ok', [\n z.object({ ok: z.literal(true) }).strict(),\n z.object({\n ok: z.literal(false),\n status: z.union([z.literal(401), z.literal(403), z.literal(404), z.literal(504)]),\n reason: z.string().min(1).max(200).regex(/^[a-zA-Z0-9_.:-]+$/),\n }).strict(),\n])\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,SAAS;AAGX,MAAM,uCAAuC,EAAE,OAAgC,CAAC,UAAU;AAC/F,MAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,EAAG,QAAO;AACxE,QAAM,YAAY,OAAO,eAAe,KAAK;AAC7C,SAAO,cAAc,OAAO,aAAa,cAAc;AACzD,CAAC;AAEM,MAAM,+BAA+B,EAAE,OAAO;AAAA,EACnD,UAAU,EAAE,OAAO;AAAA,EACnB,gBAAgB,EAAE,OAAO;AAC3B,CAAC,EAAE,OAAO,CAAC,UAAU,QAAQ,MAAM,SAAS,KAAK,CAAC,MAAM,QAAQ,MAAM,eAAe,KAAK,CAAC,CAAC;AAErF,MAAM,+BAA+B,EAAE,KAAK,CAAC,QAAQ,UAAU,YAAY,YAAY,UAAU,QAAQ,CAAC;AAC1G,MAAM,wCAAwC,EAAE,MAAM,EAAE,OAAO,CAAC;AAChE,MAAM,iCAAiC,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,MAAM,2BAA2B;AAC1G,MAAM,mBAAmB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,MAAM,mCAAmC;AAEtF,MAAM,oCAAoC,EAAE,OAAO;AAAA,EACxD,YAAY;AAAA,EACZ,cAAc;AAChB,CAAC,EAAE,OAAO;AAEH,MAAM,kCAAkC,kCAAkC,OAAO;AAAA,EACtF,iBAAiB;AACnB,CAAC;AAEM,MAAM,iCAAiC,EAAE,OAAO;AAAA,EACrD,IAAI;AAAA,EACJ,iBAAiB;AAAA,EACjB,cAAc,+BAA+B,SAAS;AAAA,EACtD,SAAS,EAAE,MAAM,4BAA4B,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EAC/D,UAAU,EAAE,OAAO,EAAE,OAAO,EAAE,SAAS;AAAA,EACvC,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,IAAM,EAAE,SAAS;AAAA,EACxD,SAAS,EAAE,OAA4C,CAAC,UAAU,OAAO,UAAU,UAAU;AAC/F,CAAC,EAAE,OAAO;AAEH,MAAM,qCAAqC,EAAE,MAAM,iCAAiC;AACpF,MAAM,iCAAiC,EAAE,mBAAmB,MAAM;AAAA,EACvE,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,IAAI,EAAE,CAAC,EAAE,OAAO;AAAA,EACzC,EAAE,OAAO;AAAA,IACP,IAAI,EAAE,QAAQ,KAAK;AAAA,IACnB,QAAQ,EAAE,MAAM,CAAC,EAAE,QAAQ,GAAG,GAAG,EAAE,QAAQ,GAAG,GAAG,EAAE,QAAQ,GAAG,GAAG,EAAE,QAAQ,GAAG,CAAC,CAAC;AAAA,IAChF,QAAQ,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,MAAM,oBAAoB;AAAA,EAC/D,CAAC,EAAE,OAAO;AACZ,CAAC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -6,14 +6,24 @@ const metadata = {
|
|
|
6
6
|
author: "Open Mercato Team",
|
|
7
7
|
license: "MIT"
|
|
8
8
|
};
|
|
9
|
+
import {
|
|
10
|
+
AttachmentStorageConfigurationError,
|
|
11
|
+
getAttachmentStoragePolicy,
|
|
12
|
+
isAttachmentStorageConfigurationError,
|
|
13
|
+
registerStorageDriverValidator
|
|
14
|
+
} from "./lib/drivers/storageValidation.js";
|
|
9
15
|
import { registerAttachmentAccessResolvers } from "./lib/access-registry.js";
|
|
10
16
|
import { syncAttachmentAccessProtection } from "./lib/access-protection.js";
|
|
11
17
|
import { createAttachmentAccessContext, evaluateAttachmentAccess } from "./lib/access-runner.js";
|
|
12
18
|
export {
|
|
19
|
+
AttachmentStorageConfigurationError,
|
|
13
20
|
createAttachmentAccessContext,
|
|
14
21
|
evaluateAttachmentAccess,
|
|
22
|
+
getAttachmentStoragePolicy,
|
|
23
|
+
isAttachmentStorageConfigurationError,
|
|
15
24
|
metadata,
|
|
16
25
|
registerAttachmentAccessResolvers,
|
|
26
|
+
registerStorageDriverValidator,
|
|
17
27
|
syncAttachmentAccessProtection
|
|
18
28
|
};
|
|
19
29
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/modules/attachments/index.ts"],
|
|
4
|
-
"sourcesContent": ["import type { ModuleInfo } from '@open-mercato/shared/modules/registry'\n\nexport const metadata: ModuleInfo = {\n name: 'attachments',\n title: 'Attachments',\n version: '0.1.0',\n description: 'File attachments and media management.',\n author: 'Open Mercato Team',\n license: 'MIT',\n}\n\nexport {\n type AttachmentOwner,\n type AttachmentProviderCleanup,\n type AttachmentService,\n type CreatedScopedAttachment,\n type CreateScopedAttachmentInput,\n type ReadScopedAttachmentInput,\n type ReadScopedAttachmentResult,\n type ReleaseScopedAttachmentInput,\n} from './lib/attachment-service'\n\nexport type {\n AttachmentAccessAction,\n AttachmentAccessDecision,\n AttachmentAccessInput,\n AttachmentAccessPartition,\n AttachmentAccessRecord,\n AttachmentAccessRequirement,\n AttachmentAccessResolver,\n AttachmentAccessResolverEntry,\n AttachmentAccessSubject,\n AttachmentAccessTarget,\n ProtectedAttachmentTarget,\n} from './lib/access-types'\nexport { registerAttachmentAccessResolvers } from './lib/access-registry'\nexport { syncAttachmentAccessProtection } from './lib/access-protection'\nexport { createAttachmentAccessContext, evaluateAttachmentAccess } from './lib/access-runner'\nexport type { AttachmentAccessContext, AttachmentAccessResult } from './lib/access-runner'\n"],
|
|
5
|
-
"mappings": "AAEO,MAAM,WAAuB;AAAA,EAClC,MAAM;AAAA,EACN,OAAO;AAAA,EACP,SAAS;AAAA,EACT,aAAa;AAAA,EACb,QAAQ;AAAA,EACR,SAAS;AACX;
|
|
4
|
+
"sourcesContent": ["import type { ModuleInfo } from '@open-mercato/shared/modules/registry'\n\nexport const metadata: ModuleInfo = {\n name: 'attachments',\n title: 'Attachments',\n version: '0.1.0',\n description: 'File attachments and media management.',\n author: 'Open Mercato Team',\n license: 'MIT',\n}\n\nexport {\n type AttachmentOwner,\n type AttachmentProviderCleanup,\n type AttachmentService,\n type CreatedScopedAttachment,\n type CreateScopedAttachmentInput,\n type ReadScopedAttachmentInput,\n type ReadScopedAttachmentResult,\n type ReleaseScopedAttachmentInput,\n} from './lib/attachment-service'\n\nexport {\n AttachmentStorageConfigurationError,\n getAttachmentStoragePolicy,\n isAttachmentStorageConfigurationError,\n registerStorageDriverValidator,\n type AttachmentStoragePolicy,\n type AttachmentStorageScope,\n type AttachmentStorageValidationStage,\n type AttachmentStorageValidationContext,\n type AttachmentStorageValidator,\n type AttachmentStorageConfigurationReason,\n} from './lib/drivers/storageValidation'\nexport type {\n AttachmentAccessAction,\n AttachmentAccessDecision,\n AttachmentAccessInput,\n AttachmentAccessPartition,\n AttachmentAccessRecord,\n AttachmentAccessRequirement,\n AttachmentAccessResolver,\n AttachmentAccessResolverEntry,\n AttachmentAccessSubject,\n AttachmentAccessTarget,\n ProtectedAttachmentTarget,\n} from './lib/access-types'\nexport { registerAttachmentAccessResolvers } from './lib/access-registry'\nexport { syncAttachmentAccessProtection } from './lib/access-protection'\nexport { createAttachmentAccessContext, evaluateAttachmentAccess } from './lib/access-runner'\nexport type { AttachmentAccessContext, AttachmentAccessResult } from './lib/access-runner'\n"],
|
|
5
|
+
"mappings": "AAEO,MAAM,WAAuB;AAAA,EAClC,MAAM;AAAA,EACN,OAAO;AAAA,EACP,SAAS;AAAA,EACT,aAAa;AAAA,EACb,QAAQ;AAAA,EACR,SAAS;AACX;AAaA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAOK;AAcP,SAAS,yCAAyC;AAClD,SAAS,sCAAsC;AAC/C,SAAS,+BAA+B,gCAAgC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -6,6 +6,7 @@ import { getAttachmentAccessRegistry } from "./access-registry.js";
|
|
|
6
6
|
import { evaluateAttachmentAccess } from "./access-runner.js";
|
|
7
7
|
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
8
8
|
import { attachmentAccessErrorBody, throwAttachmentAccessError } from "./access-errors.js";
|
|
9
|
+
import { assertAttachmentStoragePartitionExists } from "./drivers/storageValidation.js";
|
|
9
10
|
import { readAttachmentMetadata } from "./metadata.js";
|
|
10
11
|
function requiresAttachmentAccessScan(partitions) {
|
|
11
12
|
const registry = getAttachmentAccessRegistry();
|
|
@@ -19,7 +20,10 @@ async function assertAttachmentOwnerAccess(input) {
|
|
|
19
20
|
tenantId: input.attachment.tenantId,
|
|
20
21
|
organizationId: input.attachment.organizationId
|
|
21
22
|
});
|
|
22
|
-
if (!partition)
|
|
23
|
+
if (!partition) {
|
|
24
|
+
if (input.action === "delete") assertAttachmentStoragePartitionExists(false);
|
|
25
|
+
await throwAttachmentAccessError(404);
|
|
26
|
+
}
|
|
23
27
|
if (input.persistProtection) await ensureAttachmentPartitionProtection(input.em, partition);
|
|
24
28
|
const result = await evaluateAttachmentAccess({ ...input, partition, requireAuthForPublic: true });
|
|
25
29
|
if (!result.ok) await throwAttachmentAccessError(result.status);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/attachments/lib/access-query.ts"],
|
|
4
|
-
"sourcesContent": ["import { ensureAttachmentPartitionProtection } from './access-protection'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { AttachmentPartition, type Attachment } from '../data/entities'\nimport { attachmentAccessRequirementsSchema } from '../data/validators'\nimport { getAttachmentAccessRegistry } from './access-registry'\nimport { evaluateAttachmentAccess, type AttachmentAccessContext } from './access-runner'\nimport type { AttachmentAccessAction, AttachmentAccessRecord } from './access-types'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { attachmentAccessErrorBody, throwAttachmentAccessError } from './access-errors'\nimport { readAttachmentMetadata } from './metadata'\n\nexport function requiresAttachmentAccessScan(partitions: readonly AttachmentPartition[]): boolean {\n const registry = getAttachmentAccessRegistry()\n return registry.invalid || registry.resolvers.length > 0 || registry.protectedTargets.length > 0\n || partitions.some((partition) => {\n const parsed = attachmentAccessRequirementsSchema.safeParse(partition.accessResolverRequirements ?? [])\n return !parsed.success || parsed.data.length > 0\n })\n}\n\nexport async function assertAttachmentOwnerAccess(input: {\n em: EntityManager\n context: AttachmentAccessContext\n auth: NonNullable<AuthContext>\n attachment: AttachmentAccessRecord\n action: AttachmentAccessAction\n persistProtection?: boolean\n}): Promise<void> {\n const partition = await findOneWithDecryption(input.em, AttachmentPartition, { code: input.attachment.partitionCode }, undefined, {\n tenantId: input.attachment.tenantId, organizationId: input.attachment.organizationId,\n })\n if (!partition) await throwAttachmentAccessError(404)\n if (input.persistProtection) await ensureAttachmentPartitionProtection(input.em, partition!)\n const result = await evaluateAttachmentAccess({ ...input, partition: partition!, requireAuthForPublic: true })\n if (!result.ok) await throwAttachmentAccessError(result.status)\n}\n\nexport async function scanAuthorizedAttachments(input: {\n auth: NonNullable<AuthContext>\n context: AttachmentAccessContext\n partitions: readonly AttachmentPartition[]\n loadBatch(offset: number, limit: number): Promise<Attachment[]>\n offset?: number\n limit?: number\n collectTags?: boolean\n deadline?: number\n}): Promise<{ records: Attachment[]; total: number; tags: string[] }> {\n const deadline = input.deadline ?? Date.now() + 15_000\n const timeoutBody = await attachmentAccessErrorBody(504)\n let timer: ReturnType<typeof setTimeout> | undefined\n const scan = async () => {\n const partitions = new Map(input.partitions.map((partition) => [partition.code, partition]))\n const records: Attachment[] = []\n const tags = new Set<string>()\n let total = 0\n for (let batchOffset = 0; ; batchOffset += 100) {\n if (Date.now() >= deadline) await throwAttachmentAccessError(504)\n const batch = await input.loadBatch(batchOffset, 100)\n for (const attachment of batch) {\n if (Date.now() >= deadline) await throwAttachmentAccessError(504)\n const partition = partitions.get(attachment.partitionCode)\n if (!partition) continue\n const access = await evaluateAttachmentAccess({\n auth: input.auth, attachment, partition, action: 'metadata', context: input.context,\n requireAuthForPublic: true,\n })\n if (Date.now() >= deadline || (!access.ok && access.status === 504)) await throwAttachmentAccessError(504)\n if (!access.ok) continue\n if (input.collectTags) for (const tag of readAttachmentMetadata(attachment.storageMetadata).tags ?? []) tags.add(tag)\n if (total >= (input.offset ?? 0) && (input.limit === undefined || records.length < input.limit)) records.push(attachment)\n total += 1\n }\n if (batch.length < 100) break\n }\n return { records, total, tags: [...tags].sort((left, right) => left < right ? -1 : left > right ? 1 : 0) }\n }\n try {\n return await Promise.race([scan(), new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new CrudHttpError(504, timeoutBody)), Math.max(1, deadline - Date.now()))\n })])\n } finally {\n if (timer) clearTimeout(timer)\n }\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,2CAA2C;AAGpD,SAAS,6BAA6B;AACtC,SAAS,2BAA4C;AACrD,SAAS,0CAA0C;AACnD,SAAS,mCAAmC;AAC5C,SAAS,gCAA8D;AAEvE,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B,kCAAkC;AACtE,SAAS,8BAA8B;AAEhC,SAAS,6BAA6B,YAAqD;AAChG,QAAM,WAAW,4BAA4B;AAC7C,SAAO,SAAS,WAAW,SAAS,UAAU,SAAS,KAAK,SAAS,iBAAiB,SAAS,KAC1F,WAAW,KAAK,CAAC,cAAc;AAChC,UAAM,SAAS,mCAAmC,UAAU,UAAU,8BAA8B,CAAC,CAAC;AACtG,WAAO,CAAC,OAAO,WAAW,OAAO,KAAK,SAAS;AAAA,EACjD,CAAC;AACL;AAEA,eAAsB,4BAA4B,OAOhC;AAChB,QAAM,YAAY,MAAM,sBAAsB,MAAM,IAAI,qBAAqB,EAAE,MAAM,MAAM,WAAW,cAAc,GAAG,QAAW;AAAA,IAChI,UAAU,MAAM,WAAW;AAAA,IAAU,gBAAgB,MAAM,WAAW;AAAA,EACxE,CAAC;AACD,MAAI,CAAC,
|
|
4
|
+
"sourcesContent": ["import { ensureAttachmentPartitionProtection } from './access-protection'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { AttachmentPartition, type Attachment } from '../data/entities'\nimport { attachmentAccessRequirementsSchema } from '../data/validators'\nimport { getAttachmentAccessRegistry } from './access-registry'\nimport { evaluateAttachmentAccess, type AttachmentAccessContext } from './access-runner'\nimport type { AttachmentAccessAction, AttachmentAccessRecord } from './access-types'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { attachmentAccessErrorBody, throwAttachmentAccessError } from './access-errors'\nimport { assertAttachmentStoragePartitionExists } from './drivers/storageValidation'\nimport { readAttachmentMetadata } from './metadata'\n\nexport function requiresAttachmentAccessScan(partitions: readonly AttachmentPartition[]): boolean {\n const registry = getAttachmentAccessRegistry()\n return registry.invalid || registry.resolvers.length > 0 || registry.protectedTargets.length > 0\n || partitions.some((partition) => {\n const parsed = attachmentAccessRequirementsSchema.safeParse(partition.accessResolverRequirements ?? [])\n return !parsed.success || parsed.data.length > 0\n })\n}\n\nexport async function assertAttachmentOwnerAccess(input: {\n em: EntityManager\n context: AttachmentAccessContext\n auth: NonNullable<AuthContext>\n attachment: AttachmentAccessRecord\n action: AttachmentAccessAction\n persistProtection?: boolean\n}): Promise<void> {\n const partition = await findOneWithDecryption(input.em, AttachmentPartition, { code: input.attachment.partitionCode }, undefined, {\n tenantId: input.attachment.tenantId, organizationId: input.attachment.organizationId,\n })\n if (!partition) {\n if (input.action === 'delete') assertAttachmentStoragePartitionExists(false)\n await throwAttachmentAccessError(404)\n }\n if (input.persistProtection) await ensureAttachmentPartitionProtection(input.em, partition!)\n const result = await evaluateAttachmentAccess({ ...input, partition: partition!, requireAuthForPublic: true })\n if (!result.ok) await throwAttachmentAccessError(result.status)\n}\n\nexport async function scanAuthorizedAttachments(input: {\n auth: NonNullable<AuthContext>\n context: AttachmentAccessContext\n partitions: readonly AttachmentPartition[]\n loadBatch(offset: number, limit: number): Promise<Attachment[]>\n offset?: number\n limit?: number\n collectTags?: boolean\n deadline?: number\n}): Promise<{ records: Attachment[]; total: number; tags: string[] }> {\n const deadline = input.deadline ?? Date.now() + 15_000\n const timeoutBody = await attachmentAccessErrorBody(504)\n let timer: ReturnType<typeof setTimeout> | undefined\n const scan = async () => {\n const partitions = new Map(input.partitions.map((partition) => [partition.code, partition]))\n const records: Attachment[] = []\n const tags = new Set<string>()\n let total = 0\n for (let batchOffset = 0; ; batchOffset += 100) {\n if (Date.now() >= deadline) await throwAttachmentAccessError(504)\n const batch = await input.loadBatch(batchOffset, 100)\n for (const attachment of batch) {\n if (Date.now() >= deadline) await throwAttachmentAccessError(504)\n const partition = partitions.get(attachment.partitionCode)\n if (!partition) continue\n const access = await evaluateAttachmentAccess({\n auth: input.auth, attachment, partition, action: 'metadata', context: input.context,\n requireAuthForPublic: true,\n })\n if (Date.now() >= deadline || (!access.ok && access.status === 504)) await throwAttachmentAccessError(504)\n if (!access.ok) continue\n if (input.collectTags) for (const tag of readAttachmentMetadata(attachment.storageMetadata).tags ?? []) tags.add(tag)\n if (total >= (input.offset ?? 0) && (input.limit === undefined || records.length < input.limit)) records.push(attachment)\n total += 1\n }\n if (batch.length < 100) break\n }\n return { records, total, tags: [...tags].sort((left, right) => left < right ? -1 : left > right ? 1 : 0) }\n }\n try {\n return await Promise.race([scan(), new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new CrudHttpError(504, timeoutBody)), Math.max(1, deadline - Date.now()))\n })])\n } fin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,UAAU,WAAW;AAC1E,cAAQ,WAAW,MAAM,OAAO,IAAI,cAAc,KAAK,WAAW,CAAC,GAAG,KAAK,IAAI,GAAG,WAAW,KAAK,IAAI,CAAC,CAAC;AAAA,IAC1G,CAAC,CAAC,CAAC;AAAA,EACL,UAAE;AACA,QAAI,MAAO,cAAa,KAAK;AAAA,EAC/B;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import { emitCrudSideEffects } from "@open-mercato/shared/lib/commands/helpers";
|
|
3
3
|
import { Attachment, AttachmentPartition } from "../data/entities.js";
|
|
4
4
|
import { StorageDriverFactory } from "./drivers/index.js";
|
|
5
|
+
import { assertAttachmentStoragePartitionExists } from "./drivers/storageValidation.js";
|
|
5
6
|
import { ensureDefaultPartitions, resolveDefaultPartitionCode } from "./partitions.js";
|
|
6
7
|
import { buildAttachmentFileUrl } from "./imageUrls.js";
|
|
7
8
|
import { mergeAttachmentMetadata, upsertAssignment } from "./metadata.js";
|
|
@@ -13,6 +14,7 @@ async function createAttachmentFromBuffer(input) {
|
|
|
13
14
|
const code = input.partitionCode && input.partitionCode.length > 0 ? input.partitionCode : resolveDefaultPartitionCode(input.entityId);
|
|
14
15
|
let partition = await em.findOne(AttachmentPartition, { code });
|
|
15
16
|
if (!partition) {
|
|
17
|
+
assertAttachmentStoragePartitionExists(false);
|
|
16
18
|
await ensureDefaultPartitions(em);
|
|
17
19
|
partition = await em.findOne(AttachmentPartition, { code });
|
|
18
20
|
}
|