@open-mercato/core 0.10.1-develop.7741.1.61a2652671 → 0.10.1-develop.7749.1.ea3edf75e3
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/generated/entities/attachment_partition/index.js +2 -0
- package/dist/generated/entities/attachment_partition/index.js.map +2 -2
- package/dist/generated/entity-fields-registry.js +1 -0
- package/dist/generated/entity-fields-registry.js.map +2 -2
- package/dist/helpers/integration/attachmentAccessFixtures.js +144 -0
- package/dist/helpers/integration/attachmentAccessFixtures.js.map +7 -0
- package/dist/modules/attachments/api/file/[id]/route.js +16 -10
- package/dist/modules/attachments/api/file/[id]/route.js.map +2 -2
- package/dist/modules/attachments/api/image/[id]/[[...slug]]/route.js +15 -9
- package/dist/modules/attachments/api/image/[id]/[[...slug]]/route.js.map +2 -2
- package/dist/modules/attachments/api/library/[id]/route.js +100 -56
- package/dist/modules/attachments/api/library/[id]/route.js.map +3 -3
- package/dist/modules/attachments/api/library/route.js +56 -17
- package/dist/modules/attachments/api/library/route.js.map +2 -2
- package/dist/modules/attachments/api/partitions/route.js +2 -0
- package/dist/modules/attachments/api/partitions/route.js.map +2 -2
- package/dist/modules/attachments/api/route.js +74 -34
- package/dist/modules/attachments/api/route.js.map +3 -3
- package/dist/modules/attachments/api/transfer/route.js +63 -37
- package/dist/modules/attachments/api/transfer/route.js.map +2 -2
- package/dist/modules/attachments/data/entities.js +3 -0
- package/dist/modules/attachments/data/entities.js.map +2 -2
- package/dist/modules/attachments/data/validators.js +41 -0
- package/dist/modules/attachments/data/validators.js.map +7 -0
- package/dist/modules/attachments/di.js +5 -2
- package/dist/modules/attachments/di.js.map +2 -2
- package/dist/modules/attachments/generators.js +29 -0
- package/dist/modules/attachments/generators.js.map +7 -0
- package/dist/modules/attachments/index.js +8 -1
- package/dist/modules/attachments/index.js.map +2 -2
- package/dist/modules/attachments/lib/access-errors.js +35 -0
- package/dist/modules/attachments/lib/access-errors.js.map +7 -0
- package/dist/modules/attachments/lib/access-mutation.js +23 -0
- package/dist/modules/attachments/lib/access-mutation.js.map +7 -0
- package/dist/modules/attachments/lib/access-protection.js +73 -0
- package/dist/modules/attachments/lib/access-protection.js.map +7 -0
- package/dist/modules/attachments/lib/access-query.js +74 -0
- package/dist/modules/attachments/lib/access-query.js.map +7 -0
- package/dist/modules/attachments/lib/access-registry.js +87 -0
- package/dist/modules/attachments/lib/access-registry.js.map +7 -0
- package/dist/modules/attachments/lib/access-runner.js +161 -0
- package/dist/modules/attachments/lib/access-runner.js.map +7 -0
- package/dist/modules/attachments/lib/access-types.js +1 -0
- package/dist/modules/attachments/lib/access-types.js.map +7 -0
- package/dist/modules/attachments/lib/attachment-service.js +14 -6
- package/dist/modules/attachments/lib/attachment-service.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/partitions.js +3 -2
- package/dist/modules/attachments/lib/partitions.js.map +2 -2
- package/dist/modules/attachments/lib/scoped-upload-service.js +2 -0
- package/dist/modules/attachments/lib/scoped-upload-service.js.map +2 -2
- package/dist/modules/attachments/lib/target-access-service.js +12 -3
- package/dist/modules/attachments/lib/target-access-service.js.map +2 -2
- package/dist/modules/attachments/migrations/Migration20261001120000_attachments.js +38 -0
- package/dist/modules/attachments/migrations/Migration20261001120000_attachments.js.map +7 -0
- package/dist/modules/attachments/setup.js +10 -0
- package/dist/modules/attachments/setup.js.map +2 -2
- package/dist/modules/notifications/api/[id]/action/route.js +8 -0
- package/dist/modules/notifications/api/[id]/action/route.js.map +2 -2
- package/dist/modules/notifications/api/route.js +17 -0
- package/dist/modules/notifications/api/route.js.map +2 -2
- package/dist/modules/notifications/data/validators.js +1 -1
- package/dist/modules/notifications/data/validators.js.map +2 -2
- package/dist/modules/notifications/lib/notificationService.js +45 -3
- package/dist/modules/notifications/lib/notificationService.js.map +2 -2
- package/dist/modules/notifications/lib/routeHelpers.js +27 -0
- package/dist/modules/notifications/lib/routeHelpers.js.map +2 -2
- package/dist/modules/payment_gateways/lib/gateway-service.js +50 -34
- package/dist/modules/payment_gateways/lib/gateway-service.js.map +2 -2
- package/dist/modules/payment_gateways/lib/status-machine.js +10 -1
- package/dist/modules/payment_gateways/lib/status-machine.js.map +2 -2
- package/dist/modules/payment_gateways/lib/webhook-processor.js +1 -1
- package/dist/modules/payment_gateways/lib/webhook-processor.js.map +2 -2
- package/dist/modules/staff/notifications.js +4 -2
- package/dist/modules/staff/notifications.js.map +2 -2
- package/dist/modules/workflows/data/entities.js.map +2 -2
- package/dist/modules/workflows/lib/activity-executor.js +18 -4
- package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
- package/dist/modules/workflows/lib/activity-types.js +2 -2
- package/dist/modules/workflows/lib/activity-types.js.map +2 -2
- package/dist/modules/workflows/lib/condition-handler.js +7 -1
- package/dist/modules/workflows/lib/condition-handler.js.map +2 -2
- package/dist/modules/workflows/lib/duration.js +13 -0
- package/dist/modules/workflows/lib/duration.js.map +2 -2
- package/dist/modules/workflows/lib/step-handler.js +9 -2
- package/dist/modules/workflows/lib/step-handler.js.map +2 -2
- package/dist/modules/workflows/lib/task-quick-action.js +13 -10
- package/dist/modules/workflows/lib/task-quick-action.js.map +2 -2
- package/dist/modules/workflows/lib/transition-handler.js +2 -1
- package/dist/modules/workflows/lib/transition-handler.js.map +2 -2
- package/dist/modules/workflows/notifications.js +4 -0
- package/dist/modules/workflows/notifications.js.map +2 -2
- package/generated/entities/attachment_partition/index.ts +1 -0
- package/generated/entity-fields-registry.ts +1 -0
- package/package.json +7 -7
- package/src/helpers/integration/attachmentAccessFixtures.ts +141 -0
- package/src/modules/attachments/api/file/[id]/route.ts +12 -9
- package/src/modules/attachments/api/image/[id]/[[...slug]]/route.ts +10 -8
- package/src/modules/attachments/api/library/[id]/route.ts +87 -58
- package/src/modules/attachments/api/library/route.ts +40 -11
- package/src/modules/attachments/api/partitions/route.ts +2 -0
- package/src/modules/attachments/api/route.ts +68 -35
- package/src/modules/attachments/api/transfer/route.ts +65 -42
- package/src/modules/attachments/data/entities.ts +4 -0
- package/src/modules/attachments/data/validators.ts +36 -0
- package/src/modules/attachments/di.ts +4 -1
- package/src/modules/attachments/generators.ts +27 -0
- package/src/modules/attachments/i18n/de.json +4 -0
- package/src/modules/attachments/i18n/en.json +4 -0
- package/src/modules/attachments/i18n/es.json +4 -0
- package/src/modules/attachments/i18n/ko.json +4 -0
- package/src/modules/attachments/i18n/pl.json +4 -0
- package/src/modules/attachments/index.ts +18 -0
- package/src/modules/attachments/lib/access-errors.ts +32 -0
- package/src/modules/attachments/lib/access-mutation.ts +26 -0
- package/src/modules/attachments/lib/access-protection.ts +83 -0
- package/src/modules/attachments/lib/access-query.ts +86 -0
- package/src/modules/attachments/lib/access-registry.ts +117 -0
- package/src/modules/attachments/lib/access-runner.ts +183 -0
- package/src/modules/attachments/lib/access-types.ts +78 -0
- package/src/modules/attachments/lib/attachment-service.ts +8 -4
- package/src/modules/attachments/lib/createFromBuffer.ts +3 -0
- package/src/modules/attachments/lib/partitions.ts +3 -2
- package/src/modules/attachments/lib/scoped-upload-service.ts +2 -0
- package/src/modules/attachments/lib/target-access-service.ts +10 -3
- package/src/modules/attachments/migrations/.snapshot-open-mercato.json +17 -0
- package/src/modules/attachments/migrations/Migration20261001120000_attachments.ts +35 -0
- package/src/modules/attachments/setup.ts +10 -0
- package/src/modules/auth/i18n/de.json +3 -0
- package/src/modules/auth/i18n/en.json +3 -0
- package/src/modules/auth/i18n/es.json +3 -0
- package/src/modules/auth/i18n/ko.json +3 -0
- package/src/modules/auth/i18n/pl.json +3 -0
- package/src/modules/notifications/api/[id]/action/route.ts +8 -0
- package/src/modules/notifications/api/route.ts +17 -0
- package/src/modules/notifications/data/validators.ts +1 -1
- package/src/modules/notifications/i18n/de.json +2 -0
- package/src/modules/notifications/i18n/en.json +2 -0
- package/src/modules/notifications/i18n/es.json +2 -0
- package/src/modules/notifications/i18n/ko.json +2 -0
- package/src/modules/notifications/i18n/pl.json +2 -0
- package/src/modules/notifications/lib/notificationService.ts +67 -1
- package/src/modules/notifications/lib/routeHelpers.ts +38 -0
- package/src/modules/payment_gateways/lib/gateway-service.ts +50 -33
- package/src/modules/payment_gateways/lib/status-machine.ts +19 -0
- package/src/modules/payment_gateways/lib/webhook-processor.ts +1 -1
- package/src/modules/staff/notifications.ts +2 -0
- package/src/modules/workflows/AGENTS.md +2 -2
- package/src/modules/workflows/data/entities.ts +6 -0
- package/src/modules/workflows/lib/activity-executor.ts +36 -4
- package/src/modules/workflows/lib/activity-types.ts +2 -2
- package/src/modules/workflows/lib/condition-handler.ts +16 -1
- package/src/modules/workflows/lib/duration.ts +25 -0
- package/src/modules/workflows/lib/step-handler.ts +16 -1
- package/src/modules/workflows/lib/task-quick-action.ts +19 -10
- package/src/modules/workflows/lib/transition-handler.ts +2 -1
- package/src/modules/workflows/notifications.ts +4 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/attachments/lib/attachment-service.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { Attachment, AttachmentPartition } from '../data/entities'\nimport { assertAttachmentScopeInvariant, checkAttachmentAccess } from './access'\nimport type { StorageDriverFactory } from './drivers'\nimport { buildAttachmentFileUrl } from './imageUrls'\nimport {\n isScopedAttachmentUploadError,\n type ScopedAttachmentUploadErrorCode,\n type ScopedAttachmentUploadService,\n} from './scoped-upload-service'\nimport { readAttachmentMetadata, type AttachmentAssignment } from './metadata'\nimport {\n listAttachmentStorageReferences,\n lockAttachmentStorageReferences,\n removeAttachmentRecord,\n resolveAttachmentStorageRelease,\n} from './storageReferences'\nimport {\n buildAttachmentContentDisposition,\n canRenderInlineAttachment,\n hasDangerousExecutableExtension,\n} from './security'\nimport {\n isMultipartRequestWithinUploadLimit,\n resolveAttachmentMaxBytes,\n resolveAttachmentMultipartMaxBytes,\n} from './upload-limits'\n\nconst logger = createLogger('attachments').child({ component: 'attachment-service' })\n\ntype AttachmentErrorMessage = {\n key: string\n fallback: string\n}\n\n/**\n * The scoped upload service reports failures as machine codes. Each maps to the\n * translation key the public attachment route uses for the same condition, and\n * the key is resolved server-side before it reaches the response body \u2014 clients\n * render the `error` field verbatim, so handing them a raw key would surface\n * `attachments.errors.quotaExceeded` as the user-facing message.\n */\nconst SCOPED_UPLOAD_ERROR_MESSAGES: Record<ScopedAttachmentUploadErrorCode, AttachmentErrorMessage> = {\n dangerous_executable: {\n key: 'attachments.errors.dangerousExecutable',\n fallback: 'Executable file types are not allowed as attachments.',\n },\n max_upload_size: {\n key: 'attachments.errors.maxUploadSize',\n fallback: 'Attachment exceeds the maximum upload size.',\n },\n active_content: {\n key: 'attachments.errors.activeContentBlocked',\n fallback: 'Active content uploads are not allowed.',\n },\n partition_unavailable: {\n key: 'attachments.errors.partitionUnavailable',\n fallback: 'Attachment partition is not available for this scope.',\n },\n quota_exceeded: {\n key: 'attachments.errors.quotaExceeded',\n fallback: 'Attachment storage quota exceeded for this tenant.',\n },\n quota_target_exists: {\n key: 'attachments.errors.storagePathExists',\n fallback: 'The target storage path already exists.',\n },\n quota_unavailable: {\n key: 'attachments.errors.quotaUnavailable',\n fallback: 'Storage quota accounting is unavailable.',\n },\n quota_recovery_unsupported: {\n key: 'attachments.errors.quotaRecoveryUnsupported',\n fallback: 'Storage driver cannot participate in quota recovery.',\n },\n storage_failed: {\n key: 'attachments.errors.storageFailed',\n fallback: 'Failed to store the attachment file.',\n },\n persistence_failed: {\n key: 'attachments.errors.persistenceFailed',\n fallback: 'Failed to persist attachment.',\n },\n}\n\nconst UPLOAD_FAILED_MESSAGE: AttachmentErrorMessage = {\n key: 'attachments.errors.uploadFailed',\n fallback: 'Attachment upload failed.',\n}\n\nconst UPLOAD_SERVICE_UNAVAILABLE_MESSAGE: AttachmentErrorMessage = {\n key: 'attachments.errors.uploadServiceUnavailable',\n fallback: 'The attachment upload service is not available.',\n}\n\nasync function translateAttachmentError(message: AttachmentErrorMessage): Promise<string> {\n const { t } = await resolveTranslations()\n return t(message.key, message.fallback)\n}\n\nexport type AttachmentOwner = {\n entityId: string\n recordId: string\n}\n\nexport type CreateScopedAttachmentInput = AttachmentOwner & {\n tenantId: string\n organizationId: string\n partitionCode: string\n fileName: string\n declaredMimeType?: string | null\n buffer: Buffer\n assignments?: AttachmentAssignment[]\n /**\n * Persists a module-owned link inside the same transaction as the Attachment\n * row. The callback receives only the generated id, never an Attachment\n * entity or storage implementation.\n */\n persistLink?: (tx: EntityManager, attachmentId: string) => Promise<void> | void\n}\n\nexport type CreatedScopedAttachment = {\n id: string\n url: string\n fileName: string\n mimeType: string\n fileSize: number\n}\n\nexport type ReadScopedAttachmentInput = {\n attachmentId: string\n auth: NonNullable<AuthContext>\n expectedOwner: AttachmentOwner\n expectedAssignment?: AttachmentAssignment\n expectedPartitionCode?: string\n requirePrivatePartition?: boolean\n forceDownload?: boolean\n}\n\nexport type ReadScopedAttachmentResult = {\n buffer: Buffer\n contentType: string\n contentDisposition: string\n fileName: string\n mimeType: string\n}\n\nexport type ReleaseScopedAttachmentInput = {\n attachmentId: string\n tenantId: string\n organizationId: string\n expectedOwner: AttachmentOwner\n /**\n * Required: releasing an attachment deletes the row *and* the provider bytes,\n * so the caller must name the one assignment it owns. The release only\n * proceeds when that assignment is the attachment's sole reference.\n */\n expectedAssignment: AttachmentAssignment\n expectedPartitionCode?: string\n}\n\nexport type AttachmentProviderCleanup = () => Promise<void>\n\nexport interface AttachmentService {\n validateUpload(input: {\n contentLength?: string | null\n fileName?: string\n fileSize?: number\n }): void\n readUploadForm?(request: Request): Promise<FormData>\n createScoped(input: CreateScopedAttachmentInput): Promise<CreatedScopedAttachment>\n readScoped(input: ReadScopedAttachmentInput): Promise<ReadScopedAttachmentResult>\n /**\n * Permanently deletes an attachment row and its stored object once no other row references it.\n *\n * With `{ flush: false }` call it inside your own transaction and run the returned cleanup after\n * commit; `undefined` means another row still references the stored object.\n *\n * @deprecated Calling it with `{ flush: false }` outside a transaction. It still works for one\n * minor version but logs a warning, and its reference check is not locked, so two racing releases\n * of rows sharing the stored object keep it. Wrap the call in a transaction instead.\n */\n releaseScoped?(\n input: ReleaseScopedAttachmentInput,\n options?: { em?: EntityManager; flush?: boolean },\n ): Promise<AttachmentProviderCleanup | void>\n}\n\nasync function readRequestBodyWithinLimit(request: Request, maxBytes: number): Promise<Uint8Array> {\n const reader = request.body?.getReader()\n if (!reader) throw new CrudHttpError(400, { error: 'File is required' })\n const chunks: Uint8Array[] = []\n let totalBytes = 0\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n totalBytes += value.byteLength\n if (totalBytes > maxBytes) {\n await reader.cancel()\n throw new CrudHttpError(413, { error: 'Attachment exceeds the maximum upload size.' })\n }\n chunks.push(value)\n }\n } finally {\n reader.releaseLock()\n }\n const body = new Uint8Array(totalBytes)\n let offset = 0\n for (const chunk of chunks) {\n body.set(chunk, offset)\n offset += chunk.byteLength\n }\n return body\n}\n\n\nfunction assignmentMatches(candidate: AttachmentAssignment, expected: AttachmentAssignment): boolean {\n return candidate.type === expected.type && candidate.id === expected.id\n}\n\nfunction partitionMatchesScope(\n partition: AttachmentPartition,\n tenantId: string | null | undefined,\n organizationId: string | null | undefined,\n): boolean {\n const partitionTenantId = partition.tenantId ?? null\n const partitionOrganizationId = partition.organizationId ?? null\n if (partitionTenantId === null && partitionOrganizationId === null) return true\n if (partitionTenantId === null || partitionOrganizationId === null) return false\n return partitionTenantId === tenantId && partitionOrganizationId === organizationId\n}\n\nexport class DefaultAttachmentService implements AttachmentService {\n /**\n * The scoped upload service is supplied as a *resolver*, not an instance:\n * resolving it eagerly would drag its own dependencies (notably `dataEngine`)\n * into every container that merely constructs an `attachmentService`, even\n * one that never uploads. `createScoped` requires it \u2014 module uploads must\n * share the one reservation ledger rather than run a parallel quota\n * mechanism \u2014 so its absence surfaces there, at the call that needs it.\n */\n constructor(\n private readonly em: EntityManager,\n private readonly storageDriverFactory: StorageDriverFactory,\n private readonly resolveScopedUploadService?: (() => ScopedAttachmentUploadService | null) | null,\n ) {}\n\n validateUpload(input: {\n contentLength?: string | null\n fileName?: string\n fileSize?: number\n }): void {\n if (!isMultipartRequestWithinUploadLimit(input.contentLength ?? null)) {\n throw new CrudHttpError(413, { error: 'Attachment exceeds the maximum upload size.' })\n }\n if (input.fileName && hasDangerousExecutableExtension(input.fileName)) {\n throw new CrudHttpError(400, { error: 'Executable file types are not allowed as attachments.' })\n }\n if (typeof input.fileSize === 'number' && input.fileSize > resolveAttachmentMaxBytes(null)) {\n throw new CrudHttpError(413, { error: 'Attachment exceeds the maximum upload size.' })\n }\n }\n\n async readUploadForm(request: Request): Promise<FormData> {\n this.validateUpload({ contentLength: request.headers.get('content-length') })\n const contentType = request.headers.get('content-type') ?? ''\n if (!contentType.toLowerCase().includes('multipart/form-data')) {\n throw new CrudHttpError(400, { error: 'Expected multipart/form-data' })\n }\n const body = await readRequestBodyWithinLimit(request, resolveAttachmentMultipartMaxBytes())\n const responseBody = body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength) as ArrayBuffer\n try {\n return await new Response(responseBody, { headers: { 'content-type': contentType } }).formData()\n } catch {\n throw new CrudHttpError(400, { error: 'Invalid multipart/form-data' })\n }\n }\n\n async createScoped(input: CreateScopedAttachmentInput): Promise<CreatedScopedAttachment> {\n assertAttachmentScopeInvariant(input)\n this.validateUpload({ fileName: input.fileName, fileSize: input.buffer.length })\n\n // Delegate to the platform's scoped upload service rather than repeating its\n // work. It owns the fenced quota lease (reserve \u2192 storing \u2192 stored \u2192\n // complete) that the recovery worker reconciles, writes to the provider\n // outside the database transaction, and emits the attachment CRUD side\n // effects. The previous implementation here ran a *second*, independent\n // quota mechanism on a different advisory-lock key that counted only\n // committed rows, so it could not see an in-flight reservation from the\n // public attachment route and the two paths could jointly exceed a tenant's\n // quota \u2014 and it wrote to storage inside the transaction, so a crash before\n // commit left bytes nothing accounted for.\n let uploadService: ScopedAttachmentUploadService | null = null\n try {\n uploadService = this.resolveScopedUploadService?.() ?? null\n } catch (error) {\n logger.error('Scoped attachment upload service could not be resolved', { err: error })\n }\n if (!uploadService) {\n throw new CrudHttpError(500, {\n error: await translateAttachmentError(UPLOAD_SERVICE_UNAVAILABLE_MESSAGE),\n })\n }\n\n let attachment: Attachment\n try {\n attachment = await uploadService.upload({\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n entityId: input.entityId,\n recordId: input.recordId,\n fileName: input.fileName,\n buffer: input.buffer,\n declaredMimeType: input.declaredMimeType ?? null,\n assignments: input.assignments,\n partitionCode: input.partitionCode,\n requirePrivatePartition: true,\n persistLink: input.persistLink,\n })\n } catch (error) {\n if (isScopedAttachmentUploadError(error)) {\n const message = SCOPED_UPLOAD_ERROR_MESSAGES[error.code] ?? UPLOAD_FAILED_MESSAGE\n throw new CrudHttpError(error.status, { error: await translateAttachmentError(message) })\n }\n throw error\n }\n\n return {\n id: attachment.id,\n url: attachment.url ?? buildAttachmentFileUrl(attachment.id),\n fileName: attachment.fileName,\n mimeType: attachment.mimeType,\n fileSize: attachment.fileSize,\n }\n }\n\n async readScoped(input: ReadScopedAttachmentInput): Promise<ReadScopedAttachmentResult> {\n // Scope the lookup at the database boundary so a foreign-tenant row is\n // never materialized, then keep checkAttachmentAccess below as defense in\n // depth. This service only ever stores fully scoped rows, so global rows\n // and super-admin status deliberately do not widen the requested scope \u2014\n // a super admin reads another tenant's attachment by switching scope, not\n // by bypassing the filter.\n const attachment = await findOneWithDecryption(\n this.em,\n Attachment,\n {\n id: input.attachmentId,\n tenantId: input.auth.tenantId ?? null,\n organizationId: input.auth.orgId ?? null,\n },\n undefined,\n { tenantId: input.auth.tenantId, organizationId: input.auth.orgId },\n )\n if (!attachment) throw new CrudHttpError(404, { error: 'Attachment not found' })\n const partition = await findOneWithDecryption(\n this.em,\n AttachmentPartition,\n { code: attachment.partitionCode },\n undefined,\n { tenantId: input.auth.tenantId, organizationId: input.auth.orgId },\n )\n if (!partition) throw new CrudHttpError(500, { error: 'Attachment partition is not configured' })\n\n const access = checkAttachmentAccess(input.auth, attachment, partition, { requireAuthForPublic: true })\n if (!access.ok) {\n throw new CrudHttpError(access.status, { error: access.status === 401 ? 'Unauthorized' : 'Forbidden' })\n }\n if (!partitionMatchesScope(partition, input.auth.tenantId, input.auth.orgId)) {\n throw new CrudHttpError(403, { error: 'Attachment partition is not accessible for this scope' })\n }\n if (input.requirePrivatePartition && partition.isPublic) {\n throw new CrudHttpError(403, { error: 'Attachment partition is not accessible for this resource' })\n }\n if (input.expectedPartitionCode && attachment.partitionCode !== input.expectedPartitionCode) {\n throw new CrudHttpError(404, { error: 'Attachment not found' })\n }\n if (\n attachment.entityId !== input.expectedOwner.entityId ||\n attachment.recordId !== input.expectedOwner.recordId\n ) {\n throw new CrudHttpError(404, { error: 'Attachment not found' })\n }\n if (input.expectedAssignment) {\n const assignments = readAttachmentMetadata(attachment.storageMetadata).assignments ?? []\n if (!assignments.some((candidate) => assignmentMatches(candidate, input.expectedAssignment!))) {\n throw new CrudHttpError(404, { error: 'Attachment not found' })\n }\n }\n\n const driver = await this.storageDriverFactory.resolveForPartition(attachment.partitionCode, {\n tenantId: attachment.tenantId ?? '',\n organizationId: attachment.organizationId ?? '',\n })\n let result: Awaited<ReturnType<typeof driver.read>>\n try {\n result = await driver.read(attachment.partitionCode, attachment.storagePath)\n } catch {\n throw new CrudHttpError(404, { error: 'File not available' })\n }\n\n const mimeType = attachment.mimeType || 'application/octet-stream'\n const renderInline = !input.forceDownload && canRenderInlineAttachment(mimeType)\n return {\n buffer: result.buffer,\n contentType: renderInline ? result.contentType ?? mimeType : 'application/octet-stream',\n contentDisposition: buildAttachmentContentDisposition(\n attachment.fileName,\n renderInline ? 'inline' : 'attachment',\n ),\n fileName: attachment.fileName,\n mimeType,\n }\n }\n\n async releaseScoped(\n input: ReleaseScopedAttachmentInput,\n options: { em?: EntityManager; flush?: boolean } = {},\n ): Promise<AttachmentProviderCleanup | void> {\n const em = options.em ?? this.em\n // The type makes `expectedAssignment` mandatory, but this service is handed\n // out through untyped DI resolution and consumed through structural ports in\n // other packages, so the shared-reference guard is enforced at runtime too:\n // without it a caller could destroy an attachment other records still link.\n const expectedAssignment = input.expectedAssignment\n if (!expectedAssignment) {\n throw new CrudHttpError(500, {\n error: 'Attachment release requires the expected assignment of the releasing record',\n })\n }\n const isInTransaction = (em as { isInTransaction?: () => boolean }).isInTransaction\n if (\n options.flush !== false\n && typeof isInTransaction === 'function'\n && isInTransaction.call(em)\n ) {\n throw new CrudHttpError(500, {\n error: 'Attachment release inside an ambient transaction requires flush: false and deferred provider cleanup',\n })\n }\n const deferredOutsideTransaction = options.flush === false\n && typeof isInTransaction === 'function'\n && !isInTransaction.call(em)\n if (deferredOutsideTransaction) {\n logger.warn(\n '[deprecated] attachmentService.releaseScoped({ flush: false }) called outside a transaction; wrap it in a transaction so the storage reference lock is held until commit',\n { attachmentId: input.attachmentId },\n )\n }\n const scope = { tenantId: input.tenantId, organizationId: input.organizationId }\n const attachment = await findOneWithDecryption(\n em,\n Attachment,\n {\n id: input.attachmentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n },\n undefined,\n scope,\n )\n if (!attachment) throw new CrudHttpError(404, { error: 'Attachment not found' })\n if (\n attachment.entityId !== input.expectedOwner.entityId\n || attachment.recordId !== input.expectedOwner.recordId\n || (input.expectedPartitionCode && attachment.partitionCode !== input.expectedPartitionCode)\n ) {\n throw new CrudHttpError(404, { error: 'Attachment not found' })\n }\n const assignments = readAttachmentMetadata(attachment.storageMetadata).assignments ?? []\n if (!assignments.some((candidate) => assignmentMatches(candidate, expectedAssignment))) {\n throw new CrudHttpError(409, { error: 'Attachment is still referenced by another record' })\n }\n if (assignments.some((candidate) => !assignmentMatches(candidate, expectedAssignment))) {\n throw new CrudHttpError(409, { error: 'Attachment is still referenced by another record' })\n }\n\n const driver = await this.storageDriverFactory.resolveForPartition(attachment.partitionCode, scope)\n const deleteProviderBytes = () => driver.delete(attachment.partitionCode, attachment.storagePath)\n if (options.flush === false) {\n const referenceIds = deferredOutsideTransaction\n ? await listAttachmentStorageReferences(em, attachment)\n : await lockAttachmentStorageReferences(em, attachment)\n const removal = resolveAttachmentStorageRelease(referenceIds, attachment.id)\n if (!removal.removed) throw new CrudHttpError(404, { error: 'Attachment not found' })\n em.remove(attachment)\n return removal.releaseStorage ? deleteProviderBytes : undefined\n }\n const removal = await removeAttachmentRecord(em, attachment)\n if (!removal.removed) throw new CrudHttpError(404, { error: 'Attachment not found' })\n if (removal.releaseStorage) await deleteProviderBytes()\n }\n}\n"],
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import { evaluateAttachmentAccess, type AttachmentAccessContext } from './access-runner'\nimport { throwAttachmentAccessError } from './access-errors'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { Attachment, AttachmentPartition } from '../data/entities'\nimport { assertAttachmentScopeInvariant, checkAttachmentAccess } from './access'\nimport type { StorageDriverFactory } from './drivers'\nimport { buildAttachmentFileUrl } from './imageUrls'\nimport {\n isScopedAttachmentUploadError,\n type ScopedAttachmentUploadErrorCode,\n type ScopedAttachmentUploadService,\n} from './scoped-upload-service'\nimport { readAttachmentMetadata, type AttachmentAssignment } from './metadata'\nimport {\n listAttachmentStorageReferences,\n lockAttachmentStorageReferences,\n removeAttachmentRecord,\n resolveAttachmentStorageRelease,\n} from './storageReferences'\nimport {\n buildAttachmentContentDisposition,\n canRenderInlineAttachment,\n hasDangerousExecutableExtension,\n} from './security'\nimport {\n isMultipartRequestWithinUploadLimit,\n resolveAttachmentMaxBytes,\n resolveAttachmentMultipartMaxBytes,\n} from './upload-limits'\n\nconst logger = createLogger('attachments').child({ component: 'attachment-service' })\n\ntype AttachmentErrorMessage = {\n key: string\n fallback: string\n}\n\n/**\n * The scoped upload service reports failures as machine codes. Each maps to the\n * translation key the public attachment route uses for the same condition, and\n * the key is resolved server-side before it reaches the response body \u2014 clients\n * render the `error` field verbatim, so handing them a raw key would surface\n * `attachments.errors.quotaExceeded` as the user-facing message.\n */\nconst SCOPED_UPLOAD_ERROR_MESSAGES: Record<ScopedAttachmentUploadErrorCode, AttachmentErrorMessage> = {\n dangerous_executable: {\n key: 'attachments.errors.dangerousExecutable',\n fallback: 'Executable file types are not allowed as attachments.',\n },\n max_upload_size: {\n key: 'attachments.errors.maxUploadSize',\n fallback: 'Attachment exceeds the maximum upload size.',\n },\n active_content: {\n key: 'attachments.errors.activeContentBlocked',\n fallback: 'Active content uploads are not allowed.',\n },\n partition_unavailable: {\n key: 'attachments.errors.partitionUnavailable',\n fallback: 'Attachment partition is not available for this scope.',\n },\n quota_exceeded: {\n key: 'attachments.errors.quotaExceeded',\n fallback: 'Attachment storage quota exceeded for this tenant.',\n },\n quota_target_exists: {\n key: 'attachments.errors.storagePathExists',\n fallback: 'The target storage path already exists.',\n },\n quota_unavailable: {\n key: 'attachments.errors.quotaUnavailable',\n fallback: 'Storage quota accounting is unavailable.',\n },\n quota_recovery_unsupported: {\n key: 'attachments.errors.quotaRecoveryUnsupported',\n fallback: 'Storage driver cannot participate in quota recovery.',\n },\n storage_failed: {\n key: 'attachments.errors.storageFailed',\n fallback: 'Failed to store the attachment file.',\n },\n persistence_failed: {\n key: 'attachments.errors.persistenceFailed',\n fallback: 'Failed to persist attachment.',\n },\n}\n\nconst UPLOAD_FAILED_MESSAGE: AttachmentErrorMessage = {\n key: 'attachments.errors.uploadFailed',\n fallback: 'Attachment upload failed.',\n}\n\nconst UPLOAD_SERVICE_UNAVAILABLE_MESSAGE: AttachmentErrorMessage = {\n key: 'attachments.errors.uploadServiceUnavailable',\n fallback: 'The attachment upload service is not available.',\n}\n\nasync function translateAttachmentError(message: AttachmentErrorMessage): Promise<string> {\n const { t } = await resolveTranslations()\n return t(message.key, message.fallback)\n}\n\nexport type AttachmentOwner = {\n entityId: string\n recordId: string\n}\n\nexport type CreateScopedAttachmentInput = AttachmentOwner & {\n tenantId: string\n organizationId: string\n partitionCode: string\n fileName: string\n declaredMimeType?: string | null\n buffer: Buffer\n assignments?: AttachmentAssignment[]\n /**\n * Persists a module-owned link inside the same transaction as the Attachment\n * row. The callback receives only the generated id, never an Attachment\n * entity or storage implementation.\n */\n persistLink?: (tx: EntityManager, attachmentId: string) => Promise<void> | void\n}\n\nexport type CreatedScopedAttachment = {\n id: string\n url: string\n fileName: string\n mimeType: string\n fileSize: number\n}\n\nexport type ReadScopedAttachmentInput = {\n attachmentId: string\n auth: NonNullable<AuthContext>\n expectedOwner: AttachmentOwner\n expectedAssignment?: AttachmentAssignment\n expectedPartitionCode?: string\n requirePrivatePartition?: boolean\n forceDownload?: boolean\n}\n\nexport type ReadScopedAttachmentResult = {\n buffer: Buffer\n contentType: string\n contentDisposition: string\n fileName: string\n mimeType: string\n}\n\nexport type ReleaseScopedAttachmentInput = {\n attachmentId: string\n tenantId: string\n organizationId: string\n expectedOwner: AttachmentOwner\n /**\n * Required: releasing an attachment deletes the row *and* the provider bytes,\n * so the caller must name the one assignment it owns. The release only\n * proceeds when that assignment is the attachment's sole reference.\n */\n expectedAssignment: AttachmentAssignment\n expectedPartitionCode?: string\n}\n\nexport type AttachmentProviderCleanup = () => Promise<void>\n\nexport interface AttachmentService {\n validateUpload(input: {\n contentLength?: string | null\n fileName?: string\n fileSize?: number\n }): void\n readUploadForm?(request: Request): Promise<FormData>\n createScoped(input: CreateScopedAttachmentInput): Promise<CreatedScopedAttachment>\n readScoped(input: ReadScopedAttachmentInput): Promise<ReadScopedAttachmentResult>\n /**\n * Permanently deletes an attachment row and its stored object once no other row references it.\n *\n * With `{ flush: false }` call it inside your own transaction and run the returned cleanup after\n * commit; `undefined` means another row still references the stored object.\n *\n * @deprecated Calling it with `{ flush: false }` outside a transaction. It still works for one\n * minor version but logs a warning, and its reference check is not locked, so two racing releases\n * of rows sharing the stored object keep it. Wrap the call in a transaction instead.\n */\n releaseScoped?(\n input: ReleaseScopedAttachmentInput,\n options?: { em?: EntityManager; flush?: boolean },\n ): Promise<AttachmentProviderCleanup | void>\n}\n\nasync function readRequestBodyWithinLimit(request: Request, maxBytes: number): Promise<Uint8Array> {\n const reader = request.body?.getReader()\n if (!reader) throw new CrudHttpError(400, { error: 'File is required' })\n const chunks: Uint8Array[] = []\n let totalBytes = 0\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n totalBytes += value.byteLength\n if (totalBytes > maxBytes) {\n await reader.cancel()\n throw new CrudHttpError(413, { error: 'Attachment exceeds the maximum upload size.' })\n }\n chunks.push(value)\n }\n } finally {\n reader.releaseLock()\n }\n const body = new Uint8Array(totalBytes)\n let offset = 0\n for (const chunk of chunks) {\n body.set(chunk, offset)\n offset += chunk.byteLength\n }\n return body\n}\n\n\nfunction assignmentMatches(candidate: AttachmentAssignment, expected: AttachmentAssignment): boolean {\n return candidate.type === expected.type && candidate.id === expected.id\n}\n\nfunction partitionMatchesScope(\n partition: AttachmentPartition,\n tenantId: string | null | undefined,\n organizationId: string | null | undefined,\n): boolean {\n const partitionTenantId = partition.tenantId ?? null\n const partitionOrganizationId = partition.organizationId ?? null\n if (partitionTenantId === null && partitionOrganizationId === null) return true\n if (partitionTenantId === null || partitionOrganizationId === null) return false\n return partitionTenantId === tenantId && partitionOrganizationId === organizationId\n}\n\nexport class DefaultAttachmentService implements AttachmentService {\n /**\n * The scoped upload service is supplied as a *resolver*, not an instance:\n * resolving it eagerly would drag its own dependencies (notably `dataEngine`)\n * into every container that merely constructs an `attachmentService`, even\n * one that never uploads. `createScoped` requires it \u2014 module uploads must\n * share the one reservation ledger rather than run a parallel quota\n * mechanism \u2014 so its absence surfaces there, at the call that needs it.\n */\n constructor(\n private readonly em: EntityManager,\n private readonly storageDriverFactory: StorageDriverFactory,\n private readonly resolveScopedUploadService?: (() => ScopedAttachmentUploadService | null) | null,\n private readonly resolveAccessContext?: (() => AttachmentAccessContext) | null,\n ) {}\n\n validateUpload(input: {\n contentLength?: string | null\n fileName?: string\n fileSize?: number\n }): void {\n if (!isMultipartRequestWithinUploadLimit(input.contentLength ?? null)) {\n throw new CrudHttpError(413, { error: 'Attachment exceeds the maximum upload size.' })\n }\n if (input.fileName && hasDangerousExecutableExtension(input.fileName)) {\n throw new CrudHttpError(400, { error: 'Executable file types are not allowed as attachments.' })\n }\n if (typeof input.fileSize === 'number' && input.fileSize > resolveAttachmentMaxBytes(null)) {\n throw new CrudHttpError(413, { error: 'Attachment exceeds the maximum upload size.' })\n }\n }\n\n async readUploadForm(request: Request): Promise<FormData> {\n this.validateUpload({ contentLength: request.headers.get('content-length') })\n const contentType = request.headers.get('content-type') ?? ''\n if (!contentType.toLowerCase().includes('multipart/form-data')) {\n throw new CrudHttpError(400, { error: 'Expected multipart/form-data' })\n }\n const body = await readRequestBodyWithinLimit(request, resolveAttachmentMultipartMaxBytes())\n const responseBody = body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength) as ArrayBuffer\n try {\n return await new Response(responseBody, { headers: { 'content-type': contentType } }).formData()\n } catch {\n throw new CrudHttpError(400, { error: 'Invalid multipart/form-data' })\n }\n }\n\n async createScoped(input: CreateScopedAttachmentInput): Promise<CreatedScopedAttachment> {\n assertAttachmentScopeInvariant(input)\n this.validateUpload({ fileName: input.fileName, fileSize: input.buffer.length })\n\n // Delegate to the platform's scoped upload service rather than repeating its\n // work. It owns the fenced quota lease (reserve \u2192 storing \u2192 stored \u2192\n // complete) that the recovery worker reconciles, writes to the provider\n // outside the database transaction, and emits the attachment CRUD side\n // effects. The previous implementation here ran a *second*, independent\n // quota mechanism on a different advisory-lock key that counted only\n // committed rows, so it could not see an in-flight reservation from the\n // public attachment route and the two paths could jointly exceed a tenant's\n // quota \u2014 and it wrote to storage inside the transaction, so a crash before\n // commit left bytes nothing accounted for.\n let uploadService: ScopedAttachmentUploadService | null = null\n try {\n uploadService = this.resolveScopedUploadService?.() ?? null\n } catch (error) {\n logger.error('Scoped attachment upload service could not be resolved', { err: error })\n }\n if (!uploadService) {\n throw new CrudHttpError(500, {\n error: await translateAttachmentError(UPLOAD_SERVICE_UNAVAILABLE_MESSAGE),\n })\n }\n\n let attachment: Attachment\n try {\n attachment = await uploadService.upload({\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n entityId: input.entityId,\n recordId: input.recordId,\n fileName: input.fileName,\n buffer: input.buffer,\n declaredMimeType: input.declaredMimeType ?? null,\n assignments: input.assignments,\n partitionCode: input.partitionCode,\n requirePrivatePartition: true,\n persistLink: input.persistLink,\n })\n } catch (error) {\n if (isScopedAttachmentUploadError(error)) {\n const message = SCOPED_UPLOAD_ERROR_MESSAGES[error.code] ?? UPLOAD_FAILED_MESSAGE\n throw new CrudHttpError(error.status, { error: await translateAttachmentError(message) })\n }\n throw error\n }\n\n return {\n id: attachment.id,\n url: attachment.url ?? buildAttachmentFileUrl(attachment.id),\n fileName: attachment.fileName,\n mimeType: attachment.mimeType,\n fileSize: attachment.fileSize,\n }\n }\n\n async readScoped(input: ReadScopedAttachmentInput): Promise<ReadScopedAttachmentResult> {\n // Scope the lookup at the database boundary so a foreign-tenant row is\n // never materialized, then keep checkAttachmentAccess below as defense in\n // depth. This service only ever stores fully scoped rows, so global rows\n // and super-admin status deliberately do not widen the requested scope \u2014\n // a super admin reads another tenant's attachment by switching scope, not\n // by bypassing the filter.\n const attachment = await findOneWithDecryption(\n this.em,\n Attachment,\n {\n id: input.attachmentId,\n tenantId: input.auth.tenantId ?? null,\n organizationId: input.auth.orgId ?? null,\n },\n undefined,\n { tenantId: input.auth.tenantId, organizationId: input.auth.orgId },\n )\n if (!attachment) throw new CrudHttpError(404, { error: 'Attachment not found' })\n const partition = await findOneWithDecryption(\n this.em,\n AttachmentPartition,\n { code: attachment.partitionCode },\n undefined,\n { tenantId: input.auth.tenantId, organizationId: input.auth.orgId },\n )\n if (!partition) throw new CrudHttpError(500, { error: 'Attachment partition is not configured' })\n\n const access = await evaluateAttachmentAccess({\n auth: input.auth, attachment, partition, action: 'read',\n context: this.resolveAccessContext?.(), requireAuthForPublic: true,\n })\n if (!access.ok) await throwAttachmentAccessError(access.status)\n if (!partitionMatchesScope(partition, input.auth.tenantId, input.auth.orgId)) {\n throw new CrudHttpError(403, { error: 'Attachment partition is not accessible for this scope' })\n }\n if (input.requirePrivatePartition && partition.isPublic) {\n throw new CrudHttpError(403, { error: 'Attachment partition is not accessible for this resource' })\n }\n if (input.expectedPartitionCode && attachment.partitionCode !== input.expectedPartitionCode) {\n throw new CrudHttpError(404, { error: 'Attachment not found' })\n }\n if (\n attachment.entityId !== input.expectedOwner.entityId ||\n attachment.recordId !== input.expectedOwner.recordId\n ) {\n throw new CrudHttpError(404, { error: 'Attachment not found' })\n }\n if (input.expectedAssignment) {\n const assignments = readAttachmentMetadata(attachment.storageMetadata).assignments ?? []\n if (!assignments.some((candidate) => assignmentMatches(candidate, input.expectedAssignment!))) {\n throw new CrudHttpError(404, { error: 'Attachment not found' })\n }\n }\n\n const driver = await this.storageDriverFactory.resolveForPartition(attachment.partitionCode, {\n tenantId: attachment.tenantId ?? '',\n organizationId: attachment.organizationId ?? '',\n })\n let result: Awaited<ReturnType<typeof driver.read>>\n try {\n result = await driver.read(attachment.partitionCode, attachment.storagePath)\n } catch {\n throw new CrudHttpError(404, { error: 'File not available' })\n }\n\n const mimeType = attachment.mimeType || 'application/octet-stream'\n const renderInline = !input.forceDownload && canRenderInlineAttachment(mimeType)\n return {\n buffer: result.buffer,\n contentType: renderInline ? result.contentType ?? mimeType : 'application/octet-stream',\n contentDisposition: buildAttachmentContentDisposition(\n attachment.fileName,\n renderInline ? 'inline' : 'attachment',\n ),\n fileName: attachment.fileName,\n mimeType,\n }\n }\n\n async releaseScoped(\n input: ReleaseScopedAttachmentInput,\n options: { em?: EntityManager; flush?: boolean } = {},\n ): Promise<AttachmentProviderCleanup | void> {\n const em = options.em ?? this.em\n // The type makes `expectedAssignment` mandatory, but this service is handed\n // out through untyped DI resolution and consumed through structural ports in\n // other packages, so the shared-reference guard is enforced at runtime too:\n // without it a caller could destroy an attachment other records still link.\n const expectedAssignment = input.expectedAssignment\n if (!expectedAssignment) {\n throw new CrudHttpError(500, {\n error: 'Attachment release requires the expected assignment of the releasing record',\n })\n }\n const isInTransaction = (em as { isInTransaction?: () => boolean }).isInTransaction\n if (\n options.flush !== false\n && typeof isInTransaction === 'function'\n && isInTransaction.call(em)\n ) {\n throw new CrudHttpError(500, {\n error: 'Attachment release inside an ambient transaction requires flush: false and deferred provider cleanup',\n })\n }\n const deferredOutsideTransaction = options.flush === false\n && typeof isInTransaction === 'function'\n && !isInTransaction.call(em)\n if (deferredOutsideTransaction) {\n logger.warn(\n '[deprecated] attachmentService.releaseScoped({ flush: false }) called outside a transaction; wrap it in a transaction so the storage reference lock is held until commit',\n { attachmentId: input.attachmentId },\n )\n }\n const scope = { tenantId: input.tenantId, organizationId: input.organizationId }\n const attachment = await findOneWithDecryption(\n em,\n Attachment,\n {\n id: input.attachmentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n },\n undefined,\n scope,\n )\n if (!attachment) throw new CrudHttpError(404, { error: 'Attachment not found' })\n if (\n attachment.entityId !== input.expectedOwner.entityId\n || attachment.recordId !== input.expectedOwner.recordId\n || (input.expectedPartitionCode && attachment.partitionCode !== input.expectedPartitionCode)\n ) {\n throw new CrudHttpError(404, { error: 'Attachment not found' })\n }\n const assignments = readAttachmentMetadata(attachment.storageMetadata).assignments ?? []\n if (!assignments.some((candidate) => assignmentMatches(candidate, expectedAssignment))) {\n throw new CrudHttpError(409, { error: 'Attachment is still referenced by another record' })\n }\n if (assignments.some((candidate) => !assignmentMatches(candidate, expectedAssignment))) {\n throw new CrudHttpError(409, { error: 'Attachment is still referenced by another record' })\n }\n\n const driver = await this.storageDriverFactory.resolveForPartition(attachment.partitionCode, scope)\n const deleteProviderBytes = () => driver.delete(attachment.partitionCode, attachment.storagePath)\n if (options.flush === false) {\n const referenceIds = deferredOutsideTransaction\n ? await listAttachmentStorageReferences(em, attachment)\n : await lockAttachmentStorageReferences(em, attachment)\n const removal = resolveAttachmentStorageRelease(referenceIds, attachment.id)\n if (!removal.removed) throw new CrudHttpError(404, { error: 'Attachment not found' })\n em.remove(attachment)\n return removal.releaseStorage ? deleteProviderBytes : undefined\n }\n const removal = await removeAttachmentRecord(em, attachment)\n if (!removal.removed) throw new CrudHttpError(404, { error: 'Attachment not found' })\n if (removal.releaseStorage) await deleteProviderBytes()\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,gCAA8D;AACvE,SAAS,kCAAkC;AAG3C,SAAS,qBAAqB;AAC9B,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAC7B,SAAS,YAAY,2BAA2B;AAChD,SAAS,sCAA6D;AAEtE,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,OAGK;AACP,SAAS,8BAAyD;AAClE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,SAAS,aAAa,aAAa,EAAE,MAAM,EAAE,WAAW,qBAAqB,CAAC;AAcpF,MAAM,+BAAgG;AAAA,EACpG,sBAAsB;AAAA,IACpB,KAAK;AAAA,IACL,UAAU;AAAA,EACZ;AAAA,EACA,iBAAiB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AAK,EAAE,OAAO,uBAAuB,CAAC;AAAA,IAChE;AACA,UAAM,cAAc,uBAAuB,WAAW,eAAe,EAAE,eAAe,CAAC;AACvF,QAAI,CAAC,YAAY,KAAK,CAAC,cAAc,kBAAkB,WAAW,kBAAkB,CAAC,GAAG;AACtF,YAAM,IAAI,cAAc,KAAK,EAAE,OAAO,mDAAmD,CAAC;AAAA,IAC5F;AACA,QAAI,YAAY,KAAK,CAAC,cAAc,CAAC,kBAAkB,WAAW,kBAAkB,CAAC,GAAG;AACtF,YAAM,IAAI,cAAc,KAAK,EAAE,OAAO,mDAAmD,CAAC;AAAA,IAC5F;AAEA,UAAM,SAAS,MAAM,KAAK,qBAAqB,oBAAoB,WAAW,eAAe,KAAK;AAClG,UAAM,sBAAsB,MAAM,OAAO,OAAO,WAAW,eAAe,WAAW,WAAW;AAChG,QAAI,QAAQ,UAAU,OAAO;AAC3B,YAAM,eAAe,6BACjB,MAAM,gCAAgC,IAAI,UAAU,IACpD,MAAM,gCAAgC,IAAI,UAAU;AACxD,YAAMA,WAAU,gCAAgC,cAAc,WAAW,EAAE;AAC3E,UAAI,CAACA,SAAQ,QAAS,OAAM,IAAI,cAAc,KAAK,EAAE,OAAO,uBAAuB,CAAC;AACpF,SAAG,OAAO,UAAU;AACpB,aAAOA,SAAQ,iBAAiB,sBAAsB;AAAA,IACxD;AACA,UAAM,UAAU,MAAM,uBAAuB,IAAI,UAAU;AAC3D,QAAI,CAAC,QAAQ,QAAS,OAAM,IAAI,cAAc,KAAK,EAAE,OAAO,uBAAuB,CAAC;AACpF,QAAI,QAAQ,eAAgB,OAAM,oBAAoB;AAAA,EACxD;AACF;",
|
|
6
6
|
"names": ["removal"]
|
|
7
7
|
}
|
|
@@ -7,6 +7,7 @@ import { buildAttachmentFileUrl } from "./imageUrls.js";
|
|
|
7
7
|
import { mergeAttachmentMetadata, upsertAssignment } from "./metadata.js";
|
|
8
8
|
import { assertAttachmentScopeInvariant } from "./access.js";
|
|
9
9
|
import { attachmentCrudEvents, attachmentCrudIndexer } from "./crud.js";
|
|
10
|
+
import { ensureAttachmentPartitionProtection } from "./access-protection.js";
|
|
10
11
|
async function createAttachmentFromBuffer(input) {
|
|
11
12
|
const { em } = input;
|
|
12
13
|
const code = input.partitionCode && input.partitionCode.length > 0 ? input.partitionCode : resolveDefaultPartitionCode(input.entityId);
|
|
@@ -16,6 +17,7 @@ async function createAttachmentFromBuffer(input) {
|
|
|
16
17
|
partition = await em.findOne(AttachmentPartition, { code });
|
|
17
18
|
}
|
|
18
19
|
if (!partition) throw new Error(`[internal] attachment partition "${code}" is not available`);
|
|
20
|
+
await ensureAttachmentPartitionProtection(em, partition);
|
|
19
21
|
const driver = await new StorageDriverFactory(em).resolveForPartition(partition.code, {
|
|
20
22
|
tenantId: input.tenantId,
|
|
21
23
|
organizationId: input.organizationId
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/attachments/lib/createFromBuffer.ts"],
|
|
4
|
-
"sourcesContent": ["import { randomUUID } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { emitCrudSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport { Attachment, AttachmentPartition } from '../data/entities'\nimport { StorageDriverFactory } from './drivers'\nimport { ensureDefaultPartitions, resolveDefaultPartitionCode } from './partitions'\nimport { buildAttachmentFileUrl } from './imageUrls'\nimport { mergeAttachmentMetadata, upsertAssignment } from './metadata'\nimport { assertAttachmentScopeInvariant } from './access'\nimport { attachmentCrudEvents, attachmentCrudIndexer } from './crud'\n\n/** DataEngine handle whose exact type is derived from `emitCrudSideEffects` (no `any`). */\ntype CrudDataEngine = Parameters<typeof emitCrudSideEffects>[0]['dataEngine']\n\nexport type CreateAttachmentFromBufferInput = {\n em: EntityManager\n /** When provided, fires CRUD side effects (events + indexing). Omit to skip. */\n dataEngine?: CrudDataEngine\n tenantId: string\n organizationId: string\n /** Domain entity this attachment is linked to (e.g. 'customers:deal'). */\n entityId: string\n recordId: string\n fileName: string\n mimeType: string\n buffer: Buffer\n /** Storage partition; defaults to the entity's default partition. */\n partitionCode?: string | null\n}\n\nexport type CreatedAttachment = {\n id: string\n fileName: string\n mimeType: string\n fileSize: number\n url: string\n}\n\n/**\n * Create a durable `Attachment` from an in-memory buffer, linked to a domain\n * record. Additive reusable seam extracted from the upload route's store block so\n * server-side producers (e.g. the agent file-plane artifact-promotion effector,\n * #12) can materialize an attachment without going through the multipart HTTP\n * route. Resolves the partition + driver, stores the bytes, persists the row\n * atomically, and (when a `dataEngine` is passed) fires CRUD side effects so the\n * attachment is indexed and its events emitted \u2014 exactly like an uploaded file.\n */\nexport async function createAttachmentFromBuffer(input: CreateAttachmentFromBufferInput): Promise<CreatedAttachment> {\n const { em } = input\n const code = (input.partitionCode && input.partitionCode.length > 0)\n ? input.partitionCode\n : resolveDefaultPartitionCode(input.entityId)\n\n let partition = await em.findOne(AttachmentPartition, { code })\n if (!partition) {\n await ensureDefaultPartitions(em)\n partition = await em.findOne(AttachmentPartition, { code })\n }\n if (!partition) throw new Error(`[internal] attachment partition \"${code}\" is not available`)\n\n const driver = await new StorageDriverFactory(em).resolveForPartition(partition.code, {\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n })\n const stored = await driver.store({\n partitionCode: partition.code,\n orgId: input.organizationId,\n tenantId: input.tenantId,\n fileName: input.fileName,\n buffer: input.buffer,\n })\n\n const metadata = mergeAttachmentMetadata(null, {\n assignments: upsertAssignment([], { type: input.entityId, id: input.recordId }),\n })\n const attachmentId = randomUUID()\n assertAttachmentScopeInvariant({ tenantId: input.tenantId, organizationId: input.organizationId })\n const attachment = em.create(Attachment, {\n id: attachmentId,\n entityId: input.entityId,\n recordId: input.recordId,\n organizationId: input.organizationId,\n tenantId: input.tenantId,\n fileName: input.fileName,\n mimeType: input.mimeType,\n fileSize: input.buffer.length,\n partitionCode: partition.code,\n storageDriver: partition.storageDriver || 'local',\n storagePath: stored.storagePath,\n url: buildAttachmentFileUrl(attachmentId),\n content: null,\n storageMetadata: metadata,\n })\n await em.transactional(async (tx) => {\n await tx.persist(attachment).flush()\n })\n\n if (input.dataEngine) {\n await emitCrudSideEffects({\n dataEngine: input.dataEngine,\n action: 'created',\n entity: attachment,\n identifiers: {\n id: attachment.id,\n organizationId: attachment.organizationId ?? null,\n tenantId: attachment.tenantId ?? null,\n },\n events: attachmentCrudEvents,\n indexer: attachmentCrudIndexer,\n })\n }\n\n return {\n id: attachmentId,\n fileName: input.fileName,\n mimeType: input.mimeType,\n fileSize: input.buffer.length,\n url: attachment.url,\n }\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,kBAAkB;AAE3B,SAAS,2BAA2B;AACpC,SAAS,YAAY,2BAA2B;AAChD,SAAS,4BAA4B;AACrC,SAAS,yBAAyB,mCAAmC;AACrE,SAAS,8BAA8B;AACvC,SAAS,yBAAyB,wBAAwB;AAC1D,SAAS,sCAAsC;AAC/C,SAAS,sBAAsB,6BAA6B;
|
|
4
|
+
"sourcesContent": ["import { randomUUID } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { emitCrudSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport { Attachment, AttachmentPartition } from '../data/entities'\nimport { StorageDriverFactory } from './drivers'\nimport { ensureDefaultPartitions, resolveDefaultPartitionCode } from './partitions'\nimport { buildAttachmentFileUrl } from './imageUrls'\nimport { mergeAttachmentMetadata, upsertAssignment } from './metadata'\nimport { assertAttachmentScopeInvariant } from './access'\nimport { attachmentCrudEvents, attachmentCrudIndexer } from './crud'\nimport { ensureAttachmentPartitionProtection } from './access-protection'\n\n/** DataEngine handle whose exact type is derived from `emitCrudSideEffects` (no `any`). */\ntype CrudDataEngine = Parameters<typeof emitCrudSideEffects>[0]['dataEngine']\n\nexport type CreateAttachmentFromBufferInput = {\n em: EntityManager\n /** When provided, fires CRUD side effects (events + indexing). Omit to skip. */\n dataEngine?: CrudDataEngine\n tenantId: string\n organizationId: string\n /** Domain entity this attachment is linked to (e.g. 'customers:deal'). */\n entityId: string\n recordId: string\n fileName: string\n mimeType: string\n buffer: Buffer\n /** Storage partition; defaults to the entity's default partition. */\n partitionCode?: string | null\n}\n\nexport type CreatedAttachment = {\n id: string\n fileName: string\n mimeType: string\n fileSize: number\n url: string\n}\n\n/**\n * Create a durable `Attachment` from an in-memory buffer, linked to a domain\n * record. Additive reusable seam extracted from the upload route's store block so\n * server-side producers (e.g. the agent file-plane artifact-promotion effector,\n * #12) can materialize an attachment without going through the multipart HTTP\n * route. Resolves the partition + driver, stores the bytes, persists the row\n * atomically, and (when a `dataEngine` is passed) fires CRUD side effects so the\n * attachment is indexed and its events emitted \u2014 exactly like an uploaded file.\n */\nexport async function createAttachmentFromBuffer(input: CreateAttachmentFromBufferInput): Promise<CreatedAttachment> {\n const { em } = input\n const code = (input.partitionCode && input.partitionCode.length > 0)\n ? input.partitionCode\n : resolveDefaultPartitionCode(input.entityId)\n\n let partition = await em.findOne(AttachmentPartition, { code })\n if (!partition) {\n await ensureDefaultPartitions(em)\n partition = await em.findOne(AttachmentPartition, { code })\n }\n if (!partition) throw new Error(`[internal] attachment partition \"${code}\" is not available`)\n\n await ensureAttachmentPartitionProtection(em, partition)\n\n const driver = await new StorageDriverFactory(em).resolveForPartition(partition.code, {\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n })\n const stored = await driver.store({\n partitionCode: partition.code,\n orgId: input.organizationId,\n tenantId: input.tenantId,\n fileName: input.fileName,\n buffer: input.buffer,\n })\n\n const metadata = mergeAttachmentMetadata(null, {\n assignments: upsertAssignment([], { type: input.entityId, id: input.recordId }),\n })\n const attachmentId = randomUUID()\n assertAttachmentScopeInvariant({ tenantId: input.tenantId, organizationId: input.organizationId })\n const attachment = em.create(Attachment, {\n id: attachmentId,\n entityId: input.entityId,\n recordId: input.recordId,\n organizationId: input.organizationId,\n tenantId: input.tenantId,\n fileName: input.fileName,\n mimeType: input.mimeType,\n fileSize: input.buffer.length,\n partitionCode: partition.code,\n storageDriver: partition.storageDriver || 'local',\n storagePath: stored.storagePath,\n url: buildAttachmentFileUrl(attachmentId),\n content: null,\n storageMetadata: metadata,\n })\n await em.transactional(async (tx) => {\n await tx.persist(attachment).flush()\n })\n\n if (input.dataEngine) {\n await emitCrudSideEffects({\n dataEngine: input.dataEngine,\n action: 'created',\n entity: attachment,\n identifiers: {\n id: attachment.id,\n organizationId: attachment.organizationId ?? null,\n tenantId: attachment.tenantId ?? null,\n },\n events: attachmentCrudEvents,\n indexer: attachmentCrudIndexer,\n })\n }\n\n return {\n id: attachmentId,\n fileName: input.fileName,\n mimeType: input.mimeType,\n fileSize: input.buffer.length,\n url: attachment.url,\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,kBAAkB;AAE3B,SAAS,2BAA2B;AACpC,SAAS,YAAY,2BAA2B;AAChD,SAAS,4BAA4B;AACrC,SAAS,yBAAyB,mCAAmC;AACrE,SAAS,8BAA8B;AACvC,SAAS,yBAAyB,wBAAwB;AAC1D,SAAS,sCAAsC;AAC/C,SAAS,sBAAsB,6BAA6B;AAC5D,SAAS,2CAA2C;AAsCpD,eAAsB,2BAA2B,OAAoE;AACnH,QAAM,EAAE,GAAG,IAAI;AACf,QAAM,OAAQ,MAAM,iBAAiB,MAAM,cAAc,SAAS,IAC9D,MAAM,gBACN,4BAA4B,MAAM,QAAQ;AAE9C,MAAI,YAAY,MAAM,GAAG,QAAQ,qBAAqB,EAAE,KAAK,CAAC;AAC9D,MAAI,CAAC,WAAW;AACd,UAAM,wBAAwB,EAAE;AAChC,gBAAY,MAAM,GAAG,QAAQ,qBAAqB,EAAE,KAAK,CAAC;AAAA,EAC5D;AACA,MAAI,CAAC,UAAW,OAAM,IAAI,MAAM,oCAAoC,IAAI,oBAAoB;AAE5F,QAAM,oCAAoC,IAAI,SAAS;AAEvD,QAAM,SAAS,MAAM,IAAI,qBAAqB,EAAE,EAAE,oBAAoB,UAAU,MAAM;AAAA,IACpF,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ACH;AAEA,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,UAAU,MAAM;AAAA,IAChB,UAAU,MAAM;AAAA,IAChB,UAAU,MAAM,OAAO;AAAA,IACvB,KAAK,WAAW;AAAA,EAClB;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -2,6 +2,7 @@ import { AttachmentPartition } from "../data/entities.js";
|
|
|
2
2
|
import { resolveDefaultAttachmentOcrEnabled } from "./ocrConfig.js";
|
|
3
3
|
import { parseBooleanToken } from "@open-mercato/shared/lib/boolean";
|
|
4
4
|
import { E } from "../../../generated/entities.ids.generated.js";
|
|
5
|
+
import { getDeclaredAttachmentAccessRequirements } from "./access-protection.js";
|
|
5
6
|
const DEFAULT_ATTACHMENT_PARTITIONS = [
|
|
6
7
|
{
|
|
7
8
|
code: "productsMedia",
|
|
@@ -30,7 +31,6 @@ async function ensureDefaultPartitions(em) {
|
|
|
30
31
|
const existing = await repo.findAll({ fields: ["code"] });
|
|
31
32
|
const existingCodes = new Set(existing.map((entry) => entry.code));
|
|
32
33
|
const pending = DEFAULT_ATTACHMENT_PARTITIONS.filter((seed) => !existingCodes.has(seed.code));
|
|
33
|
-
if (!pending.length) return;
|
|
34
34
|
for (const seed of pending) {
|
|
35
35
|
const record = repo.create({
|
|
36
36
|
code: seed.code,
|
|
@@ -38,11 +38,12 @@ async function ensureDefaultPartitions(em) {
|
|
|
38
38
|
description: seed.description ?? null,
|
|
39
39
|
storageDriver: "local",
|
|
40
40
|
isPublic: seed.isPublic ?? false,
|
|
41
|
+
accessResolverRequirements: getDeclaredAttachmentAccessRequirements(seed.code),
|
|
41
42
|
requiresOcr: resolveDefaultAttachmentOcrEnabled()
|
|
42
43
|
});
|
|
43
44
|
em.persist(record);
|
|
44
45
|
}
|
|
45
|
-
await em.flush();
|
|
46
|
+
if (pending.length) await em.flush();
|
|
46
47
|
}
|
|
47
48
|
function sanitizePartitionCode(input) {
|
|
48
49
|
const trimmed = input.trim();
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/attachments/lib/partitions.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { AttachmentPartition } from '../data/entities'\nimport { resolveDefaultAttachmentOcrEnabled } from './ocrConfig'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { E } from '#generated/entities.ids.generated'\n\nexport type AttachmentPartitionSeed = {\n code: string\n title: string\n description?: string | null\n isPublic?: boolean\n}\n\nexport const DEFAULT_ATTACHMENT_PARTITIONS: AttachmentPartitionSeed[] = [\n {\n code: 'productsMedia',\n title: 'Products media',\n description: 'Public media uploaded for catalog products.',\n isPublic: true,\n },\n {\n code: 'privateAttachments',\n title: 'Private attachments',\n description: 'Internal attachments scoped to tenants and organizations.',\n isPublic: false,\n },\n]\n\nconst PRODUCT_MEDIA_ENTITY_IDS = new Set<string>(\n [(E as any).catalog?.catalog_product].filter(Boolean) as string[]\n)\n\nconst FALLBACK_PARTITION = 'privateAttachments'\n\nexport function resolveDefaultPartitionCode(entityId: string | null | undefined): string {\n if (!entityId) return FALLBACK_PARTITION\n if (PRODUCT_MEDIA_ENTITY_IDS.has(entityId)) return 'productsMedia'\n return FALLBACK_PARTITION\n}\n\nexport async function ensureDefaultPartitions(em: EntityManager): Promise<void> {\n const repo = em.getRepository(AttachmentPartition)\n const existing = await repo.findAll({ fields: ['code'] })\n const existingCodes = new Set(existing.map((entry) => entry.code))\n const pending = DEFAULT_ATTACHMENT_PARTITIONS.filter((seed) => !existingCodes.has(seed.code))\n
|
|
5
|
-
"mappings": "AACA,SAAS,2BAA2B;AACpC,SAAS,0CAA0C;AACnD,SAAS,yBAAyB;AAClC,SAAS,SAAS;
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { AttachmentPartition } from '../data/entities'\nimport { resolveDefaultAttachmentOcrEnabled } from './ocrConfig'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { E } from '#generated/entities.ids.generated'\nimport { getDeclaredAttachmentAccessRequirements } from './access-protection'\n\nexport type AttachmentPartitionSeed = {\n code: string\n title: string\n description?: string | null\n isPublic?: boolean\n}\n\nexport const DEFAULT_ATTACHMENT_PARTITIONS: AttachmentPartitionSeed[] = [\n {\n code: 'productsMedia',\n title: 'Products media',\n description: 'Public media uploaded for catalog products.',\n isPublic: true,\n },\n {\n code: 'privateAttachments',\n title: 'Private attachments',\n description: 'Internal attachments scoped to tenants and organizations.',\n isPublic: false,\n },\n]\n\nconst PRODUCT_MEDIA_ENTITY_IDS = new Set<string>(\n [(E as any).catalog?.catalog_product].filter(Boolean) as string[]\n)\n\nconst FALLBACK_PARTITION = 'privateAttachments'\n\nexport function resolveDefaultPartitionCode(entityId: string | null | undefined): string {\n if (!entityId) return FALLBACK_PARTITION\n if (PRODUCT_MEDIA_ENTITY_IDS.has(entityId)) return 'productsMedia'\n return FALLBACK_PARTITION\n}\n\nexport async function ensureDefaultPartitions(em: EntityManager): Promise<void> {\n const repo = em.getRepository(AttachmentPartition)\n const existing = await repo.findAll({ fields: ['code'] })\n const existingCodes = new Set(existing.map((entry) => entry.code))\n const pending = DEFAULT_ATTACHMENT_PARTITIONS.filter((seed) => !existingCodes.has(seed.code))\n for (const seed of pending) {\n const record = repo.create({\n code: seed.code,\n title: seed.title,\n description: seed.description ?? null,\n storageDriver: 'local',\n isPublic: seed.isPublic ?? false,\n accessResolverRequirements: getDeclaredAttachmentAccessRequirements(seed.code),\n requiresOcr: resolveDefaultAttachmentOcrEnabled(),\n })\n em.persist(record)\n }\n if (pending.length) await em.flush()\n}\n\nexport function sanitizePartitionCode(input: string): string {\n const trimmed = input.trim()\n const normalized = trimmed.replace(/[^a-zA-Z0-9_-]/g, '')\n return normalized\n}\n\nexport function isPartitionSettingsLocked(): boolean {\n const demoModeParsed = parseBooleanToken(process.env.DEMO_MODE ?? '')\n const demoModeEnabled = demoModeParsed === false ? false : true\n const onboardingEnabled = parseBooleanToken(process.env.SELF_SERVICE_ONBOARDING_ENABLED ?? '') === true\n return demoModeEnabled || onboardingEnabled\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,2BAA2B;AACpC,SAAS,0CAA0C;AACnD,SAAS,yBAAyB;AAClC,SAAS,SAAS;AAClB,SAAS,+CAA+C;AASjD,MAAM,gCAA2D;AAAA,EACtE;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,IACP,aAAa;AAAA,IACb,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,IACP,aAAa;AAAA,IACb,UAAU;AAAA,EACZ;AACF;AAEA,MAAM,2BAA2B,IAAI;AAAA,EACnC,CAAE,EAAU,SAAS,eAAe,EAAE,OAAO,OAAO;AACtD;AAEA,MAAM,qBAAqB;AAEpB,SAAS,4BAA4B,UAA6C;AACvF,MAAI,CAAC,SAAU,QAAO;AACtB,MAAI,yBAAyB,IAAI,QAAQ,EAAG,QAAO;AACnD,SAAO;AACT;AAEA,eAAsB,wBAAwB,IAAkC;AAC9E,QAAM,OAAO,GAAG,cAAc,mBAAmB;AACjD,QAAM,WAAW,MAAM,KAAK,QAAQ,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;AACxD,QAAM,gBAAgB,IAAI,IAAI,SAAS,IAAI,CAAC,UAAU,MAAM,IAAI,CAAC;AACjE,QAAM,UAAU,8BAA8B,OAAO,CAAC,SAAS,CAAC,cAAc,IAAI,KAAK,IAAI,CAAC;AAC5F,aAAW,QAAQ,SAAS;AAC1B,UAAM,SAAS,KAAK,OAAO;AAAA,MACzB,MAAM,KAAK;AAAA,MACX,OAAO,KAAK;AAAA,MACZ,aAAa,KAAK,eAAe;AAAA,MACjC,eAAe;AAAA,MACf,UAAU,KAAK,YAAY;AAAA,MAC3B,4BAA4B,wCAAwC,KAAK,IAAI;AAAA,MAC7E,aAAa,mCAAmC;AAAA,IAClD,CAAC;AACD,OAAG,QAAQ,MAAM;AAAA,EACnB;AACA,MAAI,QAAQ,OAAQ,OAAM,GAAG,MAAM;AACrC;AAEO,SAAS,sBAAsB,OAAuB;AAC3D,QAAM,UAAU,MAAM,KAAK;AAC3B,QAAM,aAAa,QAAQ,QAAQ,mBAAmB,EAAE;AACxD,SAAO;AACT;AAEO,SAAS,4BAAqC;AACnD,QAAM,iBAAiB,kBAAkB,QAAQ,IAAI,aAAa,EAAE;AACpE,QAAM,kBAAkB,mBAAmB,QAAQ,QAAQ;AAC3D,QAAM,oBAAoB,kBAAkB,QAAQ,IAAI,mCAAmC,EAAE,MAAM;AACnG,SAAO,mBAAmB;AAC5B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -6,6 +6,7 @@ import { createLogger } from "@open-mercato/shared/lib/logger";
|
|
|
6
6
|
import { Attachment, AttachmentPartition } from "../data/entities.js";
|
|
7
7
|
import { attachmentCrudEvents, attachmentCrudIndexer } from "./crud.js";
|
|
8
8
|
import { buildAttachmentFileUrl } from "./imageUrls.js";
|
|
9
|
+
import { ensureAttachmentPartitionProtection } from "./access-protection.js";
|
|
9
10
|
import { ensureDefaultPartitions, resolveDefaultPartitionCode } from "./partitions.js";
|
|
10
11
|
import { extractAttachmentContent } from "./textExtraction.js";
|
|
11
12
|
import { requestOcrProcessing } from "./ocrQueue.js";
|
|
@@ -66,6 +67,7 @@ class ScopedAttachmentUploadService {
|
|
|
66
67
|
if (input.requirePrivatePartition && partition.isPublic) {
|
|
67
68
|
throw new ScopedAttachmentUploadError("partition_unavailable", 403);
|
|
68
69
|
}
|
|
70
|
+
await ensureAttachmentPartitionProtection(em, partition);
|
|
69
71
|
const driver = await storageDriverFactory.resolveForPartition(partition.code, {
|
|
70
72
|
tenantId: input.tenantId,
|
|
71
73
|
organizationId: input.organizationId
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/attachments/lib/scoped-upload-service.ts"],
|
|
4
|
-
"sourcesContent": ["import { randomUUID } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { emitCrudSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { Attachment, AttachmentPartition } from '../data/entities'\nimport { attachmentCrudEvents, attachmentCrudIndexer } from './crud'\nimport type { StorageDriverFactory } from './drivers'\nimport { buildAttachmentFileUrl } from './imageUrls'\nimport { ensureDefaultPartitions, resolveDefaultPartitionCode } from './partitions'\nimport { extractAttachmentContent } from './textExtraction'\nimport { requestOcrProcessing } from './ocrQueue'\nimport { OcrService, shouldUseLlmOcr } from './ocrService'\nimport { assertAttachmentScopeInvariant } from './access'\nimport {\n mergeAttachmentMetadata,\n upsertAssignment,\n type AttachmentAssignment,\n} from './metadata'\nimport {\n detectAttachmentMimeType,\n hasDangerousExecutableExtension,\n isActiveContentAttachment,\n sanitizeUploadedFileName,\n} from './security'\nimport { resolveAttachmentMaxBytes } from './upload-limits'\nimport type { AttachmentQuotaService } from './quota-service'\n\nconst logger = createLogger('attachments')\n\nexport type ScopedAttachmentUploadErrorCode =\n | 'dangerous_executable'\n | 'max_upload_size'\n | 'active_content'\n | 'partition_unavailable'\n | 'quota_exceeded'\n | 'quota_target_exists'\n | 'quota_unavailable'\n | 'quota_recovery_unsupported'\n | 'storage_failed'\n | 'persistence_failed'\n\n// Use Symbol.for so the marker survives module duplication across bundle\n// boundaries. The production build emits this module into several server\n// chunks, so a consumer's `instanceof` compares against a different copy of the\n// class than the DI-resolved service threw from: the check silently fails, the\n// error escapes the caller's catch, and a deliberate 400/413 surfaces as a 500.\nconst SCOPED_ATTACHMENT_UPLOAD_ERROR_MARKER = Symbol.for('@open-mercato/ScopedAttachmentUploadError')\n\nexport class ScopedAttachmentUploadError extends Error {\n readonly [SCOPED_ATTACHMENT_UPLOAD_ERROR_MARKER] = true\n\n constructor(\n public readonly code: ScopedAttachmentUploadErrorCode,\n public readonly status: number,\n ) {\n super(code)\n this.name = 'ScopedAttachmentUploadError'\n }\n}\n\n/**\n * Bundle-safe check for `ScopedAttachmentUploadError`. Prefer this over\n * `instanceof` at every call site \u2014 the class is duplicated across server\n * chunks, so `instanceof` is only reliable inside this module.\n */\nexport function isScopedAttachmentUploadError(error: unknown): error is ScopedAttachmentUploadError {\n return Boolean(error)\n && typeof error === 'object'\n && (error as Record<symbol, unknown>)[SCOPED_ATTACHMENT_UPLOAD_ERROR_MARKER] === true\n}\n\nexport type ScopedAttachmentUploadInput = {\n tenantId: string\n organizationId: string\n entityId: string\n recordId: string\n fileName: string\n declaredMimeType?: string | null\n buffer: Buffer\n tags?: string[]\n assignments?: AttachmentAssignment[]\n partitionCode?: string | null\n maxBytes?: number\n /**\n * Reject a partition flagged public, so a module-owned upload (documents,\n * warranty claims) never lands where an anonymous reader can reach it. The\n * tenant/organization half of that guarantee is not this flag's job: the\n * partition lookup below already matches only a global partition or one owned\n * by this tenant and organization, whether or not the flag is set.\n */\n requirePrivatePartition?: boolean\n /**\n * Persists a module-owned link row inside the same transaction as the\n * Attachment, so a link failure cannot leave a committed orphan attachment.\n * The callback receives only the generated id, never the entity or the\n * storage implementation.\n */\n persistLink?: (tx: EntityManager, attachmentId: string) => Promise<void> | void\n}\n\ntype QuotaRecoveryScheduler = (\n payload: { reservationId: string; tenantId: string; organizationId: string },\n delayMs: number,\n) => Promise<void>\n\nexport class ScopedAttachmentUploadService {\n constructor(private readonly deps: {\n em: EntityManager\n dataEngine?: DataEngine | null\n storageDriverFactory: StorageDriverFactory\n attachmentQuotaService: AttachmentQuotaService\n attachmentQuotaRecoveryScheduler: QuotaRecoveryScheduler\n }) {}\n\n async upload(input: ScopedAttachmentUploadInput): Promise<Attachment> {\n const safeName = sanitizeUploadedFileName(input.fileName)\n if (hasDangerousExecutableExtension(safeName)) {\n throw new ScopedAttachmentUploadError('dangerous_executable', 400)\n }\n if (input.buffer.length > (input.maxBytes ?? resolveAttachmentMaxBytes())) {\n throw new ScopedAttachmentUploadError('max_upload_size', 413)\n }\n const mimeType = detectAttachmentMimeType(input.buffer, safeName, input.declaredMimeType ?? '')\n if (isActiveContentAttachment(input.buffer, safeName, mimeType)) {\n throw new ScopedAttachmentUploadError('active_content', 400)\n }\n\n const { em, storageDriverFactory, attachmentQuotaService, attachmentQuotaRecoveryScheduler } = this.deps\n await ensureDefaultPartitions(em)\n const partitionCode = input.partitionCode ?? resolveDefaultPartitionCode(input.entityId)\n const partition = await em.findOne(AttachmentPartition, {\n code: partitionCode,\n $or: [\n { tenantId: null, organizationId: null },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n ],\n })\n if (!partition) throw new ScopedAttachmentUploadError('partition_unavailable', 400)\n if (input.requirePrivatePartition && partition.isPublic) {\n throw new ScopedAttachmentUploadError('partition_unavailable', 403)\n }\n\n const driver = await storageDriverFactory.resolveForPartition(partition.code, {\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n })\n const preparedStoragePath = driver.prepareStoragePath?.({\n partitionCode: partition.code,\n orgId: input.organizationId,\n tenantId: input.tenantId,\n fileName: safeName,\n })\n if (!preparedStoragePath) {\n throw new ScopedAttachmentUploadError('quota_recovery_unsupported', 500)\n }\n\n let reservation: { id: string; leaseToken: string; expiresAt: Date } | null = null\n try {\n reservation = await attachmentQuotaService.reserve({\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n bytes: input.buffer.length,\n source: 'attachment',\n storageDriver: driver.key,\n storagePath: preparedStoragePath,\n partitionCode: partition.code,\n })\n await attachmentQuotaRecoveryScheduler({\n reservationId: reservation.id,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n }, Math.max(1_000, reservation.expiresAt.getTime() - Date.now()))\n await attachmentQuotaService.beginStorage(reservation.id, reservation.leaseToken)\n } catch (error) {\n if (reservation) {\n await attachmentQuotaService.release(reservation.id, reservation.leaseToken).catch(() => undefined)\n }\n const code = (error as { code?: unknown })?.code\n if (code === 'quota_exceeded') throw new ScopedAttachmentUploadError('quota_exceeded', 413)\n if (code === 'quota_target_exists') throw new ScopedAttachmentUploadError('quota_target_exists', 409)\n throw new ScopedAttachmentUploadError('quota_unavailable', 500)\n }\n\n if (!reservation) throw new ScopedAttachmentUploadError('quota_unavailable', 500)\n\n let storedPath = preparedStoragePath\n try {\n const stored = await driver.store({\n partitionCode: partition.code,\n orgId: input.organizationId,\n tenantId: input.tenantId,\n fileName: safeName,\n buffer: input.buffer,\n storagePath: preparedStoragePath,\n })\n storedPath = stored.storagePath\n await attachmentQuotaService.markStored(reservation.id, reservation.leaseToken)\n } catch (error) {\n await this.compensateStorage(driver, partition.code, storedPath, reservation)\n logger.error('Scoped attachment storage failed', { err: error })\n throw new ScopedAttachmentUploadError('storage_failed', 500)\n }\n\n let extractedContent: string | null = null\n const wantsLlmOcr = partition.requiresOcr && shouldUseLlmOcr(mimeType, safeName)\n const ocrService = wantsLlmOcr ? new OcrService() : null\n const useLlmOcr = Boolean(wantsLlmOcr && ocrService?.available)\n if (partition.requiresOcr && !useLlmOcr) {\n try {\n const { filePath, cleanup } = await driver.toLocalPath(partition.code, storedPath)\n try {\n extractedContent = await extractAttachmentContent({ filePath, mimeType })\n } finally {\n await cleanup().catch(() => undefined)\n }\n } catch (error) {\n logger.error('Scoped attachment text extraction failed', { err: error })\n }\n }\n\n let assignments = input.assignments?.slice() ?? []\n assignments = upsertAssignment(assignments, { type: input.entityId, id: input.recordId })\n const metadata = mergeAttachmentMetadata(null, {\n assignments,\n tags: input.tags ?? [],\n })\n const attachmentId = randomUUID()\n let attachment!: Attachment\n\n try {\n await em.transactional(async (tx) => {\n attachment = tx.create(Attachment, {\n id: attachmentId,\n entityId: input.entityId,\n recordId: input.recordId,\n organizationId: input.organizationId,\n tenantId: input.tenantId,\n fileName: safeName,\n mimeType,\n fileSize: input.buffer.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 assertAttachmentScopeInvariant({ tenantId: attachment.tenantId, organizationId: attachment.organizationId })\n await tx.persist(attachment).flush()\n await input.persistLink?.(tx, attachmentId)\n await attachmentQuotaService.completeAttachment(reservation.id, reservation.leaseToken, tx)\n })\n } catch (error) {\n await this.compensateStorage(driver, partition.code, storedPath, reservation)\n logger.error('Scoped attachment persistence failed', { err: error })\n // `persistLink` is where callers run their own authorization (the\n // documents module re-checks the edit capability inside this\n // transaction), so a deliberate HTTP error from it must reach the route\n // with its own status. Flattening it to 500 turns a documented 403 into\n // an apparent server fault.\n if (isCrudHttpError(error)) throw error\n throw new ScopedAttachmentUploadError('persistence_failed', 500)\n }\n\n if (useLlmOcr) {\n try {\n await requestOcrProcessing(em, attachment, driver, storedPath)\n } catch (error) {\n logger.error('Scoped attachment OCR scheduling failed', { err: error })\n }\n }\n if (this.deps.dataEngine) {\n await emitCrudSideEffects({\n dataEngine: this.deps.dataEngine,\n action: 'created',\n entity: attachment,\n identifiers: {\n id: attachment.id,\n organizationId: attachment.organizationId ?? null,\n tenantId: attachment.tenantId ?? null,\n },\n events: attachmentCrudEvents,\n indexer: attachmentCrudIndexer,\n })\n await this.deps.dataEngine.flushOrmEntityChanges()\n }\n return attachment\n }\n\n private async compensateStorage(\n driver: Awaited<ReturnType<StorageDriverFactory['resolveForPartition']>>,\n partitionCode: string,\n storagePath: string,\n reservation: { id: string; leaseToken: string },\n ): Promise<void> {\n try {\n await (driver.deleteStrict?.(partitionCode, storagePath) ?? driver.delete(partitionCode, storagePath))\n await this.deps.attachmentQuotaService.release(reservation.id, reservation.leaseToken)\n } catch (error) {\n logger.error('Scoped attachment compensation failed', { err: error })\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "AAAA;AAAA,SAAS,kBAAkB;AAG3B,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAAS,o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,OAAM;AAClC,YAAM,IAAI,4BAA4B,sBAAsB,GAAG;AAAA,IACjE;AAEA,QAAI,WAAW;AACb,UAAI;AACF,cAAM,qBAAqB,IAAI,YAAY,QAAQ,UAAU;AAAA,MAC/D,SAAS,OAAO;AACd,eAAO,MAAM,2CAA2C,EAAE,KAAK,MAAM,CAAC;AAAA,MACxE;AAAA,IACF;AACA,QAAI,KAAK,KAAK,YAAY;AACxB,YAAM,oBAAoB;AAAA,QACxB,YAAY,KAAK,KAAK;AAAA,QACtB,QAAQ;AAAA,QACR,QAAQ;AAAA,QACR,aAAa;AAAA,UACX,IAAI,WAAW;AAAA,UACf,gBAAgB,WAAW,kBAAkB;AAAA,UAC7C,UAAU,WAAW,YAAY;AAAA,QACnC;AAAA,QACA,QAAQ;AAAA,QACR,SAAS;AAAA,MACX,CAAC;AACD,YAAM,KAAK,KAAK,WAAW,sBAAsB;AAAA,IACnD;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAc,kBACZ,QACA,eACA,aACA,aACe;AACf,QAAI;AACF,aAAO,OAAO,eAAe,eAAe,WAAW,KAAK,OAAO,OAAO,eAAe,WAAW;AACpG,YAAM,KAAK,KAAK,uBAAuB,QAAQ,YAAY,IAAI,YAAY,UAAU;AAAA,IACvF,SAAS,OAAO;AACd,aAAO,MAAM,yCAAyC,EAAE,KAAK,MAAM,CAAC;AAAA,IACtE;AAAA,EACF;AACF;",
|
|
4
|
+
"sourcesContent": ["import { randomUUID } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { emitCrudSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { Attachment, AttachmentPartition } from '../data/entities'\nimport { attachmentCrudEvents, attachmentCrudIndexer } from './crud'\nimport type { StorageDriverFactory } from './drivers'\nimport { buildAttachmentFileUrl } from './imageUrls'\nimport { ensureAttachmentPartitionProtection } from './access-protection'\nimport { ensureDefaultPartitions, resolveDefaultPartitionCode } from './partitions'\nimport { extractAttachmentContent } from './textExtraction'\nimport { requestOcrProcessing } from './ocrQueue'\nimport { OcrService, shouldUseLlmOcr } from './ocrService'\nimport { assertAttachmentScopeInvariant } from './access'\nimport {\n mergeAttachmentMetadata,\n upsertAssignment,\n type AttachmentAssignment,\n} from './metadata'\nimport {\n detectAttachmentMimeType,\n hasDangerousExecutableExtension,\n isActiveContentAttachment,\n sanitizeUploadedFileName,\n} from './security'\nimport { resolveAttachmentMaxBytes } from './upload-limits'\nimport type { AttachmentQuotaService } from './quota-service'\n\nconst logger = createLogger('attachments')\n\nexport type ScopedAttachmentUploadErrorCode =\n | 'dangerous_executable'\n | 'max_upload_size'\n | 'active_content'\n | 'partition_unavailable'\n | 'quota_exceeded'\n | 'quota_target_exists'\n | 'quota_unavailable'\n | 'quota_recovery_unsupported'\n | 'storage_failed'\n | 'persistence_failed'\n\n// Use Symbol.for so the marker survives module duplication across bundle\n// boundaries. The production build emits this module into several server\n// chunks, so a consumer's `instanceof` compares against a different copy of the\n// class than the DI-resolved service threw from: the check silently fails, the\n// error escapes the caller's catch, and a deliberate 400/413 surfaces as a 500.\nconst SCOPED_ATTACHMENT_UPLOAD_ERROR_MARKER = Symbol.for('@open-mercato/ScopedAttachmentUploadError')\n\nexport class ScopedAttachmentUploadError extends Error {\n readonly [SCOPED_ATTACHMENT_UPLOAD_ERROR_MARKER] = true\n\n constructor(\n public readonly code: ScopedAttachmentUploadErrorCode,\n public readonly status: number,\n ) {\n super(code)\n this.name = 'ScopedAttachmentUploadError'\n }\n}\n\n/**\n * Bundle-safe check for `ScopedAttachmentUploadError`. Prefer this over\n * `instanceof` at every call site \u2014 the class is duplicated across server\n * chunks, so `instanceof` is only reliable inside this module.\n */\nexport function isScopedAttachmentUploadError(error: unknown): error is ScopedAttachmentUploadError {\n return Boolean(error)\n && typeof error === 'object'\n && (error as Record<symbol, unknown>)[SCOPED_ATTACHMENT_UPLOAD_ERROR_MARKER] === true\n}\n\nexport type ScopedAttachmentUploadInput = {\n tenantId: string\n organizationId: string\n entityId: string\n recordId: string\n fileName: string\n declaredMimeType?: string | null\n buffer: Buffer\n tags?: string[]\n assignments?: AttachmentAssignment[]\n partitionCode?: string | null\n maxBytes?: number\n /**\n * Reject a partition flagged public, so a module-owned upload (documents,\n * warranty claims) never lands where an anonymous reader can reach it. The\n * tenant/organization half of that guarantee is not this flag's job: the\n * partition lookup below already matches only a global partition or one owned\n * by this tenant and organization, whether or not the flag is set.\n */\n requirePrivatePartition?: boolean\n /**\n * Persists a module-owned link row inside the same transaction as the\n * Attachment, so a link failure cannot leave a committed orphan attachment.\n * The callback receives only the generated id, never the entity or the\n * storage implementation.\n */\n persistLink?: (tx: EntityManager, attachmentId: string) => Promise<void> | void\n}\n\ntype QuotaRecoveryScheduler = (\n payload: { reservationId: string; tenantId: string; organizationId: string },\n delayMs: number,\n) => Promise<void>\n\nexport class ScopedAttachmentUploadService {\n constructor(private readonly deps: {\n em: EntityManager\n dataEngine?: DataEngine | null\n storageDriverFactory: StorageDriverFactory\n attachmentQuotaService: AttachmentQuotaService\n attachmentQuotaRecoveryScheduler: QuotaRecoveryScheduler\n }) {}\n\n async upload(input: ScopedAttachmentUploadInput): Promise<Attachment> {\n const safeName = sanitizeUploadedFileName(input.fileName)\n if (hasDangerousExecutableExtension(safeName)) {\n throw new ScopedAttachmentUploadError('dangerous_executable', 400)\n }\n if (input.buffer.length > (input.maxBytes ?? resolveAttachmentMaxBytes())) {\n throw new ScopedAttachmentUploadError('max_upload_size', 413)\n }\n const mimeType = detectAttachmentMimeType(input.buffer, safeName, input.declaredMimeType ?? '')\n if (isActiveContentAttachment(input.buffer, safeName, mimeType)) {\n throw new ScopedAttachmentUploadError('active_content', 400)\n }\n\n const { em, storageDriverFactory, attachmentQuotaService, attachmentQuotaRecoveryScheduler } = this.deps\n await ensureDefaultPartitions(em)\n const partitionCode = input.partitionCode ?? resolveDefaultPartitionCode(input.entityId)\n const partition = await em.findOne(AttachmentPartition, {\n code: partitionCode,\n $or: [\n { tenantId: null, organizationId: null },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n ],\n })\n if (!partition) throw new ScopedAttachmentUploadError('partition_unavailable', 400)\n if (input.requirePrivatePartition && partition.isPublic) {\n throw new ScopedAttachmentUploadError('partition_unavailable', 403)\n }\n\n await ensureAttachmentPartitionProtection(em, partition)\n const driver = await storageDriverFactory.resolveForPartition(partition.code, {\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n })\n const preparedStoragePath = driver.prepareStoragePath?.({\n partitionCode: partition.code,\n orgId: input.organizationId,\n tenantId: input.tenantId,\n fileName: safeName,\n })\n if (!preparedStoragePath) {\n throw new ScopedAttachmentUploadError('quota_recovery_unsupported', 500)\n }\n\n let reservation: { id: string; leaseToken: string; expiresAt: Date } | null = null\n try {\n reservation = await attachmentQuotaService.reserve({\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n bytes: input.buffer.length,\n source: 'attachment',\n storageDriver: driver.key,\n storagePath: preparedStoragePath,\n partitionCode: partition.code,\n })\n await attachmentQuotaRecoveryScheduler({\n reservationId: reservation.id,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n }, Math.max(1_000, reservation.expiresAt.getTime() - Date.now()))\n await attachmentQuotaService.beginStorage(reservation.id, reservation.leaseToken)\n } catch (error) {\n if (reservation) {\n await attachmentQuotaService.release(reservation.id, reservation.leaseToken).catch(() => undefined)\n }\n const code = (error as { code?: unknown })?.code\n if (code === 'quota_exceeded') throw new ScopedAttachmentUploadError('quota_exceeded', 413)\n if (code === 'quota_target_exists') throw new ScopedAttachmentUploadError('quota_target_exists', 409)\n throw new ScopedAttachmentUploadError('quota_unavailable', 500)\n }\n\n if (!reservation) throw new ScopedAttachmentUploadError('quota_unavailable', 500)\n\n let storedPath = preparedStoragePath\n try {\n const stored = await driver.store({\n partitionCode: partition.code,\n orgId: input.organizationId,\n tenantId: input.tenantId,\n fileName: safeName,\n buffer: input.buffer,\n storagePath: preparedStoragePath,\n })\n storedPath = stored.storagePath\n await attachmentQuotaService.markStored(reservation.id, reservation.leaseToken)\n } catch (error) {\n await this.compensateStorage(driver, partition.code, storedPath, reservation)\n logger.error('Scoped attachment storage failed', { err: error })\n throw new ScopedAttachmentUploadError('storage_failed', 500)\n }\n\n let extractedContent: string | null = null\n const wantsLlmOcr = partition.requiresOcr && shouldUseLlmOcr(mimeType, safeName)\n const ocrService = wantsLlmOcr ? new OcrService() : null\n const useLlmOcr = Boolean(wantsLlmOcr && ocrService?.available)\n if (partition.requiresOcr && !useLlmOcr) {\n try {\n const { filePath, cleanup } = await driver.toLocalPath(partition.code, storedPath)\n try {\n extractedContent = await extractAttachmentContent({ filePath, mimeType })\n } finally {\n await cleanup().catch(() => undefined)\n }\n } catch (error) {\n logger.error('Scoped attachment text extraction failed', { err: error })\n }\n }\n\n let assignments = input.assignments?.slice() ?? []\n assignments = upsertAssignment(assignments, { type: input.entityId, id: input.recordId })\n const metadata = mergeAttachmentMetadata(null, {\n assignments,\n tags: input.tags ?? [],\n })\n const attachmentId = randomUUID()\n let attachment!: Attachment\n\n try {\n await em.transactional(async (tx) => {\n attachment = tx.create(Attachment, {\n id: attachmentId,\n entityId: input.entityId,\n recordId: input.recordId,\n organizationId: input.organizationId,\n tenantId: input.tenantId,\n fileName: safeName,\n mimeType,\n fileSize: input.buffer.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 assertAttachmentScopeInvariant({ tenantId: attachment.tenantId, organizationId: attachment.organizationId })\n await tx.persist(attachment).flush()\n await input.persistLink?.(tx, attachmentId)\n await attachmentQuotaService.completeAttachment(reservation.id, reservation.leaseToken, tx)\n })\n } catch (error) {\n await this.compensateStorage(driver, partition.code, storedPath, reservation)\n logger.error('Scoped attachment persistence failed', { err: error })\n // `persistLink` is where callers run their own authorization (the\n // documents module re-checks the edit capability inside this\n // transaction), so a deliberate HTTP error from it must reach the route\n // with its own status. Flattening it to 500 turns a documented 403 into\n // an apparent server fault.\n if (isCrudHttpError(error)) throw error\n throw new ScopedAttachmentUploadError('persistence_failed', 500)\n }\n\n if (useLlmOcr) {\n try {\n await requestOcrProcessing(em, attachment, driver, storedPath)\n } catch (error) {\n logger.error('Scoped attachment OCR scheduling failed', { err: error })\n }\n }\n if (this.deps.dataEngine) {\n await emitCrudSideEffects({\n dataEngine: this.deps.dataEngine,\n action: 'created',\n entity: attachment,\n identifiers: {\n id: attachment.id,\n organizationId: attachment.organizationId ?? null,\n tenantId: attachment.tenantId ?? null,\n },\n events: attachmentCrudEvents,\n indexer: attachmentCrudIndexer,\n })\n await this.deps.dataEngine.flushOrmEntityChanges()\n }\n return attachment\n }\n\n private async compensateStorage(\n driver: Awaited<ReturnType<StorageDriverFactory['resolveForPartition']>>,\n partitionCode: string,\n storagePath: string,\n reservation: { id: string; leaseToken: string },\n ): Promise<void> {\n try {\n await (driver.deleteStrict?.(partitionCode, storagePath) ?? driver.delete(partitionCode, storagePath))\n await this.deps.attachmentQuotaService.release(reservation.id, reservation.leaseToken)\n } catch (error) {\n logger.error('Scoped attachment compensation failed', { err: error })\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA;AAAA,SAAS,kBAAkB;AAG3B,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAAS,oBAAoB;AAC7B,SAAS,YAAY,2BAA2B;AAChD,SAAS,sBAAsB,6BAA6B;AAE5D,SAAS,8BAA8B;AACvC,SAAS,2CAA2C;AACpD,SAAS,yBAAyB,mCAAmC;AACrE,SAAS,gCAAgC;AACzC,SAAS,4BAA4B;AACrC,SAAS,YAAY,uBAAuB;AAC5C,SAAS,sCAAsC;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;A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ACxB,YAAM,oBAAoB;AAAA,QACxB,YAAY,KAAK,KAAK;AAAA,QACtB,QAAQ;AAAA,QACR,QAAQ;AAAA,QACR,aAAa;AAAA,UACX,IAAI,WAAW;AAAA,UACf,gBAAgB,WAAW,kBAAkB;AAAA,UAC7C,UAAU,WAAW,YAAY;AAAA,QACnC;AAAA,QACA,QAAQ;AAAA,QACR,SAAS;AAAA,MACX,CAAC;AACD,YAAM,KAAK,KAAK,WAAW,sBAAsB;AAAA,IACnD;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAc,kBACZ,QACA,eACA,aACA,aACe;AACf,QAAI;AACF,aAAO,OAAO,eAAe,eAAe,WAAW,KAAK,OAAO,OAAO,eAAe,WAAW;AACpG,YAAM,KAAK,KAAK,uBAAuB,QAAQ,YAAY,IAAI,YAAY,UAAU;AAAA,IACvF,SAAS,OAAO;AACd,aAAO,MAAM,yCAAyC,EAAE,KAAK,MAAM,CAAC;AAAA,IACtE;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
2
2
|
import { Attachment, AttachmentPartition } from "../data/entities.js";
|
|
3
|
-
import {
|
|
3
|
+
import { evaluateAttachmentAccess } from "./access-runner.js";
|
|
4
4
|
import { readAttachmentMetadata } from "./metadata.js";
|
|
5
5
|
class AttachmentTargetAccessService {
|
|
6
|
-
constructor(em) {
|
|
6
|
+
constructor(em, resolveAccessContext) {
|
|
7
7
|
this.em = em;
|
|
8
|
+
this.resolveAccessContext = resolveAccessContext;
|
|
8
9
|
}
|
|
9
10
|
async canAccessLinkedTarget(input) {
|
|
10
11
|
if (!input.targets.length) return false;
|
|
@@ -28,7 +29,15 @@ class AttachmentTargetAccessService {
|
|
|
28
29
|
]
|
|
29
30
|
});
|
|
30
31
|
if (!partition) return false;
|
|
31
|
-
|
|
32
|
+
const access = await evaluateAttachmentAccess({
|
|
33
|
+
auth: input.auth,
|
|
34
|
+
attachment,
|
|
35
|
+
partition,
|
|
36
|
+
action: "read",
|
|
37
|
+
context: this.resolveAccessContext?.(),
|
|
38
|
+
requireAuthForPublic: true
|
|
39
|
+
});
|
|
40
|
+
if (!access.ok) return false;
|
|
32
41
|
const metadata = readAttachmentMetadata(attachment.storageMetadata);
|
|
33
42
|
return input.targets.some((target) => attachment.entityId === target.entityId && attachment.recordId === target.recordId || metadata.assignments?.some((assignment) => assignment.type === target.entityId && assignment.id === target.recordId) === true);
|
|
34
43
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/attachments/lib/target-access-service.ts"],
|
|
4
|
-
"sourcesContent": ["import 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 { Attachment, AttachmentPartition } from '../data/entities'\nimport {
|
|
5
|
-
"mappings": "AAEA,SAAS,6BAA6B;AACtC,SAAS,YAAY,2BAA2B;AAChD,SAAS,
|
|
4
|
+
"sourcesContent": ["import 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 { Attachment, AttachmentPartition } from '../data/entities'\nimport { evaluateAttachmentAccess, type AttachmentAccessContext } from './access-runner'\nimport { readAttachmentMetadata } from './metadata'\n\nexport type AttachmentRecordTarget = {\n entityId: string\n recordId: string\n}\n\nexport type AttachmentTargetAccessInput = {\n attachmentId: string\n tenantId: string\n organizationId: string\n auth: Exclude<AuthContext, null>\n targets: AttachmentRecordTarget[]\n}\n\nexport class AttachmentTargetAccessService {\n constructor(\n private readonly em: EntityManager,\n private readonly resolveAccessContext?: (() => AttachmentAccessContext) | null,\n ) {}\n\n async canAccessLinkedTarget(input: AttachmentTargetAccessInput): Promise<boolean> {\n if (!input.targets.length) return false\n const attachment = await findOneWithDecryption(\n this.em,\n Attachment,\n {\n id: input.attachmentId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n },\n {},\n { tenantId: input.tenantId, organizationId: input.organizationId },\n )\n if (!attachment) return false\n\n const partition = await this.em.findOne(AttachmentPartition, {\n code: attachment.partitionCode,\n $or: [\n { tenantId: null, organizationId: null },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n ],\n })\n if (!partition) return false\n const access = await evaluateAttachmentAccess({\n auth: input.auth, attachment, partition, action: 'read',\n context: this.resolveAccessContext?.(), requireAuthForPublic: true,\n })\n if (!access.ok) return false\n\n const metadata = readAttachmentMetadata(attachment.storageMetadata)\n return input.targets.some((target) => (\n (attachment.entityId === target.entityId && attachment.recordId === target.recordId)\n || metadata.assignments?.some((assignment) => (\n assignment.type === target.entityId && assignment.id === target.recordId\n )) === true\n ))\n }\n}\n"],
|
|
5
|
+
"mappings": "AAEA,SAAS,6BAA6B;AACtC,SAAS,YAAY,2BAA2B;AAChD,SAAS,gCAA8D;AACvE,SAAS,8BAA8B;AAehC,MAAM,8BAA8B;AAAA,EACzC,YACmB,IACA,sBACjB;AAFiB;AACA;AAAA,EAChB;AAAA,EAEH,MAAM,sBAAsB,OAAsD;AAChF,QAAI,CAAC,MAAM,QAAQ,OAAQ,QAAO;AAClC,UAAM,aAAa,MAAM;AAAA,MACvB,KAAK;AAAA,MACL;AAAA,MACA;AAAA,QACE,IAAI,MAAM;AAAA,QACV,UAAU,MAAM;AAAA,QAChB,gBAAgB,MAAM;AAAA,MACxB;AAAA,MACA,CAAC;AAAA,MACD,EAAE,UAAU,MAAM,UAAU,gBAAgB,MAAM,eAAe;AAAA,IACnE;AACA,QAAI,CAAC,WAAY,QAAO;AAExB,UAAM,YAAY,MAAM,KAAK,GAAG,QAAQ,qBAAqB;AAAA,MAC3D,MAAM,WAAW;AAAA,MACjB,KAAK;AAAA,QACH,EAAE,UAAU,MAAM,gBAAgB,KAAK;AAAA,QACvC,EAAE,UAAU,MAAM,UAAU,gBAAgB,MAAM,eAAe;AAAA,MACnE;AAAA,IACF,CAAC;AACD,QAAI,CAAC,UAAW,QAAO;AACvB,UAAM,SAAS,MAAM,yBAAyB;AAAA,MAC5C,MAAM,MAAM;AAAA,MAAM;AAAA,MAAY;AAAA,MAAW,QAAQ;AAAA,MACjD,SAAS,KAAK,uBAAuB;AAAA,MAAG,sBAAsB;AAAA,IAChE,CAAC;AACD,QAAI,CAAC,OAAO,GAAI,QAAO;AAEvB,UAAM,WAAW,uBAAuB,WAAW,eAAe;AAClE,WAAO,MAAM,QAAQ,KAAK,CAAC,WACxB,WAAW,aAAa,OAAO,YAAY,WAAW,aAAa,OAAO,YACxE,SAAS,aAAa,KAAK,CAAC,eAC7B,WAAW,SAAS,OAAO,YAAY,WAAW,OAAO,OAAO,QACjE,MAAM,IACR;AAAA,EACH;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { Migration } from "@mikro-orm/migrations";
|
|
2
|
+
class Migration20261001120000_attachments extends Migration {
|
|
3
|
+
up() {
|
|
4
|
+
this.addSql('alter table "attachment_partitions" add column if not exists "access_resolver_requirements" jsonb null;');
|
|
5
|
+
this.addSql(`
|
|
6
|
+
update attachment_partitions as partition
|
|
7
|
+
set access_resolver_requirements = coalesce(partition.access_resolver_requirements, '[]'::jsonb)
|
|
8
|
+
|| '[{"resolverId":"documents.document-attachments","targetEntity":"documents:document"}]'::jsonb,
|
|
9
|
+
updated_at = now()
|
|
10
|
+
where (partition.access_resolver_requirements is null or jsonb_typeof(partition.access_resolver_requirements) = 'array')
|
|
11
|
+
and not coalesce(partition.access_resolver_requirements, '[]'::jsonb)
|
|
12
|
+
@> '[{"resolverId":"documents.document-attachments","targetEntity":"documents:document"}]'::jsonb
|
|
13
|
+
and exists (
|
|
14
|
+
select 1 from attachments as attachment
|
|
15
|
+
where attachment.partition_code = partition.code
|
|
16
|
+
and (
|
|
17
|
+
btrim(attachment.entity_id) = 'documents:document'
|
|
18
|
+
or exists (
|
|
19
|
+
select 1
|
|
20
|
+
from jsonb_array_elements(
|
|
21
|
+
case jsonb_typeof(attachment.storage_metadata->'assignments')
|
|
22
|
+
when 'array' then attachment.storage_metadata->'assignments'
|
|
23
|
+
when 'object' then jsonb_build_array(attachment.storage_metadata->'assignments')
|
|
24
|
+
else '[]'::jsonb
|
|
25
|
+
end
|
|
26
|
+
) as assignment
|
|
27
|
+
where jsonb_typeof(assignment) = 'object'
|
|
28
|
+
and btrim(assignment->>'type') = 'documents:document'
|
|
29
|
+
)
|
|
30
|
+
)
|
|
31
|
+
);
|
|
32
|
+
`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export {
|
|
36
|
+
Migration20261001120000_attachments
|
|
37
|
+
};
|
|
38
|
+
//# sourceMappingURL=Migration20261001120000_attachments.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/modules/attachments/migrations/Migration20261001120000_attachments.ts"],
|
|
4
|
+
"sourcesContent": ["import { Migration } from '@mikro-orm/migrations'\n\nexport class Migration20261001120000_attachments extends Migration {\n override up(): void {\n this.addSql('alter table \"attachment_partitions\" add column if not exists \"access_resolver_requirements\" jsonb null;')\n this.addSql(`\n update attachment_partitions as partition\n set access_resolver_requirements = coalesce(partition.access_resolver_requirements, '[]'::jsonb)\n || '[{\"resolverId\":\"documents.document-attachments\",\"targetEntity\":\"documents:document\"}]'::jsonb,\n updated_at = now()\n where (partition.access_resolver_requirements is null or jsonb_typeof(partition.access_resolver_requirements) = 'array')\n and not coalesce(partition.access_resolver_requirements, '[]'::jsonb)\n @> '[{\"resolverId\":\"documents.document-attachments\",\"targetEntity\":\"documents:document\"}]'::jsonb\n and exists (\n select 1 from attachments as attachment\n where attachment.partition_code = partition.code\n and (\n btrim(attachment.entity_id) = 'documents:document'\n or exists (\n select 1\n from jsonb_array_elements(\n case jsonb_typeof(attachment.storage_metadata->'assignments')\n when 'array' then attachment.storage_metadata->'assignments'\n when 'object' then jsonb_build_array(attachment.storage_metadata->'assignments')\n else '[]'::jsonb\n end\n ) as assignment\n where jsonb_typeof(assignment) = 'object'\n and btrim(assignment->>'type') = 'documents:document'\n )\n )\n );\n `)\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,iBAAiB;AAEnB,MAAM,4CAA4C,UAAU;AAAA,EACxD,KAAW;AAClB,SAAK,OAAO,yGAAyG;AACrH,SAAK,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KA2BX;AAAA,EACH;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -1,4 +1,14 @@
|
|
|
1
|
+
import { syncAttachmentAccessProtection } from "./lib/access-protection.js";
|
|
2
|
+
import { ensureDefaultPartitions } from "./lib/partitions.js";
|
|
1
3
|
const setup = {
|
|
4
|
+
async onTenantCreated({ em }) {
|
|
5
|
+
await ensureDefaultPartitions(em);
|
|
6
|
+
await syncAttachmentAccessProtection(em);
|
|
7
|
+
},
|
|
8
|
+
async seedDefaults({ em }) {
|
|
9
|
+
await ensureDefaultPartitions(em);
|
|
10
|
+
await syncAttachmentAccessProtection(em);
|
|
11
|
+
},
|
|
2
12
|
defaultRoleFeatures: {
|
|
3
13
|
admin: ["attachments.*", "attachments.view", "attachments.manage"],
|
|
4
14
|
employee: ["attachments.view"]
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/modules/attachments/setup.ts"],
|
|
4
|
-
"sourcesContent": ["import type { ModuleSetupConfig } from '@open-mercato/shared/modules/setup'\n\nexport const setup: ModuleSetupConfig = {\n defaultRoleFeatures: {\n admin: ['attachments.*', 'attachments.view', 'attachments.manage'],\n employee: ['attachments.view'],\n },\n}\n\nexport default setup\n"],
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import type { ModuleSetupConfig } from '@open-mercato/shared/modules/setup'\nimport { syncAttachmentAccessProtection } from './lib/access-protection'\nimport { ensureDefaultPartitions } from './lib/partitions'\n\nexport const setup: ModuleSetupConfig = {\n async onTenantCreated({ em }) {\n await ensureDefaultPartitions(em)\n await syncAttachmentAccessProtection(em)\n },\n async seedDefaults({ em }) {\n await ensureDefaultPartitions(em)\n await syncAttachmentAccessProtection(em)\n },\n defaultRoleFeatures: {\n admin: ['attachments.*', 'attachments.view', 'attachments.manage'],\n employee: ['attachments.view'],\n },\n}\n\nexport default setup\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,sCAAsC;AAC/C,SAAS,+BAA+B;AAEjC,MAAM,QAA2B;AAAA,EACtC,MAAM,gBAAgB,EAAE,GAAG,GAAG;AAC5B,UAAM,wBAAwB,EAAE;AAChC,UAAM,+BAA+B,EAAE;AAAA,EACzC;AAAA,EACA,MAAM,aAAa,EAAE,GAAG,GAAG;AACzB,UAAM,wBAAwB,EAAE;AAChC,UAAM,+BAA+B,EAAE;AAAA,EACzC;AAAA,EACA,qBAAqB;AAAA,IACnB,OAAO,CAAC,iBAAiB,oBAAoB,oBAAoB;AAAA,IACjE,UAAU,CAAC,kBAAkB;AAAA,EAC/B;AACF;AAEA,IAAO,gBAAQ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -89,6 +89,14 @@ const openApi = {
|
|
|
89
89
|
}
|
|
90
90
|
}
|
|
91
91
|
},
|
|
92
|
+
403: {
|
|
93
|
+
description: "The stored action command is not declared by the notification type with the same action id and command, or the user lacks the features the declared action requires (`code: notification_action_forbidden`)",
|
|
94
|
+
content: {
|
|
95
|
+
"application/json": {
|
|
96
|
+
schema: actionConflictResponseSchema
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
},
|
|
92
100
|
400: {
|
|
93
101
|
description: "Action not found or failed",
|
|
94
102
|
content: {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/notifications/api/%5Bid%5D/action/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { executeActionSchema } from '../../../data/validators'\nimport { actionConflictResponseSchema, actionResultResponseSchema, errorResponseSchema } from '../../openapi'\nimport {\n NOTIFICATION_RESOURCE_KIND,\n notificationCrudErrorResponse,\n notificationValidationErrorResponse,\n resolveNotificationContext,\n runGuardedNotificationWrite,\n} from '../../../lib/routeHelpers'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { resolveNotificationActionHref, toSafeNotificationHref } from '../../../lib/safeHref'\n\nexport const metadata = {\n POST: { requireAuth: true },\n}\n\nexport async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {\n const { id } = await params\n const { service, scope, ctx } = await resolveNotificationContext(req)\n\n const body = await req.json().catch(() => ({}))\n const parsed = executeActionSchema.safeParse(body)\n if (!parsed.success) {\n return notificationValidationErrorResponse(parsed.error)\n }\n const input = parsed.data\n\n try {\n const guarded = await runGuardedNotificationWrite(\n ctx.container,\n scope,\n req,\n {\n resourceKind: NOTIFICATION_RESOURCE_KIND,\n resourceId: id,\n operation: 'custom',\n payload: input as Record<string, unknown>,\n },\n () => service.executeAction(id, input, scope),\n )\n if (!guarded.ok) return guarded.response\n const { notification, result } = guarded.result\n\n const action = notification.actionData?.actions?.find((a) => a.id === input.actionId)\n const href = toSafeNotificationHref(resolveNotificationActionHref(action?.href, notification.sourceEntityId)) ?? undefined\n\n return Response.json({\n ok: true,\n result,\n href,\n })\n } catch (error) {\n const errorResponse = notificationCrudErrorResponse(error)\n if (errorResponse) return errorResponse\n\n const { t } = await resolveTranslations()\n const fallback = t('notifications.error.action', 'Failed to execute action')\n const message = error instanceof Error && error.message ? error.message : fallback\n return Response.json({ error: message }, { status: 400 })\n }\n}\n\nexport const openApi = {\n POST: {\n summary: 'Execute notification action',\n tags: ['Notifications'],\n parameters: [\n {\n name: 'id',\n in: 'path',\n required: true,\n schema: { type: 'string', format: 'uuid' },\n },\n ],\n requestBody: {\n required: true,\n content: {\n 'application/json': {\n schema: executeActionSchema,\n },\n },\n },\n responses: {\n 200: {\n description: 'Action executed successfully',\n content: {\n 'application/json': {\n schema: actionResultResponseSchema,\n },\n },\n },\n 409: {\n description: 'The notification action was already executed (`code: notification_action_already_executed`), or a mutation guard or the action command reported a conflict',\n content: {\n 'application/json': {\n schema: actionConflictResponseSchema,\n },\n },\n },\n 400: {\n description: 'Action not found or failed',\n content: {\n 'application/json': {\n schema: errorResponseSchema,\n },\n },\n },\n },\n },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,2BAA2B;AACpC,SAAS,8BAA8B,4BAA4B,2BAA2B;AAC9F;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,+BAA+B,8BAA8B;AAE/D,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,KAAK;AAC5B;AAEA,eAAsB,KAAK,KAAc,EAAE,OAAO,GAAwC;AACxF,QAAM,EAAE,GAAG,IAAI,MAAM;AACrB,QAAM,EAAE,SAAS,OAAO,IAAI,IAAI,MAAM,2BAA2B,GAAG;AAEpE,QAAM,OAAO,MAAM,IAAI,KAAK,EAAE,MAAM,OAAO,CAAC,EAAE;AAC9C,QAAM,SAAS,oBAAoB,UAAU,IAAI;AACjD,MAAI,CAAC,OAAO,SAAS;AACnB,WAAO,oCAAoC,OAAO,KAAK;AAAA,EACzD;AACA,QAAM,QAAQ,OAAO;AAErB,MAAI;AACF,UAAM,UAAU,MAAM;AAAA,MACpB,IAAI;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,QACE,cAAc;AAAA,QACd,YAAY;AAAA,Q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,MACF;AAAA,MACA,KAAK;AAAA,QACH,aAAa;AAAA,QACb,SAAS;AAAA,UACP,oBAAoB;AAAA,YAClB,QAAQ;AAAA,UACV;AAAA,QACF;AAAA,MACF;AAAA,MACA,KAAK;AAAA,QACH,aAAa;AAAA,QACb,SAAS;AAAA,UACP,oBAAoB;AAAA,YAClB,QAAQ;AAAA,UACV;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
4
|
+
"sourcesContent": ["import { executeActionSchema } from '../../../data/validators'\nimport { actionConflictResponseSchema, actionResultResponseSchema, errorResponseSchema } from '../../openapi'\nimport {\n NOTIFICATION_RESOURCE_KIND,\n notificationCrudErrorResponse,\n notificationValidationErrorResponse,\n resolveNotificationContext,\n runGuardedNotificationWrite,\n} from '../../../lib/routeHelpers'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { resolveNotificationActionHref, toSafeNotificationHref } from '../../../lib/safeHref'\n\nexport const metadata = {\n POST: { requireAuth: true },\n}\n\nexport async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {\n const { id } = await params\n const { service, scope, ctx } = await resolveNotificationContext(req)\n\n const body = await req.json().catch(() => ({}))\n const parsed = executeActionSchema.safeParse(body)\n if (!parsed.success) {\n return notificationValidationErrorResponse(parsed.error)\n }\n const input = parsed.data\n\n try {\n const guarded = await runGuardedNotificationWrite(\n ctx.container,\n scope,\n req,\n {\n resourceKind: NOTIFICATION_RESOURCE_KIND,\n resourceId: id,\n operation: 'custom',\n payload: input as Record<string, unknown>,\n },\n () => service.executeAction(id, input, scope),\n )\n if (!guarded.ok) return guarded.response\n const { notification, result } = guarded.result\n\n const action = notification.actionData?.actions?.find((a) => a.id === input.actionId)\n const href = toSafeNotificationHref(resolveNotificationActionHref(action?.href, notification.sourceEntityId)) ?? undefined\n\n return Response.json({\n ok: true,\n result,\n href,\n })\n } catch (error) {\n const errorResponse = notificationCrudErrorResponse(error)\n if (errorResponse) return errorResponse\n\n const { t } = await resolveTranslations()\n const fallback = t('notifications.error.action', 'Failed to execute action')\n const message = error instanceof Error && error.message ? error.message : fallback\n return Response.json({ error: message }, { status: 400 })\n }\n}\n\nexport const openApi = {\n POST: {\n summary: 'Execute notification action',\n tags: ['Notifications'],\n parameters: [\n {\n name: 'id',\n in: 'path',\n required: true,\n schema: { type: 'string', format: 'uuid' },\n },\n ],\n requestBody: {\n required: true,\n content: {\n 'application/json': {\n schema: executeActionSchema,\n },\n },\n },\n responses: {\n 200: {\n description: 'Action executed successfully',\n content: {\n 'application/json': {\n schema: actionResultResponseSchema,\n },\n },\n },\n 409: {\n description: 'The notification action was already executed (`code: notification_action_already_executed`), or a mutation guard or the action command reported a conflict',\n content: {\n 'application/json': {\n schema: actionConflictResponseSchema,\n },\n },\n },\n 403: {\n description: 'The stored action command is not declared by the notification type with the same action id and command, or the user lacks the features the declared action requires (`code: notification_action_forbidden`)',\n content: {\n 'application/json': {\n schema: actionConflictResponseSchema,\n },\n },\n },\n 400: {\n description: 'Action not found or failed',\n content: {\n 'application/json': {\n schema: errorResponseSchema,\n },\n },\n },\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,2BAA2B;AACpC,SAAS,8BAA8B,4BAA4B,2BAA2B;AAC9F;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,+BAA+B,8BAA8B;AAE/D,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,KAAK;AAC5B;AAEA,eAAsB,KAAK,KAAc,EAAE,OAAO,GAAwC;AACxF,QAAM,EAAE,GAAG,IAAI,MAAM;AACrB,QAAM,EAAE,SAAS,OAAO,IAAI,IAAI,MAAM,2BAA2B,GAAG;AAEpE,QAAM,OAAO,MAAM,IAAI,KAAK,EAAE,MAAM,OAAO,CAAC,EAAE;AAC9C,QAAM,SAAS,oBAAoB,UAAU,IAAI;AACjD,MAAI,CAAC,OAAO,SAAS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