REST API
An attachment has both a stored file and a record describing it. Upload the file, associate it with the business record, then use the media endpoint appropriate to its access settings.
Open the API Explorer at /docs/api on your Open Mercato instance to inspect request and response schemas or try a call with an API key.
All examples assume the environment variables defined in REST API Overview:
export BASE_URL="http://localhost:3000/api"
export API_KEY="<paste your API key secret here>"
export ORG_ID="<organization uuid in scope>"
export TENANT_ID="<tenant uuid in scope>"
export RECORD_ID="<entity record id you want to attach files to>"
X-Api-Key: $API_KEY on every request. API-key calls must always include organizationId and tenantId in payloads.attachments.view for read-only endpoints, attachments.manage for uploads, updates, transfers, partitions, and deletes.cf_<slug> keys or a customFields object. Multipart uploads accept a JSON string for customFields.OM_ATTACHMENT_STORAGE_POLICY=legacy is the default and retains the existing local fallback for absent partitions, null drivers and unregistered driver keys. Set OM_ATTACHMENT_STORAGE_POLICY=strict in every web, worker and CLI process to reject those configurations before selecting or constructing storage. Invalid policy values also fail closed. No schema migration is required.
Strict policy is checked on every factory resolution, including direct and late new StorageDriverFactory(em) construction and cache hits. Explicit local and legacyPublic drivers remain supported; a null configuration on an explicitly selected local driver means an empty object. Provider drivers require a synchronous validator registered before work starts:
import {
registerExternalStorageDriver,
registerStorageDriverValidator,
} from '@open-mercato/core/modules/attachments/lib/drivers'
registerStorageDriverValidator('custom_storage', ({ config, stage, scope }) => {
if (typeof config.bucket !== 'string' || !config.bucket.trim()) return false
if (stage === 'resolved' && scope && config.tenantId !== scope.tenantId) return false
return true
})
registerExternalStorageDriver('custom_storage', (config) => createCustomStorageDriver(config))
createCustomStorageDriver above is supplied by the provider. Validators return exactly true to accept and must be synchronous, side-effect free, and avoid logging configuration. They receive the driver key, configuration, optional partition code, optional tenant/organization scope and stage (configured before credential enhancement; resolved afterward or immediately before construction). Generic object/scope validation also runs after enhancement. Rejected/throwing validators, missing validators and enhancement failures never fall back to local storage; diagnostics discard provider exception messages and causes.
The registration returns a disposer for lifecycle cleanup. Policy helpers, the validator/context types, AttachmentStorageConfigurationError and isAttachmentStorageConfigurationError are also exported from @open-mercato/core/modules/attachments. Use the discriminator across bundled module boundaries, not instanceof. The stable code is ATTACHMENT_STORAGE_CONFIGURATION_INVALID; reasons are invalid_policy, partition_missing, driver_missing, unknown_driver, invalid_config, invalid_scope, validator_missing, validator_rejected and enhancement_failed. Errors contain no configuration, credentials, partition names or scope IDs.
Attachment upload, file/image retrieval and deletion routes return HTTP 503 with a localized error, the stable code, and reason. Configuration rejection happens before thumbnail or attachment metadata removal. Worker and CLI paths preserve the typed error; CLI deletion rejects instead of reporting success. Authentication and owning-record authorization remain separate checks.
These error-mapping and side-effect guarantees cover the attachments module's own routes, quota recovery worker and CLI. Independent warranty portal attachment handlers, the documents attachment download route and enterprise agent_orchestrator attachment staging still use factory validation, but do not yet provide the same caller-level handling; #7941 tracks this work. Errors there may be generic or swallowed, and warranty portal deletion may remove metadata before strict rejection, leaving orphaned bytes. Audit those paths before enabling strict mode in deployments that use them.
The S3 provider registers its own validator. Strict mode supports explicit ambient credentials and the existing default credential chain when no credential fields are supplied; it rejects partial/conflicting keys and incomplete environment-prefix credentials. Endpoint validation uses the existing endpoint-safety policy, including supported HTTP MinIO and the explicit OM_STORAGE_S3_ALLOW_INTERNAL_ENDPOINTS choice. Core introduces no S3-specific preconfiguration.
Before enabling strict mode, inventory partitions and register every external driver's validator in all process bootstraps. Ensure initialization has created the intended partitions; strict uploads do not manufacture missing defaults or substitute another partition. To roll back, restore legacy and restart all processes; no data is moved or deleted.
Use attachmentService for cross-module business operations. Explicit low-level driver construction, standalone S3 APIs and deprecated filesystem helpers do not select a partition driver and are outside this policy. Applications requiring this validation should migrate those callers to the service/factory. The policy is not a filesystem sandbox.
Open Mercato supports two text-extraction methods for attachments:
Environment Variables
Configure LLM-based OCR with the following variables in your .env:
# Required for LLM-based OCR
OPENAI_API_KEY="<openai-api-key>"
# Optional: OCR model selection (default: gpt-4o)
# Supported models: gpt-4o, gpt-4o-mini
OCR_MODEL=gpt-4o
# Optional: Custom prompt for text extraction
# OCR_DEFAULT_PROMPT="Extract all text content from this image..."
# Optional attachment defaults and limits
# OM_DEFAULT_ATTACHMENT_OCR_ENABLED=true
# OM_ATTACHMENT_MAX_UPLOAD_MB=25
# OM_ATTACHMENT_TENANT_QUOTA_MB=512
Attachment env naming follows the standard OM_* prefix. Legacy OPENMERCATO_* aliases are still read for backward compatibility, but new deployments should use the OM_* names.
How it works
pdfjs-dist; text-layer content is used directly when available, and scanned/image-only pages are rendered through the Node canvas backend before OCRAttachment.content field and shown in the metadata dialogpdf2pic, GraphicsMagick, Ghostscript, or external binaries are used in any extraction pathpdfjs-dist, and DOCX files are parsed with mammothNo additional setup required – extraction runs in-process with no external binaries.
Supported formats and their extractors:
| Format | Extractor |
|---|---|
Plain text (text/*, .txt, .md, .csv, .log) | Direct UTF-8 read |
PDF (.pdf) | pdfjs-dist – text layer content |
Word document (.docx) | mammoth |
Formats not extracted (returned as no content): .doc (legacy binary Word), .xlsx, .xls, .pptx, .ppt, .msg, and other Office/Outlook formats. LLM-based OCR remains available for these files where the partition is configured with an OCR model.
OM_DEFAULT_ATTACHMENT_OCR_ENABLED=true|false controls whether new partitions opt into OCR by default.OM_ATTACHMENT_MAX_UPLOAD_MB=<number> sets the global upload cap per file before field-specific limits are applied. Default: 25.OM_ATTACHMENT_TENANT_QUOTA_MB=<number> sets the tenant-wide stored attachment quota. Default: 512.requiresOcr flag; disable it to skip extraction for that partition.GET /attachments?entityId=<id>&recordId=<id>Feature: attachments.view
Returns files assigned to a specific entity record, ordered newest first.
curl -X GET "$BASE_URL/attachments?entityId=catalog:catalog_product&recordId=$RECORD_ID" \
-H "X-Api-Key: $API_KEY" \
-H "Accept: application/json"
The payload includes id, fileName, fileSize, createdAt, partitionCode, url, thumbnailUrl, tags, and assignments.
Pagination is optional and opt-in: pass both page (minimum 1) and pageSize (minimum 1, maximum 100) to page the result. When you do, the response adds total, page, pageSize, and totalPages alongside items; when you omit either one, only the newest 100 attachments for the record are returned, without those fields – page with page and pageSize to reach the rest. Paging is unclamped, exactly like the other list endpoints – a page past the end returns an empty items array and echoes back the page you asked for, so a loop that keeps requesting the next page while the current one is full terminates on its own. Use totalPages if you need to know where the list ends before you get there.
POST /attachments (multipart)Feature: attachments.manage
Fields:
entityId and recordId – required.file – required binary part.fieldKey (validates max size/extension + partition overrides from custom-field definitions), partitionCode override, tags (JSON string array), assignments (JSON string array of { type, id, href?, label? }), customFields JSON map.curl -X POST "$BASE_URL/attachments" \
-H "X-Api-Key: $API_KEY" \
-F "entityId=catalog:catalog_product" \
-F "recordId=$RECORD_ID" \
-F "file=@./hero.jpg" \
-F "tags=[\"hero\",\"web\"]"
Response contains the stored item plus a prebuilt thumbnailUrl (/api/attachments/image/{id}).
DELETE /attachments?id=<uuid>Feature: attachments.manage
curl -X DELETE "$BASE_URL/attachments?id=$ATTACHMENT_ID" \
-H "X-Api-Key: $API_KEY"
Deletes the record, purges cached thumbnails, and removes the stored asset.
Use the library endpoints to browse or edit attachments across entities.
GET /attachments/libraryFeature: attachments.view
Query parameters: page (default 1), pageSize (max 100), search (file name substring), partition, tags (comma separated), sortField (fileName, fileSize, createdAt), sortDir.
curl -X GET "$BASE_URL/attachments/library?page=1&pageSize=20&tags=hero" \
-H "X-Api-Key: $API_KEY"
Response includes paginated items, available partitions, and discovered tag list.
GET /attachments/library/{id}Feature: attachments.view
Returns metadata for a single attachment: base fields, tags, assignments (enriched with labels/links when possible), partition label, and any custom field values.
PATCH /attachments/library/{id}Feature: attachments.manage
Body accepts tags (array), assignments (array of { type, id, href?, label? }), plus optional custom-field keys (cf_<slug> or customFields). Returns the updated tags/assignments/custom fields.
DELETE /attachments/library/{id}Feature: attachments.manage
Removes the attachment and its stored file.
Endpoint: POST /attachments/transfer
Feature: attachments.manage
Move multiple attachments within the same entity to a new record id.
curl -X POST "$BASE_URL/attachments/transfer" \
-H "X-Api-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"entityId": "catalog:catalog_product",
"attachmentIds": ["'$ATTACHMENT_ID'"],
"fromRecordId": "old-record-id",
"toRecordId": "new-record-id"
}'
Assignments pointing at fromRecordId are rewritten to toRecordId.
Partition endpoints let you route uploads to different buckets or visibility tiers.
GET /attachments/partitions (attachments.manage)code, title, description, isPublic, requiresOcr, envKey.POST /attachments/partitions (attachments.manage)code, title, optional description, isPublic, requiresOcr. Fails when the environment locks partition management (demo/onboarding).PUT /attachments/partitions (attachments.manage)id, code (immutable), title, optional description, isPublic, requiresOcr.DELETE /attachments/partitions?id=<uuid> (attachments.manage)409.Structure extraction turns a PDF, DOCX, text or image attachment into an ordered tree of sections (chapters, clauses, paragraphs, list items, tables). Every section carries a page range, heading path, number label (for example §8.12), character offsets into the extraction's normalized text and a stable anchor key. Extraction is deterministic and runs in-process with pure-JS engines (pdf_layout, docx, ocr, text); no external binaries are used.
extractDocumentStructure – when enabled on a partition, every new upload is enqueued on the attachments-document-structure queue. Off by default.indexDocumentSections – opt-in per-section search indexing. Requires extractDocumentStructure.Warning · Plaintext egress
Section text is encrypted at rest, but indexDocumentSections sends section plaintext to the configured search stores (fulltext and vector). Enable it only for non-sensitive corpora such as public regulations or product manuals.
requiresOcr, capped by OM_ATTACHMENT_OCR_MAX_PAGES; pages beyond the cap become page_unreadable placeholders and the extraction is partial.completed, partial or skipped extraction.All routes require an organization context (400 without one) and return 404 for attachments outside the caller's scope.
GET /attachments/structure/{id} (attachments.view) – extraction summary and outline. Query: includeOutline, maxDepth (1–8). Returns extraction: null when the attachment has never been extracted.GET /attachments/structure/{id}/sections (attachments.view) – paged sections. Query: parentId, anchorKey, numberLabel, page, kinds, afterOrdinal, limit (1–100), includeText, includeDescendants, maxCharsPerSection. Returns extractionId: null and no items when the attachment has not been extracted.POST /attachments/structure/{id} (attachments.manage) – request extraction. Body: { force?, ocr?: 'auto' | 'never' | 'force' }. Returns 202 when a job was enqueued, 200 with the current extraction when it is already current and force is false, 413 above OM_ATTACHMENT_STRUCTURE_MAX_BYTES, 422 for unsupported types. The request is not undoable.Modules read structure through the attachmentDocumentStructureService DI service instead of querying the extraction tables directly.
# Request extraction for one attachment (enqueued; runs even when the partition switch is off)
yarn mercato attachments structure extract --attachment <id> --tenant <tenantId> --org <orgId> [--force] [--ocr auto|never|force]
# Enqueue every attachment in enabled partitions that has no live extraction (paged; --dry-run lists targets only)
yarn mercato attachments structure backfill --tenant <tenantId> [--org <orgId>] [--partition <code>] [--limit <n>] [--dry-run]
# Re-extract live extractions produced by an older engine version
yarn mercato attachments structure backfill --tenant <tenantId> --below-engine-version <n>
# Print the outline (or JSON); section text is printed only with --with-text
yarn mercato attachments structure dump --attachment <id> --tenant <tenantId> --org <orgId> [--format outline|json] [--with-text]
Backfill never runs extraction inline. With OCR-enabled partitions a large backfill multiplies OCR cost; start with --dry-run and a --limit.
When a partition has indexDocumentSections enabled, each section of a live extraction is indexed as the attachments:attachment_document_section search entity (strategies fulltext, vector and tokens). Off by default.
Warning · Plaintext egress
Indexed section text and heading paths are sent to the fulltext and vector stores in plaintext. Enable the flag only for corpora whose content may leave the encrypted database (DOC-Q3), such as public regulations or product manuals.
Gate. A section is indexed only when its extraction is live (not superseded or deleted) and its partition has indexDocumentSections on. The gate is the entity's shouldIndex hook. It is enforced in SearchIndexer (every path, including manual reindex) and in the query_index token writer, which evaluates it per record before writing search_tokens. A rejected or failing check fails closed: the record is removed from every strategy. A manual mercato search reindex therefore cannot push sections of non-opted partitions.
What triggers sync. Work runs on the attachments-document-structure queue as section-search jobs:
completed and partial extractions: index on enable, delete on disable).Enqueue failures are reported as errors but never fail the extraction or the purge.
Backfill CLI.
yarn mercato attachments structure search-sync --partition <code> [--tenant <tenantId>] [--org <orgId>] [--mode index|delete] [--dry-run]
--partition is required; --org requires --tenant. Without --tenant all tenants using the partition are covered.--mode defaults to the partition's current flag (index when enabled, delete when disabled). A mode that contradicts the flag is refused.--dry-run scans and reports how many extractions would be enqueued without writing anything.0 success, 2 invalid or missing arguments, 1 partition not found, mode contradicting the partition flag, or partition outside the given tenant.Results. Search results show the citation as the title (for example §8.12 Retention (p. 14)), the attachment file name as the subtitle, and link to the attachments library (/backend/storage/attachments). Results require the attachments.view feature.
Caution · Snippet visibility
Search has no per-record post-filter for this entity. Any attachments.view holder in the organization can see snippets of indexed sections, including for attachments they could not open. Opening an attachment still enforces checkAttachmentAccess. Do not enable section search for partitions whose files have per-record access restrictions.
Known gap. If an attachment is purged between a partition toggle-off and the delete job for its extraction, a few search records can remain until the next reindex.
AI citations. The attachments.get_document_sections AI tool emits attachment citations for the sections it returns (label, page or number locator, a quote of up to 1000 characters, and a link to the attachments library), so answers can reference the exact section.
| Variable | Default | Meaning |
|---|---|---|
OM_ATTACHMENT_STRUCTURE_MAX_BYTES | 52428800 (50 MiB) | Larger files are skipped as too_large |
OM_ATTACHMENT_STRUCTURE_MAX_PAGES | 1000 | Page cap for pdf_layout |
OM_ATTACHMENT_STRUCTURE_MAX_SECTIONS | 20000 | Above this the extraction is partial |
OM_ATTACHMENT_STRUCTURE_MAX_SECTION_CHARS | 16000 | Longer sections are split into paragraphs |
OM_ATTACHMENT_STRUCTURE_OCR_MIN_CHARS_PER_PAGE | 40 | Text-layer threshold below which a page is OCR'd |
OM_ATTACHMENT_STRUCTURE_TIMEOUT_MS | 180000 | Per-job wall clock |
OM_ATTACHMENT_STRUCTURE_WORKER_CONCURRENCY | 2 | Concurrent jobs per worker (max 20) |
OM_ATTACHMENT_OCR_MAX_PAGES (existing) | 50 | OCR page cap, shared with upload OCR |
These routes stream files and thumbnails. Access depends on partition visibility:
Public partitions: no token required unless requireAuthForPublic is enabled server-side.
Private partitions: require auth; scope must match attachment organizationId/tenantId or be a superadmin.
Download original file – GET /attachments/file/{id}
Add ?download=1 to force a download response. Respects partition cache headers.
Serve/rescale image – GET /attachments/image/{id}/{slug?}?width=<n>&height=<n>&cropType=cover|contain
Returns a resized image (Sharp) and caches thumbnails per size. Omit width/height to stream the original image type while keeping access controls in place.