# AGENTS Source: https://docs.mareaalcalina.com/AGENTS # AGENTS.md — Marea Alcalina API > Following the [agents.md spec](https://agents.md/). This file is for AI agents (Claude, GPT, Cursor, Continue.dev, generic LLM-driven tools) consuming the Marea public API. For the full doc index in agent-friendly markdown form, fetch [llms.txt](https://docs.mareaalcalina.com/llms.txt). ## What this API is for Operations + retention API for small-business commerce. Bootstrap users, manage storefronts + products (food menus or retail / service catalogs), publish to public hosted URLs. End-customer order channels are the operator's choice — WhatsApp, web checkout, or in-person pickup — and configurable per storefront. The API does not lock the channel. ## Auth model The **default credential is `mk_user_*`** — one key per user, covers **all** storefronts that user owns (1 on Free, up to 5,000 on Agency Growth). The key is owner-scoped, not storefront-scoped. You do NOT issue a separate key per storefront. A second credential, `mk_dev_*`, exists *only* for partner-style callers (agents, vertical SaaS, agencies) that bootstrap Marea accounts for *other* people. Most integrations never hold one. **End-user AI clients do not paste a key: they connect over OAuth.** When a merchant adds Marea to Claude, ChatGPT, Cursor or any MCP client, the client discovers OAuth 2.1 + PKCE from the `WWW-Authenticate` challenge on a 401 from `POST https://mcp.mareaalcalina.com/mcp` (RFC 9728), the merchant signs in to Marea and authorizes. Consent mints a per-user `mk_user_*` behind the token, so everything below about user-key scope still applies. OAuth grants carry `marea.read`, `marea.write` and `marea.publish`, and can never call `marea.bootstrap_user`. Static keys stay the path for servers, CI and agents with no browser. See the [MCP connect guide](https://docs.mareaalcalina.com/quickstart/mcp). Full model: [API keys](https://docs.mareaalcalina.com/concepts/keys). * `mk_user_*` — **per-user key**, owner-scoped (covers all the user's storefronts). Either minted from the user's own dashboard, OR returned by `POST /v1/users` in the partner bootstrap response. Bootstrap-issued keys start **restricted** (only `me:verify` + `me:resendVerification`) until the 6-digit code is verified, then upgraded in-place to `catalog:read`, `catalog:write`, `storefront:publish`. Cannot bootstrap, cannot see other users' data. Default `rpd: 10000`. * `mk_dev_*` — **partner / developer key**, held by the integrator. Holds `developer:bootstrap`, `developer:read`, `developer:issueUserKey`, `developer:webhooks`. Used to bootstrap users and manage webhook endpoints — **never** to touch a catalog. Default `rpd: 50` (configurable at issue time; the dev `rpd` IS the bootstrap cap). Both pass as `Authorization: Bearer ` (or `X-API-Key: ` as a fallback). ## Common patterns * **Bootstrap → verify → use.** `POST /v1/users` returns a *restricted* `mk_user_*` key + emails the user a 6-digit code. The user reads the code aloud (or the agent fetches it via Gmail-MCP), agent calls `POST /v1/users/:userId/verify`, the same key is upgraded to full per-user scope. See [Bootstrap quickstart](https://docs.mareaalcalina.com/quickstart/bootstrap). * **Idempotency on every mutation.** Pass `Idempotency-Key: ` on every `POST` and `PATCH`. Same key + same body returns the original response (replay-safe). Same key + different body returns `409 idempotency_conflict`. See [Safe mutations](https://docs.mareaalcalina.com/concepts/safe-mutations). * **Branch on `error.type`, not `error.message`.** The `type` field is a stable 10-value enum; `message` is English today and its wording may change. See [Errors](https://docs.mareaalcalina.com/concepts/errors). * **Surface `nextActions[]` verbatim.** Errors carry `{ label, method, url }[]` with the concrete actions the user can take (empty when there is nothing to do, for example on 429 or a validation error). Don't paraphrase; render verbatim. * **Read rate-limit headers proactively.** `X-RateLimit-Remaining` is on every response. When you hit `429`, read `Retry-After` (seconds) and back off. Defaults: `rpm: 60`. Dev keys: `rpd: 50`. User keys: `rpd: 10000`. * **Markdown for ingestion.** Every doc page also serves at `.md` (e.g., `/concepts/errors.md`); use that variant when ingesting docs into your context — cleaner than the HTML. ## When to call which tool REST (always available) and MCP tool (when the user has connected Marea in their AI client, over OAuth or with a static key: see the [MCP connect guide](https://docs.mareaalcalina.com/quickstart/mcp)). Ten `marea.*` tools. | Goal | REST | MCP tool | | - | - | - | | Bootstrap a new user | `POST /v1/users` (dev key) | `marea.bootstrap_user` | | Verify the 6-digit email code | `POST /v1/users/:userId/verify` | (use REST in v1) | | Read identity / plan / budget | `GET /v1/me` | `marea.whoami` | | Create a storefront | `POST /v1/storefronts` | `marea.create_storefront` | | Update storefront fields | `PATCH /v1/storefronts/:id` | `marea.update_storefront` | | Add a product | `POST /v1/storefronts/:id/products` | `marea.create_product` | | Update a product | `PATCH /v1/storefronts/:id/products/:productId` | `marea.update_product` | | List the user's storefronts | `GET /v1/storefronts` | `marea.list_storefronts` | | Read one storefront in full | `GET /v1/storefronts/:id` | `marea.get_storefront` | | List a storefront's products | `GET /v1/storefronts/:id/products` | `marea.list_products` | | Publish to public URL (needs user confirmation) | `POST /v1/storefronts/:id/publish` | `marea.publish_storefront` | | Remove a product from the menu | `PATCH .../products/:productId` with `hide: true` | `marea.update_product` with `hide: true` | **There is no delete tool for products, and no delete endpoint either.** Hiding is the way: `hide: true` takes the item off the customer-facing menu and keeps its history. Treat "delete that dish" as a request to hide it, and say so. Prefer the MCP tool when the user has Marea connected: ids, scopes and plan gates are already resolved for that account. Fall back to REST when MCP isn't available. On an OAuth connection the tool list is already filtered by the granted scopes, so a tool that is absent means the scope was not granted, not that the call would fail. ## What NOT to do * **Don't swallow `nextActions[]`.** The most common agent failure mode is silently retrying past a 402 (paywall) or 451 (ToS not accepted) without ever surfacing the action to the user. Render the array verbatim. * **Don't auto-accept the ToS on the user's behalf.** A 451 → modal flow requires user input by design. The agent cannot bypass. * **Don't bootstrap past your dev key's `rpd` cap.** Default is 50/day (configurable at issue time). Hitting it returns 429 `rate_limited` with `code: rate_limit_exceeded` and `rpd_exceeded` in `error.message`. Read `Retry-After` (seconds-until-the-day-rolls-over) and back off. * **Don't call publish without explicit user confirmation.** Publish is destructive and user-visible. Ask the user in plain language and wait for a yes; never chain it automatically after a create or update. The MCP tool is annotated `destructiveHint: true`, so most clients also show their own confirmation, but that is the client's gate, not yours. * **Don't cache `mk_user_*` keys across users or sessions.** Per-user keys belong in the user's own context. * **Don't poll verification status faster than the API allows.** The user-facing rate limit is `rpm: 60` per user-key. Poll at most once every 30s during the verify window; better, create a webhook endpoint subscribed to `user.verified` — see [Webhook endpoints](https://docs.mareaalcalina.com/concepts/webhooks). * **Don't reuse the same `Idempotency-Key` with a *different* body.** That returns `409 idempotency_conflict` and you must generate a fresh key. If you're retrying with edits, that's a new request — new key. * **Don't branch on `error.message`.** Branch on `error.type` (stable enum) or `error.code` (stable string). ## Errors Every error follows the same envelope: `{ type, code, message, doc, requestId, recoverable, retryAfterMs, nextActions, upgrade, requiredScopes? }`. Branch on `error.type`. The 10 stable types: | `error.type` | Typical HTTP | Surface to user? | Retry? | What to do | | - | - | - | - | - | | `rate_limited` | 429 | No (transparent) | Yes after `retryAfterMs` | Sleep + retry same request + same `Idempotency-Key` | | `invalid_request` | 400 / 410 | No (fix client-side) | No | Fix the body. Includes `invalid_idempotency_key`, `idempotency_snapshot_unavailable` | | `auth` (401) | 401 | Maybe | No | Re-prompt for a valid key. Codes: `missing_authorization`, `invalid_authorization_format`, `key_not_found`, `key_revoked` | | `auth` (insufficient scope) | 403 | Maybe | No | Read `requiredScopes` + `heldScopes` arrays; ask user/dev for a key with the right scope | | `not_found` | 404 | Maybe | No | Confirm the id. May also be a silent cross-tenant denial if the calling key doesn't own the resource | | `plan_limit` | 402 | **Yes (paywall)** | No | Surface `error.upgrade.upgradeUrl` verbatim. The user must upgrade, then retry | | `internal` | 500 | Yes (with `requestId`) | Once with backoff | Then escalate. Surface `requestId` so support can trace | | `conflict` | 409 | No | Yes after 1s | `idempotency_in_flight` — the same key is still processing. Retry with same key | | `idempotency_conflict` | 409 | No | Yes with **new** `Idempotency-Key` | Same key was used earlier with a different body. Generate a fresh UUID | | `service_unavailable` | 503 | Yes (after retries) | Yes with backoff | Exponential backoff | | `tos_not_accepted` | 451 | **Yes (link to dashboard)** | After user accepts | Surface `nextActions[0].url` (modal). Agent cannot bypass | Full error matrix at [/concepts/errors](https://docs.mareaalcalina.com/concepts/errors). ## Where to find docs * **llms.txt index:** [https://docs.mareaalcalina.com/llms.txt](https://docs.mareaalcalina.com/llms.txt) — agent-curated overview of the entire surface * **llms-full.txt:** [https://docs.mareaalcalina.com/llms-full.txt](https://docs.mareaalcalina.com/llms-full.txt) — concatenation of all pages (Mintlify auto-emits in production) * **Per-page markdown:** `https://docs.mareaalcalina.com/.md` (e.g., `/concepts/errors.md`) * **OpenAPI 3.1 spec:** [https://api.mareaalcalina.com/v1/openapi.json](https://api.mareaalcalina.com/v1/openapi.json) — Zod-derived from the cloud-functions code; 5-min cached * **Postman collection:** [https://docs.mareaalcalina.com/marea.postman.json](https://docs.mareaalcalina.com/marea.postman.json) — auto-generated from the OpenAPI spec * **MCP server:** [https://mcp.mareaalcalina.com/mcp](https://mcp.mareaalcalina.com/mcp) (streamable HTTP, POST only); 10 `marea.*` tools. Merchants connect it in Claude, ChatGPT, Cursor or Claude Code over OAuth; developers and headless agents pass a static `mk_user_*` / `mk_dev_*` bearer. Verify and resend are deliberately REST-only * **API catalog (RFC 9727):** [https://mareaalcalina.com/.well-known/api-catalog](https://mareaalcalina.com/.well-known/api-catalog) — discoverability for agent crawlers ## Conventions * **Locale:** `Accept-Language` sets the applied defaults on `POST /v1/users` (language, currency, country). Error messages are English regardless of the header today. * **Currency:** configurable per storefront. Pass `currency: "MXN" | "USD" | "CAD" | "BRL" | ...` on storefront create. * **Phone format:** E.164 (`+52...`). * **Timestamps:** ISO 8601 strings. * **IDs:** prefixed (`usr_`, `stf_`, `prd_`, `dev_`). # Use this to confirm which user (or developer) the calling key acts as. Source: https://docs.mareaalcalina.com/api/use-this-to-confirm-which-user-or-developer-the-calling-key-acts-as /openapi.json get /v1/me Returns identity, plan info, and rate-limit window for the calling key. Branches on key type. # Use this to issue an additional restricted user key for a verified user you previously bootstrapped (e.g. a second integration). Source: https://docs.mareaalcalina.com/api/use-this-to-issue-an-additional-restricted-user-key-for-a-verified-user-you-previously-bootstrapped-eg-a-second-integration /openapi.json post /v1/users/{userId}/keys Validates that the user was bootstrapped by THIS developer and is verified (verificationStatus==="verified"). Returns the raw user key once. Cross-developer attempt → 404 leak-less; pre-verify call → 422. # Use this to list every user this developer key has bootstrapped (paginated 50/page). Source: https://docs.mareaalcalina.com/api/use-this-to-list-every-user-this-developer-key-has-bootstrapped-paginated-50page /openapi.json get /v1/users Returns users where createdByDeveloper.keyId === ctx.keyId, ordered by createdAt DESC. Use the returned `nextCursor` (createdAt ISO string) for the next page. # Use this to poll the status of a user you previously bootstrapped (verificationStatus, plan, recent events). Source: https://docs.mareaalcalina.com/api/use-this-to-poll-the-status-of-a-user-you-previously-bootstrapped-verificationstatus-plan-recent-events /openapi.json get /v1/users/{userId} Returns the user DTO. Cross-developer isolation: only users that THIS developer key bootstrapped are visible — wrong-id or other-developer's-user → 404 leak-less per RFC §10.4. # Use this when an agent wants to create a Marea account on behalf of a user with one round-trip (account + storefront + verification email). Source: https://docs.mareaalcalina.com/api/use-this-when-an-agent-wants-to-create-a-marea-account-on-behalf-of-a-user-with-one-round-trip-account-+-storefront-+-verification-email /openapi.json post /v1/users Creates a Firebase Auth user + Firestore user doc + restricted user key + (optionally) a starter storefront via createMenuCore + sends a 6-digit verification email. Returns 201, or 207 when the account was created but the storefront was not fully applied (plan-cap overflow, or the storefront could not be created at all — see errors[]). The account and userKey are returned either way; the userKey is returned ONCE — store it. # Use this when the user has read back the 6-digit code from their email and you want to upgrade the user-key to full scope. Source: https://docs.mareaalcalina.com/api/use-this-when-the-user-has-read-back-the-6-digit-code-from-their-email-and-you-want-to-upgrade-the-user-key-to-full-scope /openapi.json post /v1/users/{userId}/verify Validates the 6-digit code (3 attempts max), upgrades the bootstrap user-key from restricted to full scope (same key — no rotation), flips agentBootstrapped→false + verificationStatus→verified, fires the user.verified webhook stub. Cross-tenant/wrong-id → 404 leak-less. # Use this when the user is ready to take their storefront live. Source: https://docs.mareaalcalina.com/api/use-this-when-the-user-is-ready-to-take-their-storefront-live /openapi.json post /v1/storefronts/{storefrontId}/publish Publishes the current state of the storefront. Returns 402 if the plan does not permit publishing, 422 if the storefront has 0 products, 451 if ToS not accepted (PRD-7 hook). Idempotent on republish. # Use this when the user wants the full configuration of a single storefront. Source: https://docs.mareaalcalina.com/api/use-this-when-the-user-wants-the-full-configuration-of-a-single-storefront /openapi.json get /v1/storefronts/{storefrontId} Returns the storefront DTO including the live `published` flag and `_links`. 404 on unknown id or cross-tenant. # Use this when the user wants to add a product to an existing storefront. Source: https://docs.mareaalcalina.com/api/use-this-when-the-user-wants-to-add-a-product-to-an-existing-storefront /openapi.json post /v1/storefronts/{storefrontId}/products # Use this when the user wants to change ANY field of an existing product. Source: https://docs.mareaalcalina.com/api/use-this-when-the-user-wants-to-change-any-field-of-an-existing-product /openapi.json patch /v1/storefronts/{storefrontId}/products/{productId} # Use this when the user wants to change ANY field of an existing storefront. Source: https://docs.mareaalcalina.com/api/use-this-when-the-user-wants-to-change-any-field-of-an-existing-storefront /openapi.json patch /v1/storefronts/{storefrontId} Partial PATCH (mutability rule §6.18.1.1). Deep-merge for nested objects, full-replace for arrays. # Use this when the user wants to create a new online storefront from scratch. Source: https://docs.mareaalcalina.com/api/use-this-when-the-user-wants-to-create-a-new-online-storefront-from-scratch /openapi.json post /v1/storefronts Creates a storefront from a `StorefrontManifest`. Returns 201 with the full storefront. If the manifest contains more products than the plan allows, returns **207 Multi-Status** with the storefront created (up to plan cap) plus an `errors` array describing the over-cap items. # Use this when the user wants to discover storefronts on their Marea account. Source: https://docs.mareaalcalina.com/api/use-this-when-the-user-wants-to-discover-storefronts-on-their-marea-account /openapi.json get /v1/storefronts Returns the bearer user's storefronts ordered by storefront id, paginated. `published` is omitted from list items — call GET /v1/storefronts/{storefrontId} for the live publish status; `_links.publicUrl` is returned here. Pass the opaque `nextCursor` back as `cursor` for the next page; `nextCursor` is null on the last page. # Use this when the user wants to list products in a storefront's catalog. Source: https://docs.mareaalcalina.com/api/use-this-when-the-user-wants-to-list-products-in-a-storefronts-catalog /openapi.json get /v1/storefronts/{storefrontId}/products Returns products under the storefront ordered by product id, paginated. Hidden products (`hide:true`) are excluded by default — pass `includeHidden=true` to see them. Pass the opaque `nextCursor` back as `cursor` for the next page; `nextCursor` is null on the last page. # Use this when the verification email may have been lost or the code expired and you want to issue a fresh code without re-bootstrapping. Source: https://docs.mareaalcalina.com/api/use-this-when-the-verification-email-may-have-been-lost-or-the-code-expired-and-you-want-to-issue-a-fresh-code-without-re-bootstrapping /openapi.json post /v1/users/{userId}/resendVerification Per-user rate-limited (3/hour, 5/day). Overwrites the existing apiVerificationCodes/{email} doc — old code is voided automatically. Returns the new expiry timestamp. # Use this when you want to fetch a single webhook endpoint by its id. Source: https://docs.mareaalcalina.com/api/use-this-when-you-want-to-fetch-a-single-webhook-endpoint-by-its-id /openapi.json get /v1/webhook_endpoints/{id} Returns the endpoint excluding the signing secret. Useful for verifying current event subscriptions, enablement status, and recent-delivery summary. # Use this when you want to list every webhook endpoint owned by the caller (developer scope). Source: https://docs.mareaalcalina.com/api/use-this-when-you-want-to-list-every-webhook-endpoint-owned-by-the-caller-developer-scope /openapi.json get /v1/webhook_endpoints Returns up to 16 endpoints (cap per account). Never returns the signing secret — use `POST /v1/webhook_endpoints/{id}/rotate-secret` if you need a new one. # Use this when you want to patch one or more fields of an existing webhook endpoint (url, description, enabled, subscribedEvents). Source: https://docs.mareaalcalina.com/api/use-this-when-you-want-to-patch-one-or-more-fields-of-an-existing-webhook-endpoint-url-description-enabled-subscribedevents /openapi.json post /v1/webhook_endpoints/{id} Accepts a partial update; only the fields present in the body are modified. Cannot rotate the signing secret here — use the dedicated rotate-secret callable / endpoint. Does NOT return the signing secret. # Use this when you want to permanently delete a webhook endpoint. To stop dispatch without losing the URL, use `enabled: false` via the update endpoint instead. Source: https://docs.mareaalcalina.com/api/use-this-when-you-want-to-permanently-delete-a-webhook-endpoint-to-stop-dispatch-without-losing-the-url-use-`enabled:-false`-via-the-update-endpoint-instead /openapi.json delete /v1/webhook_endpoints/{id} Hard delete — there is no soft-delete state for endpoints. Idempotent for 404 callers (returns 404 if already absent). # Use this when you want to register a webhook endpoint that receives one or more event types (`user.verified`, `user.cancelled`, `order.*`). Source: https://docs.mareaalcalina.com/api/use-this-when-you-want-to-register-a-webhook-endpoint-that-receives-one-or-more-event-types-`userverified`-`usercancelled`-`order*` /openapi.json post /v1/webhook_endpoints Creates a webhook endpoint as a first-class object. The returned `signingSecret` is the only time the secret is visible — store it now; rotate via `POST /v1/webhook_endpoints/{id}/rotate-secret` if lost. Per-event subscription is controlled by `subscribedEvents`. A developer endpoint can subscribe to `order.*` events from any storefront the caller bootstrapped — Marea resolves the merchant → developer chain at dispatch time, so one endpoint covers every storefront. Hard caps: 16 endpoints per account; URL ≤2048 chars; HTTPS only; rejects loopback / private / metadata hostnames. # Use this when you want to rotate the signing secret of a webhook endpoint. Returns the new secret ONCE; the old secret stops working immediately. Source: https://docs.mareaalcalina.com/api/use-this-when-you-want-to-rotate-the-signing-secret-of-a-webhook-endpoint-returns-the-new-secret-once;-the-old-secret-stops-working-immediately /openapi.json post /v1/webhook_endpoints/{id}/rotate-secret No overlap window in v1 — coordinate the rotation with your receiver. The returned `signingSecret` is the only time the new secret is visible; store it before responding to the next webhook. Bumps `signingSecretVersion` by one. # Webhook receiver helpers Source: https://docs.mareaalcalina.com/api/webhooks/receiver-helpers Verify Marea webhook signatures (all event types). HMAC-SHA256 with the endpoint's raw 32-byte signing secret; 5-min replay window. # Webhook receiver helpers Marea signs every webhook with HMAC-SHA256 over `"."` using the endpoint's raw signing secret (the 64-char hex string returned at create / rotate time). The signature is in the `X-Marea-Signature` request header: ``` X-Marea-Signature: t=1714867200,v1=abc123def456... (64-char hex) ``` Reject any webhook where `|now - t| > 300` (5-minute replay window). ## Node.js / TypeScript ```typescript theme={null} import * as crypto from 'crypto'; const REPLAY_WINDOW_SECONDS = 300; /** * Verify a Marea webhook signature. * * @param rawBody Raw bytes from req.body — do NOT JSON.parse and re-stringify * @param sigHeader Value of the X-Marea-Signature header ("t=...,v1=...") * @param secret The endpoint's `signingSecret` (64-char hex, returned at create/rotate) */ export function verifyMareaWebhook( rawBody: string | Buffer, sigHeader: string | undefined, secret: string, ): boolean { if (!sigHeader) return false; if (!/^[0-9a-f]{64}$/i.test(secret)) return false; const parts = Object.fromEntries( sigHeader.split(',').map((p) => { const [k, v] = p.split('='); return [k.trim(), v?.trim()]; }), ); const ts = Number(parts.t); const sig = parts.v1; if (!Number.isInteger(ts) || ts <= 0 || !sig || !/^[0-9a-f]+$/.test(sig)) { return false; } // 5-minute replay window if (Math.abs(Math.floor(Date.now() / 1000) - ts) > REPLAY_WINDOW_SECONDS) { return false; } const bodyString = Buffer.isBuffer(rawBody) ? rawBody.toString('utf8') : rawBody; const signingKey = Buffer.from(secret, 'hex'); const expected = crypto .createHmac('sha256', signingKey) .update(`${ts}.${bodyString}`) .digest('hex'); const expectedBuf = Buffer.from(expected, 'hex'); const actualBuf = Buffer.from(sig, 'hex'); if (expectedBuf.length !== actualBuf.length) return false; return crypto.timingSafeEqual(expectedBuf, actualBuf); } // Express handler — read req.body as Buffer/string, NOT a parsed object import express from 'express'; const app = express(); app.post( '/marea-webhook', express.raw({ type: 'application/json' }), (req, res) => { const rawBody = req.body.toString('utf8'); // Look up the secret for the endpoint that produced this delivery. // If you only have one endpoint, a single env var is enough. const endpointId = req.headers['x-marea-endpoint-id'] as string | undefined; const secret = lookupSecretForEndpoint(endpointId) ?? process.env.MAREA_WEBHOOK_SECRET!; const ok = verifyMareaWebhook( rawBody, req.headers['x-marea-signature'] as string | undefined, secret, ); if (!ok) return res.status(401).end(); const envelope = JSON.parse(rawBody); // envelope.type === 'user.verified' | 'user.cancelled' | 'order.created' | ... // envelope.eventId is a UUID v4 — use it for idempotency handleEventAsync(envelope).catch(console.error); res.status(200).end(); }, ); ``` ## Python ```python theme={null} import hmac import hashlib import re import time from typing import Optional, Union REPLAY_WINDOW_SECONDS = 300 _HEX64 = re.compile(r'^[0-9a-fA-F]{64}$') def verify_marea_webhook( raw_body: Union[bytes, str], signature_header: Optional[str], secret: str, ) -> bool: """Verify a Marea webhook signature. Returns True iff valid. secret: the endpoint's `signingSecret` (64-char hex), returned at create/rotate time. """ if not signature_header or not _HEX64.match(secret): return False parts = {} for kv in signature_header.split(','): if '=' not in kv: continue k, v = kv.split('=', 1) parts[k.strip()] = v.strip() try: ts = int(parts.get('t', '0')) except ValueError: return False sig = parts.get('v1', '') if ts <= 0 or not sig or not re.match(r'^[0-9a-f]+$', sig): return False if abs(int(time.time()) - ts) > REPLAY_WINDOW_SECONDS: return False body_bytes = raw_body if isinstance(raw_body, bytes) else raw_body.encode('utf-8') signing_key = bytes.fromhex(secret) signed_string = f"{ts}.".encode('utf-8') + body_bytes expected = hmac.new(signing_key, signed_string, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, sig) ``` ## Multiple endpoints, one receiver If you serve multiple endpoints from one HTTP server, dispatch on the `X-Marea-Endpoint-Id` header and look up the corresponding secret: ```javascript theme={null} const SECRETS = { mk_we_a1b2c3d4e5f60789: process.env.MAREA_PROD_SECRET, mk_we_1a2b3c4d5e6f0789: process.env.MAREA_STAGING_SECRET, }; function lookupSecretForEndpoint(endpointId) { return SECRETS[endpointId]; } ``` ## Source disambiguation (developer vs merchant) The `X-Marea-Source` header tells you which kind of activity produced the delivery: | `X-Marea-Source` | Meaning | | - | - | | `developer` | A `user.*` lifecycle event on an account your developer key bootstrapped | | `merchant` | An `order.*` event from a storefront owned by an account your developer key bootstrapped | Either way, the signature is computed with the same algorithm using the endpoint's own `signingSecret`. You do not need to maintain a different verifier per source. ## Idempotency Every envelope includes an `eventId` (UUID v4) as a stable idempotency key across retries: ```javascript theme={null} async function handleEventAsync(envelope) { const seen = await redis.set( `marea:${envelope.eventId}`, '1', 'EX', 86400, 'NX', ); // 24h TTL, only-if-not-exists if (!seen) return; // already processed await yourBusinessLogic(envelope); } ``` Marea retries failed deliveries up to 3 times (0s / +30s / +5min). The retry payload uses the same `eventId`. ## Detecting in-flight secret rotation Every delivery includes `X-Marea-Signing-Version` (an integer that bumps each time you rotate the endpoint's secret). If you receive a delivery with a version number you've never seen, assume rotation happened — pull the new secret from your secret manager (or the dashboard reveal modal if you triggered the rotate yourself) before retrying signature verification. # Changelog Source: https://docs.mareaalcalina.com/changelog/index Marea API release notes — RSS available at /changelog.rss # Changelog **2026-09-17** REST v1: stricter validation, working upgrade link, WhatsApp number frozen on PATCH **Changed: validation and pagination on the REST API, plus one behavior change.** * **`PATCH /v1/storefronts/{storefrontId}` rejects `whatsapp`.** The order number is set at creation and changed in the dashboard. A patch that includes it, even as `null`, returns `400 invalid_request` and writes nothing. `marea.update_storefront` on the MCP no longer accepts it either. * **The `402` upgrade link works.** `error.upgrade.upgradeUrl` opens the plan screen in the dashboard with the monthly Basic plan preselected. It used to point at a route that did not exist. * **Stricter input rules.** `currency` must be an ISO 4217 code and `businessType` one of the dashboard values (both listed in the OpenAPI spec). `whatsapp` must be E.164 at creation. `salePrice` must be below `price`, `stock` cannot be negative, delivery ranges cannot overlap, and image URLs must be `http(s)`. Text fields refuse HTML tags and inline handlers; ordinary text with `=` or `<` is fine. * **Cursors are opaque and id-ordered.** `nextCursor` is now based on the document id, so pages no longer skip items that share a timestamp. Cursors from before this change are ignored and the list restarts at page one. * **`GET /v1/me` returns `scopes`** and, when the account cannot publish, `_links.upgradeUrl`. The MCP server uses `scopes` to list only the tools a static key can call. * **OpenAPI is machine-consumable.** Every operation has an `operationId`, parameters and request bodies. `openapi.json` and the Postman collection are re-vendored. * **Idempotent replays of a failed write** return the original error again instead of `200` with an empty body. **2026-09-15** MCP server 1.1.0: connect from Claude, ChatGPT or Cursor without a key **Added: OAuth 2.1 on the MCP server, and three read tools.** Merchants can now connect Marea to an AI client themselves. Add `https://mcp.mareaalcalina.com/mcp` as a custom connector in Claude, ChatGPT, Cursor or Claude Code, sign in to Marea, authorize, and the tools are live. No key to paste and no JSON file to edit. * **OAuth 2.1 + PKCE**, discovered from the `WWW-Authenticate` challenge on a 401 (RFC 9728). Client ID Metadata Documents are the preferred registration path; Dynamic Client Registration at `/oauth/register` still works. Scopes: `marea.read`, `marea.write`, `marea.publish`. * **Consent mints a per-user key** named after the app, visible and deletable in the dashboard under Desarrolladores, Claves API. Deleting it disconnects the app. Token revocation is at `POST /oauth/revoke` (RFC 7009). * **Ten tools now.** The three new ones are `marea.list_storefronts`, `marea.get_storefront` and `marea.list_products`. Every argument now carries a description, and `businessType` uses the dashboard's own values. * **Publish confirmation is the client's.** The in-band elicitation gate and its `_confirmed` argument are gone; `marea.publish_storefront` is annotated `destructiveHint: true` and clients show their own prompt. `_idempotencyKey` and `_acceptLanguage` are unchanged. * **Static keys are unchanged.** `Authorization: Bearer mk_user_*` (own account) or `mk_dev_*` (partners that bootstrap accounts) stays the path for servers, CI and agents with no browser. `marea.bootstrap_user` needs `mk_dev_*` and is never reachable over OAuth. See [Connect Marea to your AI client](/quickstart/mcp). **2026-05-15** Self-serve user keys from the dashboard **Added — One-click `mk_user_*` issuance for verified users.** Verified users can now mint and list their own `mk_user_*` keys directly from the dashboard at [mareaalcalina.com/developers/keys](https://mareaalcalina.com/developers/keys) — no partner bootstrap required. Keys issued this way start with the full post-verify scope set (catalog read/write, storefront publish), so you can drive the API against your own storefronts in a single click. What this means for you: * **No more "you must be bootstrapped by a partner" path** for solo builders. Sign up, verify, then issue a key. * **Multiple keys per user.** Mint one per environment or per integration; list and revoke them from the same page. * **The raw key is shown once.** Copy it on issuance — only the SHA-256 hash is stored server-side. See [Concepts → Keys](/concepts/keys) for the full key model, and the [quickstart](/quickstart/bootstrap) to wire your first request. **2026-05-12** PRD-14 — Stripe-style webhook endpoints (model unification) **Added — Webhook endpoints as first-class objects.** Stripe-style endpoint model: each endpoint owns its URL, its `subscribedEvents[]` list, and its own 64-char-hex `signingSecret`. Up to 16 endpoints per account. * **REST CRUD**: `POST /v1/webhook_endpoints`, `GET /v1/webhook_endpoints`, `GET /v1/webhook_endpoints/:id`, `POST /v1/webhook_endpoints/:id` (update), `DELETE /v1/webhook_endpoints/:id`. Required scope: `developer:webhooks` (new keys) or `developer:bootstrap` (existing keys continue to work via any-of). * **Order events on developer endpoints**: a single developer endpoint receives `order.*` events from every storefront your key bootstrapped — no per-merchant endpoint registration needed. * **Signing**: HMAC-SHA256 with the endpoint's raw 64-char-hex `signingSecret` for every event type. * **Envelope** carries `eventId` (UUID v4 — receiver dedup key) + `apiVersion: 2026-05-12`. Headers: `X-Marea-Endpoint-Id`, `X-Marea-Signing-Version`. * **Dashboard** at `/developers/webhooks` manages endpoints (create / edit / pause / rotate / delete / test fire / view recent deliveries). * **Phase B (deferred)**: the same multi-endpoint model will roll out for merchant-configured page webhooks in a follow-up release. **2026-05-10** Docs site accuracy + DX overhaul **Improved — comprehensive docs audit + Stripe-style cleanup.** Following the first public publish, a senior-engineer pass cross-checked every claim in the docs against the cloud-functions Zod contracts as ground truth. * **API Reference** now covers all 13 v1 operations (previously a Phase-1 stub with `/v1/me` only). `openapi.json` is script-generated from the cloud-functions Zod schemas via `@asteasolutions/zod-to-openapi` (zero drift): tags, operationIds, both security schemes (Bearer + X-API-Key), rate-limit response headers, idempotency headers, and full `$ref` to `ApiErrorResponse` on every 4xx/5xx. * **Stripe-style URL slugs.** API reference pages now ship at clean URLs like `/api/storefronts/create-storefront` and `/api/identity/get-current-identity` (previously they were verbose auto-slugified sentences). * **Plan limits corrected.** `plan.limits` shape is `{storefronts, products, publishable}` (not the docs' previous `{maxStorefronts, maxProducts, canPublish}` invention). Free plan has two variants (`FREE_NEW` 1 storefront, `FREE_OLD` legacy 3 storefronts). Pre-paywall accounts have a 2,000 draft-product cap. Single-product POST returns `plan_max_products_reached`, not `products_over_limit` (the latter is the 207-batch path). * **Scopes corrected.** Eight real scopes: `developer:bootstrap`, `developer:read`, `developer:issueUserKey`, `catalog:read`, `catalog:write`, `storefront:publish`, `me:verify`, `me:resendVerification`. Earlier docs referenced a non-existent `users:bootstrap` — now removed everywhere. * **Error codes**: \~40 real `error.code` values cross-checked against `grep ApiError` across `src/api/`. Removed fabricated codes (`validation_failed`, `product_not_found`, `invalid_request_body`, `rpd_exceeded`-as-code) that the docs invented; replaced with the real ones (`invalid_request`, `storefront_not_found`, `rate_limit_exceeded`). `rpd_exceeded`/`rpm_exceeded` continue to surface inside `error.message` only. * **MCP quickstart**: install path now uses the `mcp-remote` bridge (verified package). Tool count corrected to 7 (verify + resend are REST-only by design). * **Four concept pages** that were placeholders are now real content: `verification-flow`, `tos-jurisdiction`, `arco-procedures`, `versioning`. Each is sourced from cloud-functions handlers, with TTLs, lockouts, cancel reasons, and breaking-change rules from code. * **Homepage**: removed redundant H1 + intro paragraph that duplicated frontmatter title/description (Mintlify renders both automatically). Added a "Webhook surfaces" CardGroup so first-time readers see both surfaces. * **Receiver helpers**: `concepts/webhooks` now ships full JS + Python verifiers in `api/webhooks/*.mdx`, with the `X-Marea-Source` (`developer` vs `merchant`) header disambiguating event sources. 19 files changed; Mintlify validate + broken-links both green. # ARCO procedures (LFPDPPP) Source: https://docs.mareaalcalina.com/concepts/arco-procedures Mexican data-rights compliance: Acceso, Rectificación, Cancelación, Oposición. Endpoints and retention windows. # ARCO procedures Marea Alcalina is a Mexican corporation and is subject to **LFPDPPP** (Articles 16–18), the Mexican federal personal-data-protection statute. Every account holder has four enumerated rights — collectively **ARCO**: | Right | Spanish | What the user can do | | - | - | - | | **A**cceso | Acceso | Access a copy of their personal data | | **R**ectificación | Rectificación | Correct inaccurate or incomplete data | | **C**ancelación | Cancelación | Delete their account and all associated data | | **O**posición | Oposición | Object to specific processing of their data | Brazilian residents have a parallel set of rights under LGPD (Lei Geral de Proteção de Dados). The technical surfaces below honor both. ## How users exercise ARCO ### Access + Rectification (online, self-serve) The dashboard at [mareaalcalina.com/dashboard](https://mareaalcalina.com/dashboard) exposes: * Account email, displayName, language, currency, country, plan, verification status, `tosAcceptedAt`. * Every storefront the account owns + its products. * Each user key issued for the account (label, prefix, scopes, last used). API equivalents: | Endpoint | Key | Returns | | - | - | - | | `GET /v1/me` | `mk_user_*` / `mk_dev_*` | Identity + plan + rate-limit window + dashboard links | | `GET /v1/users/:userId` | `mk_dev_*` (developer scope) | The full user DTO for users the dev key bootstrapped | | `GET /v1/users` | `mk_dev_*` (developer scope) | Paginated list of users the dev key bootstrapped | Storefront and product contents are exposed through the dashboard for Acceso today; the API v1 catalog surface is currently write-only (`POST` / `PATCH`), so for an LFPDPPP Acceso request that needs storefront contents, direct the user to the dashboard above. Rectification of catalog data goes through `PATCH /v1/storefronts/:storefrontId` (deep-merge, see [Storefronts](/concepts/storefronts)). ### Cancellation (hard delete) Three paths trigger an LFPDPPP-compliant hard delete: | Path | Triggered by | Idempotent | | - | - | - | | Dashboard "Delete account" button | User (interactive) | Yes | | `DELETE /public/v1/bootstrap/:previewToken` (or two-step `GET` confirm flow) | Bootstrap-email recipient | Yes | | Scheduled cleanup (`30d_unverified` or `90d_no_tos`) | System | Yes | The public bootstrap-cancel endpoint is unauthenticated by API key — the **preview token is the auth** (256-bit random, 24h TTL, single-use). The link is embedded in every bootstrap verification email so a user who didn't ask for an account can self-cancel without ever logging in. Hard delete removes, in this order: 1. **API keys** — every `apiKeys` doc where `ownerUid == :uid` (batched, 500-per-batch). 2. **Verification codes** — `apiVerificationCodes/{email}`. 3. **Preview tokens** — every `apiPreviewTokens` doc for this user. 4. **Storefronts + products** — `users/{uid}/menus/**` recursive delete. 5. **User document + subcollections** — `users/{uid}` recursive delete. 6. **Audit trail** — one append to `tosAcceptanceLog` recording reason + summary BEFORE the Auth delete. 7. **Firebase Auth user** — `auth().deleteUser(uid)`. Frees the email for re-signup. 8. **Webhook fan-out** — `user.cancelled` event (see [Webhooks](/concepts/webhooks)) with one of the locked `reason` values. `reason` enum in the `user.cancelled` webhook: | Value | Triggered by | | - | - | | `user_clicked_cancel` | Public bootstrap-cancel endpoint | | `squatting_defense` | Email squatting defense (PRD-4) | | `30d_unverified` | Scheduled cleanup — never verified within 30 days | | `90d_no_tos` | Scheduled cleanup — verified but ToS not accepted within 90 days | | `key_revoked` | All other administrative or revocation-cascading deletes | ### Opposition To object to a specific processing activity (marketing, analytics, etc.) without cancelling the account, users may write to the contact channel below. Marea applies the change within the LFPDPPP-prescribed response window (20 business days from a verifiable request). ## Retention * An **active** account is retained while it has a paid plan, has not invoked Cancelación, and has accepted ToS (or is within the 90-day window for agent-bootstrapped accounts). * A **hard-deleted** account is removed from Firestore + Firebase Auth within the same job invocation. Orphan Cloud Logging entries decay per Google Cloud's standard retention (default 30 days). * A **revoked API key** stops authenticating within \~60 seconds end-to-end and is retained server-side for audit purposes only (the `keyHash` is kept; the raw key was never stored). ## Contact channel LFPDPPP / LGPD requests not satisfied by the self-serve paths above should be sent to the contact email on the dashboard footer. Marea's response SLA matches LFPDPPP statutory timelines (20 business days; 15 days for follow-ups). ## What an agent should know * **Never** create an account on behalf of a user who has not authorized it. The cancel hatch protects misuse, but the user-rights regime treats unauthorized creation as a violation by the creating party. * If the agent receives `user.cancelled` (any reason) for a user it bootstrapped, the agent must **stop** all downstream automation for that user and delete any local cached state. * The agent **cannot** accept the ToS on the user's behalf. See [ToS jurisdiction](/concepts/tos-jurisdiction) for the 451 flow. ## Verification in code * `src/api/public/bootstrap.cancel.ts` — public unauthenticated cancellation endpoint (preview-token auth). * `src/api/services/account-delete.service.ts` — `hardDeleteUserAccount` ordering + audit-log write. * `src/api/scheduled/CleanupUnverifiedAccounts.ts` — 30d / 90d sweep policy. * `src/api/services/webhooks.service.ts` — `user.cancelled` event + `CancelReason` enum. # Errors Source: https://docs.mareaalcalina.com/concepts/errors Canonical error envelope, the 10-value type enum, the full code reference, and an agent-actionable recovery matrix. # Errors Every non-2xx response uses the **same envelope**. Agents branch on `error.type` (a stable 10-value enum); each error carries `nextActions[]` — concrete steps to surface to the user. ## Envelope shape ```json theme={null} { "error": { "type": "rate_limited", "code": "rate_limit_exceeded", "message": "Rate limit exceeded (rpm_exceeded). Retry after 23s.", "doc": "https://docs.mareaalcalina.com/concepts/rate-limits", "param": null, "requestId": "req_30a9358b-70bd-44f3-aa5d-8983b558ad84", "recoverable": true, "retryAfterMs": 23000, "nextActions": [ { "label": "Wait 23s and retry the same request.", "method": null, "url": null } ], "upgrade": null } } ``` ## Field guarantees | Field | Type | Notes | | - | - | - | | `type` | enum (10 values) | Stable. Agents branch on this. See the table below. | | `code` | string | Stable, machine-readable. Finer-grained than `type`. | | `message` | string | Human-readable, in English today (localization may come later). Do not branch on it. | | `doc` | string | Link to the relevant docs page for this code. | | `param` | string \| `null` | Name of the offending field (`null` if not field-specific). Never missing. | | `requestId` | string | `req_` — surface to the user when reporting bugs. | | `recoverable` | boolean | `true` means a retry is meaningful (with appropriate changes). | | `retryAfterMs` | integer \| `null` | When set, also returned as the `Retry-After` header (in seconds). | | `nextActions` | array | **Always an array** (possibly empty). `null` is not allowed. Each entry: `{ label, method, url }`. | | `upgrade` | object \| `null` | `{ currentPlan, requiredPlan, upgradeUrl, previewUrl? }`. Set only on `plan_limit` errors. | | `requiredScopes` | string\[] (optional) | Present only when the failure is a scope mismatch. | | `heldScopes` | string\[] (optional) | Present only when the failure is a scope mismatch. | ## The 10 error types | `type` | Typical HTTP | When it happens | Agent action | | - | - | - | - | | `rate_limited` | 429 | rpm or rpd quota exceeded | Read `retryAfterMs`, sleep, retry. `recoverable: true`. See [Rate limits](/concepts/rate-limits). | | `invalid_request` | 400 / 410 / 422 | Malformed body, invalid `Idempotency-Key`, oversize snapshot, empty publish | Fix the body and reissue. Do not retry the exact same request. | | `auth` | 401 / 403 | Missing / invalid / revoked key, missing scope | 401 → fix credential. 403 with `requiredScopes` → request an upscoped key. | | `not_found` | 404 | Resource missing OR cross-tenant access (silent denial) | Confirm the id is correct AND the key owns it. | | `plan_limit` | 402 | Plan ceiling hit (publish blocked, product cap exceeded) | Surface `upgrade.upgradeUrl` to the user as a CTA. See [Plan limits](/concepts/plan-limits). | | `internal` | 500 | Server bug | Surface `requestId`. Retry once with backoff, then escalate. | | `conflict` | 409 | `Idempotency-Key` in flight (same key still processing) | Wait `retryAfterMs` and retry with the same key. | | `idempotency_conflict` | 409 | Same `Idempotency-Key` reused with a **different** body | Generate a NEW `Idempotency-Key`. See [Safe mutations](/concepts/safe-mutations). | | `service_unavailable` | 503 | Dependency outage or feature flag off | Retry with exponential backoff. | | `tos_not_accepted` | 451 | Calling user has not accepted the Terms of Service | Surface `nextActions[0]` (dashboard link). User must accept; agent cannot bypass. See [ToS jurisdiction](/concepts/tos-jurisdiction). | ## Recovery matrix | If `error.type` is | Surface to user? | Retry? | What to do | | - | - | - | - | | `rate_limited` | No (transparent) | Yes after `retryAfterMs` | Sleep + retry same request + same `Idempotency-Key` | | `invalid_request` | No (fix client-side) | No (without fixing) | Fix the body. Do not retry blindly. | | `auth` (401) | Maybe (credential issue) | No | Re-prompt for a valid key | | `auth` (403, scope) | Maybe | No | Request a key with `requiredScopes` | | `not_found` | Maybe ("not found") | No | Confirm id; confirm key ownership | | `plan_limit` | **Yes** (paywall CTA) | No | Surface `upgrade.upgradeUrl` verbatim | | `internal` | Yes (with `requestId`) | Once with backoff | Then escalate | | `conflict` (in-flight idempotency) | No | Yes after 1s | Retry with same `Idempotency-Key` | | `idempotency_conflict` | No | Yes with NEW key | Generate a fresh `Idempotency-Key` | | `service_unavailable` | Yes (after retries) | Yes with backoff | Exponential backoff | | `tos_not_accepted` | **Yes** (ToS link) | After user accepts | Surface `nextActions[0].url` | ## Stable code reference Every code below is emitted by production code today. Agents may branch on `code` for finer-grained handling than `type`. ### Auth (401 / 403) | `code` | HTTP | Source | | - | - | - | | `missing_authorization` | 401 | `src/api/middleware/apiKey.ts` | | `invalid_authorization_format` | 401 | `src/api/middleware/apiKey.ts` | | `key_not_found` | 401 | `src/api/middleware/apiKey.ts` | | `key_revoked` | 401 | `src/api/middleware/apiKey.ts` | | `insufficient_scope` | 403 | `src/api/middleware/scope.ts` — includes `requiredScopes`/`heldScopes` | | `developer_context_unresolved` | 401 | Bootstrap / issue-key handlers when developer ctx is missing | | `tenant_unresolved` | 401 | Catalog / verify handlers when owner ctx is missing | | `developer_not_found` | 404 | `src/api/v1/me.get.ts` — dev account missing from Firebase Auth | ### Validation (400 / 410 / 413 / 422) | `code` | HTTP | Source | | - | - | - | | `invalid_request` | 400 | Zod validation failure (per-field) | | `invalid_json` | 400 | Body parsing failure | | `invalid_idempotency_key` | 400 | `src/api/middleware/idempotency.ts` | | `invalid_storefront_id` | 400 | `src/api/services/translation/storefront-id.ts` | | `invalid_product_id` | 400 | `src/api/services/translation/storefront-id.ts` | | `invalid_email_syntax` | 400 | Bootstrap email validation | | `invalid_email_mx` | 400 | Bootstrap MX-record check | | `code_invalid` | 400 | `src/api/v1/users.verify.ts` | | `code_expired` | 410 | `src/api/v1/users.verify.ts` | | `idempotency_snapshot_unavailable` | 410 | `src/api/middleware/idempotency.ts` (oversize replay) | | `payload_too_large` | 413 | Body parser | | `no_products` | 422 | `src/api/v1/storefronts.publish.ts` (empty storefront) | | `user_not_verified` | 422 | `src/api/v1/users.issueKey.ts` (pre-verify additional key) | | `blocks_explicit_not_supported` | 422 | Storefront manifest (legacy block fields) | | `theme_preset_not_supported` | 422 | Storefront manifest (theme presets not on plan) | ### Not found (404) | `code` | HTTP | Source | | - | - | - | | `storefront_not_found` | 404 | `src/api/v1/storefronts.*` — also fires on cross-tenant access | | `user_not_found` | 404 | Verify, resend, issue-key handlers — also cross-tenant | | `code_not_found` | 404 | `src/api/v1/users.verify.ts` — no active verification code | ### Conflicts (409) | `code` | HTTP | Source | | - | - | - | | `idempotency_in_flight` | 409 | `src/api/middleware/idempotency.ts` — emits `Retry-After: 1` | | `idempotency_conflict` | 409 | `src/api/middleware/idempotency.ts` — different body, same key | | `email_exists` | 409 | Bootstrap — email already registered | ### Plan / paywall (402) | `code` | HTTP | Source | | - | - | - | | `plan_blocks_publish` | 402 | `src/api/v1/storefronts.publish.ts` (`NO_ACTIVO` plan) | | `plan_max_products_reached` | 402 | `src/services/catalog/productCreateCore.ts` — single-product POST would exceed the plan cap | | `plan_max_storefronts_reached` | 402 | `src/services/catalog/createMenuCore.ts` — would exceed the per-plan storefront cap | | `products_over_limit` | 207/402 | `src/api/v1/storefronts.create.ts` (manifest with too many products) — 207 partial OR 402 over cap | ### Rate limit (429) | `code` | HTTP | Source | | - | - | - | | `rate_limit_exceeded` | 429 | `src/api/middleware/rateLimit.ts` — `rpm_exceeded` / `rpd_exceeded` | | `too_many_attempts` | 429 | `src/api/v1/users.verify.ts` — 3 wrong codes | | `bootstrap_ip_rate_limited` | 429 | `src/api/services/bootstrap.service.ts` | | `bootstrap_quota_exhausted` | 429 | `src/api/services/bootstrap.service.ts` | | `resend_hour_limit` | 429 | `src/api/v1/users.resendVerification.ts` | | `resend_day_limit` | 429 | `src/api/v1/users.resendVerification.ts` | ### ToS (451) | `code` | HTTP | Source | | - | - | - | | `tos_required` | 451 | Reserved on `storefronts.publish` — see [ToS jurisdiction](/concepts/tos-jurisdiction) | ### Service / internal (500 / 503) | `code` | HTTP | Source | | - | - | - | | `api_disabled` | 503 | `src/api/middleware/featureFlag.ts` — kill switch | | `verify_unexpected_state` | 500 | `src/api/v1/users.verify.ts` — defense-in-depth fall-through | | `internal_error` | 500 | Unhandled exception path | ## What NOT to do * **Do not branch on `error.message`**: it is English today, may be localized later, and its wording can change. Branch on `error.type` (enum) and `error.code` (string). * **Do not swallow `nextActions[]`.** The most common agent-failure mode is silently retrying past a `402` (paywall) or `451` (ToS) without ever showing the user the action. * **Do not auto-accept the ToS** on the user's behalf. The 451 → modal flow requires user input by design. * **Do not retry `invalid_request`** with the same body. Fix the body first. * **Do not branch on HTTP status alone.** Several types share a status (409 for two conflict shapes; 404 for both real-missing and cross-tenant). The `type` + `code` pair disambiguates. ## Verification in code * `src/api/contracts/error.zod.ts` — the locked envelope schema (10 type values). * `src/api/api-error.ts` — the `ApiError` class that wires status + type + code + recovery hints. * `src/api/middleware/errors.ts` — the global error handler that emits the envelope. # API keys Source: https://docs.mareaalcalina.com/concepts/keys User-key is the default for almost everyone. Developer-key exists for partners bootstrapping users on others' behalf. # API keys Almost every integration with Marea uses **one kind of key**: a `mk_user_*` issued to a single Marea user, used to manage **all** of that user's storefronts and products. A second kind — `mk_dev_*` — exists for a separate class of caller: agents, vertical-SaaS, and agencies that create Marea accounts on behalf of *other* people. Most readers will never need one. ```http theme={null} GET /v1/me HTTP/1.1 Host: api.mareaalcalina.com Authorization: Bearer mk_user_xxxxxxxxxxxxxxxx ``` Format is locked: `^mk_(dev|user)_[A-Za-z0-9]+$`. The random suffix is 24 base62 chars (\~143 bits of entropy). ## The default: `mk_user_*` (user-key) A user-key represents one specific Marea user and is the credential you use for everything that happens *inside* that user's account. > [!NOTE] > > **One key covers ALL of that user's storefronts.** A user-key is **owner-scoped, not storefront-scoped**. The same `mk_user_*` can `GET` / `POST` / `PATCH` / `publish` against every storefront the user owns — whether that's 1 (Free plan) or 5,000 (Agency Growth plan). You do *not* issue a separate key per storefront. You do *not* pass a `Storefront-Id` header — the storefront is in the URL path; the key proves you own it. | Holds | Default scopes | | - | - | | One specific end-user (and **all** their storefronts) | `catalog:read`, `catalog:write`, `storefront:publish` (after verify) | **How to get one:** * If you signed up at [mareaalcalina.com](https://mareaalcalina.com) and own a storefront, mint a `mk_user_*` in one click from your dashboard at [`/developers/keys`](https://mareaalcalina.com/developers/keys). * If you were bootstrapped through a partner integration, you received your `mk_user_*` in the `POST /v1/users` response — store it then. **What you can do with it:** * `GET /v1/me` — confirm identity, read your plan + limits * `GET /v1/storefronts`, `POST /v1/storefronts`, `PATCH /v1/storefronts/:id` — manage your storefronts * `POST .../products`, `PATCH .../products/:id`, `GET .../products` — manage your catalog * `POST .../publish` — take a storefront live (gated by ToS + plan) * *(after Phase B)* `POST /v1/webhook_endpoints` — receive `order.*` events from your store **What you can't do:** * Bootstrap other users (that requires `developer:bootstrap`, held only by `mk_dev_*`) * See or edit anyone else's data — tenant boundary is encoded in the key itself ### Pre-verify vs post-verify scopes If your `mk_user_*` came from a fresh `POST /v1/users` (partner bootstrap), it starts with a **restricted** scope set — `me:verify`, `me:resendVerification`, `catalog:read`. The only mutating calls it can make are verify and resend. When the user submits the 6-digit code (`POST /v1/users/:userId/verify`), the **same key** is upgraded in place to `catalog:read`, `catalog:write`, `storefront:publish`. No rotation — store the value once at bootstrap time. User-keys minted from the dashboard (self-issued by an already-verified user) start in the full post-verify state. ### Keys created by AI connections There is a third way a `mk_user_*` comes into existence: you connect Marea to an AI client over MCP. When you press Autorizar on the consent screen, Marea mints a key for that connection and names it after the app and its domain, for example `Claude · claude.ai` or `ChatGPT · chatgpt.com`. You never see it or paste it. The OAuth token the client holds resolves to that key on every call, so the REST API sees an ordinary per-user key with your usual scopes. Two things follow from that: * **The key is yours to delete.** It is listed in your dashboard under Desarrolladores, Claves API, next to the keys you minted yourself. Delete it and the app is disconnected: its next call comes back 401, the OAuth grant behind it is dropped, and the client has to send you through sign-in again if you want it back. * **It is a per-user key, with the limits of one.** No OAuth connection can bootstrap accounts for other people, whatever scopes were granted, because `developer:bootstrap` is held only by `mk_dev_*`. Revoking the token from the app side (its connector settings, or `POST /oauth/revoke` on the MCP server) ends the OAuth grant but leaves the key in place. Deleting the key is the action that works from Marea's side alone, without touching the app. See [Connect Marea to your AI client](/quickstart/mcp). ## The advanced case: `mk_dev_*` (partner / developer key) A `mk_dev_*` is for callers that act on behalf of *many* users — three real archetypes: 1. **AI agents** (Claude, ChatGPT, Cursor) that bootstrap Marea accounts as part of helping their own end-users. 2. **Vertical SaaS** (e.g., a LATAM restaurant-management product) embedding Marea so their customers get a storefront without the SaaS building one. 3. **Agencies** running marketing for many small clients — one operator console, many client storefronts. If none of those describe you, skip this section. | Holds | Default scopes | | - | - | | The partner integration itself | `developer:bootstrap`, `developer:read`, `developer:issueUserKey`, `developer:webhooks` | **How to get one:** Issue from the developer dashboard at [mareaalcalina.com/developers/keys](https://mareaalcalina.com/developers/keys). The raw value is shown once; server-side only the SHA-256 hash is stored. **What you can do with it:** * `POST /v1/users` — bootstrap a new Marea user (returns their `mk_user_*` in the response) * `GET /v1/users`, `GET /v1/users/:userId` — list / inspect users you've bootstrapped * `POST /v1/users/:userId/keys` — mint an additional `mk_user_*` for a user you've bootstrapped (e.g., a second integration) * All `/v1/webhook_endpoints/*` operations — manage your webhook endpoints (`user.*` lifecycle on accounts you bootstrapped + `order.*` from those accounts' storefronts) **What you can't do:** * Touch any user's catalog directly. To edit a user's storefront, use the `mk_user_*` you got back from their bootstrap. Even a partner who owns a Marea storefront themselves uses *their own* `mk_user_*` for that storefront — the dev-key never grants catalog access. The split is a security boundary: a leaked `mk_dev_*` can bootstrap new fake accounts and read user metadata, but can't rewrite a single user's prices. ## Authenticating Pass the key in `Authorization: Bearer ` (preferred). `X-API-Key: ` is accepted as a fallback. Any other header — or a non-`Bearer` `Authorization` scheme — fails with `invalid_authorization_format`. ## Scopes table Scope checks run after key lookup. Endpoints declare a required scope set; the auth layer supports both `any` (one-of) and `all` (require-all) semantics. | Scope | Held by | Used by | | - | - | - | | `catalog:read` | user keys | `GET /v1/storefronts/...`, `GET .../products` | | `catalog:write` | user keys | `POST` / `PATCH` on storefronts and products | | `storefront:publish` | user keys | `POST /v1/storefronts/:storefrontId/publish` | | `me:verify` | restricted user keys (pre-verify) | `POST /v1/users/:userId/verify` | | `me:resendVerification` | restricted user keys | `POST /v1/users/:userId/resendVerification` | | `developer:bootstrap` | dev keys | `POST /v1/users` | | `developer:read` | dev keys | `GET /v1/users`, `GET /v1/users/:userId` | | `developer:issueUserKey` | dev keys | `POST /v1/users/:userId/keys` | | `developer:webhooks` | dev keys | `POST /v1/webhook_endpoints` + the rest of `/v1/webhook_endpoints/...` | `GET /v1/me` accepts any of the user scopes; developer keys bypass the scope check entirely (a developer key always sees its own identity). ### Scope mismatch (403) ```json theme={null} { "error": { "type": "auth", "code": "insufficient_scope", "message": "Missing required scopes: catalog:write.", "requiredScopes": ["catalog:write"], "heldScopes": ["developer:bootstrap"], "recoverable": false } } ``` Surface `requiredScopes` and `heldScopes` verbatim — the diff between them tells you exactly which kind of key you should have used (`mk_user_*` for catalog scopes; `mk_dev_*` for developer scopes). ## Rotation There is no `rotate` call. To rotate: 1. Revoke the old key. 2. Issue a new one (developer dashboard for `mk_dev_*`; user dashboard for `mk_user_*`; or `POST /v1/users/:userId/keys` with a developer key for an additional user-key on a bootstrapped user). 3. Update your client. ## Revocation Revoked keys stop authenticating within \~60s end-to-end (the negative-lookup cache TTL). After revocation: * The key returns `401 key_revoked` on every request. * Webhook endpoints are NOT tied to a single key — they belong to your account and survive key revocation. Revoking a single key does not delete or disable any endpoint. See [Webhook endpoints](/concepts/webhooks) for the lifecycle. * Revocation is **non-cascading**: revoking a developer key does NOT revoke the user keys it minted. To wipe everything for an owner, the owner-scoped revoke-all path is used (operator path; not in the public API). ## Auth errors (401) | `error.code` | When | Recovery | | | - | - | - | - | | `missing_authorization` | Neither `Authorization` nor `X-API-Key` present | Add the header | | | `invalid_authorization_format` | Header present but not \`Bearer mk\_(dev | user)\_...\` | Fix the format | | `key_not_found` | Key not recognized (typo or never issued) | Issue a new key | | | `key_revoked` | Key was issued but later revoked | Issue a new key | | All four are 401 with `recoverable: false`. Don't loop — fix the credential. # Marea AI Source: https://docs.mareaalcalina.com/concepts/marea-ai Marea AI is the in-product chat editor merchants use to build and edit their storefront. It is a merchant-facing feature, not a public API surface — this page explains the boundary. # Marea AI **Marea AI** is the conversational editor built into the Marea dashboard. A merchant opens a chat panel inside the storefront editor and asks for changes in plain language — "add a testimonials section", "change the colors to match this photo", "create a product for the IPA" — and Marea AI applies them to the storefront draft. It is a **merchant-facing product feature**. It is **not** part of the public API, and you do not call it from an integration. This page exists so the boundary is explicit: if you are building against Marea, the surfaces below are yours; Marea AI is the merchant's. ## Marea AI vs. the developer surfaces | | Marea AI | Public API / MCP | | - | - | - | | Audience | The merchant, in the dashboard | Developers and AI agents you build | | Interface | Chat panel in the storefront editor | REST (`api.mareaalcalina.com`) + MCP (`mcp.mareaalcalina.com`) | | Auth | The merchant's dashboard session | An `mk_dev_*` developer key | | Scope | One storefront — the merchant's own | Any storefront your key is authorized for | | Documented in | The in-product help, not here | The rest of this site | Marea AI and the public API write the same storefront model — a change a merchant makes by chat and a change you make by `PATCH` land in the same place. They are two front doors to one catalog, not two catalogs. ## What this means for an integration * **You cannot drive Marea AI through the API.** There is no "send a prompt to Marea AI" endpoint. To make catalog changes programmatically, use the [REST API](/quickstart/bootstrap) or the [MCP server](/quickstart/mcp) directly. * **Edits are not exclusive.** A storefront edited by a merchant in Marea AI is still fully editable through your API key, and vice versa. Both honor the same [draft / publish](/concepts/publishing) lifecycle. * **Drafts are shared.** Marea AI edits the storefront's working draft. If your integration reads a draft, expect it may also reflect the merchant's chat edits. ## When to point a merchant at Marea AI If you are building a tool *for* merchants and a request is really "let me edit my page in natural language", that is what Marea AI already does inside the dashboard — point the merchant there rather than rebuilding it. Use the API for programmatic, multi-storefront, or headless integrations. # Plan limits and the publish gate Source: https://docs.mareaalcalina.com/concepts/plan-limits Storefront caps, product caps, the pre-paywall publish block, and the 207 Multi-Status path when a manifest exceeds plan caps. # Plan limits Every Marea user is on a plan. The plan determines: 1. How many storefronts the user can have 2. How many products per storefront 3. Whether the user can publish at all (pre-paywall accounts cannot) 4. Per-transaction platform fee, multi-branch availability, and monthly-orders visibility (covered below) Your agent should read the user's plan from `GET /v1/me` (`plan.tier` + `plan.limits`) and surface `_links.upgradeUrl` if a higher tier is required. The numbers below are the canonical caps from `plan-limits.ts`; custom plans can override the storefront cap via `planQuantity`, and the `/v1/me` response always reflects the live cap. > [!NOTE] > > The API surfaces a **coarse-grained 4-value tier** (`free`, `basic`, `pro`, `business`) for SDK stability. Internally there are more numeric sub-plans (e.g. `business_200`, `business_500`, `agency_growth`) that collapse to `"business"` on the wire. The numeric `planQuantity` field carries the true storefront ceiling for custom plans. ## The `plan.limits` shape `/v1/me` returns this exact shape — fields are not pluralized the way you might expect: ```json theme={null} { "plan": { "tier": "free", "limits": { "storefronts": 1, "products": 30, "publishable": true } }, "planQuantity": null } ``` | Field | Meaning | | - | - | | `limits.storefronts` | Maximum storefronts the user can own. | | `limits.products` | Maximum products **per storefront** (each storefront gets its own bucket). | | `limits.publishable` | `true` if the plan permits making a storefront publicly available. Only `false` for pre-paywall accounts. | | `planQuantity` | If non-null, the per-account override for `limits.storefronts` (custom/agency plans). | ## Per-plan caps | Surfaced tier | Internal plans | `storefronts` | `products` per storefront | `publishable` | | - | - | - | - | - | | `free` (pre-paywall) | `NO_ACTIVO` (9) | 1 | 2,000 (drafts only — see note) | **false** | | `free` | `FREE_NEW` (8) | 1 | 30 | true | | `free` | `FREE_OLD` (2, legacy) | 3 | 30 | true | | `basic` | `BASIC_MONTHLY` (4) / `BASIC_YEARLY` (5) | 3 | 60 | true | | `pro` | `PRO_MONTHLY` (1) / `PRO_YEARLY` (3) | 15 | 200 | true | | `business` | `BUSINESS_MONTHLY` (6) / `BUSINESS_YEARLY` (7) | 50 | 2,000 | true | | `business` | `BUSINESS_200` (11) | 200 | 2,000 | true | | `business` | `BUSINESS_500` (12) | 500 | 2,000 | true | | `business` | `BUSINESS_1000` (13) | 1,000 | 2,000 | true | | `business` | `AGENCY` (20, legacy) | 20 | 2,000 | true | | `business` | `AGENCY_MONTHLY` (21) / `AGENCY_YEARLY` (22) | 5,000 | 2,000 | true | > [!WARNING] > > **Pre-paywall accounts.** A pre-paywall user (`NO_ACTIVO`) collapses to `"free"` on the wire but `limits.publishable === false`. The product cap shows as 2,000 to permit full authoring preview before checkout, but `POST .../publish` returns **402** and orders are blocked upstream. Use `plan.limits.publishable` — never the tier name — to decide whether a publish call will succeed. ## Beyond storefronts + products `plan-limits.ts` also encodes several plan-derived behaviors. Most are not surfaced verbatim in `/v1/me.plan.limits` today (the public limits object is the locked 3-field shape above), but they govern what the user can do once they hit the dashboard. Surface these to the user when an upgrade CTA needs context: | Capability | Free (`NO_ACTIVO`/`FREE_*`) | Basic | Pro | Business | Agency | | - | - | - | - | - | - | | Platform fee (Stripe + PayPal) | 2.5% | 1.9% | 1.5% | 0.9% | 0% | | Multi-branch (locations per storefront) | 0 (off) | 0 (off) | 0 (off) | 3 | unlimited | | Monthly orders visible in dashboard | 30 (`NO_ACTIVO` = 0) | 200 | 1,000 | unlimited | unlimited | Monthly-order visibility gates dashboard surface — orders still arrive via WhatsApp regardless. The `0` for `NO_ACTIVO` means dashboard order intake is fully disabled until the user picks a plan. ## Scopes vs. plan Plan tier does **not** determine the scopes a user key holds. Scopes are set per-key at issuance (`catalog:read`, `catalog:write`, `storefront:publish`). The publish scope passes the auth layer for any plan, but the `storefronts/:id/publish` handler then re-checks `plan.limits.publishable` and returns 402 for pre-paywall accounts. In other words: the scope says "this key is permitted to attempt publishing", and the plan says "this account is permitted to actually publish". Both must be true. ## What happens at the limit ### 402 `plan_blocks_publish` — pre-paywall accounts only `POST /v1/storefronts/:id/publish` returns **402** when the user is in the pre-paywall state (`NO_ACTIVO`, plan 9). Once any paid plan or legacy free plan is active, this endpoint stops rejecting. ```json theme={null} { "error": { "type": "plan_limit", "code": "plan_blocks_publish", "message": "Your plan does not permit publishing. Upgrade to publish this storefront.", "recoverable": true, "upgrade": { "currentPlan": "free", "requiredPlan": "basic", "upgradeUrl": "https://mareaalcalina.com/menus/profile?changePlan=basic&frequency=monthly&planSource=api" } } } ``` Surface `upgrade.upgradeUrl` to the user as a CTA. Do not retry without a plan change. > [!NOTE] > > `currentPlan: "free"` here is the coarse-grained tier surface — pre-paywall and `FREE_*` both collapse to `"free"` so upgrade copy stays consistent. The authoritative signal is `plan.limits.publishable` from `/v1/me`, not the tier string. ### 207 `products_over_limit` — bulk manifest exceeds product cap `POST /v1/storefronts` accepts a manifest with up to 100 products in a single call. If the user's plan caps lower than the manifest count, the storefront is still created **up to the cap** and the response status is **207 Multi-Status**: ```json theme={null} { "storefront": { "id": "stf_xxx", "...": "..." }, "errors": [ { "type": "plan_limit", "code": "products_over_limit", "message": "Plan limit of 30 products reached. This product was not created.", "param": "products", "doc": "https://docs.mareaalcalina.com/errors/products_over_limit", "recoverable": true, "recovery": { "skippedCount": 12, "skippedProducts": [ { "index": 30, "title": "Tacos al pastor" }, { "index": 31, "title": "Tacos de chorizo" } ], "upgrade": { "currentPlan": "free", "requiredPlan": "basic", "upgradeUrl": "https://mareaalcalina.com/menus/profile?changePlan=basic&frequency=monthly&planSource=api" } } } ] } ``` > [!NOTE] > > The `message` is emitted per skipped product (same string for each row), not pre-aggregated. Code that branches on `message` will get one identical string per row in `errors[]` — use `recovery.skippedCount` for the total. The storefront is real and usable. `errors[].recovery.skippedProducts` tells your agent exactly which items were dropped, with the original manifest index. Surface the upgrade CTA — once the user upgrades, retry the dropped products via `POST /v1/storefronts/:storefrontId/products`. ### 402 `plan_max_products_reached` — individual product POST hit the cap Once the storefront exists, individual `POST /v1/storefronts/:storefrontId/products` calls that would push past the per-storefront product cap return a plain **402** with the same `upgrade` shape: ```json theme={null} { "error": { "type": "plan_limit", "code": "plan_max_products_reached", "message": "Plan limit of 30 products reached. Upgrade to add more.", "param": "products", "recoverable": true, "upgrade": { "currentPlan": "free", "requiredPlan": "basic", "upgradeUrl": "https://mareaalcalina.com/menus/profile?changePlan=basic&frequency=monthly&planSource=api" } } } ``` Note the different `code` from the bulk path: single-product POSTs do **not** return 207 — there's nothing partial to report. ## Reading the user's current plan ```http theme={null} GET /v1/me HTTP/1.1 Authorization: Bearer mk_user_xxxxxxxxxxxxxxxx ``` ```json theme={null} { "id": "usr_xxx", "type": "user", "plan": { "tier": "free", "limits": { "storefronts": 1, "products": 30, "publishable": true } }, "planQuantity": null, "_links": { "upgradeUrl": "https://mareaalcalina.com/menus/profile?changePlan=basic&frequency=monthly&planSource=api", "dashboardUrl": "https://mareaalcalina.com/dashboard" } } ``` Check `plan.limits.publishable` before calling publish, and compare current storefront / product counts against `plan.limits.{storefronts, products}` before bulk-creating to avoid the 207 round-trip. ## What this page does NOT cover * **Pricing.** Pricing, billing cycles, and promotional terms live at [mareaalcalina.com](https://mareaalcalina.com). The numbers above are the technical caps; what each plan costs is on the public pricing page. * **Plan sub-tiers on the wire.** Business and Agency have multiple internal sub-tiers (200 / 500 / 1,000 storefronts, monthly / yearly cadences, legacy variants). Agents see the public 4-value tier surface; the underlying numeric plan ID is not exposed. The true storefront ceiling for custom plans is in `planQuantity`. * **Cache TTLs.** `/v1/me` reads the user doc through a 30-second in-instance cache (BL-4). A plan change made through the dashboard becomes visible to the API within 30 seconds without any explicit invalidation. # Publishing a storefront Source: https://docs.mareaalcalina.com/concepts/publishing POST /v1/storefronts/:storefrontId/publish — the publish gates (402, 422, 451), the auto-version flow, and idempotent republish. # Publishing `POST /v1/storefronts/:storefrontId/publish` takes a draft storefront live. It is the only operation that exposes the storefront to the public internet — every other catalog mutation only changes the draft. Required scope: `storefront:publish` (held by user keys after verification; not held by developer keys, not held by restricted pre-verify user keys). ## Behavior The handler enforces the following gates in this order: | Order | Gate | On failure | | - | - | - | | 1 | Plan paywall | `402 plan_blocks_publish` if `plan == NO_ACTIVO` (pre-paywall state). FREE / BASIC / PRO / BUSINESS all OK. | | 2 | ToS gate | `451 tos_not_accepted` if `users/{uid}.tosAcceptedAt` is null — see [ToS jurisdiction](/concepts/tos-jurisdiction) | | 3 | Ownership pre-check | `404 storefront_not_found` (leak-less) if the storefront isn't owned by the caller's user | | 4 | Empty-storefront guard | `422 no_products` if the storefront has zero products | | 5 | Auto-version | If `versionId` is omitted, a fresh version snapshot is created atomically | | 6 | Publish transaction | Marks the version published; idempotent on republish of the same version (200 + same DTO) | The plan paywall and ToS gate are account-level checks that fire **before** any storefront read, so an unauthorized caller cannot probe whether a storefront id exists by status-code timing. The ownership pre-check runs **before** the empty-products check for the same reason: a wrong-user-key probe cannot distinguish "empty storefront I own" from "storefront I don't own". ## Request ```http theme={null} POST /v1/storefronts/stf_abc/publish HTTP/1.1 Authorization: Bearer mk_user_... Idempotency-Key: 2f1a8c4b-2e3a-4b9d-9f1a-8c4b2e3a4b9d Content-Type: application/json {} ``` Body is optional. Pass `{ "versionId": "ver_xxx" }` to publish a specific named version; omit for auto-version (the common case). Include `Idempotency-Key` if you want the call to be safe to retry — see [Safe mutations](/concepts/safe-mutations). ## Successful response (200) ```json theme={null} { "storefront": { "id": "stf_abc", "name": "Tacos La Marea", "published": true, "publishedDate": "2026-05-10T01:23:45Z", "_links": { "previewUrl": "https://marea.pro/preview/", "publicUrl": "https://marea.pro/tacos-la-marea", "editUrl": "https://mareaalcalina.com/dashboard/menu/stf_abc" } } } ``` `_links.publicUrl` is now non-null. Surface it to the user. The owner can change the link from the dashboard a limited number of times. Old URLs keep working and redirect to the current one, so read `_links.publicUrl` again when you need the latest value. ## Republishing Calling publish a second time on the same storefront: * If the version already published matches the request, the call is **idempotent**: the same 200 + DTO is returned. * If a new version is created (auto-version with new content), a fresh public snapshot is generated. This means an agent can call publish on every "save" without worrying about the user seeing a flicker — publish is cheap when nothing changed. ## Error responses ### 402 `plan_blocks_publish` — pre-paywall account ```json theme={null} { "error": { "type": "plan_limit", "code": "plan_blocks_publish", "message": "Your plan does not permit publishing. Upgrade to publish this storefront.", "recoverable": true, "upgrade": { "currentPlan": "free", "requiredPlan": "basic", "upgradeUrl": "https://mareaalcalina.com/menus/profile?changePlan=basic&frequency=monthly&planSource=api" } } } ``` Today only the `NO_ACTIVO` (pre-paywall) state hits this. Free, Basic, Pro, and Business all publish successfully. Surface `upgrade.upgradeUrl` as a CTA. Do **not** retry until the user upgrades. ### 422 `no_products` — empty storefront ```json theme={null} { "error": { "type": "invalid_request", "code": "no_products", "message": "Cannot publish an empty storefront. Add at least one product first.", "recoverable": true, "nextActions": [ { "label": "Add at least one product before publishing.", "method": "POST", "url": "/v1/storefronts/stf_abc/products" } ] } } ``` Add at least one product, then retry publish with the same `Idempotency-Key`. ### 451 `tos_not_accepted` — user hasn't accepted ToS ```json theme={null} { "error": { "type": "tos_not_accepted", "code": "tos_required", "message": "User must accept the Terms of Service before publishing.", "recoverable": true, "nextActions": [ { "label": "Accept Terms of Service", "method": "GET", "url": "https://mareaalcalina.com/terms?accept=true" } ] } } ``` The user must accept the ToS via the dashboard modal — the agent **cannot** bypass. Surface `nextActions[0].url` verbatim. Once accepted, retry publish with the same `Idempotency-Key`. See [ToS jurisdiction](/concepts/tos-jurisdiction). ### 404 — storefront not found OR cross-tenant access If your `mk_user_*` key doesn't own the storefront, you get `404 storefront_not_found` (silent denial — not 403). See [Storefronts](/concepts/storefronts). ## What NOT to do * **Don't auto-publish.** Publishing is destructive and user-visible — once it's live, the URL is shared and may be indexed. Always require explicit user confirmation. * **Don't retry 402 / 422 / 451** without surfacing `nextActions[]` to the user. Each is a `recoverable: true` error that needs user input, not a backoff. * **Don't auto-accept the ToS.** The 451 → modal flow is counsel-reviewed and intentional. ## Verification in code * `src/api/v1/storefronts.publish.ts` — the handler with the locked step order. * `src/utils/publish.utils.ts` — `runPublishTransaction`. * `src/models/plan-limits.ts` — `isPublishable()` (the 402 gate condition). # Rate limits and 429 handling Source: https://docs.mareaalcalina.com/concepts/rate-limits Per-key minute + day buckets. Stripe-compatible X-RateLimit-* headers. Read Retry-After and back off. # Rate limits Marea uses **per-key minute and day buckets** with Stripe-compatible headers. Counts increment **before** the handler runs, so 4xx and 5xx responses still count against your quota — that's deliberate, and it defends against spam-of-invalid-requests abuse. ## Headers on every response ```http theme={null} X-RateLimit-Limit: 60 ← rpm (requests-per-minute) for this key X-RateLimit-Remaining: 47 ← remaining in the current minute window X-RateLimit-Reset: 1714867260 ← epoch seconds when the minute rolls over ``` When you hit a limit, you also get: ```http theme={null} HTTP/1.1 429 Too Many Requests Retry-After: 23 ``` `Retry-After` is in seconds. For minute-bucket overflow it's seconds-until-the-next-minute (always ≤ 60). For day-bucket overflow it can be up to **86,400 seconds** (a full day). > [!NOTE] > > The headers report on the **minute bucket only** — there is no `X-RateLimit-Remaining-Day` header. Use `GET /v1/me`'s `rateLimit.remainingDay` for the day-bucket counter. ## Default budgets Read your live values from `GET /v1/me` (the `rateLimit` object). Values stored on the API key doc at issuance time: | Key prefix | Key type | `rpm` | `rpd` | Notes | | - | - | - | - | - | | `mk_user_*` | User scope | 60 | 10,000 | Primary issuance via `POST /v1/users` (bootstrap, in the `userKey` field). Additional per-user keys via `POST /v1/users/:userId/keys`. | | `mk_dev_*` | Developer scope | 60 | 50 (default) | The dev-key `rpd` is the **bootstrap-per-day ceiling** — see below. | > [!WARNING] > > **The developer key's `rpd` is intentionally tiny.** Developer keys exist to bootstrap accounts (`POST /v1/users`) and issue per-user keys (`POST /v1/users/:userId/keys`), not to drive sustained traffic. The `rpd: 50` default is the bootstrap-per-day cap (configurable at issuance time per the `IssueDeveloperKeyParams` contract). Once an account is bootstrapped, route all subsequent traffic through that account's `mk_user_*` key — that one gets the full 10,000/day budget. > > The middleware does not distinguish "this request is a bootstrap call" from "this request is something else" — it simply enforces whatever `rpd` is stored on the developer key. If you exhaust 50 requests on a dev key in a single day, you're locked out of that dev key for the rest of the UTC day, full stop. To check your remaining budget at any time, call `GET /v1/me`. The response includes: ```json theme={null} { "rateLimit": { "rpm": 60, "rpd": 50, "remainingMinute": 60, "remainingDay": 47 } } ``` > [!NOTE] > > **Header vs. body precision.** The exact `remainingMinute` value lives in the response headers (`X-RateLimit-Remaining`). The `/v1/me` body's `remainingMinute` is approximate — it's the value at response-assembly time, not at your next request. For backoff logic, trust the headers. ## 429 response shape ```json theme={null} { "error": { "type": "rate_limited", "code": "rate_limit_exceeded", "message": "Rate limit exceeded (rpm_exceeded). Retry after 23s.", "recoverable": true, "retryAfterMs": 23000, "nextActions": [ { "label": "Wait 23s and retry the same request.", "method": null, "url": null } ] } } ``` The `message` field tells you which bucket overflowed: * `message` contains `rpm_exceeded` → minute bucket. Wait `Retry-After` seconds (always ≤ 60), then retry. * `message` contains `rpd_exceeded` → day bucket. `Retry-After` is the seconds-remaining-in-the-day (up to 86,400). **Do not retry tight; wait the indicated time or escalate to the user.** The `retryAfterMs` field on the error body mirrors `Retry-After` in milliseconds. Both `recoverable: true` and `nextActions[0].label` indicate that the call is safe to repeat once the window opens. ## Recommended agent backoff Minute-bucket overflow: ``` attempt 1: hit 429, message contains "rpm_exceeded", Retry-After: 23 → sleep 23s, retry attempt 2: succeed (200) ``` Day-bucket overflow: ``` attempt 1: hit 429, message contains "rpd_exceeded", Retry-After: 41200 → surface to user: "Daily quota reached. Try tomorrow or upgrade." → DO NOT auto-retry ``` When using `Idempotency-Key`, **keep the same key across retries** — the server treats the eventual successful call as a replay-safe completion of the original request. See [Safe mutations](/concepts/safe-mutations). ## What counts against your quota Every authenticated request to a `/v1` endpoint — 200, 4xx, 5xx — counts. The increment happens **before** the handler runs, so a malformed body that the handler would have rejected with a 422 still consumes one minute-bucket slot and one day-bucket slot. Exceptions: * Unauthenticated requests (rejected at the apiKey middleware before rate-limit increments) do not count. * The health-check shortcut at `/healthz` does not pass through the rate-limit middleware. * If the rate-limit Firestore transaction itself fails (infrastructure error), the request is **failed open** — it proceeds without an increment and without a 429. A structured log entry is emitted so the 5xx-rate alert surfaces the underlying infra failure. ## Conventions Stripe-compatible headers and semantics — `X-RateLimit-*` plus `Retry-After`. The same backoff library you'd use for Stripe works here unchanged. Buckets are **per key, not per account**. If a single user has both `mk_user_keyA` and `mk_user_keyB`, each gets its own 60/10,000 budget. This is by design: a misbehaving integration on one key can't starve a well-behaved integration on another key for the same user. # Idempotency and safe mutations Source: https://docs.mareaalcalina.com/concepts/safe-mutations Stripe-style idempotency keys on every POST and PATCH. Replays return the original response; body mismatches return 409 idempotency_conflict. # Safe mutations Marea honors `Idempotency-Key` on every `POST` and `PATCH`. Replays of the **same key + same body** return the **same response** (status + body, including failures). This lets agents retry network errors without double-creating resources. ```http theme={null} POST /v1/users HTTP/1.1 Host: api.mareaalcalina.com Authorization: Bearer mk_dev_... Content-Type: application/json Idempotency-Key: 2f1a8c4b-2e3a-4b9d-9f1a-8c4b2e3a4b9d { "email": "owner@taqueria.example", "displayName": "La Taquería", "sourceAgent": "claude-code" } ``` ## Header contract | Property | Value | | - | - | | Header name | `Idempotency-Key` | | Length | 1–255 characters | | Character class | ASCII printable only (`0x20`–`0x7E`) | | Recommended format | UUID v4 | | Applies to | `POST` and `PATCH` | | Ignored on | `GET`, `OPTIONS`, `DELETE` | Invalid headers (too short, too long, or containing non-printable bytes) return `400 invalid_idempotency_key`. The regex is `^[\x20-\x7e]{1,255}$`. ## Match key A stored idempotency record is keyed on the triple `(keyId, method+path, Idempotency-Key)`. The body is hashed (canonical JSON, sorted keys, SHA-256 hex) and compared on every replay. * **Cross-key replays don't work.** Different API keys with the same `Idempotency-Key` are independent requests. * **Cross-endpoint replays don't work.** `POST /v1/storefronts` and `POST /v1/storefronts/:id/products` with the same `Idempotency-Key` are independent. ## Outcomes | Match status | What you get | When | | - | - | - | | `owned` | Handler runs; response is stored for future replays | First time the key is seen | | `replay` | Original response replayed verbatim (same status + body) | Same key + same body; original completed | | `in_flight` | `409 conflict` + `Retry-After: 1` (`recoverable: true`) | Same key + still processing | | `conflict` | `409 idempotency_conflict` (`recoverable: false`) | Same key + **different** body | | `oversize` | `410 idempotency_snapshot_unavailable` (rare) | Original response exceeded the 100 KB snapshot cap | ## Missing the header Sending `POST` / `PATCH` **without** `Idempotency-Key` is not an error. The request proceeds and Marea returns a `Marea-Recommendation: include-idempotency-key` response header to nudge you. Skipping the header is fine for one-shot calls; include it for any retry-prone integration. ## The four 409 / 410 error shapes ### `in_flight` — same key still processing ```json theme={null} { "error": { "type": "conflict", "code": "idempotency_in_flight", "message": "Another request with this Idempotency-Key is still being processed. Retry shortly.", "recoverable": true, "retryAfterMs": 1000 } } ``` Wait 1s and retry with the **same key**. Two concurrent calls on the same key are serialized server-side — only one wins `owned`; the other waits or replays. ### `conflict` — same key, different body ```json theme={null} { "error": { "type": "idempotency_conflict", "code": "idempotency_conflict", "message": "Idempotency-Key was used earlier with a different request body.", "recoverable": false, "nextActions": [ { "label": "Generate a new Idempotency-Key for this request.", "method": null, "url": null } ] } } ``` Generate a **fresh** key. Don't reuse it. The most common cause is an agent retrying with edits ("same call, but change the email") — that's a new request and needs a new key. ### `invalid_idempotency_key` — format error ```json theme={null} { "error": { "type": "invalid_request", "code": "invalid_idempotency_key", "message": "Idempotency-Key must be 1-255 ASCII printable chars.", "param": "Idempotency-Key", "recoverable": false } } ``` Fix the header. UUID v4 is the safe default. ### `idempotency_snapshot_unavailable` — oversize response ```json theme={null} { "error": { "type": "invalid_request", "code": "idempotency_snapshot_unavailable", "message": "The original response was too large to store. Retry without the Idempotency-Key.", "recoverable": false, "nextActions": [ { "label": "Reissue the request without the Idempotency-Key.", "method": null, "url": null } ] } } ``` Response snapshots are capped at **100 KB** (Firestore doc-size headroom). On the rare oversize response, the original is marked oversize and future replays return 410 — drop the header and reissue. ## What is stored The first successful response is persisted as `(keyId, method+path, Idempotency-Key) → { status, body }`. Failed responses are also stored — a replay of a failed call returns the same failure. The stored snapshot is held to back replays; there is no client-controlled TTL. ## Convention Stripe-style. If you already use a Stripe retry library that drives `Idempotency-Key`, it works on Marea unchanged. ## Verification in code * `src/api/middleware/idempotency.ts` — header parsing + replay vs. owned vs. conflict branching. * `src/api/services/apiIdempotency.service.ts` — `acquireOrReplay`, `complete`, `fail`, snapshot cap (`SNAPSHOT_MAX_BYTES`). # Storefronts Source: https://docs.mareaalcalina.com/concepts/storefronts What a storefront is in Marea, how it is created and updated, the previewUrl / publicUrl split, and cross-tenant access rules. # Storefronts A **storefront** is the unit of catalog ownership in Marea. One user owns one or more storefronts; each has a name, a category list, products, branding, contact info, business hours, delivery settings, and a publishable hosted URL. Under the hood a storefront is the `users/{ownerUid}/menus/{menuId}` document; the API surface presents it with the typed id `stf_`. Internal ids never leak across the API — every handler strips the `stf_` prefix at the top before any Firestore access. | Concept | API surface | Notes | | - | - | - | | Storefront id | `stf_` | Opaque, agent-stable | | Product id | `prd_` | Opaque, agent-stable | | Preview link | `_links.previewUrl` | 24h token, anyone with the link can open | | Public link | `_links.publicUrl` | `null` until publish; the owner can change it, old URLs redirect | | Edit link | `_links.editUrl` | Dashboard deep link for the owner | ## Lifecycle ``` created (draft) ←─ POST /v1/storefronts │ ├─ previewUrl available immediately (24h-token preview) │ └─ POST /v1/storefronts/:storefrontId/publish ──▶ public live URL │ ├─ 402 if pre-paywall account ├─ 422 if 0 products └─ 451 if ToS not accepted ``` A storefront is created in **draft** state. Anyone with the `previewUrl` can open it; the URL token expires after 24 hours. To make it public, call `POST /v1/storefronts/:storefrontId/publish` (see [Publishing](/concepts/publishing)). ## Creating a storefront `POST /v1/storefronts` accepts a `StorefrontManifest`. Required scope: `catalog:write` (user keys only). ```http theme={null} POST /v1/storefronts HTTP/1.1 Authorization: Bearer mk_user_... Idempotency-Key: 2f1a8c4b-2e3a-4b9d-9f1a-8c4b2e3a4b9d Content-Type: application/json { "name": "Tacos La Marea", "businessType": "restaurante", "language": "es", "currency": "MXN", "categories": [ { "title": "Tacos", "description": "Estilo tradicional" }, { "title": "Bebidas", "description": null } ], "products": [ { "title": "Taco al pastor", "price": 25, "imageUrl": "https://...", "category": "Tacos" }, { "title": "Coca Cola", "price": 30, "imageUrl": null, "category": "Bebidas" } ], "schedule": [{ "day": "mon", "open": "08:00", "close": "22:00" }] } ``` * `products` is optional in the manifest. To batch-add more after creation, use the product endpoints. * If the manifest contains more products than the plan allows, the response is **`207 Multi-Status`** with the storefront created up to the plan cap plus an `errors` array describing the over-cap items. See [Plan limits](/concepts/plan-limits). * Idempotency: send `Idempotency-Key` to make retries safe. See [Safe mutations](/concepts/safe-mutations). Response (`StorefrontDto`): ```json theme={null} { "storefront": { "id": "stf_abc123", "name": "Tacos La Marea", "language": "es", "currency": "MXN", "published": false, "categories": [{ "title": "Tacos", "description": "Estilo tradicional" }], "products": [{ "id": "prd_xyz", "title": "Taco al pastor", "price": 25 }], "_links": { "previewUrl": "https://marea.pro/preview/", "publicUrl": null, "editUrl": "https://mareaalcalina.com/dashboard/menu/stf_abc123" } } } ``` `_links.publicUrl` is `null` until publish — never expose the preview URL as the "public" URL. ## Updating a storefront `PATCH /v1/storefronts/:storefrontId` is a **partial** update. Required scope: `catalog:write`. Three merge rules: | Field shape | Behavior | | - | - | | Nested object | Deep-merge. `{ "delivery": { "fee": 50 } }` only changes `delivery.fee`. | | Array | Full-replace. `{ "categories": [...] }` overwrites the whole array. | | Explicit `null` | Clears the field. `{ "delivery": null }` removes the delivery config. | Returns the updated `StorefrontDto` (`200 OK`). Republishing is a separate call — `PATCH` only mutates the draft. ## Products Products live on the storefront. Use `POST /v1/storefronts/:storefrontId/products` to create and `PATCH /v1/storefronts/:storefrontId/products/:productId` to update. Both require `catalog:write` and accept `Idempotency-Key`. The per-plan product ceiling is enforced on every create; over-cap creates return `402 plan_limit` with `upgrade.upgradeUrl` populated. ## Cross-tenant access is silently denied If your `mk_user_*` key tries to access a storefront owned by a different user, the API returns **`404 storefront_not_found`** — not `403`. The 404 also fires before the empty-storefront check on publish to avoid leaking existence by status-code timing. Common cause when you get a 404 on a stable `stf_` id you used moments ago: you're sending the wrong user key (e.g. dev environment vs. prod). Confirm with `GET /v1/me` which user the key acts as. ## What a storefront does NOT include * A storefront is **not** a channel. Where customers reach you (WhatsApp, web, in-person) is per-storefront configuration; the channel mix is not surfaced as a top-level field today. * A storefront is **not** an order ledger. Orders are a separate resource — subscribe to `order.created`, `order.status_updated`, `order.paid` via [Webhook endpoints](/concepts/webhooks). * Storefronts do not own subscriptions. Billing/plan lives on the owning user (see `/v1/me`). ## Limits See [Plan limits](/concepts/plan-limits) for per-plan storefront-count and product-count ceilings. The product cap is per-storefront, not per-account. ## Verification in code * `src/api/v1/storefronts.create.ts` * `src/api/v1/storefronts.update.ts` * `src/api/v1/storefronts.publish.ts` * `src/api/services/translation/storefront-id.ts` (`stf_` ↔ menuId translation) * `src/api/services/shape/storefront.shape.ts` (`toStorefrontDto`) # ToS, jurisdiction, and the 451 response Source: https://docs.mareaalcalina.com/concepts/tos-jurisdiction Terms of Service acceptance, Mexican-law jurisdiction, the 90-day no-ToS cleanup, and the 451 tos_not_accepted error shape. # Terms of Service and jurisdiction Marea Alcalina is incorporated under **Mexican law** (LFPDPPP — *Ley Federal de Protección de Datos Personales en Posesión de los Particulares*). All accounts agree to the ToS at sign-up; agent-bootstrapped accounts inherit a deferred-acceptance flow described below. This page documents: 1. How ToS acceptance is tracked. 2. The `451 tos_not_accepted` error envelope. 3. The 90-day no-ToS cleanup (involuntary deletion). 4. Jurisdiction. For the related Mexican data-rights flow (Acceso, Rectificación, Cancelación, Oposición), see [ARCO procedures](/concepts/arco-procedures). ## How acceptance is tracked Each user document has a `tosAcceptedAt` timestamp: | State | `tosAcceptedAt` value | Surface in `GET /v1/me` | | - | - | - | | Not yet accepted | `null` | `tosAcceptedAt: null` | | Accepted (any path) | ISO-8601 timestamp string | `tosAcceptedAt: "2026-04-15T10:00:00Z"` | Dashboard sign-ups accept ToS at the same step that creates the account. **Agent-bootstrapped accounts** (`POST /v1/users`) are created with `tosAcceptedAt: null` and `agentBootstrapped: true` — the user is expected to accept ToS later via the dashboard modal during their first interactive visit. ## The 90-day cleanup A scheduled job runs daily at 03:00 America/Mexico\_City and applies four sweeps for agent-bootstrapped accounts: | Sweep | Trigger | Action | | - | - | - | | Unverified 30d | `verificationStatus: pending` + `createdAt < now-30d` | Hard-delete (`reason: 30d_unverified`) | | Day 7 reminder | Verified, `tosAcceptedAt: null`, verified 7+ days ago | Email reminder #1 | | Day 14 reminder | Same, 14+ days, reminder count = 1 | Email reminder #2 | | Day 60 pre-deletion warning | Same, 60+ days, no warning sent yet (feature-flag gated) | Email warning #3 | | No-ToS 90d | Verified, `tosAcceptedAt: null`, verified 90+ days ago | Hard-delete (`reason: 90d_no_tos`) | The 90d cleanup is governed by Mexican counsel guidance — an agent that creates an account on behalf of a user does not have authority to bind that user to the ToS, so the user must accept (or implicitly reject by not visiting) within a bounded window. ## The 451 error envelope `451 tos_not_accepted` is the error type that ToS-gated mutations return when the calling user has not accepted the ToS. The `POST /v1/storefronts/:storefrontId/publish` endpoint enforces this gate today (right after the plan paywall, before ownership / empty-storefront checks — see [Publishing](/concepts/publishing)). Other public-facing mutations will adopt the same gate as they ship. ```json theme={null} { "error": { "type": "tos_not_accepted", "code": "tos_required", "message": "User must accept the Terms of Service before this operation.", "doc": "https://docs.mareaalcalina.com/concepts/tos-jurisdiction", "param": null, "recoverable": true, "retryAfterMs": null, "nextActions": [ { "label": "Open the Marea dashboard and accept the Terms of Service.", "method": "GET", "url": "https://mareaalcalina.com/dashboard" } ], "upgrade": null } } ``` Agent contract for `451 tos_not_accepted`: * **Surface `nextActions[0].url` verbatim.** The user must accept the ToS through the dashboard modal — the agent **cannot** accept on the user's behalf. * Treat it as `recoverable: true`. After the user accepts, the next call (same `Idempotency-Key`) succeeds. * Do **not** retry without surfacing the action. This is the canonical agent-failure-mode for this error. The enum value `tos_not_accepted` is locked in the error envelope (`src/api/contracts/error.zod.ts`). The publish endpoint enforces the gate today via `assertTosAccepted(ctx)` in `src/api/v1/storefronts.publish.ts`; a `users/{uid}.tosAcceptedAt` of `null` or absent fires the 451. ## Jurisdiction | Property | Value | | - | - | | Governing law | Mexican federal law | | Privacy framework | LFPDPPP (Articles 16–18 → user rights; see [ARCO procedures](/concepts/arco-procedures)) | | Brazilian residual | LGPD disclosures apply to Brazilian residents | | Disputes | Courts of Mexico City | The current production ToS is available at the dashboard sign-up flow. Modal copy is counsel-reviewed; do not paraphrase it here — the dashboard URL is the source of truth. ## What the agent surfaces to the user | Situation | Surface | | - | - | | Bootstrap completed | "Your account is created. Open the dashboard within 90 days to accept the Terms of Service." | | `451 tos_not_accepted` | Verbatim `nextActions[0].label` + click-through to `nextActions[0].url` | | Day-7 / Day-14 / Day-60 reminder email | The user receives these directly from Marea — agent doesn't surface anything | | 90d cleanup fired | Agent receives a `user.cancelled` webhook with `reason: 90d_no_tos` (see [Webhooks](/concepts/webhooks)) | ## Verification in code * `src/api/contracts/error.zod.ts` — locked `tos_not_accepted` enum value. * `src/api/scheduled/CleanupUnverifiedAccounts.ts` — 30d/60d/90d sweeps. * `src/api/constants/cleanup.constants.ts` — `TOS_DEADLINE_DAYS`, `TOS_REMINDER_DAYS`, `TOS_PREDELETION_WARNING_DAY`. * `src/api/services/account-delete.service.ts` — `hardDeleteUserAccount` (reason: `90d_no_tos`). # Verification flow Source: https://docs.mareaalcalina.com/concepts/verification-flow POST /v1/users returns a restricted key + emails a 6-digit code; POST /v1/users/:userId/verify upgrades the key to full scope. Plain code by design. # Verification flow `POST /v1/users` (bootstrap) creates the user, returns a **restricted** `mk_user_*` key, and emails the user a **6-digit code**. The agent then submits the code to `POST /v1/users/:userId/verify` — the **same key** is upgraded in place to full scope. No key rotation; store the value once. ``` Agent (dev key) User │ │ │ POST /v1/users │ ├─────────────────────────▶ │ │ { email, displayName, │ │ sourceAgent: "..." } │ │ │ │ 201 + restricted user key │ ◀─────────────────────────┤ │ │ + verificationExpiresAt │ │ │ │ email with 6-digit code (15 min TTL) │ │ │ │ reads code aloud OR │ │ agent reads it from Gmail MCP │ │ │ POST /v1/users/:userId/verify │ ├─────────────────────────▶ │ │ { code: "123456" } │ │ │ │ 200 { verificationStatus: │ ◀─────────────────────────┤ │ │ "verified" } │ │ │ │ same key — now has │ │ catalog:write + storefront:publish │ ``` ## Step 1 — `POST /v1/users` Required scope: `developer:bootstrap`. Returns `201 Created` (or `207 Multi-Status` if a starter manifest had over-cap products): ```http theme={null} POST /v1/users HTTP/1.1 Authorization: Bearer mk_dev_... Content-Type: application/json Idempotency-Key: 2f1a8c4b-2e3a-4b9d-9f1a-8c4b2e3a4b9d { "email": "owner@taqueria.example", "displayName": "La Taquería", "country": "MX", "language": "es", "currency": "MXN", "businessType": "restaurante", "sourceAgent": "claude-code", "initialStorefront": { "name": "Tacos La Marea", "products": [ ... ] } } ``` `sourceAgent` is required (1–64 chars, `[A-Za-z0-9 _.-]+` only). It is embedded in the verification email so the user can see which agent triggered the account. Response: ```json theme={null} { "userId": "usr_...", "storefrontId": "stf_...", "userKey": "mk_user_...", "verificationStatus": "pending", "verificationExpiresAt": "2026-05-10T20:15:00Z", "verificationDeliveryHint": "email-only", "appliedDefaults": { "language": "es", "currency": "MXN", "country": "MX", "businessType": "restaurante" }, "idempotent": false } ``` **Store `userKey` immediately.** It is shown once. It starts with the restricted scope set: | Scope | Purpose | | - | - | | `catalog:read` | Inspect the draft storefront | | `me:verify` | Submit the 6-digit code | | `me:resendVerification` | Request a fresh code if the email was lost | Until verify, the restricted key **cannot** create/update catalog data or publish. ## Step 2 — submit the code ```http theme={null} POST /v1/users/:userId/verify HTTP/1.1 Authorization: Bearer mk_user_... Content-Type: application/json { "code": "123456" } ``` Required scope: `me:verify`. The `:userId` path param **must** match the key's owner — cross-tenant or wrong-id attempts return `404 user_not_found` (leak-less, never 403). On success (`200`): ```json theme={null} { "userId": "usr_...", "verificationStatus": "verified" } ``` The same key's scope set is upgraded in place to `catalog:read`, `catalog:write`, `storefront:publish`. Cache propagation is bounded by the 30s positive auth cache; the planLimits cache for the user is invalidated immediately so `GET /v1/me` reflects `verified` on the next call. ### Code rules | Property | Value | | - | - | | Format | 6 decimal digits (`^\d{6}$`) | | TTL | 15 minutes from issuance | | Max attempts | 3 wrong attempts → `429 too_many_attempts` (must resend) | | Storage | Stored **in plain text** (intentional — see below) | | Source of randomness | `crypto.randomInt` (CSPRNG) | Plain-text storage is **intentional**. The user-reads-aloud flow requires the agent to be able to *say* the code on screen. A bcrypt-hashed code would only support submit-then-check, not the agentic read-aloud variant. Defense-in-depth lives elsewhere: 3-attempts lockout, 15-min TTL, per-user resend rate-limit, and the leak-less 404 on cross-tenant verify. ### Verify error shapes | Status | `error.code` | Meaning | Agent action | | - | - | - | - | | `400` | `code_invalid` | The submitted code doesn't match | Re-prompt the user; on 3rd wrong attempt, resend | | `404` | `code_not_found` | No active code for this user (never sent, or fully consumed) | Call `POST /v1/users/:userId/resendVerification` | | `404` | `user_not_found` | `:userId` doesn't match the key's owner (silent denial) | Use the correct user key | | `410` | `code_expired` | Code older than 15 min | Resend | | `429` | `too_many_attempts` | 3 wrong attempts in this verification window | Resend | ## Step 3 — resend (when needed) ```http theme={null} POST /v1/users/:userId/resendVerification HTTP/1.1 Authorization: Bearer mk_user_... ``` Required scope: `me:resendVerification`. Per-user rate-limited at **3 / hour** and **5 / day**. Overwrites the existing code doc — the old code is invalidated on resend. Returns: ```json theme={null} { "verificationStatus": "pending", "verificationExpiresAt": "2026-05-10T20:30:00Z" } ``` | Status | `error.code` | Meaning | | - | - | - | | `429` | `resend_hour_limit` | 3 resends used in the current hour | | `429` | `resend_day_limit` | 5 resends used today | ## Variants of step 2 **A — User reads the code aloud.** Default. Agent says "I sent you a 6-digit code; tell me the number." User reads from email. Agent submits. **B — Silent verification via Gmail MCP.** If the user's mailbox is connected to the agent (e.g. Gmail MCP), the agent reads the verification email programmatically, extracts the 6-digit code, and submits — no manual step. The API contract is identical; only the source of the code differs. ## Account-cancellation hatch Every bootstrap email also embeds a single-use **cancel link** (24h TTL) pointing at `https://api.mareaalcalina.com/public/v1/bootstrap/:previewToken`. The user opens it, confirms once (GET → POST, two-step to defeat email-preview crawlers), and the account is hard-deleted. This is the LFPDPPP-required cancellation hatch for accounts created by an agent (see [ARCO procedures](/concepts/arco-procedures)). ## Verification in code * `src/api/v1/users.bootstrap.ts` * `src/api/v1/users.verify.ts` * `src/api/v1/users.resendVerification.ts` * `src/api/services/verification.service.ts` — 3-attempt lockout + scope upgrade. * `src/services/verification/sendVerificationCodeCore.ts` — code generation + email delivery (15-min API TTL). * `src/api/public/bootstrap.cancel.ts` — emergency cancel endpoint. # Versioning Source: https://docs.mareaalcalina.com/concepts/versioning How Marea versions its API: stable URL prefix, additive evolution, the Sunset header, and webhook payload pinning. # Versioning Marea's public API is on **v1**. This page documents what counts as a breaking change, how the API evolves additively, and where versions surface to clients (URL, headers, webhook payloads). ## URL versioning | Surface | Current value | Stability | | - | - | - | | URL prefix | `/v1/*` | Stable. Will remain mounted at least 12 months after v2 GA. | | OpenAPI spec URL | `https://api.mareaalcalina.com/v1/openapi.json` | Stable. Mintlify pulls this for the API reference tab. | | Public hosted-storefront base | `https://marea.pro/` | Stable. | A breaking change ships under a new prefix (`/v2/*`). v1 remains live during the deprecation window. There is no `Marea-Api-Version` header today — version is in the URL. ## What counts as additive (non-breaking) The following changes can land on `/v1/*` without notice: * Adding new endpoints. * Adding new fields to a response body. * Adding new optional fields to a request body. * Adding new values to an open-ended enum (only if the field is documented as open-ended). * Adding new `error.code` values within an existing `error.type`. * Adding new headers (request or response). * Tightening internal implementation (cache TTLs, retry backoff, etc.) when the external behavior is unchanged. Clients should be **forward-compatible** with all of the above. In particular: * Treat unknown fields in responses as ignorable. * Branch on `error.type` first (closed 10-value enum); fall back to `error.code` when finer-grained. * Do not parse `error.message`: its wording can change and it may be localized in a future version. ## What counts as breaking The following changes never ship to `/v1/*`; they require a new prefix: * Removing or renaming a field, header, or endpoint. * Changing a field's type (e.g. string → number). * Tightening a response (e.g. an optional field becoming required, a nullable field becoming non-null). * Changing the meaning of an enum value (or removing one). * Changing the 10-value `error.type` enum. * Changing the `Idempotency-Key` contract (header name, length, character class, snapshot cap). ## Deprecation signaling When a v1 endpoint or field is scheduled for sunset, two signals surface: 1. The **`Sunset` HTTP response header** carries an RFC 8594 date for the planned removal: ```http theme={null} Sunset: Wed, 30 Nov 2027 00:00:00 GMT ``` `Sunset` is in the CORS expose-headers list — browser clients can read it. 2. The **changelog** entry under the [Releases tab](/changelog) documents the rationale and the migration path. Clients should monitor `Sunset` headers in production and surface them to operators. There is no `Deprecation` header in v1 today; rely on `Sunset` + the changelog. ## Webhook payload versioning Every webhook envelope carries `apiVersion` (date-based). Receivers can lock to a specific schema even as new versions roll out: | Webhook event family | Current `apiVersion` | Where it appears | | - | - | - | | `user.*` and `order.*` | `2026-05-12` | `apiVersion` field on every envelope | Receivers can inspect `apiVersion` and branch payload handling on it. See [Webhook endpoints](/concepts/webhooks) for the locked envelope shape. ## Surfaces an agent should know | You depend on | How to verify | | - | - | | The `error.type` enum | 10 locked values. See [Errors](/concepts/errors). Branch on this, not `code` or `message`. | | The scope set | Defined in `src/api/services/scope.constants.ts`. New scopes are additive; existing scopes are stable. | | The `Idempotency-Key` shape | 1–255 ASCII printable. Locked. See [Safe mutations](/concepts/safe-mutations). | | The `stf_` / `prd_` id format | Locked. Internal ids never appear on the wire. | ## Verification in code * `src/api/server.ts` — `/v1/*` mount point. * `src/api/middleware/cors.ts` — `Sunset` in the expose-headers list. * `src/api/types/webhook.types.ts` — `PAGE_WEBHOOK_API_VERSION` constant. * `src/api/contracts/error.zod.ts` — the locked 10-value `type` enum. # Webhook endpoints Source: https://docs.mareaalcalina.com/concepts/webhooks Real-time event delivery via Stripe-style endpoints. Each endpoint has its own URL, raw signing secret, and event subscription list. HMAC-SHA256 signed payloads, 3 retries, 5-minute replay window. # Webhook endpoints Marea POSTs JSON events to **webhook endpoints** you register. An endpoint is a first-class object — it has its own URL, its own signing secret, its own set of subscribed events, and its own delivery log. You can register up to **16 endpoints per account** (e.g. one for production, one for staging, one for an internal audit log). Stripe-style model: events fan out to every enabled endpoint whose `subscribedEvents` list contains the event type. Adding a new destination is one POST; you do not need a new developer key. ## Available events | Event type | When it fires | | - | - | | `order.created` | A new order is placed on a storefront you bootstrapped | | `order.status_updated` | An order's `orderStatus` or `customStatus` changes | | `order.paid` | An order is paid successfully | | `user.verified` | A user you bootstrapped verifies their email after sign-up | | `user.cancelled` | A user you bootstrapped cancels OR is deleted by Marea (the `reason` field tells you which) | > [!NOTE] > > **Where order events come from.** A single developer endpoint receives `order.*` events for every storefront your key bootstrapped — you do not register one endpoint per merchant. If you revoke the key that bootstrapped a given user, their order events stop flowing to your endpoint automatically. ## Create an endpoint ```bash theme={null} curl -X POST https://api.mareaalcalina.com/v1/webhook_endpoints \ -H "Authorization: Bearer mk_dev_xxxxxxxxxxxxxxxx" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-server.com/marea-webhook", "description": "production", "enabled": true, "subscribedEvents": ["user.verified", "user.cancelled", "order.paid"] }' ``` Response (`201 Created`): ```json theme={null} { "endpointId": "mk_we_a1b2c3d4e5f60789", "scope": "developer", "url": "https://your-server.com/marea-webhook", "description": "production", "enabled": true, "subscribedEvents": ["user.verified", "user.cancelled", "order.paid"], "signingSecret": "8f3e0c9a7b4d2f1e6a5c8d9f0e3b7a4c8f5d2e1a6b9c0f3e8d4a7c2b5f1e9a0c", "signingSecretVersion": 1, "createdAt": "2026-05-12T19:00:00.000Z", "updatedAt": "2026-05-12T19:00:00.000Z", "lastDeliveryAt": null, "lastDeliveryStatus": null, "consecutiveFailures": 0 } ``` > [!WARNING] > > **The `signingSecret` is returned exactly once.** Store it now in your secret manager. If you lose it, [rotate the secret](#rotate-the-signing-secret) — the old secret stops working immediately (no overlap window in v1). Required scope: `developer:webhooks` (added to new keys automatically) or `developer:bootstrap` (existing keys keep working). ## List, update, delete ```bash theme={null} # List curl https://api.mareaalcalina.com/v1/webhook_endpoints \ -H "Authorization: Bearer mk_dev_xxxxxxxxxxxxxxxx" # Get one curl https://api.mareaalcalina.com/v1/webhook_endpoints/mk_we_a1b2c3d4e5f60789 \ -H "Authorization: Bearer mk_dev_xxxxxxxxxxxxxxxx" # Update (PATCH-style — only the fields you send are modified) curl -X POST https://api.mareaalcalina.com/v1/webhook_endpoints/mk_we_a1b2c3d4e5f60789 \ -H "Authorization: Bearer mk_dev_xxxxxxxxxxxxxxxx" \ -H "Content-Type: application/json" \ -d '{ "subscribedEvents": ["order.paid"] }' # Delete (permanent — see "Pause an endpoint" below if you just want to stop deliveries temporarily) curl -X DELETE https://api.mareaalcalina.com/v1/webhook_endpoints/mk_we_a1b2c3d4e5f60789 \ -H "Authorization: Bearer mk_dev_xxxxxxxxxxxxxxxx" ``` ### Pause an endpoint To stop deliveries without losing the URL, signing secret, or subscribed events, set `enabled: false`. Marea filters disabled endpoints out of fan-out before any HTTP attempt — zero retries, zero delivery rows. Flip it back when your receiver is ready: ```bash theme={null} # Pause curl -X POST https://api.mareaalcalina.com/v1/webhook_endpoints/mk_we_a1b2c3d4e5f60789 \ -H "Authorization: Bearer mk_dev_xxxxxxxxxxxxxxxx" \ -H "Content-Type: application/json" \ -d '{ "enabled": false }' # Resume curl -X POST https://api.mareaalcalina.com/v1/webhook_endpoints/mk_we_a1b2c3d4e5f60789 \ -H "Authorization: Bearer mk_dev_xxxxxxxxxxxxxxxx" \ -H "Content-Type: application/json" \ -d '{ "enabled": true }' ``` The same lever is one click away in the dashboard at `/developers/webhooks` (each row has a Pause / Resume button). Use it during deploys, receiver outages, or signing-secret swaps. ### URL validation URLs are rejected at registration time when: * the scheme is not `https:` (HTTP is never accepted) * the length exceeds 2048 characters * the hostname is `localhost`, `0.0.0.0`, `metadata.google.internal`, anywhere in `127.0.0.0/8`, `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `169.254.0.0/16`, IPv6 ULA (`fc00::/7`), IPv6 link-local (`fe80::/10`), or any hostname ending in `.internal` / `.local` The same validator runs in the dashboard, the REST endpoint, and the per-store integrations panel. Operate your receiver on a public-DNS HTTPS host you control. ## Event envelope Every webhook is a `POST` with `Content-Type: application/json`. The body is the same envelope shape across all event types: ```json theme={null} { "type": "user.verified", "eventId": "5c7a4e1b-9d3f-4a82-b1c5-7e6f0a3b8d2c", "timestamp": "2026-05-12T19:42:11.823Z", "apiVersion": "2026-05-12", "data": { "userId": "QqV9pK3nL...", "developerKeyId": "kid_abc123", "verifiedAt": "2026-05-12T19:42:11.823Z" } } ``` `eventId` is a UUID v4 — use it as the idempotency key on your receiver. Marea may retry; processing the same `eventId` more than once must be a no-op on your side. ### Payload `data` shapes #### `user.verified` ```json theme={null} { "userId": "QqV9pK3nL...", "developerKeyId": "kid_abc123", "verifiedAt": "2026-05-12T19:42:11.823Z" } ``` #### `user.cancelled` ```json theme={null} { "userId": "QqV9pK3nL...", "developerKeyId": "kid_abc123", "cancelledAt": "2026-05-12T22:03:45.117Z", "reason": "user_clicked_cancel" } ``` Cancellation reasons (5-value enum): | `reason` | Meaning | | - | - | | `user_clicked_cancel` | User explicitly cancelled their account from the dashboard | | `squatting_defense` | An unverified bootstrap account was cleaned up so a real user could sign up with the same email | | `30d_unverified` | Bootstrapped account never verified their email; cleaned up after 30 days | | `90d_no_tos` | Verified user never accepted updated Terms of Service after 90 days; cleaned up | | `key_revoked` | Developer key that bootstrapped the user was revoked; the user was cleaned up as part of revocation | #### `order.created` / `order.status_updated` / `order.paid` `order.created` carries the full order payload (items, pricing, customer, delivery, payment method): ```json theme={null} { "type": "order.created", "eventId": "8f7c6d5e-1234-5678-90ab-cdef12345678", "timestamp": "2026-05-13T20:35:22.123Z", "apiVersion": "2026-05-12", "data": { "orderId": "order_abc123", "publicOrderId": 1042, "userId": "user_uid_lupita", "menuId": "menu_taqueria_main", "orderStatus": "pending", "customStatus": { "id": "received", "label": "Recibido" }, "totalPrice": 285.50, "subtotalPrice": 250.00, "deliveryPrice": 35.50, "currency": "MXN", "items": [ { "title": "Taco al Pastor", "amount": 5, "price": 25.00 } ], "customer": { "name": "Juan Pérez", "phone": "+525512345678" }, "paymentMethod": { "name": "Stripe" }, "paymentStatus": "completed", "createdAt": "2026-05-13T20:35:18.456Z" } } ``` `order.status_updated` is a slim payload (`previousState` → `newState` only) — receivers cache `order.created` and merge by `orderId`. `order.paid` is shaped like `order.created` plus `data.paymentMethod.id` and `data.paidAt`. Test fires from the dashboard add `__test: true` to the envelope. ## Headers Marea sends | Header | Meaning | | - | - | | `X-Marea-Signature` | `t=,v1=` — verify before trusting the body | | `X-Marea-Event-Type` | Same as `data.type` | | `X-Marea-Event-Id` | Same as envelope's `eventId` | | `X-Marea-Endpoint-Id` | The endpoint that triggered this delivery (useful when one receiver multiplexes multiple endpoints) | | `X-Marea-Signing-Version` | Endpoint's `signingSecretVersion`; bumps on every rotate. Useful for detecting in-flight rotation. | | `X-Marea-Source` | `developer` for `user.*` events on accounts you bootstrapped; `merchant` for `order.*` events from those accounts' storefronts | | `User-Agent` | `marea-webhook/1.0` | ## Verify signatures Every webhook is signed with HMAC-SHA256. The signed string is `"."`; the result is hex-encoded in the `v1=` field. 1. Parse `t=` and `v1=` from `X-Marea-Signature` 2. Reject if `|now - t| > 300` (5-minute replay window) 3. Compute `HMAC-SHA256(signingSecret, ".")` and hex-encode 4. Compare against `v1` using a constant-time function 5. On match: trust the payload. On mismatch: respond `401`. The `signingSecret` is the raw 64-char hex string returned at create/rotate time — no further derivation needed. Ready-to-paste verifiers in JavaScript and Python live in [Webhook receiver helpers](/api/webhooks/receiver-helpers). > [!WARNING] > > Always verify against the **raw request body bytes**, not a JSON-parsed and re-stringified version. Whitespace differences will break the signature match. ## Rotate the signing secret ```bash theme={null} curl -X POST https://api.mareaalcalina.com/v1/webhook_endpoints/mk_we_a1b2c3d4e5f60789/rotate-secret \ -H "Authorization: Bearer mk_dev_xxxxxxxxxxxxxxxx" ``` Response includes the new secret. `signingSecretVersion` bumps by 1; the old secret stops working immediately. Coordinate the rotation with your receiver — there is no overlap window in v1. ## Retry behavior Marea expects a `2xx` response from your endpoint within **5 seconds**. Anything else (non-2xx, timeout, connection error) triggers the retry path: | Attempt | Delay from first dispatch | | - | - | | 1 | Immediate | | 2 | +30 seconds | | 3 | +5 minutes | After attempt 3 fails, the delivery row is marked `max_attempts_reached`. For `user.*` events specifically, we also send a delivery-failure email to the developer who owns the endpoint so a misconfigured receiver doesn't silently lose lifecycle events. You can inspect recent deliveries in the dashboard at `/developers/webhooks/{endpointId}` (last 50 per endpoint, 30-day retention). There is no automatic replay endpoint. If you need bulletproof delivery, queue events on your end so a transient receiver outage doesn't lose them. ## Receiver implementation tips * **Respond 200 immediately**, then process asynchronously. Marea's 5-second timeout is tight. * **Idempotency**: use `eventId` from the envelope as your dedupe key. Retries are rare but possible. * **Constant-time signature comparison**: use `crypto.timingSafeEqual` (Node) or `hmac.compare_digest` (Python). Never `===` on HMAC. * **Multiplex one server across multiple endpoints**: the `X-Marea-Endpoint-Id` header tells you which endpoint a delivery came from. * **Test with `webhook.site`** while wiring up: register a test endpoint pointed at your unique `webhook.site` URL, fire test events from the dashboard, then move the URL to your real receiver. ## Limitations and roadmap * **Hard cap of 16 endpoints per account.** We'll raise it if real-world usage justifies. * **No overlap window on secret rotation.** To roll a secret without dropping events, create a second endpoint with the same `subscribedEvents`, point your receiver at both for a brief cutover, then pause and delete the old one. * **No event-replay endpoint.** Once the 3 retries fail, the event is gone — queue events on your side if you need bulletproof delivery. For receiver-side helpers (signature verification code in JS + Python), see [Webhook receiver helpers](/api/webhooks/receiver-helpers). # Cloud functions AGENTS Source: https://docs.mareaalcalina.com/coordination/cloud-functions-AGENTS # DRAFT — `marea-alcalina-cloud-functions/AGENTS.md` > **Coordinated PR target** (BL-DOC-5): Agent A owns `marea-alcalina-cloud-functions/`. PRD-12 (this repo) is responsible for drafting the engineer-side AGENTS.md content; Agent A reviews + commits it to the cloud-functions repo. Do NOT directly write into the cloud-functions repo from here. > > Once Agent A merges this draft to `marea-alcalina-cloud-functions/AGENTS.md`, delete this file from `marea-alcalina-docs/coordination/`. *** # AGENTS.md — Marea Cloud Functions ## What this repo is Firebase Cloud Functions backing Marea Alcalina (catalog + orders + WhatsApp + email + payments). Public REST API at `api.mareaalcalina.com/v1/*` (PRD-1+). ## Architecture * Express + middleware chain (PRD-1 §10.x — 12 middleware in fixed order). * Firestore for data; Cloud Tasks for webhook delivery. * Two-tier API keys: `mk_dev_*` (developer; can bootstrap) + `mk_user_*` (per-user; cannot bootstrap) — PRD-1 + PRD-6. ## Repo conventions * All v1 endpoints in `src/api/v1/`. * Refactored cores in `src/api/services/` (PRD-2 + PRD-3). * Middleware in `src/api/middleware/`. * Zod schemas drive request validation AND OpenAPI generation (PRD-1 §10.3 via `@asteasolutions/zod-to-openapi`). * NEVER scan full Firestore collections — Firestore reads cost money. Always use targeted queries (see `feedback_firestore_reads.md` in user memory). * NEVER invent MRR / pricing / plan facts — pull from Stripe API or `plan-limits.shared.ts` only (see `feedback_no_invent_match_stripe.md`). ## Where to find specs * PRDs: `Strategic-2026-Plan/prds/PRD-{03..13}-public-api-*.md` * Playbook: `Strategic-2026-Plan/prds/00-PUBLIC-API-V1-IMPLEMENTATION-PLAYBOOK.md` * RFC: `Strategic-2026-Plan/rfcs/RFC-public-api-v1.md` * Strategy: `Strategic-2026-Plan/05-PUBLIC-API-V1-EXECUTION-STRATEGY.md` ## Key invariants (BL locks) * Idempotency cross-instance race protection (PRD-1). * 6-digit verification code is PLAIN, not bcrypt-hashed (PRD-3 BL-BOOT-3 — intentional: enables read-aloud variant). * `hardDeleteUserAccount` is atomic (PRD-3 BL-BOOT-8). * Publish endpoint middleware order: `planLimits → requireTosAccepted → idempotency` (PRD-7 BL-TOS-3). * `bootstrapRpd: 50` per `mk_dev_*` key per day (PRD-1). * 5-minute replay window on webhook signatures (PRD-8). ## Testing & deploy * `npm run build` after non-trivial changes (per `feedback_always_build_to_verify.md` — tsc alone misses Angular template / i18n / Tailwind issues; for cloud-functions it catches missing imports + Zod schema drift). * Validate CI configs before push (per `feedback_validate_before_push.md`). * Production deploy is gated on Stage-0 ship checklist in playbook §9. # Marea Alcalina API Source: https://docs.mareaalcalina.com/index Spin up a digital menu or product catalog + a public hosted storefront, then sell through WhatsApp, web checkout, or in-person — in under 10 calls. Storefronts ship in Spanish (default), English, or Portuguese. The order channel is the operator's choice — WhatsApp, web checkout, or in-person pickup — configurable per storefront. > [!NOTE] > > **These docs are agent-first.** Every page is also available as raw markdown at `.md`, and every API reference page ships with a copy-paste-for-LLM block. Every error returns a `nextActions[]` array (`{label, method, url}`) — surface it to the user verbatim; **do NOT swallow 402 / 451 / 422 silently.** If you're an agent reading these docs to integrate, start with [llms.txt](/llms.txt) and [AGENTS.md](/AGENTS.md). ## What kind of integration are you building? > [card] [I run a store on Marea](/quickstart/products) > > You signed up at [mareaalcalina.com](https://mareaalcalina.com), you have a storefront, you want API access to it (POS sync, custom dashboard, automation). **This is the common case.** Grab your `mk_user_*` from the dashboard and start with [Add products](/quickstart/products). > [card] [I'm building an agent or integration](/quickstart/bootstrap) > > You're building an AI agent, vertical SaaS, or agency tool that creates Marea accounts for *other* people. You need to bootstrap users on their behalf. Start with [Bootstrap a user](/quickstart/bootstrap). If you're not sure which one you are, you're probably the first one. ## Auth in 30 seconds Every call uses a Bearer token. The one you use depends on what you're doing: ```http theme={null} GET /v1/me HTTP/1.1 Host: api.mareaalcalina.com Authorization: Bearer mk_user_xxxxxxxxxxxxxxxx ``` | Key prefix | Who holds it | Use it for | | - | - | - | | `mk_user_*` | A specific Marea user | **Default.** All catalog + storefront + product + publish calls — **across every storefront that user owns** (1 on Free, up to 5,000 on Agency Growth). Owner-scoped, not storefront-scoped. Mints from your dashboard. | | `mk_dev_*` | An agent / partner integration | Bootstrapping *other* users via `POST /v1/users`, then using each returned `mk_user_*` to manage all of that user's storefronts. Mints from the developer dashboard. | **Most integrations only ever need `mk_user_*`.** Partners ([three archetypes](/concepts/keys#partner-keys)) hold one `mk_dev_*` and many `mk_user_*` — one per user they bootstrap. Full model: [/concepts/keys](/concepts/keys). ## Five things every integration must do 1. **Send `Idempotency-Key` on every POST and PATCH.** Same key + same body returns the original response (replay-safe). See [Safe mutations](/concepts/safe-mutations). 2. **Branch on `error.type`, not `error.message`.** The `type` field is a stable 10-value enum; message wording can change. See [Errors](/concepts/errors). 3. **Surface `nextActions[]` verbatim.** It's a `{label, method, url}[]` array of concrete remediation steps. Don't paraphrase. 4. **Read `X-RateLimit-Remaining` and respect `Retry-After`.** See [Rate limits](/concepts/rate-limits) for current numbers. 5. **Handle the publish gates.** `POST .../publish` returns 402 (pre-paywall), 422 (0 products), or 451 (ToS not accepted) — surface each `nextActions[]` explicitly; don't auto-accept ToS or auto-publish without user confirmation. See [Publishing](/concepts/publishing). ## Webhooks Marea uses a **Stripe-style endpoint model**: register an endpoint (URL + signing secret + `subscribedEvents[]`) and Marea fans out matching events to it. Up to 16 endpoints per account. > [card] [Webhook endpoints](/concepts/webhooks) > > Five events: `user.verified`, `user.cancelled`, `order.created`, `order.status_updated`, `order.paid`. A single developer endpoint receives `order.*` from every storefront the key bootstrapped — no per-merchant registration needed. > [card] [Receiver helpers](/api/webhooks/receiver-helpers) > > Drop-in JavaScript and Python verifiers: HMAC-SHA256 + 5-minute replay window using the endpoint's raw 64-char-hex `signingSecret`. One algorithm for every event type. ## Agent-friendly resources * [**llms.txt**](/llms.txt) — job-to-be-done index of the entire docs surface * [**AGENTS.md**](/AGENTS.md) — common patterns + what NOT to do (cheatsheet) * [**OpenAPI 3.1 spec**](https://api.mareaalcalina.com/v1/openapi.json) — Zod-derived; 5-min cached * [**Postman collection**](/marea.postman.json) — auto-generated from the OpenAPI spec * [**MCP server**](https://mcp.mareaalcalina.com/mcp): 10 `marea.*` tools. Merchants connect it in Claude, ChatGPT or Cursor over OAuth; developers pass a static key * **Per-page markdown:** every page is also at `.md` (e.g., [/concepts/errors.md](/concepts/errors)) # Bootstrap a user account Source: https://docs.mareaalcalina.com/quickstart/bootstrap Create a Marea account on behalf of a user with one POST. The response gives you a per-user key — use it for everything after this. # Bootstrap a user account > [!NOTE] > > **This is the partner / agent flow.** Use it when you're building an AI agent, vertical SaaS, or agency tool that creates Marea accounts for *other* people. If you already own a Marea storefront and just want API access to it, you don't need this — grab your `mk_user_*` from your dashboard and skip straight to [Add products](/quickstart/products). One call creates the user, a starter storefront, and a per-user API key. Marea also emails a 6-digit code to the user; a follow-up call verifies it and unlocks catalog writes. You never touch the user's password. The whole flow is two HTTP calls. ```bash theme={null} # Your own developer key — set this once. export MAREA_DEV_KEY=mk_dev_xxxxxxxxxxxxxxxx ``` ## Step 1 — Create the user ```bash theme={null} curl -s -X POST https://api.mareaalcalina.com/v1/users \ -H "Authorization: Bearer $MAREA_DEV_KEY" \ -H "Content-Type: application/json" \ -H "Accept-Language: es-MX" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "email": "owner@taqueria.example", "displayName": "Marea Taqueria", "country": "MX", "currency": "MXN", "businessType": "restaurant", "sourceAgent": "claude-desktop" }' ``` Response — **201 Created**: ```json theme={null} { "userId": "usr_4f1a2b3c4d5e6f7a8b9c0d1e", "storefrontId": "stf_9a8b7c6d5e4f3a2b1c0d9e8f", "userKey": "mk_user_01HZX9K8QW7VPYR3M2N1B4FJSA", "verificationStatus": "pending", "verificationExpiresAt": "2026-05-10T18:23:00.000Z", "appliedDefaults": { "language": "es", "currency": "MXN", "country": "MX", "businessType": "restaurant" } } ``` > [!WARNING] > > **`userKey` is shown once.** Store it now — there's no way to read it back. Treat it like a password. ```bash theme={null} # Save the key returned in the response. export MAREA_USER_KEY=mk_user_01HZX9K8QW7VPYR3M2N1B4FJSA export USER_ID=usr_4f1a2b3c4d5e6f7a8b9c0d1e ``` From here on, **every catalog call uses `$MAREA_USER_KEY`**. You only reach back for `$MAREA_DEV_KEY` when bootstrapping another user, listing your users, or managing webhook endpoints. ### Required body fields | Field | Required | Notes | | - | - | - | | `email` | yes | Where the 6-digit code is sent. | | `displayName` | yes | Shown in the dashboard + on the storefront. | | `sourceAgent` | yes | Your agent identifier — e.g. `claude-desktop`. Logged on the user. | | `country` / `language` / `currency` / `businessType` | no | Inferred from `Accept-Language` if omitted; reported back in `appliedDefaults`. | | `initialStorefront` | no | Full [`StorefrontManifest`](/concepts/storefronts) if you want products in the same call. | ### Partial-success (207) If `initialStorefront.products[]` exceeds the user's plan cap, Marea returns **207** with the storefront created up to the cap and an `errors[]` array describing what was skipped. Surface those verbatim and prompt for upgrade. See [Plan limits](/concepts/plan-limits). ## Step 2 — Verify the 6-digit code The user gets a code in their inbox. Either ask them to read it aloud, or read it via the Gmail MCP — see [Verification flow](/concepts/verification-flow). ```bash theme={null} curl -s -X POST https://api.mareaalcalina.com/v1/users/$USER_ID/verify \ -H "Authorization: Bearer $MAREA_USER_KEY" \ -H "Content-Type: application/json" \ -d '{ "code": "123456" }' ``` Response — **200 OK**: ```json theme={null} { "userId": "usr_4f1a2b3c4d5e6f7a8b9c0d1e", "verificationStatus": "verified" } ``` The **same `$MAREA_USER_KEY`** is now upgraded in place — it gains `catalog:read`, `catalog:write`, `storefront:publish` on top of the verify scopes it already had. **Do not rotate or re-issue.** You can now call any product or storefront endpoint. ### If the code is wrong / expired / never arrived ```bash theme={null} # 3/hour, 5/day per user. curl -s -X POST https://api.mareaalcalina.com/v1/users/$USER_ID/resendVerification \ -H "Authorization: Bearer $MAREA_USER_KEY" ``` ## Two keys, one mental model You only see two API keys in the whole API: * **`$MAREA_DEV_KEY`** — your agent's own key, issued from [/developers/keys](https://mareaalcalina.com/developers/keys). Used to bootstrap users and manage webhook endpoints. Never grants catalog access. * **`$MAREA_USER_KEY`** — a single user's key, returned by `POST /v1/users`. Used for everything you do on behalf of that user (catalog reads, product writes, publish) **across every storefront the user owns**. One key per user, not one key per storefront. Tenant boundary is baked into the key — it can only see/edit that user's data. If you hit `403 insufficient_scope`, you're sending the wrong key. The error response includes `requiredScopes[]` and `heldScopes[]` so you can tell at a glance which one was needed. Full model + rotation rules: [/concepts/keys](/concepts/keys). ## Errors you should branch on Every non-2xx follows the [§9.6 envelope](/concepts/errors): `{ type, code, message, doc, param, requestId, recoverable, retryAfterMs, nextActions[], upgrade }`. Branch on `error.type` and `error.code` — never on `error.message` (localized). ### Step 1 — `POST /v1/users` | HTTP | `error.code` | What happened | Agent action | | - | - | - | - | | 400 | `invalid_request` | Email malformed, missing field, etc. | Fix the body, reissue with a NEW `Idempotency-Key`. | | 401 | `missing_authorization` / `invalid_authorization_format` / `key_not_found` / `key_revoked` | Bad/missing/revoked dev key | Re-prompt for a valid `mk_dev_*`. | | 403 | `insufficient_scope` | Dev key lacks `developer:bootstrap` | Issue a key with the right scope (see `requiredScopes` in body). | | 409 | `email_exists` | The email already has a Marea account | Send the user to log in. | | 429 | `rate_limit_exceeded` (message contains `rpd_exceeded`) | Dev-key daily cap hit (50/day default) | Sleep `retryAfterMs`, then retry. | > [accordion] Full error response examples (auth, conflict, rate-limit) > > ```json theme={null} > // 401 — missing header > { > "error": { > "type": "auth", > "code": "missing_authorization", > "message": "Authorization header is required.", > "doc": "https://docs.mareaalcalina.com/concepts/keys#authorization", > "param": "Authorization", > "requestId": "req_30a9358b-70bd-44f3-aa5d-8983b558ad84", > "recoverable": false, > "retryAfterMs": null, > "nextActions": [ > { "label": "Get a developer key.", "method": null, "url": "https://mareaalcalina.com/developers/keys" } > ], > "upgrade": null > } > } > ``` > > ```json theme={null} > // 409 — email already exists > { > "error": { > "type": "conflict", > "code": "email_exists", > "message": "An account with this email already exists.", > "doc": "https://docs.mareaalcalina.com/concepts/errors#email_exists", > "param": "email", > "requestId": "req_30a9358b-70bd-44f3-aa5d-8983b558ad84", > "recoverable": false, > "retryAfterMs": null, > "nextActions": [ > { "label": "The user already has a Marea account — send them to log in.", "method": null, "url": "https://mareaalcalina.com/login" } > ], > "upgrade": null > } > } > ``` > > ```json theme={null} > // 429 — dev key hit daily cap > { > "error": { > "type": "rate_limited", > "code": "rate_limit_exceeded", > "message": "rpd_exceeded — Developer key has reached its daily quota.", > "doc": "https://docs.mareaalcalina.com/concepts/rate-limits", > "param": null, > "requestId": "req_30a9358b-70bd-44f3-aa5d-8983b558ad84", > "recoverable": true, > "retryAfterMs": 21600000, > "nextActions": [{ "label": "Wait and retry after the reset.", "method": null, "url": null }], > "upgrade": null > } > } > ``` ### Step 2 — `POST /v1/users/:userId/verify` | HTTP | `error.code` | What happened | Agent action | | - | - | - | - | | 400 | `code_invalid` | Wrong digits | Ask the user to re-read — up to 3 attempts before lockout. | | 404 | `code_not_found` | No active code (already verified or never sent) | Call resend, then retry. | | 404 | `user_not_found` | `:userId` doesn't match the calling key | Wrong `$MAREA_USER_KEY` for this `$USER_ID`. | | 410 | `code_expired` | 15-minute TTL elapsed | Call resend, then retry. | | 429 | `too_many_attempts` | 3 failed attempts on the same code | Call resend (issues a new code), then retry. | Full error matrix at [/concepts/errors](/concepts/errors). Idempotency rules at [/concepts/safe-mutations](/concepts/safe-mutations). Rate-limit defaults at [/concepts/rate-limits](/concepts/rate-limits). ## For agents Copy this block into your AI assistant to give it everything it needs:
``────────────────────────────────────────────────────────────
You can bootstrap a Marea user account and verify their email via the Marea Catalog API.
Endpoint: POST https://api.mareaalcalina.com/v1/users
Header: Authorization: Bearer 
Body schema: { "email": "owner@taqueria.example", "displayName": "Marea Taqueria", "sourceAgent": "claude-desktop" }
What this does: Creates a Marea user, an optional starter storefront, and a per-user key. Capture `userKey` from the 201 response — that's the key you use for every subsequent catalog/publish/product call for this user. Then POST /v1/users/:userId/verify with the 6-digit code from the user's inbox to upgrade that same key to full scope. The userKey is returned ONCE — store it immediately.
Errors: 429 rate_limited (code: rate_limit_exceeded, message contains rpd_exceeded → dev-key daily cap; sleep retryAfterMs); 409 conflict (email_exists → tell the user to log in); 400 invalid_request (fix body, new Idempotency-Key); 207 Multi-Status (initialStorefront exceeded plan cap — accepted up to cap, errors[] lists skipped). Verify: 400 code_invalid, 410 code_expired (resend), 429 too_many_attempts (resend), 404 user_not_found (wrong key).
Full reference (markdown): https://docs.mareaalcalina.com/api/catalog/bootstrap-user.md
────────────────────────────────────────────────────────────``
## Next steps * [Add and edit products](/quickstart/products) — use `$MAREA_USER_KEY` from here on. * [Publish a storefront](/quickstart/publish) — handle the 402 paywall, 422 empty, and 451 ToS gates. * [Install MCP in Claude Desktop / Cursor / Continue.dev](/quickstart/mcp) — same flow, exposed as `marea.*` tools. # Connect Marea to Claude, ChatGPT or your AI client Source: https://docs.mareaalcalina.com/quickstart/mcp Connect your Marea account to an AI client over MCP and manage your menu by talking to it. OAuth for merchants, static keys for developers. # Connect Marea to your AI client Marea runs an MCP server at `https://mcp.mareaalcalina.com/mcp`. Connect it once and your AI client manages your page for you. **What the AI can do:** list your products and prices; add or edit products (title, description, price, sale price, category, stock, photo by URL); hide a sold-out item and bring it back; change hours, delivery, pickup and dine-in, branding and categories; create a new page and publish it when you say so. **What it cannot do yet:** read or manage orders and customers; delete a product (hide it instead); upload a photo from your computer (a public image URL works); change the WhatsApp number that receives orders (set at creation, changed in the dashboard). Publishing needs the same two things as in the dashboard: accepted terms and a plan that can publish. If either is missing, the AI shows you the link to fix it. ## ChatGPT **1. Open connectors** In ChatGPT settings, open Connectors (on some plans it lives under Apps or developer mode). **2. Add the server** Create a connector with this URL and choose OAuth. There is no client id or secret to paste. ``` https://mcp.mareaalcalina.com/mcp ``` **3. Connect** Sign in to Marea in the window that opens and press Autorizar. ## Claude (claude.ai, Desktop, mobile) **1. Open connectors** Settings (Ajustes), then Connectors (Conectores), then add a custom connector. **2. Add the server** Name it `Marea` and paste the same URL: ``` https://mcp.mareaalcalina.com/mcp ``` **3. Connect** Click Connect, sign in with the account that owns your page, and press Autorizar. ## Claude Code, Cursor, VS Code Add the URL as an HTTP MCP server with no headers. The first call returns a `401` with an OAuth challenge and the client opens your browser to sign in. ```bash theme={null} # Claude Code claude mcp add --transport http marea https://mcp.mareaalcalina.com/mcp ``` ```json theme={null} // Cursor: ~/.cursor/mcp.json { "mcpServers": { "marea": { "url": "https://mcp.mareaalcalina.com/mcp" } } } ``` ## Check it worked, then try these Ask **"¿Qué cuenta de Marea tienes conectada?"**. The AI calls `marea.whoami` and answers with your email and plan. Then: * "¿Qué productos tengo en mi menú y a qué precio?" * "Sube el precio de los tacos al pastor a 45 pesos." * "Oculta el flan, se nos acabó." * "Cambia el horario del domingo a 9:00 a 17:00." * "Agrega 'Agua de horchata' a 25 pesos en la categoría Bebidas." * "Publica mi página." (the AI asks you to confirm; publishing is customer visible) Hours, delivery, pickup and dine-in changes go live immediately. Design changes wait for publish. ## Developers and agents without a browser Pass a key as a bearer header: `mk_user_*` for your own account, `mk_dev_*` only if you create Marea accounts for other people. Mint keys at [mareaalcalina.com/developers/keys](https://mareaalcalina.com/developers/keys); see [API keys](/concepts/keys). > [tab] Claude Desktop (config file) > > ```json theme={null} > { > "mcpServers": { > "marea": { > "command": "npx", > "args": ["-y", "mcp-remote", "https://mcp.mareaalcalina.com/mcp", > "--header", "Authorization: Bearer mk_user_your_key_here"] > } > } > } > ``` > [tab] OpenAI Agents SDK > > ```python theme={null} > from agents.mcp import MCPServerStreamableHttp > > marea = MCPServerStreamableHttp( > name="marea", > params={"url": "https://mcp.mareaalcalina.com/mcp", > "headers": {"Authorization": "Bearer mk_user_your_key_here"}}, > ) > ``` > > With the Anthropic Messages API, list the server under `mcp_servers` with `url` and `authorization_token`. > [tab] curl > > ```bash theme={null} > curl -sS https://mcp.mareaalcalina.com/mcp \ > -H "Authorization: Bearer mk_user_your_key_here" \ > -H "Content-Type: application/json" \ > -H "Accept: application/json, text/event-stream" \ > -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' > ``` > > `401` means the key is missing or revoked. `406` means the `Accept` header was dropped. ## The tools | Tool | What it does | REST call behind it | Needs | | - | - | - | - | | `marea.whoami` | Connected account, plan, remaining quota | `GET /v1/me` | `marea.read` | | `marea.list_storefronts` | Your pages with id, name, slug and links | `GET /v1/storefronts` | `marea.read` | | `marea.get_storefront` | One page in full: hours, delivery, branding, categories, published state | `GET /v1/storefronts/:id` | `marea.read` | | `marea.list_products` | Products of one page with prices and hidden state | `GET /v1/storefronts/:id/products` | `marea.read` | | `marea.create_storefront` | Create a page, optionally with up to 100 products | `POST /v1/storefronts` | `marea.write` | | `marea.update_storefront` | Change hours, delivery, pickup, currency, branding, categories | `PATCH /v1/storefronts/:id` | `marea.write` | | `marea.create_product` | Add one product | `POST /v1/storefronts/:id/products` | `marea.write` | | `marea.update_product` | Change a product, or hide it with `hide: true` | `PATCH /v1/storefronts/:id/products/:productId` | `marea.write` | | `marea.publish_storefront` | Take the page live | `POST /v1/storefronts/:id/publish` | `marea.publish` | | `marea.bootstrap_user` | Create a Marea account for someone else | `POST /v1/users` | `mk_dev_*` key only | An OAuth connection only lists the tools its scopes cover. There is no bootstrap scope: `marea.bootstrap_user` needs a developer key. Email verification stays on REST because the six digit code needs the person in the loop. ## For AI agents * **Read first:** [`llms.txt`](https://docs.mareaalcalina.com/llms.txt) and [`AGENTS.md`](https://docs.mareaalcalina.com/AGENTS.md). Every page also serves as Markdown at `.md`. * **Tool descriptions are the spec.** Every argument is described; `businessType` and `currency` list their accepted values. Read `tools/list` once per session. * **Ids are prefixed and opaque:** pages `stf_…`, products `prd_…`. Get them from list tools or from what a create call returns. Never construct one. * **Start with `marea.list_storefronts`.** If there is more than one page, ask which one before writing. * **Updates are patches, except arrays.** Omitted fields keep their value, but `categories`, `blocks` and each `schedule` day are replaced whole. To add a category, read the current list and send it complete. * **Hide, do not delete.** `hide: true` on `marea.update_product` takes an item off the menu and keeps it. * **Results are JSON** in `content[0].text` and, on success, `structuredContent`. REST errors return `isError: true` with the envelope (`type`, `code`, `message`, `nextActions[]`, `upgrade`) in `_meta.error`; schema failures return a plain `-32602` message naming the field. Branch on `code`; show `nextActions[]` and `upgrade.upgradeUrl` verbatim. * **Publishing needs a person.** Confirm before calling `marea.publish_storefront`; never chain it after an edit. Expect `451` (terms) or `402` (plan) and surface the link. * **Retries:** set `_idempotencyKey` (UUID v4) on any write you might retry; the same key within 24h returns the original result. Back off on `429` for `Retry-After` seconds. `_acceptLanguage` only affects bootstrap defaults; error messages are English. * **Language:** merchants are Spanish-speaking (Mexico, Colombia, Costa Rica, Peru). Product names, categories and `businessType` values are Spanish. ## Disconnect From the AI client's connector settings, or from the dashboard: each connection is a key named after the app (for example `Claude · claude.ai`) under Desarrolladores, Claves API. Delete it and the app loses access on its next call. ## Troubleshooting * **"Couldn't reach the server":** check the URL ends in `/mcp`. `GET` answers `405`; that is expected. * **"Authorization failed" or the consent page loops:** sign in to Marea with the account that owns the page, then retry. The consent page shows the host of the app that is asking. * **Publish blocked:** `402` means the plan cannot publish (upgrade link in the response); `451` means the terms are not accepted (dashboard link in the response). * **Tools disappeared:** the connection's key was deleted in the dashboard. Reconnect from the client. * **`401` with a static key:** the header was dropped by an editor, or the key was revoked. Re-paste or mint a new key. * **`429`:** wait `Retry-After` seconds. See [Rate limits](/concepts/rate-limits). ## Discovery and transport Streamable HTTP, stateless, `POST` only. OAuth clients discover everything from the `WWW-Authenticate` challenge on a `401`. For clients built by hand: | Document | URL | | - | - | | Protected resource metadata (RFC 9728) | `https://mcp.mareaalcalina.com/.well-known/oauth-protected-resource` (also `/mcp` path form) | | Authorization server metadata (RFC 8414) | `https://mcp.mareaalcalina.com/.well-known/oauth-authorization-server` | | Server manifest | `https://mcp.mareaalcalina.com/.well-known/mcp.json` | Registration: Client ID Metadata Documents (preferred) or Dynamic Client Registration. Redirect URIs: any `https://` URI, or loopback with any port. Access tokens last 60 minutes; refresh tokens 90 days and rotate. Registry listing: `com.mareaalcalina/storefront`. ## Next steps * [Add and edit products](/quickstart/products), the REST view of the product tools. * [Publish a storefront](/quickstart/publish), the 402, 422 and 451 gates. * [API keys](/concepts/keys), including the keys an AI connection creates. # Add and edit products Source: https://docs.mareaalcalina.com/quickstart/products User-key CRUD on the catalog. POST a product (201), PATCH a product (200) — both partial-merge friendly, both honor Idempotency-Key. # Add and edit products Every catalog operation uses your `mk_user_*` key. You get it one of two ways: * **You own a Marea store.** Mint `$MAREA_USER_KEY` from your dashboard (the `mk_user_*` represents *you*). This is the common case. * **You're a partner.** The user-key was returned in the `POST /v1/users` response when you bootstrapped the user — see [Bootstrap a user account](/quickstart/bootstrap). ```bash theme={null} export MAREA_USER_KEY=mk_user_xxxxxxxxxxxxxxxx export STOREFRONT_ID=stf_xxxxxxxxxxxxxxxx # GET /v1/storefronts if you don't know it ``` Both endpoints below require scope `catalog:write` and honor `Idempotency-Key` (see [Safe mutations](/concepts/safe-mutations)). ## Add a product `POST /v1/storefronts/{storefrontId}/products` — returns **201 Created** with the full product DTO. ```bash curl theme={null} curl -X POST https://api.mareaalcalina.com/v1/storefronts/$STOREFRONT_ID/products \ -H "Authorization: Bearer $MAREA_USER_KEY" \ -H "Content-Type: application/json" \ -H "Accept-Language: es-MX" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "title": "Taco al pastor", "price": 25, "imageUrl": "https://example.com/pastor.jpg", "category": "Tacos", "description": "Marinated pork, pineapple, cilantro, onion." }' ``` ```javascript JavaScript theme={null} const res = await fetch( `https://api.mareaalcalina.com/v1/storefronts/${storefrontId}/products`, { method: "POST", headers: { "Authorization": `Bearer ${userKey}`, "Content-Type": "application/json", "Idempotency-Key": crypto.randomUUID(), }, body: JSON.stringify({ title: "Taco al pastor", price: 25, imageUrl: "https://example.com/pastor.jpg", category: "Tacos", description: "Marinated pork, pineapple, cilantro, onion.", }), }, ); const { product } = await res.json(); ``` ```python Python theme={null} import uuid, requests res = requests.post( f"https://api.mareaalcalina.com/v1/storefronts/{storefront_id}/products", headers={ "Authorization": f"Bearer {user_key}", "Content-Type": "application/json", "Idempotency-Key": str(uuid.uuid4()), }, json={ "title": "Taco al pastor", "price": 25, "imageUrl": "https://example.com/pastor.jpg", "category": "Tacos", "description": "Marinated pork, pineapple, cilantro, onion.", }, ) product = res.json()["product"] ``` ### Response — 201 Created ```json theme={null} { "product": { "id": "prd_8c4b2e3a4b9d9f1a8c4b2e3a", "title": "Taco al pastor", "description": "Marinated pork, pineapple, cilantro, onion.", "price": 25, "salePrice": null, "category": "Tacos", "subcategory": null, "imageUrl": "https://example.com/pastor.jpg", "thumbnailUrl": null, "sku": null, "slug": null, "position": 12, "cartProduct": null, "hide": null, "stock": null, "tags": null, "extraProductsCategory": null, "imageProcessingPending": true, "createdAt": "2026-05-10T18:25:00.000Z", "updatedAt": "2026-05-10T18:25:00.000Z" } } ``` `imageProcessingPending: true` means Marea will sweep the source URL into its own CDN asynchronously; `imageUrl` continues to serve from the source until then. ### Required + optional fields | Field | Type | Required | Notes | | - | - | - | - | | `title` | string (1–200) | yes | | | `price` | number (≥ 0) | yes | Storefront currency. | | `description` | string | no | | | `salePrice` | number (≥ 0) | no | If set + below `price`, shown crossed-out. | | `category` / `subcategory` | string | no | | | `imageUrl` / `thumbnailUrl` | URL | no | Both swept into Marea CDN async (BL-CAT-10). | | `sku` / `slug` | string | no | | | `position` | int | no | Defaults to last + 1. | | `cartProduct` / `hide` | boolean | no | | | `stock` | int | no | Surfaced on the storefront as inventory remaining. | | `tags` | string\[] | no | | | `extraProductsCategory` | object\[] | no | Modifier groups (size, toppings). See OpenAPI schema. | ## Update a product `PATCH /v1/storefronts/{storefrontId}/products/{productId}` — returns **200 OK** with the full updated `ProductDto`. Every field is PATCHable (no immutable fields). ```bash curl theme={null} curl -X PATCH https://api.mareaalcalina.com/v1/storefronts/$STOREFRONT_ID/products/$PRODUCT_ID \ -H "Authorization: Bearer $MAREA_USER_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "price": 28, "salePrice": 25 }' ``` ```javascript JavaScript theme={null} const res = await fetch( `https://api.mareaalcalina.com/v1/storefronts/${storefrontId}/products/${productId}`, { method: "PATCH", headers: { "Authorization": `Bearer ${userKey}`, "Content-Type": "application/json", "Idempotency-Key": crypto.randomUUID(), }, body: JSON.stringify({ price: 28, salePrice: 25 }), }, ); const { product } = await res.json(); ``` ```python Python theme={null} res = requests.patch( f"https://api.mareaalcalina.com/v1/storefronts/{storefront_id}/products/{product_id}", headers={ "Authorization": f"Bearer {user_key}", "Content-Type": "application/json", "Idempotency-Key": str(uuid.uuid4()), }, json={"price": 28, "salePrice": 25}, ) product = res.json()["product"] ``` Partial update — only the fields you send change. **To clear an optional field, send `null`** (e.g. `{ "imageUrl": null }`). Omitting a field leaves it untouched. ## Idempotency Same `Idempotency-Key` + same body within 24 hours → original response replayed (no duplicate writes). Same key + **different** body → `409 idempotency_conflict`. See [Safe mutations](/concepts/safe-mutations). If your batch importer hits a transient network error mid-flight, retry with the **same** `Idempotency-Key` per product — the server is replay-safe. ## Plan caps and 402 mid-batch The single-product `POST` endpoint returns **`402 plan_limit` (`plan_max_products_reached`)** the moment a write would exceed the user's plan cap. Stop the batch as soon as you see it; surface `error.upgrade.upgradeUrl`; do not retry until the user upgrades. ```json theme={null} // 402 — adding this product would exceed the plan cap { "error": { "type": "plan_limit", "code": "plan_max_products_reached", "message": "Plan limit of 30 products reached. Upgrade to add more.", "doc": "https://docs.mareaalcalina.com/concepts/plan-limits#products", "param": "products", "requestId": "req_...", "recoverable": true, "retryAfterMs": null, "nextActions": [ { "label": "Upgrade the plan to add more products.", "method": null, "url": "https://mareaalcalina.com/menus/profile?changePlan=basic&frequency=monthly&planSource=api" } ], "upgrade": { "currentPlan": "free", "requiredPlan": "basic", "upgradeUrl": "https://mareaalcalina.com/menus/profile?changePlan=basic&frequency=monthly&planSource=api" } } } ``` ### Bulk-load alternative: 207 Multi-Status If you're seeding a whole catalog at once, use `POST /v1/storefronts` with the manifest's `products[]` array (or pass `initialStorefront.products` on `POST /v1/users`). When the manifest exceeds the plan cap, Marea returns **`207 Multi-Status`** — the storefront is created with products up to the cap and the response `errors[]` array lists what was skipped: ```json theme={null} { "storefront": { "id": "stf_...", "name": "Tacos La Marea", "published": false }, "errors": [ { "type": "plan_limit", "code": "products_over_limit", "message": "Skipped 'Taco al pastor': free tier allows 30 products.", "details": { "skippedCount": 5, "skippedProducts": [/* ... */] } } ] } ``` Surface the skipped list to the user and offer the upgrade; the accepted products are already live. ## Other recoverable errors ```json theme={null} // 404 — wrong storefrontId/productId, or cross-tenant (leak-less) { "error": { "type": "not_found", "code": "storefront_not_found", "message": "Storefront not found.", "doc": "https://docs.mareaalcalina.com/concepts/errors#not_found", "param": null, "requestId": "req_...", "recoverable": false, "retryAfterMs": null, "nextActions": [], "upgrade": null } } ``` ```json theme={null} // 400 — body validation (e.g. negative price) { "error": { "type": "invalid_request", "code": "invalid_request", "message": "price must be ≥ 0.", "doc": "https://docs.mareaalcalina.com/concepts/errors", "param": "price", "requestId": "req_...", "recoverable": true, "retryAfterMs": null, "nextActions": [ { "label": "Fix the body, then retry with a NEW Idempotency-Key.", "method": null, "url": null } ], "upgrade": null } } ``` Quick lookup: | HTTP | `error.type` / `code` | What happened | Agent action | | - | - | - | - | | 400 | `invalid_request` | Body validation (negative price, missing title, malformed field) — see `error.param` for which field failed | Fix the body, reissue with a NEW `Idempotency-Key`. | | 402 | `plan_limit` / `plan_max_products_reached` | This single-product write would exceed the plan cap | Surface `error.upgrade.upgradeUrl`; do not retry until upgrade. | | 404 | `not_found` / `storefront_not_found` | Wrong storefront id, or this user-key doesn't own it (silent cross-tenant). Product not-found also surfaces here. | Confirm the ids; cannot infer ownership. | | 409 | `idempotency_conflict` | Same `Idempotency-Key` reused with a different body | Generate a fresh UUID for the retry. | | 429 | `rate_limited` / `rate_limit_exceeded` (message contains `rpm_exceeded`) | Per-user `rpm: 60` cap | Sleep `Retry-After` (seconds), retry with the same key. | ## Cross-references * [Storefronts](/concepts/storefronts) — parent-object model. * [Plan limits](/concepts/plan-limits) — product caps per plan (Free 30, Basic 60, Pro 200, Business 2000+). * [Safe mutations](/concepts/safe-mutations) — `Idempotency-Key` semantics. ## For agents Copy this block into your AI assistant to give it everything it needs:
`────────────────────────────────────────────────────────────
You can add a product to a Marea storefront via the Marea Catalog API.
Endpoint: POST https://api.mareaalcalina.com/v1/storefronts/{storefrontId}/products
Header: Authorization: Bearer 
Body schema: { "title": "Taco al pastor", "price": 25, "category": "Tacos" }
What this does: Adds a product to an existing storefront the user-key owns. Returns 201 with the full product DTO. Honors Idempotency-Key. Required: title (1-200 chars), price (≥ 0). Optional: description, salePrice, category, subcategory, imageUrl, thumbnailUrl, sku, slug, position, cartProduct, hide, stock, tags, extraProductsCategory. For bulk imports, prefer POST /v1/storefronts with manifest.products[] which returns 207 Multi-Status when the plan cap is exceeded.
Errors: 402 plan_limit/plan_max_products_reached (surface upgrade.upgradeUrl; do not retry); 404 not_found (wrong id or cross-tenant — silent); 400 invalid_request (fix body, NEW Idempotency-Key); 409 idempotency_conflict (new UUID); 429 rate_limited (sleep retryAfterMs, retry with same key).
Full reference (markdown): https://docs.mareaalcalina.com/api/catalog/create-product.md
────────────────────────────────────────────────────────────`
# Publish a storefront Source: https://docs.mareaalcalina.com/quickstart/publish POST .../publish with the four gates: 402 (pre-paywall), 422 (empty), 451 (ToS), 200 (live publicUrl). Idempotent on republish. # Publish a storefront Publish is the one operation that takes a storefront from draft to public — the URL becomes shareable, indexable, and live for end customers. Required scope: `storefront:publish`. **Always require explicit user confirmation before calling** — publish is user-visible. ## Pre-flight checklist Before calling publish: 1. The storefront must have **at least one product** (else 422 `no_products`). 2. The user must be on **any active plan** — Free, Basic, Pro, Business, or Agency. Pre-paywall accounts (just-signed-up, no plan picked) get 402. 3. The user must have **accepted the dashboard ToS modal** (else 451). The agent cannot bypass this. Short-circuit with `GET /v1/me` if you want to surface a CTA before the publish round-trip: ```json theme={null} { "plan": { "tier": "free", "limits": { "publishable": true, "products": 30, "storefronts": 1 } }, "tosAcceptedAt": "2026-04-15T10:23:00Z" } ``` If `plan.limits.publishable` is `false` or `tosAcceptedAt` is `null`, surface the appropriate next-action to the user before attempting publish. ## Request `POST /v1/storefronts/{storefrontId}/publish` — body is optional. ```bash curl theme={null} curl -X POST https://api.mareaalcalina.com/v1/storefronts/$STOREFRONT_ID/publish \ -H "Authorization: Bearer $MAREA_USER_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{}' ``` ```javascript JavaScript theme={null} const res = await fetch( `https://api.mareaalcalina.com/v1/storefronts/${storefrontId}/publish`, { method: "POST", headers: { "Authorization": `Bearer ${userKey}`, "Content-Type": "application/json", "Idempotency-Key": crypto.randomUUID(), }, body: JSON.stringify({}), }, ); const { storefront } = await res.json(); // Surface storefront._links.publicUrl to the user. ``` ```python Python theme={null} import uuid, requests res = requests.post( f"https://api.mareaalcalina.com/v1/storefronts/{storefront_id}/publish", headers={ "Authorization": f"Bearer {user_key}", "Content-Type": "application/json", "Idempotency-Key": str(uuid.uuid4()), }, json={}, ) storefront = res.json()["storefront"] ``` Send `{ "versionId": "ver_xxx" }` to publish a specific version snapshot; omit for auto-version (the common case — Marea creates a fresh snapshot from the current draft). ## 200 OK — success ```json theme={null} { "storefront": { "id": "stf_9a8b7c6d5e4f3a2b1c0d9e8f", "name": "Tacos La Marea", "language": "es", "currency": "MXN", "businessType": "restaurant", "published": true, "publishedDate": "2026-05-10T18:30:00.000Z", "_links": { "previewUrl": "https://marea.pro/preview/pv_8c4b2e3a4b9d", "publicUrl": "https://marea.pro/tacos-la-marea", "editUrl": "https://mareaalcalina.com/dashboard/menu/stf_9a8b7c6d5e4f3a2b1c0d9e8f" } } } ``` Surface `_links.publicUrl` to the user: that's the share-and-print-and-QR-code URL. If the owner later changes the link in the dashboard, this URL keeps working and redirects to the new one. ## The four error gates Every error follows the §9.6 envelope verbatim. Branch on `error.type` + `error.code`; surface `nextActions[]` to the user without paraphrasing. ### 402 — plan paywall (`plan_blocks_publish`) The user is pre-paywall (no plan picked yet). Surface `error.upgrade.upgradeUrl` as a CTA; do not retry until the user upgrades. ```json theme={null} { "error": { "type": "plan_limit", "code": "plan_blocks_publish", "message": "Your plan does not permit publishing. Upgrade to publish this storefront.", "doc": "https://docs.mareaalcalina.com/concepts/plan-limits#publish-paywall", "param": null, "requestId": "req_30a9358b-70bd-44f3-aa5d-8983b558ad84", "recoverable": true, "retryAfterMs": null, "nextActions": [ { "label": "Pick a plan to publish.", "method": null, "url": "https://mareaalcalina.com/menus/profile?changePlan=basic&frequency=monthly&planSource=api" } ], "upgrade": { "currentPlan": "free", "requiredPlan": "basic", "upgradeUrl": "https://mareaalcalina.com/menus/profile?changePlan=basic&frequency=monthly&planSource=api" } } } ``` ### 422 — empty storefront (`no_products`) The storefront has 0 products. Use `nextActions[0].url` to add a product before retrying. ```json theme={null} { "error": { "type": "invalid_request", "code": "no_products", "message": "Cannot publish an empty storefront. Add at least one product first.", "doc": "https://docs.mareaalcalina.com/concepts/publishing#no-products", "param": null, "requestId": "req_30a9358b-70bd-44f3-aa5d-8983b558ad84", "recoverable": true, "retryAfterMs": null, "nextActions": [ { "label": "Add at least one product before publishing.", "method": "POST", "url": "/v1/storefronts/stf_9a8b7c6d5e4f3a2b1c0d9e8f/products" } ], "upgrade": null } } ``` ### 451 — ToS not accepted (`tos_required`) The user hasn't accepted the dashboard ToS modal. The agent **cannot** bypass — the user must complete the modal in their browser. Retry with the same `Idempotency-Key` after the user accepts. ```json theme={null} { "error": { "type": "tos_not_accepted", "code": "tos_required", "message": "The account holder must accept the Marea Terms of Service before this storefront can be published.", "doc": "https://docs.mareaalcalina.com/concepts/tos-jurisdiction", "param": null, "requestId": "req_30a9358b-70bd-44f3-aa5d-8983b558ad84", "recoverable": true, "retryAfterMs": null, "nextActions": [ { "label": "Open the dashboard so the user can accept the Terms of Service.", "method": "GET", "url": "https://mareaalcalina.com/dashboard/tos" } ], "upgrade": null } } ``` ### 404 — not found (`storefront_not_found`) Wrong `storefrontId`, or this user-key doesn't own it. Cross-tenant returns 404 (leak-less), not 403 — you cannot infer existence. ## Summary table | HTTP | `error.type` / `code` | Why | What to do | | - | - | - | - | | 402 | `plan_limit` / `plan_blocks_publish` | Pre-paywall account | Surface `error.upgrade.upgradeUrl`; do not retry until upgrade. | | 422 | `invalid_request` / `no_products` | 0 products | Use `error.nextActions[0]` (POST products URL), then retry. | | 451 | `tos_not_accepted` / `tos_required` | ToS modal not completed | Surface `nextActions[0].url` (dashboard). Agent cannot bypass. Retry with same `Idempotency-Key` after user accepts. | | 404 | `not_found` / `storefront_not_found` | Wrong id or cross-tenant | Confirm id + ownership; cannot retry blindly. | | 429 | `rate_limited` / `rpm_exceeded` | Per-user `rpm: 60` cap | Sleep `Retry-After`, retry with same key. | ## Idempotent republishing Calling publish on an already-published storefront with the same `versionId` is a **no-op** that returns 200 with the same DTO. To republish a new version, omit `versionId` (auto-version) — Marea creates a fresh snapshot, runs the publish, and the live URL points at the new content. You can keep the same `Idempotency-Key` across retries of the same publish attempt; generate a fresh key for a new republish. ## Cross-references * [Publishing concept](/concepts/publishing) — full gate semantics + idempotency rules. * [ToS jurisdiction](/concepts/tos-jurisdiction) — what the 451 ToS modal contains. * [Plan limits](/concepts/plan-limits) — per-plan storefront caps + the publish-block-on-pre-paywall rule. ## For agents Copy this block into your AI assistant to give it everything it needs:
`────────────────────────────────────────────────────────────
You can publish a Marea storefront to its public URL via the Marea Catalog API.
Endpoint: POST https://api.mareaalcalina.com/v1/storefronts/{storefrontId}/publish
Header: Authorization: Bearer 
Body schema: {}
What this does: Takes a draft storefront live. Returns 200 with storefront._links.publicUrl on success. Idempotent on republish (same versionId → no-op). Always require explicit user confirmation before calling — publish is user-visible. Pre-flight: GET /v1/me first to check plan.limits.publishable and tosAcceptedAt.
Errors: 402 plan_limit/plan_blocks_publish (pre-paywall — surface upgrade.upgradeUrl, do not retry); 422 invalid_request/no_products (add a product first via nextActions[0]); 451 tos_not_accepted/tos_required (surface dashboard URL; agent cannot bypass; retry with same Idempotency-Key after user accepts); 404 not_found (wrong id or cross-tenant — silent); 429 rate_limited (sleep retryAfterMs).
Full reference (markdown): https://docs.mareaalcalina.com/api/catalog/publish-storefront.md
────────────────────────────────────────────────────────────`