Open MercatoDocsSearch docsAPI reference

REST API

Attachments 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>"

Storage configuration policy

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.

OCR / text extraction

Open Mercato supports two text-extraction methods for attachments:

  1. LLM-based OCR (recommended) – uses OpenAI's GPT-4o vision capabilities for images and PDFs
  2. Pure-JS extraction – in-process fallback for plain text, PDFs, and DOCX files when LLM OCR is unavailable

LLM-based OCR (images and PDFs)

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

Pure-JS extraction (plain text, PDF, DOCX)

No additional setup required – extraction runs in-process with no external binaries.

Supported formats and their extractors:

FormatExtractor
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.

Configuration

Attachments per record

List attachments – 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.

Upload attachment – POST /attachments (multipart)

Feature: attachments.manage

Fields:

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 attachment – 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.

Attachment library

Use the library endpoints to browse or edit attachments across entities.

Search library – GET /attachments/library

Feature: 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.

Retrieve attachment – 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.

Update metadata – 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 attachment – DELETE /attachments/library/{id}

Feature: attachments.manage

Removes the attachment and its stored file.

Transfer attachments between records

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.

Storage partitions

Partition endpoints let you route uploads to different buckets or visibility tiers.

Document structure

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.

Partition switches

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.

Extraction lifecycle

API routes

All routes require an organization context (400 without one) and return 404 for attachments outside the caller's scope.

Modules read structure through the attachmentDocumentStructureService DI service instead of querying the extraction tables directly.

CLI

# 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:

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]

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.

Configuration

VariableDefaultMeaning
OM_ATTACHMENT_STRUCTURE_MAX_BYTES52428800 (50 MiB)Larger files are skipped as too_large
OM_ATTACHMENT_STRUCTURE_MAX_PAGES1000Page cap for pdf_layout
OM_ATTACHMENT_STRUCTURE_MAX_SECTIONS20000Above this the extraction is partial
OM_ATTACHMENT_STRUCTURE_MAX_SECTION_CHARS16000Longer sections are split into paragraphs
OM_ATTACHMENT_STRUCTURE_OCR_MIN_CHARS_PER_PAGE40Text-layer threshold below which a page is OCR'd
OM_ATTACHMENT_STRUCTURE_TIMEOUT_MS180000Per-job wall clock
OM_ATTACHMENT_STRUCTURE_WORKER_CONCURRENCY2Concurrent jobs per worker (max 20)
OM_ATTACHMENT_OCR_MAX_PAGES (existing)50OCR page cap, shared with upload OCR

File delivery and imaging

These routes stream files and thumbnails. Access depends on partition visibility:

Next: Authentication and permissions API