@12-apps/marketplace 1.20.1 → 1.20.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -282,29 +282,61 @@ async function deliverAdmitted(config, admitted) {
282
282
  }
283
283
  __name(deliverAdmitted, "deliverAdmitted");
284
284
  async function admitApp(config, request) {
285
- const { provider = "" } = request.params;
286
- if (!config.engine.knows(provider)) return { status: 404, body: { error: "unknown_provider" } };
287
- const raw = request.request;
288
- if (!raw) return { status: 400, body: { error: "raw_request_required" } };
289
- const rawBody = await raw.text();
290
- const payload = parsedJson(rawBody);
291
- if (payload === void 0) return { status: 400, body: { error: "invalid_json" } };
285
+ const read = await readAppDelivery(config, request);
286
+ if ("status" in read) return read;
287
+ const { provider, payload } = read;
288
+ const signedByApp = await appSigned(config, read);
292
289
  const probe = config.engine.presence(provider, payload);
293
- if (probe) {
294
- const signature2 = config.engine.readSignature(provider, (name) => raw.headers.get(name));
295
- return await config.engine.signedByApp(provider, rawBody, signature2) ? presenceAnswer(probe) : UNAUTHORIZED;
296
- }
290
+ if (probe) return signedByApp ? presenceAnswer(probe) : UNAUTHORIZED;
297
291
  const found = await appConnection(config, provider, payload);
298
292
  if ("status" in found) return found;
299
- const signature = config.engine.readSignature(provider, (name) => raw.headers.get(name));
300
- const secret = found.target.webhookSecret;
301
- if (!secret || !config.engine.verifySignature(provider, rawBody, signature, secret)) {
293
+ if ("unheld" in found) {
294
+ if (!signedByApp) return UNAUTHORIZED;
295
+ config.logger.warn(`marketplace.webhook: app ${provider} delivery names a merchant no single store holds; recorded`);
296
+ return { unclaimed: true, provider, payload };
297
+ }
298
+ if (!signedByApp && !signedByStore(config, read, found.target.webhookSecret)) {
302
299
  config.logger.warn(`marketplace.webhook: app ${provider} delivery for ${found.clientId} refused`);
303
300
  return UNAUTHORIZED;
304
301
  }
305
302
  return { ...found, provider, payload };
306
303
  }
307
304
  __name(admitApp, "admitApp");
305
+ async function readAppDelivery(config, request) {
306
+ const { provider = "" } = request.params;
307
+ if (!config.engine.knows(provider)) return { status: 404, body: { error: "unknown_provider" } };
308
+ const raw = request.request;
309
+ if (!raw) return { status: 400, body: { error: "raw_request_required" } };
310
+ const rawBody = await raw.text();
311
+ const payload = parsedJson(rawBody);
312
+ if (payload === void 0) return { status: 400, body: { error: "invalid_json" } };
313
+ return { provider, rawBody, payload, signature: config.engine.readSignature(provider, (name) => raw.headers.get(name)) };
314
+ }
315
+ __name(readAppDelivery, "readAppDelivery");
316
+ async function appSigned(config, delivery) {
317
+ try {
318
+ return await config.engine.signedByApp(delivery.provider, delivery.rawBody, delivery.signature);
319
+ } catch (error) {
320
+ config.logger.error(`marketplace.webhook: app ${delivery.provider} key unavailable: ${String(error)}`);
321
+ return false;
322
+ }
323
+ }
324
+ __name(appSigned, "appSigned");
325
+ function signedByStore(config, delivery, secret) {
326
+ if (secret === null || secret === "") return false;
327
+ return config.engine.verifySignature(delivery.provider, delivery.rawBody, delivery.signature, secret);
328
+ }
329
+ __name(signedByStore, "signedByStore");
330
+ async function deliverUnclaimed(config, unclaimed) {
331
+ const { provider, payload } = unclaimed;
332
+ const status = config.engine.answerStatus(provider);
333
+ const event = config.engine.normalize(provider, payload);
334
+ if (!event) return { status, body: { received: true, ignored: "unrecognized_payload" } };
335
+ const outcome = await config.engine.deliver({ clientId: null, event, payload, settings: null });
336
+ if (outcome.kind === "failed") return { status: 500, body: { received: true, error: outcome.reason } };
337
+ return { status, body: { received: true, outcome: outcome.kind } };
338
+ }
339
+ __name(deliverUnclaimed, "deliverUnclaimed");
308
340
  function parsedJson(rawBody) {
309
341
  try {
310
342
  return JSON.parse(rawBody);
@@ -316,7 +348,7 @@ __name(parsedJson, "parsedJson");
316
348
  async function appConnection(config, provider, payload) {
317
349
  const merchantId = config.engine.normalize(provider, payload)?.externalMerchantId ?? null;
318
350
  const clientId = merchantId === null ? null : await config.engine.tenantFor(provider, merchantId);
319
- if (!clientId) return UNAUTHORIZED;
351
+ if (!clientId) return { unheld: true };
320
352
  try {
321
353
  const target = await config.engine.target(clientId, provider);
322
354
  return target ? { clientId, target } : UNAUTHORIZED;
@@ -333,7 +365,8 @@ function appWebhookRoute(config) {
333
365
  kind: "webhook",
334
366
  handle: /* @__PURE__ */ __name(async (request) => {
335
367
  const admitted = await admitApp(config, request);
336
- return "status" in admitted ? admitted : deliverAdmitted(config, admitted);
368
+ if ("status" in admitted) return admitted;
369
+ return "unclaimed" in admitted ? deliverUnclaimed(config, admitted) : deliverAdmitted(config, admitted);
337
370
  }, "handle")
338
371
  };
339
372
  }
@@ -770,4 +803,4 @@ export {
770
803
  MARKETPLACE_JOBS,
771
804
  createApiMarketplace
772
805
  };
773
- //# sourceMappingURL=chunk-C2MFGZ3H.js.map
806
+ //# sourceMappingURL=chunk-PXMOEX3T.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server/http.ts","../src/server/link-routes.ts","../src/server/webhook.ts","../src/server/routes.ts","../src/server/jobs.ts","../src/server/index.ts"],"sourcesContent":["import type { z } from \"zod\";\n\nimport type { WireResponse } from \"@12-apps/wiring\";\n\nimport type { MarketplaceEngine } from \"../core/engine\";\nimport type { MarketplaceLogger } from \"../core/ports\";\nimport type { MarketplaceServerCopy } from \"./copy\";\n\n/**\n * What the route descriptors share: the config, the actor, and the two answer\n * shapes every handler uses.\n */\n\n/** Whoever the host resolved: the tenant this request may act inside. */\nexport interface MarketplaceActor {\n /** The tenant's id — every engine call is scoped to it. */\n clientId: string;\n /** The person, for the audit line an archive writes. Null for a system caller. */\n userId?: string | null;\n}\n\nexport interface MarketplaceApiConfig {\n /** The mounted engine (`createMarketplaceEngine`). */\n engine: MarketplaceEngine;\n /** Every sentence the routes answer a person with. Required, no defaults. */\n copy: MarketplaceServerCopy;\n /**\n * Which tenant a webhook's URL slug names, or null for none. The webhook is\n * unauthenticated by design (a marketplace cannot sign in), so the tenant\n * comes from the URL and is then proved by that tenant's signature secret.\n */\n tenantBySlug: (slug: string) => Promise<string | null>;\n /** Where the routes say what they refused. The manifest's `marketplace` namespace. */\n logger: MarketplaceLogger;\n}\n\n/** A 200 in the `{ data }` envelope. */\nexport function ok(data: unknown): WireResponse {\n return { status: 200, body: { data } };\n}\n\n/** A refusal in the `{ error }` envelope, with any extra fields beside it. */\nexport function refuse(status: number, error: string, extra: Record<string, unknown> = {}): WireResponse {\n return { status, body: { error, ...extra } };\n}\n\n/** The parsed value, or the 422 that names every problem and its path. */\nexport function parse<T>(\n schema: z.ZodType<T>,\n value: unknown,\n copy: MarketplaceServerCopy,\n): { ok: true; value: T } | { ok: false; response: WireResponse } {\n const parsed = schema.safeParse(value ?? {});\n if (parsed.success) return { ok: true, value: parsed.data };\n const problems = parsed.error.issues.map((issue) => ({\n path: issue.path.map((segment) => (typeof segment === \"number\" ? segment : String(segment))),\n code: \"INVALID_INPUT\",\n message: issue.message,\n }));\n return { ok: false, response: refuse(422, copy.invalidInput, { problems }) };\n}\n\n/** An ISO string, or null. */\nexport function iso(value: Date | null | undefined): string | null {\n return value ? value.toISOString() : null;\n}\n","import type { WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { MarketplaceIntegrationView } from \"../core/integration\";\nimport type { LinkFailure, LinkPendingView, LinkRefusalCode } from \"../core/linking\";\nimport { MARKETPLACE_MANAGE } from \"./contribution\";\nimport { iso, ok, parse, refuse, type MarketplaceActor, type MarketplaceApiConfig } from \"./http\";\nimport {\n cancelLinkBody,\n checkLinkBody,\n finishLinkBody,\n linkMerchantsQuery,\n linkStateQuery,\n selectLinkMerchantBody,\n startLinkBody,\n} from \"./mcp-link\";\n\n/**\n * Linking a store through the software's own marketplace app (FUT-5613), as\n * HTTP, beside the connection routes and behind the same permission:\n *\n * - `GET …/marketplace/link?provider=` — whether linking is available, and the code in progress;\n * - `POST …/marketplace/link/start` — a new portal code (the verifier stays on the server);\n * - `POST …/marketplace/link/finish` — the pasted authorization code, for the store's tokens;\n * - `GET …/marketplace/link/merchants?provider=` — the marketplace stores the grant covers;\n * - `PUT …/marketplace/link/merchant` — which of them this store is;\n * - `POST …/marketplace/link/check` — centralized linking (FUT-5798): ask the app's list now;\n * - `POST …/marketplace/link/cancel` — Cancelar: end the linking in progress.\n *\n * No answer ever carries a token, a verifier or the app's credentials.\n */\n\nconst BASE = \"/admin/:tenantSlug/marketplace/link\";\n\n/** The HTTP status each refusal answers. */\nconst STATUS: Readonly<Record<LinkRefusalCode, number>> = {\n UNAVAILABLE: 409,\n NO_LINK_IN_PROGRESS: 409,\n LINK_EXPIRED: 409,\n CODE_REFUSED: 422,\n MARKETPLACE_REFUSED: 502,\n NOT_LINKED: 409,\n UNKNOWN_MERCHANT: 422,\n MERCHANT_TAKEN: 409,\n};\n\n/** A failure as the routes answer it: the host's sentence, the code, and the marketplace's own words. */\nfunction failed(config: MarketplaceApiConfig, failure: LinkFailure): WireResponse {\n const words = config.copy.link;\n if (failure.kind === \"retry\") {\n return refuse(503, words?.tryAgain ?? \"MARKETPLACE_UNREACHABLE\", { code: \"MARKETPLACE_UNREACHABLE\" });\n }\n return refuse(STATUS[failure.code], words?.problems[failure.code] ?? failure.code, {\n code: failure.code,\n ...(failure.message === null ? {} : { marketplaceStatus: failure.status, marketplaceMessage: failure.message }),\n });\n}\n\nconst pendingOut = (pending: LinkPendingView | null) =>\n pending\n ? {\n ...pending,\n expiresAt: pending.expiresAt.toISOString(),\n ...(pending.seenAt === undefined ? {} : { seenAt: iso(pending.seenAt) }),\n ...(pending.checkedAt === undefined ? {} : { checkedAt: iso(pending.checkedAt) }),\n }\n : null;\n\nfunction connectionOut(row: MarketplaceIntegrationView) {\n return { ...row, lastEventAt: iso(row.lastEventAt), lastVerifiedAt: iso(row.lastVerifiedAt), archivedAt: iso(row.archivedAt) };\n}\n\n/** An unknown provider, before anything is asked of the engine. */\nfunction unknown(config: MarketplaceApiConfig, id: string): WireResponse | null {\n return config.engine.knows(id) ? null : refuse(422, config.copy.problems.UNKNOWN_PROVIDER, { code: \"UNKNOWN_PROVIDER\" });\n}\n\nfunction readRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(linkStateQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const state = await engine.linkState({ clientId: actor.clientId, ...parsed.value });\n return ok({ available: state.available, pending: pendingOut(state.pending) });\n },\n },\n {\n method: \"GET\",\n path: `${BASE}/merchants`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(linkMerchantsQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const result = await engine.linkedMerchants({ clientId: actor.clientId, provider: parsed.value.provider });\n return result.kind === \"listed\" ? ok(result.merchants) : failed(config, result);\n },\n },\n ];\n}\n\nfunction writeRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"POST\",\n path: `${BASE}/start`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(startLinkBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const result = await engine.startLink({ clientId: actor.clientId, ...parsed.value });\n return result.kind === \"started\" ? ok(pendingOut(result.pending)) : failed(config, result);\n },\n },\n {\n method: \"POST\",\n path: `${BASE}/finish`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(finishLinkBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const result = await engine.finishLink({ clientId: actor.clientId, actorId: actor.userId ?? null, ...parsed.value });\n if (result.kind !== \"linked\") return failed(config, result);\n return ok({ integration: connectionOut(result.integration), merchants: result.merchants });\n },\n },\n {\n method: \"PUT\",\n path: `${BASE}/merchant`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(selectLinkMerchantBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const result = await engine.selectLinkedMerchant({ clientId: actor.clientId, actorId: actor.userId ?? null, ...parsed.value });\n return result.kind === \"selected\" ? ok({ integration: connectionOut(result.integration) }) : failed(config, result);\n },\n },\n ...appRoutes(config),\n ];\n}\n\n/** Centralized linking (FUT-5798): the manual check, and Cancelar. */\nfunction appRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"POST\",\n path: `${BASE}/check`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(checkLinkBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const result = await engine.checkLink({ clientId: actor.clientId, provider: parsed.value.provider });\n return result.kind === \"checked\" ? ok({ pending: pendingOut(result.pending), merchants: result.merchants }) : failed(config, result);\n },\n },\n {\n method: \"POST\",\n path: `${BASE}/cancel`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(cancelLinkBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n await engine.cancelLink({ clientId: actor.clientId, provider: parsed.value.provider });\n return ok({ cancelled: true });\n },\n },\n ];\n}\n\n/** The linking routes, in mount order. */\nexport function linkRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n return [...readRoutes(config), ...writeRoutes(config)];\n}\n","import type { WireRequest, WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { PresenceProbe } from \"../core/adapter\";\nimport type { IngestionTarget } from \"../core/integration\";\nimport type { MarketplaceApiConfig } from \"./http\";\n\n/**\n * `POST /webhooks/marketplace/:tenantSlug/:provider` — inbound deliveries for\n * ONE store, from any registered marketplace.\n *\n * PUBLIC by design (`kind: \"webhook\"`): a marketplace cannot authenticate as a\n * user. The store is attributed from the URL slug, then the delivery is\n * verified against THAT store's secret, through the provider's own adapter\n * (which header carries the signature, and how it is computed) — the route\n * itself knows no marketplace.\n *\n * It answers 2xx for almost everything, deliberately: 200, or the status the\n * adapter states (`webhookAnswerStatus`: iFood's 202, FUT-5984). A marketplace\n * redelivers on any non-2xx, so the only failures worth signalling are the\n * ones a redelivery could fix: a genuine processing failure answers 500, and\n * the inbox row it left is retried by the sweep regardless. Refusals (unknown\n * slug, no connection, bad signature) answer 401, indistinguishably, so a\n * prober cannot learn which stores exist. The bodies are machine codes: the\n * reader is a server, not a person.\n */\n\nconst UNAUTHORIZED: WireResponse = { status: 401, body: { error: \"unauthorized\" } };\n\n/**\n * The tenant the slug names and its connection to this marketplace, or the\n * 401 that ends the request. A blob that will not open is a 401 too, logged:\n * a key problem must never read as \"no secret configured\".\n */\nasync function connectionOf(\n config: MarketplaceApiConfig,\n tenantSlug: string,\n provider: string,\n): Promise<{ clientId: string; target: IngestionTarget } | WireResponse> {\n const clientId = await config.tenantBySlug(tenantSlug);\n if (!clientId) {\n config.logger.warn(`marketplace.webhook: unknown tenant slug \"${tenantSlug}\" (${provider})`);\n return UNAUTHORIZED;\n }\n try {\n const target = await config.engine.target(clientId, provider);\n // No connection at all: refused rather than stored — without one there is\n // no secret to verify against.\n return target ? { clientId, target } : UNAUTHORIZED;\n } catch (error) {\n config.logger.error(\n `marketplace.webhook: ${tenantSlug} ${provider} credentials do not open: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n return UNAUTHORIZED;\n }\n}\n\n/** The verified, parsed delivery, or the answer that ends the request. */\nasync function admit(\n config: MarketplaceApiConfig,\n request: WireRequest<unknown>,\n): Promise<{ clientId: string; provider: string; payload: unknown; target: IngestionTarget } | WireResponse> {\n const { tenantSlug = \"\", provider = \"\" } = request.params;\n const { engine } = config;\n if (!engine.knows(provider)) return { status: 404, body: { error: \"unknown_provider\" } };\n const raw = request.request;\n if (!raw) return { status: 400, body: { error: \"raw_request_required\" } };\n\n const connection = await connectionOf(config, tenantSlug, provider);\n if (\"status\" in connection) return connection;\n const rawBody = await raw.text();\n const signature = engine.readSignature(provider, (name) => raw.headers.get(name));\n if (!engine.verifySignature(provider, rawBody, signature, connection.target.webhookSecret)) {\n config.logger.warn(`marketplace.webhook: ${tenantSlug} ${provider} signature rejected`);\n return UNAUTHORIZED;\n }\n try {\n return { ...connection, provider, payload: JSON.parse(rawBody) as unknown };\n } catch {\n return { status: 400, body: { error: \"invalid_json\" } };\n }\n}\n\ninterface Admitted {\n clientId: string;\n provider: string;\n payload: unknown;\n target: IngestionTarget;\n}\n\n/** Record and act on one verified delivery. */\nasync function handleWebhook(config: MarketplaceApiConfig, request: WireRequest<unknown>): Promise<WireResponse> {\n const admitted = await admit(config, request);\n if (\"status\" in admitted) return admitted;\n return deliverAdmitted(config, admitted);\n}\n\n/**\n * The answer to a proven presence heartbeat (FUT-5984, iFood's `KEEPALIVE`):\n * 202, and in the per-merchant mode every merchant it asked about named\n * online. Nothing is recorded.\n */\nfunction presenceAnswer(probe: PresenceProbe): WireResponse {\n return probe.merchantIds === null\n ? { status: 202, body: { received: true } }\n : { status: 202, body: { merchantIds: [...probe.merchantIds] } };\n}\n\n/** Record and act on a delivery whose store and signature are proven. */\nasync function deliverAdmitted(config: MarketplaceApiConfig, admitted: Admitted): Promise<WireResponse> {\n const { clientId, provider, payload, target } = admitted;\n const { engine } = config;\n const probe = engine.presence(provider, payload);\n if (probe) return presenceAnswer(probe);\n const status = engine.answerStatus(provider);\n\n const event = engine.normalize(provider, payload);\n if (!event) {\n // Nothing the adapter can key on. 2xx: redelivering an unreadable payload\n // produces an identical unreadable payload.\n config.logger.warn(`marketplace.webhook: ${provider} payload did not normalize`);\n return { status, body: { received: true, ignored: \"unrecognized_payload\" } };\n }\n const outcome = await engine.deliver({\n clientId,\n event,\n payload,\n // A DISABLED connection still stores its deliveries and ingests nothing;\n // the retry sweep ingests them if the store turns it back on.\n settings: target.enabled\n ? { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds, followStatus: target.followStatus }\n : null,\n });\n if (outcome.kind === \"failed\") {\n return { status: 500, body: { received: true, error: outcome.reason } };\n }\n // After the inbox row is written: iFood's 202 means \"recorded\" (FUT-5984).\n return { status, body: { received: true, outcome: outcome.kind } };\n}\n\n/** A proven delivery to the app's address that no single store holds: recorded with no store, never acted on. */\ninterface Unclaimed {\n unclaimed: true;\n provider: string;\n payload: unknown;\n}\n\n/**\n * The store a delivery to the APP's single address belongs to, and its\n * connection (FUT-5613).\n *\n * The marketplace signs every delivery to this address with the APP's key\n * (its webhook key, else its client secret), whichever way the store's own\n * connection authenticates (FUT-6363): a store connected through the\n * credentials form keeps its own key, or none, and checking an app delivery\n * against it refused every order event while the heartbeat, already checked\n * against the app, passed. So the app's key is checked FIRST, before any\n * store is looked up; a store's own key is still accepted once the store is\n * found. Nothing unsigned is ever admitted.\n *\n * An app-signed delivery whose merchant no single live connection holds is\n * genuine, so it is answered 2xx and recorded with no store (`Unclaimed`):\n * a 401 would only make the marketplace redeliver it until it disabled the\n * subscription, and the stored row is how a half-finished link is found.\n */\nasync function admitApp(\n config: MarketplaceApiConfig,\n request: WireRequest<unknown>,\n): Promise<Admitted | Unclaimed | WireResponse> {\n const read = await readAppDelivery(config, request);\n if (\"status\" in read) return read;\n const { provider, payload } = read;\n const signedByApp = await appSigned(config, read);\n // A presence heartbeat names no store: proved by the app's own key, with no statement (FUT-5984).\n const probe = config.engine.presence(provider, payload);\n if (probe) return signedByApp ? presenceAnswer(probe) : UNAUTHORIZED;\n const found = await appConnection(config, provider, payload);\n if (\"status\" in found) return found;\n if (\"unheld\" in found) {\n if (!signedByApp) return UNAUTHORIZED;\n config.logger.warn(`marketplace.webhook: app ${provider} delivery names a merchant no single store holds; recorded`);\n return { unclaimed: true, provider, payload };\n }\n // The app's address never takes an unsigned delivery, whatever the store's own setting.\n if (!signedByApp && !signedByStore(config, read, found.target.webhookSecret)) {\n config.logger.warn(`marketplace.webhook: app ${provider} delivery for ${found.clientId} refused`);\n return UNAUTHORIZED;\n }\n return { ...found, provider, payload };\n}\n\n/** A delivery to the app's address, read: its marketplace, bytes, JSON and signature, or the answer that ends it. */\ninterface AppDelivery {\n provider: string;\n rawBody: string;\n payload: unknown;\n signature: string | null;\n}\n\nasync function readAppDelivery(config: MarketplaceApiConfig, request: WireRequest<unknown>): Promise<AppDelivery | WireResponse> {\n const { provider = \"\" } = request.params;\n if (!config.engine.knows(provider)) return { status: 404, body: { error: \"unknown_provider\" } };\n const raw = request.request;\n if (!raw) return { status: 400, body: { error: \"raw_request_required\" } };\n const rawBody = await raw.text();\n const payload = parsedJson(rawBody);\n if (payload === undefined) return { status: 400, body: { error: \"invalid_json\" } };\n return { provider, rawBody, payload, signature: config.engine.readSignature(provider, (name) => raw.headers.get(name)) };\n}\n\n/**\n * Whether the app's key signed the delivery. A host credentials port that\n * throws proves nothing (logged): the store's own key may still prove it, and\n * the marketplace redelivers a refusal.\n */\nasync function appSigned(config: MarketplaceApiConfig, delivery: AppDelivery): Promise<boolean> {\n try {\n return await config.engine.signedByApp(delivery.provider, delivery.rawBody, delivery.signature);\n } catch (error) {\n config.logger.error(`marketplace.webhook: app ${delivery.provider} key unavailable: ${String(error)}`);\n return false;\n }\n}\n\n/** Whether the store's OWN key, when it has one, signed the delivery. An absent key proves nothing. */\nfunction signedByStore(config: MarketplaceApiConfig, delivery: AppDelivery, secret: string | null): boolean {\n if (secret === null || secret === \"\") return false;\n return config.engine.verifySignature(delivery.provider, delivery.rawBody, delivery.signature, secret);\n}\n\n/** Record a proven delivery no store holds (`no tenant claims this merchant`), and answer it as recorded. */\nasync function deliverUnclaimed(config: MarketplaceApiConfig, unclaimed: Unclaimed): Promise<WireResponse> {\n const { provider, payload } = unclaimed;\n const status = config.engine.answerStatus(provider);\n const event = config.engine.normalize(provider, payload);\n if (!event) return { status, body: { received: true, ignored: \"unrecognized_payload\" } };\n const outcome = await config.engine.deliver({ clientId: null, event, payload, settings: null });\n if (outcome.kind === \"failed\") return { status: 500, body: { received: true, error: outcome.reason } };\n return { status, body: { received: true, outcome: outcome.kind } };\n}\n\n/** A JSON body, or undefined when it is not JSON. */\nfunction parsedJson(rawBody: string): unknown {\n try {\n return JSON.parse(rawBody) as unknown;\n } catch {\n return undefined;\n }\n}\n\n/** The store whose live connection holds the merchant a delivery names, or the 401. */\nasync function appConnection(\n config: MarketplaceApiConfig,\n provider: string,\n payload: unknown,\n): Promise<{ clientId: string; target: IngestionTarget } | { unheld: true } | WireResponse> {\n const merchantId = config.engine.normalize(provider, payload)?.externalMerchantId ?? null;\n const clientId = merchantId === null ? null : await config.engine.tenantFor(provider, merchantId);\n // No single live connection holds the merchant: the only case a proven delivery may be recorded with no store.\n if (!clientId) return { unheld: true };\n try {\n const target = await config.engine.target(clientId, provider);\n return target ? { clientId, target } : UNAUTHORIZED;\n } catch (error) {\n config.logger.error(`marketplace.webhook: app ${provider} key of ${clientId} unavailable: ${String(error)}`);\n return UNAUTHORIZED;\n }\n}\n\n/**\n * `POST /webhooks/marketplace/:provider` — the ONE address the software's own\n * app registers with a marketplace, for every store linked through it\n * (FUT-5613). The delivery must carry the app's valid signature (or, once its\n * store is found, that store's own): unsigned or mis-signed is refused here.\n * The store is found by the merchant id the delivery names; a proven delivery\n * no single store holds is recorded with none (FUT-6363).\n */\nexport function appWebhookRoute(config: MarketplaceApiConfig): WireRoute<unknown> {\n return {\n method: \"POST\",\n path: \"/webhooks/marketplace/:provider\",\n kind: \"webhook\",\n handle: async (request) => {\n const admitted = await admitApp(config, request);\n if (\"status\" in admitted) return admitted;\n return \"unclaimed\" in admitted ? deliverUnclaimed(config, admitted) : deliverAdmitted(config, admitted);\n },\n };\n}\n\n/** The webhook descriptor. Raw body required: signatures are computed over bytes. */\nexport function webhookRoute(config: MarketplaceApiConfig): WireRoute<unknown> {\n return {\n method: \"POST\",\n path: \"/webhooks/marketplace/:tenantSlug/:provider\",\n kind: \"webhook\",\n handle: (request) => handleWebhook(config, request),\n };\n}\n","import type { WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { BulkProblem } from \"../core/bulk\";\nimport type { DecisionProblem } from \"../core/cancellation\";\nimport type { MarketplaceIntegrationView } from \"../core/integration\";\nimport type { MarketplaceMenuLinkView } from \"../core/menu-links\";\nimport { MARKETPLACE_DECIDE, MARKETPLACE_MANAGE } from \"./contribution\";\nimport type { MarketplaceServerCopy } from \"./copy\";\nimport { iso, ok, parse, refuse, type MarketplaceActor, type MarketplaceApiConfig } from \"./http\";\nimport {\n decideMarketplaceOrdersBody,\n listMarketplaceAcceptancesQuery,\n listMarketplaceIntegrationsQuery,\n listMarketplaceMenuLinksQuery,\n upsertMarketplaceIntegrationsBody,\n upsertMarketplaceMenuLinksBody,\n} from \"./mcp\";\nimport { linkRoutes } from \"./link-routes\";\nimport { appWebhookRoute, webhookRoute } from \"./webhook\";\n\n/**\n * The marketplace HTTP surface as framework-neutral wiring descriptors: the\n * webhook every marketplace posts to, and, per entity, one read and one bulk\n * write — connections, SKU links, decisions — for a store's staff and its MCP\n * tools alike.\n *\n * There is no authentication, tenant resolution or RBAC in here: each\n * descriptor DECLARES the permission it needs and the host's guard answers it;\n * the actor arrives already resolved. Paths are relative to the host's mount.\n */\n\nexport type MarketplaceRoute = WireRoute<MarketplaceActor> | WireRoute<unknown>;\n\nconst BASE = \"/admin/:tenantSlug/marketplace\";\n\n/** The 409 code of a decision on an order that is no longer on the clock. */\nexport const ORDER_NOT_PENDING_CODE = \"MARKETPLACE_ORDER_NOT_PENDING\";\n\nconst NOT_PENDING = new Set([\"NOT_FOUND\", \"ALREADY_DECIDED\", \"EXPIRED\", \"CONFLICT\"]);\n\n/** A connection as the read returns it: dates as ISO, the adapter's half beside it. */\nfunction integrationOut(config: MarketplaceApiConfig, row: MarketplaceIntegrationView) {\n const adapter = config.engine.adapter(row.provider);\n return {\n ...row,\n lastEventAt: iso(row.lastEventAt),\n lastVerifiedAt: iso(row.lastVerifiedAt),\n archivedAt: iso(row.archivedAt),\n capabilities: adapter ? adapter.capabilities : null,\n reasons: adapter ? [...adapter.cancellationReasons()] : [],\n };\n}\n\nfunction linkOut(link: MarketplaceMenuLinkView) {\n return { ...link, lastSeenAt: link.lastSeenAt.toISOString() };\n}\n\n/** Each problem with its sentence; a host refusal keeps the host's own words. */\nfunction problemsOut(copy: MarketplaceServerCopy, problems: readonly (BulkProblem | DecisionProblem)[]) {\n return problems.map((problem) => {\n const host = \"host\" in problem ? problem.host : undefined;\n return {\n ...problem,\n message: host?.message ?? (problem.code === \"MERCHANT_TAKEN\" ? (copy.link?.problems.MERCHANT_TAKEN ?? problem.code) : copy.problems[problem.code]),\n ...(host ? { hostCode: host.code, details: host.details } : {}),\n };\n });\n}\n\n/** A refused bulk write: 422, nothing saved, every problem with its path. */\nfunction refusedBulk(copy: MarketplaceServerCopy, problems: readonly BulkProblem[]): WireResponse {\n return refuse(422, copy.nothingSaved, { problems: problemsOut(copy, problems) });\n}\n\n/**\n * A refused decision call. The host's own refusal is a 409 carrying ITS code\n * (`MARKETPLACE_STOCK_ASK` and the short lines in `details`); an order no\n * longer on the clock a 409; anything else (a reason, an item) a 422.\n */\nfunction refusedDecisions(copy: MarketplaceServerCopy, problems: readonly DecisionProblem[]): WireResponse {\n const out = problemsOut(copy, problems);\n const host = problems.find((problem) => problem.code === \"HOST_REFUSED\")?.host;\n if (host) return refuse(409, host.message, { code: host.code, details: host.details, problems: out });\n if (problems.some((problem) => NOT_PENDING.has(problem.code))) {\n return refuse(409, copy.orderNoLongerPending, { code: ORDER_NOT_PENDING_CODE, problems: out });\n }\n return refuse(422, copy.nothingSaved, { problems: out });\n}\n\nfunction integrationRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceIntegrationsQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const rows = await engine.integrations(actor.clientId, {\n providers: parsed.value.ids,\n includeArchived: parsed.value.includeArchived === \"true\",\n });\n return ok(rows.map((row) => integrationOut(config, row)));\n },\n },\n {\n method: \"PUT\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(upsertMarketplaceIntegrationsBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.upsertIntegrations({\n clientId: actor.clientId,\n actorId: actor.userId ?? null,\n validateOnly: parsed.value.validateOnly,\n rows: parsed.value.integrations.map((row) =>\n \"credentials\" in row && row.credentials\n ? { ...row, credentials: { ...row.credentials, webhookSecret: row.credentials.webhookSecret ?? null } }\n : row,\n ) as Parameters<typeof engine.upsertIntegrations>[0][\"rows\"],\n });\n if (result.kind === \"refused\") return refusedBulk(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, integrations: result.rows.map((row) => integrationOut(config, row)) });\n },\n },\n ];\n}\n\nfunction menuLinkRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: `${BASE}/menu-links`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceMenuLinksQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const links = await engine.menuLinks({\n clientId: actor.clientId,\n provider: parsed.value.provider,\n unmappedOnly: parsed.value.unmapped === \"true\",\n ids: parsed.value.ids,\n });\n return ok(links.map(linkOut));\n },\n },\n {\n method: \"PUT\",\n path: `${BASE}/menu-links`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(upsertMarketplaceMenuLinksBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.upsertMenuLinks({\n clientId: actor.clientId,\n rows: parsed.value.links,\n validateOnly: parsed.value.validateOnly,\n });\n if (result.kind === \"refused\") return refusedBulk(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, links: result.rows.map(linkOut) });\n },\n },\n ];\n}\n\nfunction acceptanceRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: `${BASE}/acceptances`,\n permission: MARKETPLACE_DECIDE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceAcceptancesQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const pending = await engine.pending(actor.clientId, parsed.value.ids);\n return ok(\n pending.map((order) => ({\n ...order,\n acknowledgeBy: iso(order.acknowledgeBy),\n externalDueAt: iso(order.externalDueAt),\n })),\n );\n },\n },\n {\n method: \"POST\",\n path: `${BASE}/acceptances`,\n permission: MARKETPLACE_DECIDE,\n handle: async ({ actor, body }) => {\n const parsed = parse(decideMarketplaceOrdersBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.decideMany({\n clientId: actor.clientId,\n decisions: parsed.value.decisions,\n validateOnly: parsed.value.validateOnly,\n });\n if (result.kind === \"refused\") return refusedDecisions(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, decisions: result.rows });\n },\n },\n ];\n}\n\n/** The whole surface, in mount order. */\nexport function marketplaceRoutes(config: MarketplaceApiConfig): MarketplaceRoute[] {\n return [\n webhookRoute(config),\n appWebhookRoute(config),\n ...integrationRoutes(config),\n ...linkRoutes(config),\n ...menuLinkRoutes(config),\n ...acceptanceRoutes(config),\n ];\n}\n","import type { JobsContribution, WireJobBlueprint } from \"@12-apps/wiring\";\n\nimport type { MarketplaceEngine } from \"../core/engine\";\nimport { CatalogueRetryError, type CatalogueJobPayload } from \"../core/catalogue-job\";\nimport { AcknowledgeRetryError, type AcknowledgeJobPayload } from \"../core/acknowledge\";\nimport { FetchOrderRetryError, type FetchOrderJobPayload } from \"../core/fetch-order\";\nimport { CancellationReasonsRetryError, type CancellationReasonsJobPayload } from \"../core/order-reasons\";\nimport { OutboundRetryError } from \"../core/outbound\";\nimport type { OutboundJobPayload } from \"../core/outbound-queue\";\nimport { AvailabilityRetryError } from \"../core/pause-job\";\nimport { DisputeAnswerRetryError, type DisputeAnswerJobPayload } from \"../core/dispute-job\";\nimport type { AvailabilityJobPayload } from \"../core/pause-store\";\n\n/**\n * The engine's eleven jobs, declared here because every number in them is the\n * engine's knowledge, not a host's:\n *\n * - `expire-acceptances`, every minute: the unit being measured is minutes (a\n * default window is five), so a coarser tick would make \"expired\" mean\n * anywhere from five to twenty.\n * - `reconcile-inbox`, every five minutes: nothing races a deadline here, and\n * each pass re-runs real ingestion work; the engine's attempt bound retires\n * a payload that will never succeed.\n * - `outbound`, on demand: one call to a marketplace, three attempts with\n * backoff. Its idempotency is the ROW's (the engine re-reads it), never the\n * queue's dedupe alone.\n * - `fetch-order`, on demand: one GET of an order a marketplace's event only\n * announced (`orderToFetch`), then the one ingest path. Three attempts with\n * backoff; the reconciliation sweep re-queues a row still owed.\n * - `acknowledge`, on demand: tells the marketplace a store's recorded events\n * were received (FUT-5984, iFood). Three attempts with backoff; the\n * reconcile pass re-queues a store still owing some.\n * - `cancellation-reasons`, on demand: reads one order's own cancellation\n * reasons once, after its ingest (FUT-5984, iFood). Three attempts; the\n * static list stays the fallback.\n * - `catalogue`, on demand: one publish or withdraw of one product on one\n * marketplace's catalogue (FUT-4768). Three attempts with backoff; the\n * last one stamps FAILED with a failure code.\n * - `outbound-sweep`, every five minutes: re-queues every call a row still\n * owes (a PENDING request, an accept with no confirm stamp, a catalogue\n * publish or withdraw on its way) once it is older than the job's own retry\n * span, so a refused enqueue or a dead process loses nothing.\n * - `availability`, on demand: brings one marketplace in line with the host's\n * last pause or resume ask for one store (FUT-4851). Three attempts with\n * backoff; the last one stamps FAILED with a failure code.\n * - `dispute-answer`, on demand: sends one store's answer to a buyer's\n * dispute (FUT-6099). Three attempts with backoff; the last gives the\n * answer back OPEN, and the outbound sweep re-queues one still owed.\n * - `availability-sweep`, every five minutes: resumes a pause past its\n * `until` (the host stopped renewing it), re-queues an ask still owed, and\n * gives up on one older than a day.\n *\n * What stays the host's: whether to run them at all, on which runtime, and the\n * lease implementation. A host with no worker declines `jobs` in writing.\n *\n * Bound with `{ engine }`, these arrive at a runner as\n * `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,\n * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.acknowledge`,\n * `marketplace.cancellation-reasons`, `marketplace.catalogue`,\n * `marketplace.outbound-sweep`, `marketplace.availability`,\n * `marketplace.availability-sweep`, `marketplace.link-check` and\n * `marketplace.dispute-answer`.\n */\n\n/** What the host closes over at bind time: the mounted engine. */\nexport interface MarketplaceJobDeps {\n engine: Pick<\n MarketplaceEngine,\n | \"expireLapsed\"\n | \"retryable\"\n | \"reprocess\"\n | \"runOutbound\"\n | \"runFetchOrder\"\n | \"runAcknowledge\"\n | \"sweepAcknowledgements\"\n | \"runCancellationReasons\"\n | \"runCatalogue\"\n | \"sweepOutbound\"\n | \"runAvailability\"\n | \"sweepAvailability\"\n | \"sweepLinks\"\n | \"runDisputeAnswer\"\n >;\n}\n\n/** The single-flight queue name (`@12-apps/jobs`' `SWEEP_QUEUE`), as a literal. */\nexport const MARKETPLACE_SWEEP_QUEUE = \"sweeps\";\n\n/** How long one sweep pass may hold its name. */\nconst SWEEP_LEASE_MS = 5 * 60_000;\n\n/** The outbound job's attempts: the last one stamps the failure. */\nexport const MARKETPLACE_OUTBOUND_ATTEMPTS = 3;\n\nconst expireAcceptances: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"expire-acceptances\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"* * * * *\", timezone: \"UTC\" },\n // Never retried by the queue: the next tick re-finds everything from the rows.\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.expireLapsed();\n if (result.expired === 0) return;\n context.logger.info(\n `marketplace.expire-acceptances: expired ${result.expired} order(s) across ${result.tenants} tenant(s).`,\n );\n },\n};\n\nconst reconcileInbox: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"reconcile-inbox\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const pending = await deps.engine.retryable();\n let ingested = 0;\n // One event's failure never wedges the batch: `reprocess` never throws.\n for (const event of pending) {\n const outcome = await deps.engine.reprocess(event);\n if (outcome.kind === \"ingested\") ingested += 1;\n }\n // The events still owed an acknowledgment are re-queued, one job per store (FUT-5984).\n const { requeued } = await deps.engine.sweepAcknowledgements();\n if (pending.length === 0 && requeued === 0) return;\n context.logger.info(\n `marketplace.reconcile-inbox: re-ran ${pending.length} stored delivery(ies), ${ingested} became order(s); ` +\n `re-queued the acknowledgment of ${requeued} store(s).`,\n );\n },\n};\n\nconst outbound: WireJobBlueprint<OutboundJobPayload, MarketplaceJobDeps> = {\n name: \"outbound\",\n attempts: MARKETPLACE_OUTBOUND_ATTEMPTS,\n backoff: { type: \"exponential\", delayMs: 30_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runOutbound(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.outbound: ${payload.action} ${payload.orderId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof OutboundRetryError) context.logger.warn(`marketplace.outbound: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The fetch job's attempts: the last one settles the inbox row FAILED. */\nexport const MARKETPLACE_FETCH_ORDER_ATTEMPTS = 3;\n\nconst fetchOrder: WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps> = {\n name: \"fetch-order\",\n attempts: MARKETPLACE_FETCH_ORDER_ATTEMPTS,\n // Short: an order waiting for its body is on the store's acceptance clock.\n backoff: { type: \"exponential\", delayMs: 5_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runFetchOrder(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.fetch-order: inbox ${payload.inboxId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof FetchOrderRetryError) context.logger.warn(`marketplace.fetch-order: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The acknowledgment's attempts: the last one leaves the events owed, for the reconcile pass. */\nconst MARKETPLACE_ACKNOWLEDGE_ATTEMPTS = 3;\n\nconst acknowledge: WireJobBlueprint<AcknowledgeJobPayload, MarketplaceJobDeps> = {\n name: \"acknowledge\",\n attempts: MARKETPLACE_ACKNOWLEDGE_ATTEMPTS,\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runAcknowledge(payload, { attempt: context.attempt, maxAttempts: context.maxAttempts });\n if (outcome.kind === \"skipped\") context.logger.info(`marketplace.acknowledge: ${payload.provider} ${payload.clientId} skipped: ${outcome.reason}`);\n } catch (error) {\n if (error instanceof AcknowledgeRetryError) context.logger.warn(`marketplace.acknowledge: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The reasons read's attempts: the last one leaves the static list in place. */\nconst MARKETPLACE_CANCELLATION_REASONS_ATTEMPTS = 3;\n\nconst cancellationReasons: WireJobBlueprint<CancellationReasonsJobPayload, MarketplaceJobDeps> = {\n name: \"cancellation-reasons\",\n attempts: MARKETPLACE_CANCELLATION_REASONS_ATTEMPTS,\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runCancellationReasons(payload, { attempt: context.attempt, maxAttempts: context.maxAttempts });\n if (outcome.kind === \"skipped\") context.logger.info(`marketplace.cancellation-reasons: ${payload.orderId} skipped: ${outcome.reason}`);\n } catch (error) {\n if (error instanceof CancellationReasonsRetryError) context.logger.warn(`marketplace.cancellation-reasons: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The catalogue job's attempts: the last one stamps FAILED. */\nconst MARKETPLACE_CATALOGUE_ATTEMPTS = 3;\n\nconst catalogue: WireJobBlueprint<CatalogueJobPayload, MarketplaceJobDeps> = {\n name: \"catalogue\",\n attempts: MARKETPLACE_CATALOGUE_ATTEMPTS,\n // Short: a person is watching the switch say \"sending\".\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runCatalogue(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.catalogue: ${payload.action} ${payload.publicationId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof CatalogueRetryError) context.logger.warn(`marketplace.catalogue: ${error.message}`);\n throw error;\n }\n },\n};\n\nconst outboundSweep: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"outbound-sweep\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.sweepOutbound();\n const idle = result.requeued + result.givenUp + result.timedOut + result.catalogueRequeued === 0;\n if (idle) return;\n context.logger.info(\n `marketplace.outbound-sweep: re-queued ${result.requeued} call(s) and ${result.catalogueRequeued} catalogue ` +\n `call(s), timed out ${result.timedOut} cancellation request(s), gave up on ${result.givenUp}.`,\n );\n },\n};\n\n/** The availability job's attempts: the last one stamps FAILED. */\nexport const MARKETPLACE_AVAILABILITY_ATTEMPTS = 3;\n\nconst availability: WireJobBlueprint<AvailabilityJobPayload, MarketplaceJobDeps> = {\n name: \"availability\",\n attempts: MARKETPLACE_AVAILABILITY_ATTEMPTS,\n // Short: a store is open on the marketplace while the kitchen is paused.\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runAvailability(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.availability: ${payload.provider} ${payload.clientId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof AvailabilityRetryError) context.logger.warn(`marketplace.availability: ${error.message}`);\n throw error;\n }\n },\n};\n\nconst availabilitySweep: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"availability-sweep\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.sweepAvailability();\n if (result.expired + result.requeued + result.givenUp === 0) return;\n context.logger.info(\n `marketplace.availability-sweep: resumed ${result.expired} expired pause(s), re-queued ${result.requeued}, ` +\n `gave up on ${result.givenUp}.`,\n );\n },\n};\n\n/**\n * `link-check` (FUT-5798), each minute and once more half a minute later\n * (queued by the tick, only while a store waits): every centralized link\n * attempt still waiting asks the app's list, and a store whose authorization\n * arrived is hinted. Never retried: the next pass re-finds it from the rows.\n */\nconst linkCheck: WireJobBlueprint<{ half?: boolean } | undefined, MarketplaceJobDeps> = {\n name: \"link-check\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"* * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (payload, deps, context) => {\n const result = await deps.engine.sweepLinks({ half: payload?.half === true });\n if (result.seen.length === 0) return;\n context.logger.info(`marketplace.link-check: saw the authorization of ${result.seen.length} store(s); ${result.waiting} still waiting.`);\n },\n};\n\n/** The dispute answer's attempts: the last one gives the answer back for a person to send again. */\nconst MARKETPLACE_DISPUTE_ANSWER_ATTEMPTS = 3;\n\nconst disputeAnswer: WireJobBlueprint<DisputeAnswerJobPayload, MarketplaceJobDeps> = {\n name: \"dispute-answer\",\n attempts: MARKETPLACE_DISPUTE_ANSWER_ATTEMPTS,\n // Short: the marketplace's deadline is minutes, and a person waits on the card.\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runDisputeAnswer(payload, { attempt: context.attempt, maxAttempts: context.maxAttempts });\n if (outcome.kind === \"skipped\") context.logger.info(`marketplace.dispute-answer: ${payload.disputeId} skipped: ${outcome.reason}`);\n } catch (error) {\n if (error instanceof DisputeAnswerRetryError) context.logger.warn(`marketplace.dispute-answer: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The jobs contribution. */\nexport const MARKETPLACE_JOBS = {\n namespace: \"marketplace\",\n blueprints: {\n \"expire-acceptances\": expireAcceptances,\n \"reconcile-inbox\": reconcileInbox,\n outbound,\n \"fetch-order\": fetchOrder,\n acknowledge,\n \"cancellation-reasons\": cancellationReasons,\n catalogue,\n \"outbound-sweep\": outboundSweep,\n availability,\n \"availability-sweep\": availabilitySweep,\n \"link-check\": linkCheck,\n \"dispute-answer\": disputeAnswer,\n },\n} as const satisfies JobsContribution<MarketplaceJobDeps>;\n","import type { MarketplaceEngine } from \"../core/engine\";\nimport type { MarketplaceApiConfig } from \"./http\";\nimport { marketplaceRoutes, type MarketplaceRoute } from \"./routes\";\n\n/**\n * `@12-apps/marketplace/server` — the engine's HTTP surface, jobs, MCP tools\n * and permissions, as wiring-contract values.\n *\n * ```ts\n * const engine = createMarketplaceEngine({ …ports, adapters });\n * const api = createApiMarketplace({ engine, copy, tenantBySlug, logger });\n * // api.routes: mount under `/api` (the hono adapter does it in one line)\n * ```\n */\n\n/** What `createApiMarketplace` hands back: the routes, and the engine they serve. */\nexport interface ApiMarketplace {\n routes: MarketplaceRoute[];\n engine: MarketplaceEngine;\n}\n\n/** Build the route table over a mounted engine. */\nexport function createApiMarketplace(config: MarketplaceApiConfig): ApiMarketplace {\n if (!config.logger) {\n throw new Error(\"@12-apps/marketplace: the observability namespace needs a logger; pass `logger`.\");\n }\n return { routes: marketplaceRoutes(config), engine: config.engine };\n}\n\nexport type { MarketplaceActor, MarketplaceApiConfig } from \"./http\";\nexport type { MarketplaceRoute } from \"./routes\";\nexport type { MarketplaceLinkCopy, MarketplaceServerCopy } from \"./copy\";\nexport {\n MARKETPLACE_DECIDE,\n MARKETPLACE_MANAGE,\n MARKETPLACE_PERMISSIONS,\n} from \"./contribution\";\nexport {\n MARKETPLACE_AVAILABILITY_ATTEMPTS,\n MARKETPLACE_FETCH_ORDER_ATTEMPTS,\n MARKETPLACE_JOBS,\n MARKETPLACE_OUTBOUND_ATTEMPTS,\n MARKETPLACE_SWEEP_QUEUE,\n type MarketplaceJobDeps,\n} from \"./jobs\";\nexport {\n MARKETPLACE_MCP_TOOLS,\n decideMarketplaceOrdersBody,\n listMarketplaceAcceptancesQuery,\n listMarketplaceIntegrationsQuery,\n listMarketplaceMenuLinksQuery,\n marketplaceParams,\n upsertMarketplaceIntegrationsBody,\n upsertMarketplaceMenuLinksBody,\n} from \"./mcp\";\nexport { ORDER_NOT_PENDING_CODE } from \"./routes\";\nexport type { MarketplaceProblemCode } from \"./copy\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCO,SAAS,GAAG,MAA6B;AAC9C,SAAO,EAAE,QAAQ,KAAK,MAAM,EAAE,KAAK,EAAE;AACvC;AAFgB;AAKT,SAAS,OAAO,QAAgB,OAAe,QAAiC,CAAC,GAAiB;AACvG,SAAO,EAAE,QAAQ,MAAM,EAAE,OAAO,GAAG,MAAM,EAAE;AAC7C;AAFgB;AAKT,SAAS,MACd,QACA,OACA,MACgE;AAChE,QAAM,SAAS,OAAO,UAAU,SAAS,CAAC,CAAC;AAC3C,MAAI,OAAO,QAAS,QAAO,EAAE,IAAI,MAAM,OAAO,OAAO,KAAK;A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ACpB;AACF;;;AC7UO,SAAS,qBAAqB,QAA8C;AACjF,MAAI,CAAC,OAAO,QAAQ;AAClB,UAAM,IAAI,MAAM,kFAAkF;AAAA,EACpG;AACA,SAAO,EAAE,QAAQ,kBAAkB,MAAM,GAAG,QAAQ,OAAO,OAAO;AACpE;AALgB;","names":["BASE"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createApiMarketplace
3
- } from "../chunk-C2MFGZ3H.js";
3
+ } from "../chunk-PXMOEX3T.js";
4
4
  import "../chunk-LO7OKO6V.js";
5
5
  import "../chunk-T6A46MH3.js";
6
6
  import "../chunk-Q5RMVNU5.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  MARKETPLACE_JOBS,
3
3
  createApiMarketplace
4
- } from "../chunk-C2MFGZ3H.js";
4
+ } from "../chunk-PXMOEX3T.js";
5
5
  import "../chunk-LO7OKO6V.js";
6
6
  import "../chunk-T6A46MH3.js";
7
7
  import "../chunk-Q5RMVNU5.js";
@@ -6,7 +6,7 @@ import {
6
6
  MARKETPLACE_SWEEP_QUEUE,
7
7
  ORDER_NOT_PENDING_CODE,
8
8
  createApiMarketplace
9
- } from "../chunk-C2MFGZ3H.js";
9
+ } from "../chunk-PXMOEX3T.js";
10
10
  import {
11
11
  MARKETPLACE_DECIDE,
12
12
  MARKETPLACE_MANAGE,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/marketplace",
3
- "version": "1.20.1",
3
+ "version": "1.20.2",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "One marketplace integration engine for every marketplace: the durable inbox, the ingest pipeline, the acceptance clock and its sweep, the SKU map, the integration settings with sealed credentials, and the outbound engine (confirm, cancellation request, retries), behind an adapter port. Each marketplace is an adapter at its own subpath (./ifood, ./99food and ./keeta on Open Delivery, ./rappi). Framework-neutral wiring route descriptors (./server) with a Hono adapter (./hono), dep-free job blueprints, MCP tools and the package-owned Prisma partial + migrations.",
@@ -138,41 +138,107 @@ async function deliverAdmitted(config: MarketplaceApiConfig, admitted: Admitted)
138
138
  return { status, body: { received: true, outcome: outcome.kind } };
139
139
  }
140
140
 
141
+ /** A proven delivery to the app's address that no single store holds: recorded with no store, never acted on. */
142
+ interface Unclaimed {
143
+ unclaimed: true;
144
+ provider: string;
145
+ payload: unknown;
146
+ }
147
+
141
148
  /**
142
149
  * The store a delivery to the APP's single address belongs to, and its
143
- * connection: resolved from the merchant the payload names, then proved by
144
- * the signature (FUT-5613). The payload is read before it is verified only to
145
- * find whose key verifies it; nothing of it is acted on until it is.
150
+ * connection (FUT-5613).
151
+ *
152
+ * The marketplace signs every delivery to this address with the APP's key
153
+ * (its webhook key, else its client secret), whichever way the store's own
154
+ * connection authenticates (FUT-6363): a store connected through the
155
+ * credentials form keeps its own key, or none, and checking an app delivery
156
+ * against it refused every order event while the heartbeat, already checked
157
+ * against the app, passed. So the app's key is checked FIRST, before any
158
+ * store is looked up; a store's own key is still accepted once the store is
159
+ * found. Nothing unsigned is ever admitted.
160
+ *
161
+ * An app-signed delivery whose merchant no single live connection holds is
162
+ * genuine, so it is answered 2xx and recorded with no store (`Unclaimed`):
163
+ * a 401 would only make the marketplace redeliver it until it disabled the
164
+ * subscription, and the stored row is how a half-finished link is found.
146
165
  */
147
166
  async function admitApp(
148
167
  config: MarketplaceApiConfig,
149
168
  request: WireRequest<unknown>,
150
- ): Promise<Admitted | WireResponse> {
151
- const { provider = "" } = request.params;
152
- if (!config.engine.knows(provider)) return { status: 404, body: { error: "unknown_provider" } };
153
- const raw = request.request;
154
- if (!raw) return { status: 400, body: { error: "raw_request_required" } };
155
- const rawBody = await raw.text();
156
- const payload = parsedJson(rawBody);
157
- if (payload === undefined) return { status: 400, body: { error: "invalid_json" } };
169
+ ): Promise<Admitted | Unclaimed | WireResponse> {
170
+ const read = await readAppDelivery(config, request);
171
+ if ("status" in read) return read;
172
+ const { provider, payload } = read;
173
+ const signedByApp = await appSigned(config, read);
158
174
  // A presence heartbeat names no store: proved by the app's own key, with no statement (FUT-5984).
159
175
  const probe = config.engine.presence(provider, payload);
160
- if (probe) {
161
- const signature = config.engine.readSignature(provider, (name) => raw.headers.get(name));
162
- return (await config.engine.signedByApp(provider, rawBody, signature)) ? presenceAnswer(probe) : UNAUTHORIZED;
163
- }
176
+ if (probe) return signedByApp ? presenceAnswer(probe) : UNAUTHORIZED;
164
177
  const found = await appConnection(config, provider, payload);
165
178
  if ("status" in found) return found;
179
+ if ("unheld" in found) {
180
+ if (!signedByApp) return UNAUTHORIZED;
181
+ config.logger.warn(`marketplace.webhook: app ${provider} delivery names a merchant no single store holds; recorded`);
182
+ return { unclaimed: true, provider, payload };
183
+ }
166
184
  // The app's address never takes an unsigned delivery, whatever the store's own setting.
167
- const signature = config.engine.readSignature(provider, (name) => raw.headers.get(name));
168
- const secret = found.target.webhookSecret;
169
- if (!secret || !config.engine.verifySignature(provider, rawBody, signature, secret)) {
185
+ if (!signedByApp && !signedByStore(config, read, found.target.webhookSecret)) {
170
186
  config.logger.warn(`marketplace.webhook: app ${provider} delivery for ${found.clientId} refused`);
171
187
  return UNAUTHORIZED;
172
188
  }
173
189
  return { ...found, provider, payload };
174
190
  }
175
191
 
192
+ /** A delivery to the app's address, read: its marketplace, bytes, JSON and signature, or the answer that ends it. */
193
+ interface AppDelivery {
194
+ provider: string;
195
+ rawBody: string;
196
+ payload: unknown;
197
+ signature: string | null;
198
+ }
199
+
200
+ async function readAppDelivery(config: MarketplaceApiConfig, request: WireRequest<unknown>): Promise<AppDelivery | WireResponse> {
201
+ const { provider = "" } = request.params;
202
+ if (!config.engine.knows(provider)) return { status: 404, body: { error: "unknown_provider" } };
203
+ const raw = request.request;
204
+ if (!raw) return { status: 400, body: { error: "raw_request_required" } };
205
+ const rawBody = await raw.text();
206
+ const payload = parsedJson(rawBody);
207
+ if (payload === undefined) return { status: 400, body: { error: "invalid_json" } };
208
+ return { provider, rawBody, payload, signature: config.engine.readSignature(provider, (name) => raw.headers.get(name)) };
209
+ }
210
+
211
+ /**
212
+ * Whether the app's key signed the delivery. A host credentials port that
213
+ * throws proves nothing (logged): the store's own key may still prove it, and
214
+ * the marketplace redelivers a refusal.
215
+ */
216
+ async function appSigned(config: MarketplaceApiConfig, delivery: AppDelivery): Promise<boolean> {
217
+ try {
218
+ return await config.engine.signedByApp(delivery.provider, delivery.rawBody, delivery.signature);
219
+ } catch (error) {
220
+ config.logger.error(`marketplace.webhook: app ${delivery.provider} key unavailable: ${String(error)}`);
221
+ return false;
222
+ }
223
+ }
224
+
225
+ /** Whether the store's OWN key, when it has one, signed the delivery. An absent key proves nothing. */
226
+ function signedByStore(config: MarketplaceApiConfig, delivery: AppDelivery, secret: string | null): boolean {
227
+ if (secret === null || secret === "") return false;
228
+ return config.engine.verifySignature(delivery.provider, delivery.rawBody, delivery.signature, secret);
229
+ }
230
+
231
+ /** Record a proven delivery no store holds (`no tenant claims this merchant`), and answer it as recorded. */
232
+ async function deliverUnclaimed(config: MarketplaceApiConfig, unclaimed: Unclaimed): Promise<WireResponse> {
233
+ const { provider, payload } = unclaimed;
234
+ const status = config.engine.answerStatus(provider);
235
+ const event = config.engine.normalize(provider, payload);
236
+ if (!event) return { status, body: { received: true, ignored: "unrecognized_payload" } };
237
+ const outcome = await config.engine.deliver({ clientId: null, event, payload, settings: null });
238
+ if (outcome.kind === "failed") return { status: 500, body: { received: true, error: outcome.reason } };
239
+ return { status, body: { received: true, outcome: outcome.kind } };
240
+ }
241
+
176
242
  /** A JSON body, or undefined when it is not JSON. */
177
243
  function parsedJson(rawBody: string): unknown {
178
244
  try {
@@ -187,10 +253,11 @@ async function appConnection(
187
253
  config: MarketplaceApiConfig,
188
254
  provider: string,
189
255
  payload: unknown,
190
- ): Promise<{ clientId: string; target: IngestionTarget } | WireResponse> {
256
+ ): Promise<{ clientId: string; target: IngestionTarget } | { unheld: true } | WireResponse> {
191
257
  const merchantId = config.engine.normalize(provider, payload)?.externalMerchantId ?? null;
192
258
  const clientId = merchantId === null ? null : await config.engine.tenantFor(provider, merchantId);
193
- if (!clientId) return UNAUTHORIZED;
259
+ // No single live connection holds the merchant: the only case a proven delivery may be recorded with no store.
260
+ if (!clientId) return { unheld: true };
194
261
  try {
195
262
  const target = await config.engine.target(clientId, provider);
196
263
  return target ? { clientId, target } : UNAUTHORIZED;
@@ -203,8 +270,10 @@ async function appConnection(
203
270
  /**
204
271
  * `POST /webhooks/marketplace/:provider` — the ONE address the software's own
205
272
  * app registers with a marketplace, for every store linked through it
206
- * (FUT-5613). The store is found by the merchant id the delivery names, and
207
- * the delivery must carry a valid signature: unsigned is refused here.
273
+ * (FUT-5613). The delivery must carry the app's valid signature (or, once its
274
+ * store is found, that store's own): unsigned or mis-signed is refused here.
275
+ * The store is found by the merchant id the delivery names; a proven delivery
276
+ * no single store holds is recorded with none (FUT-6363).
208
277
  */
209
278
  export function appWebhookRoute(config: MarketplaceApiConfig): WireRoute<unknown> {
210
279
  return {
@@ -213,7 +282,8 @@ export function appWebhookRoute(config: MarketplaceApiConfig): WireRoute<unknown
213
282
  kind: "webhook",
214
283
  handle: async (request) => {
215
284
  const admitted = await admitApp(config, request);
216
- return "status" in admitted ? admitted : deliverAdmitted(config, admitted);
285
+ if ("status" in admitted) return admitted;
286
+ return "unclaimed" in admitted ? deliverUnclaimed(config, admitted) : deliverAdmitted(config, admitted);
217
287
  },
218
288
  };
219
289
  }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server/http.ts","../src/server/link-routes.ts","../src/server/webhook.ts","../src/server/routes.ts","../src/server/jobs.ts","../src/server/index.ts"],"sourcesContent":["import type { z } from \"zod\";\n\nimport type { WireResponse } from \"@12-apps/wiring\";\n\nimport type { MarketplaceEngine } from \"../core/engine\";\nimport type { MarketplaceLogger } from \"../core/ports\";\nimport type { MarketplaceServerCopy } from \"./copy\";\n\n/**\n * What the route descriptors share: the config, the actor, and the two answer\n * shapes every handler uses.\n */\n\n/** Whoever the host resolved: the tenant this request may act inside. */\nexport interface MarketplaceActor {\n /** The tenant's id — every engine call is scoped to it. */\n clientId: string;\n /** The person, for the audit line an archive writes. Null for a system caller. */\n userId?: string | null;\n}\n\nexport interface MarketplaceApiConfig {\n /** The mounted engine (`createMarketplaceEngine`). */\n engine: MarketplaceEngine;\n /** Every sentence the routes answer a person with. Required, no defaults. */\n copy: MarketplaceServerCopy;\n /**\n * Which tenant a webhook's URL slug names, or null for none. The webhook is\n * unauthenticated by design (a marketplace cannot sign in), so the tenant\n * comes from the URL and is then proved by that tenant's signature secret.\n */\n tenantBySlug: (slug: string) => Promise<string | null>;\n /** Where the routes say what they refused. The manifest's `marketplace` namespace. */\n logger: MarketplaceLogger;\n}\n\n/** A 200 in the `{ data }` envelope. */\nexport function ok(data: unknown): WireResponse {\n return { status: 200, body: { data } };\n}\n\n/** A refusal in the `{ error }` envelope, with any extra fields beside it. */\nexport function refuse(status: number, error: string, extra: Record<string, unknown> = {}): WireResponse {\n return { status, body: { error, ...extra } };\n}\n\n/** The parsed value, or the 422 that names every problem and its path. */\nexport function parse<T>(\n schema: z.ZodType<T>,\n value: unknown,\n copy: MarketplaceServerCopy,\n): { ok: true; value: T } | { ok: false; response: WireResponse } {\n const parsed = schema.safeParse(value ?? {});\n if (parsed.success) return { ok: true, value: parsed.data };\n const problems = parsed.error.issues.map((issue) => ({\n path: issue.path.map((segment) => (typeof segment === \"number\" ? segment : String(segment))),\n code: \"INVALID_INPUT\",\n message: issue.message,\n }));\n return { ok: false, response: refuse(422, copy.invalidInput, { problems }) };\n}\n\n/** An ISO string, or null. */\nexport function iso(value: Date | null | undefined): string | null {\n return value ? value.toISOString() : null;\n}\n","import type { WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { MarketplaceIntegrationView } from \"../core/integration\";\nimport type { LinkFailure, LinkPendingView, LinkRefusalCode } from \"../core/linking\";\nimport { MARKETPLACE_MANAGE } from \"./contribution\";\nimport { iso, ok, parse, refuse, type MarketplaceActor, type MarketplaceApiConfig } from \"./http\";\nimport {\n cancelLinkBody,\n checkLinkBody,\n finishLinkBody,\n linkMerchantsQuery,\n linkStateQuery,\n selectLinkMerchantBody,\n startLinkBody,\n} from \"./mcp-link\";\n\n/**\n * Linking a store through the software's own marketplace app (FUT-5613), as\n * HTTP, beside the connection routes and behind the same permission:\n *\n * - `GET …/marketplace/link?provider=` — whether linking is available, and the code in progress;\n * - `POST …/marketplace/link/start` — a new portal code (the verifier stays on the server);\n * - `POST …/marketplace/link/finish` — the pasted authorization code, for the store's tokens;\n * - `GET …/marketplace/link/merchants?provider=` — the marketplace stores the grant covers;\n * - `PUT …/marketplace/link/merchant` — which of them this store is;\n * - `POST …/marketplace/link/check` — centralized linking (FUT-5798): ask the app's list now;\n * - `POST …/marketplace/link/cancel` — Cancelar: end the linking in progress.\n *\n * No answer ever carries a token, a verifier or the app's credentials.\n */\n\nconst BASE = \"/admin/:tenantSlug/marketplace/link\";\n\n/** The HTTP status each refusal answers. */\nconst STATUS: Readonly<Record<LinkRefusalCode, number>> = {\n UNAVAILABLE: 409,\n NO_LINK_IN_PROGRESS: 409,\n LINK_EXPIRED: 409,\n CODE_REFUSED: 422,\n MARKETPLACE_REFUSED: 502,\n NOT_LINKED: 409,\n UNKNOWN_MERCHANT: 422,\n MERCHANT_TAKEN: 409,\n};\n\n/** A failure as the routes answer it: the host's sentence, the code, and the marketplace's own words. */\nfunction failed(config: MarketplaceApiConfig, failure: LinkFailure): WireResponse {\n const words = config.copy.link;\n if (failure.kind === \"retry\") {\n return refuse(503, words?.tryAgain ?? \"MARKETPLACE_UNREACHABLE\", { code: \"MARKETPLACE_UNREACHABLE\" });\n }\n return refuse(STATUS[failure.code], words?.problems[failure.code] ?? failure.code, {\n code: failure.code,\n ...(failure.message === null ? {} : { marketplaceStatus: failure.status, marketplaceMessage: failure.message }),\n });\n}\n\nconst pendingOut = (pending: LinkPendingView | null) =>\n pending\n ? {\n ...pending,\n expiresAt: pending.expiresAt.toISOString(),\n ...(pending.seenAt === undefined ? {} : { seenAt: iso(pending.seenAt) }),\n ...(pending.checkedAt === undefined ? {} : { checkedAt: iso(pending.checkedAt) }),\n }\n : null;\n\nfunction connectionOut(row: MarketplaceIntegrationView) {\n return { ...row, lastEventAt: iso(row.lastEventAt), lastVerifiedAt: iso(row.lastVerifiedAt), archivedAt: iso(row.archivedAt) };\n}\n\n/** An unknown provider, before anything is asked of the engine. */\nfunction unknown(config: MarketplaceApiConfig, id: string): WireResponse | null {\n return config.engine.knows(id) ? null : refuse(422, config.copy.problems.UNKNOWN_PROVIDER, { code: \"UNKNOWN_PROVIDER\" });\n}\n\nfunction readRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(linkStateQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const state = await engine.linkState({ clientId: actor.clientId, ...parsed.value });\n return ok({ available: state.available, pending: pendingOut(state.pending) });\n },\n },\n {\n method: \"GET\",\n path: `${BASE}/merchants`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(linkMerchantsQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const result = await engine.linkedMerchants({ clientId: actor.clientId, provider: parsed.value.provider });\n return result.kind === \"listed\" ? ok(result.merchants) : failed(config, result);\n },\n },\n ];\n}\n\nfunction writeRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"POST\",\n path: `${BASE}/start`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(startLinkBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const result = await engine.startLink({ clientId: actor.clientId, ...parsed.value });\n return result.kind === \"started\" ? ok(pendingOut(result.pending)) : failed(config, result);\n },\n },\n {\n method: \"POST\",\n path: `${BASE}/finish`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(finishLinkBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const result = await engine.finishLink({ clientId: actor.clientId, actorId: actor.userId ?? null, ...parsed.value });\n if (result.kind !== \"linked\") return failed(config, result);\n return ok({ integration: connectionOut(result.integration), merchants: result.merchants });\n },\n },\n {\n method: \"PUT\",\n path: `${BASE}/merchant`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(selectLinkMerchantBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const result = await engine.selectLinkedMerchant({ clientId: actor.clientId, actorId: actor.userId ?? null, ...parsed.value });\n return result.kind === \"selected\" ? ok({ integration: connectionOut(result.integration) }) : failed(config, result);\n },\n },\n ...appRoutes(config),\n ];\n}\n\n/** Centralized linking (FUT-5798): the manual check, and Cancelar. */\nfunction appRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"POST\",\n path: `${BASE}/check`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(checkLinkBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n const result = await engine.checkLink({ clientId: actor.clientId, provider: parsed.value.provider });\n return result.kind === \"checked\" ? ok({ pending: pendingOut(result.pending), merchants: result.merchants }) : failed(config, result);\n },\n },\n {\n method: \"POST\",\n path: `${BASE}/cancel`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(cancelLinkBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const refusal = unknown(config, parsed.value.provider);\n if (refusal) return refusal;\n await engine.cancelLink({ clientId: actor.clientId, provider: parsed.value.provider });\n return ok({ cancelled: true });\n },\n },\n ];\n}\n\n/** The linking routes, in mount order. */\nexport function linkRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n return [...readRoutes(config), ...writeRoutes(config)];\n}\n","import type { WireRequest, WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { PresenceProbe } from \"../core/adapter\";\nimport type { IngestionTarget } from \"../core/integration\";\nimport type { MarketplaceApiConfig } from \"./http\";\n\n/**\n * `POST /webhooks/marketplace/:tenantSlug/:provider` — inbound deliveries for\n * ONE store, from any registered marketplace.\n *\n * PUBLIC by design (`kind: \"webhook\"`): a marketplace cannot authenticate as a\n * user. The store is attributed from the URL slug, then the delivery is\n * verified against THAT store's secret, through the provider's own adapter\n * (which header carries the signature, and how it is computed) — the route\n * itself knows no marketplace.\n *\n * It answers 2xx for almost everything, deliberately: 200, or the status the\n * adapter states (`webhookAnswerStatus`: iFood's 202, FUT-5984). A marketplace\n * redelivers on any non-2xx, so the only failures worth signalling are the\n * ones a redelivery could fix: a genuine processing failure answers 500, and\n * the inbox row it left is retried by the sweep regardless. Refusals (unknown\n * slug, no connection, bad signature) answer 401, indistinguishably, so a\n * prober cannot learn which stores exist. The bodies are machine codes: the\n * reader is a server, not a person.\n */\n\nconst UNAUTHORIZED: WireResponse = { status: 401, body: { error: \"unauthorized\" } };\n\n/**\n * The tenant the slug names and its connection to this marketplace, or the\n * 401 that ends the request. A blob that will not open is a 401 too, logged:\n * a key problem must never read as \"no secret configured\".\n */\nasync function connectionOf(\n config: MarketplaceApiConfig,\n tenantSlug: string,\n provider: string,\n): Promise<{ clientId: string; target: IngestionTarget } | WireResponse> {\n const clientId = await config.tenantBySlug(tenantSlug);\n if (!clientId) {\n config.logger.warn(`marketplace.webhook: unknown tenant slug \"${tenantSlug}\" (${provider})`);\n return UNAUTHORIZED;\n }\n try {\n const target = await config.engine.target(clientId, provider);\n // No connection at all: refused rather than stored — without one there is\n // no secret to verify against.\n return target ? { clientId, target } : UNAUTHORIZED;\n } catch (error) {\n config.logger.error(\n `marketplace.webhook: ${tenantSlug} ${provider} credentials do not open: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n return UNAUTHORIZED;\n }\n}\n\n/** The verified, parsed delivery, or the answer that ends the request. */\nasync function admit(\n config: MarketplaceApiConfig,\n request: WireRequest<unknown>,\n): Promise<{ clientId: string; provider: string; payload: unknown; target: IngestionTarget } | WireResponse> {\n const { tenantSlug = \"\", provider = \"\" } = request.params;\n const { engine } = config;\n if (!engine.knows(provider)) return { status: 404, body: { error: \"unknown_provider\" } };\n const raw = request.request;\n if (!raw) return { status: 400, body: { error: \"raw_request_required\" } };\n\n const connection = await connectionOf(config, tenantSlug, provider);\n if (\"status\" in connection) return connection;\n const rawBody = await raw.text();\n const signature = engine.readSignature(provider, (name) => raw.headers.get(name));\n if (!engine.verifySignature(provider, rawBody, signature, connection.target.webhookSecret)) {\n config.logger.warn(`marketplace.webhook: ${tenantSlug} ${provider} signature rejected`);\n return UNAUTHORIZED;\n }\n try {\n return { ...connection, provider, payload: JSON.parse(rawBody) as unknown };\n } catch {\n return { status: 400, body: { error: \"invalid_json\" } };\n }\n}\n\ninterface Admitted {\n clientId: string;\n provider: string;\n payload: unknown;\n target: IngestionTarget;\n}\n\n/** Record and act on one verified delivery. */\nasync function handleWebhook(config: MarketplaceApiConfig, request: WireRequest<unknown>): Promise<WireResponse> {\n const admitted = await admit(config, request);\n if (\"status\" in admitted) return admitted;\n return deliverAdmitted(config, admitted);\n}\n\n/**\n * The answer to a proven presence heartbeat (FUT-5984, iFood's `KEEPALIVE`):\n * 202, and in the per-merchant mode every merchant it asked about named\n * online. Nothing is recorded.\n */\nfunction presenceAnswer(probe: PresenceProbe): WireResponse {\n return probe.merchantIds === null\n ? { status: 202, body: { received: true } }\n : { status: 202, body: { merchantIds: [...probe.merchantIds] } };\n}\n\n/** Record and act on a delivery whose store and signature are proven. */\nasync function deliverAdmitted(config: MarketplaceApiConfig, admitted: Admitted): Promise<WireResponse> {\n const { clientId, provider, payload, target } = admitted;\n const { engine } = config;\n const probe = engine.presence(provider, payload);\n if (probe) return presenceAnswer(probe);\n const status = engine.answerStatus(provider);\n\n const event = engine.normalize(provider, payload);\n if (!event) {\n // Nothing the adapter can key on. 2xx: redelivering an unreadable payload\n // produces an identical unreadable payload.\n config.logger.warn(`marketplace.webhook: ${provider} payload did not normalize`);\n return { status, body: { received: true, ignored: \"unrecognized_payload\" } };\n }\n const outcome = await engine.deliver({\n clientId,\n event,\n payload,\n // A DISABLED connection still stores its deliveries and ingests nothing;\n // the retry sweep ingests them if the store turns it back on.\n settings: target.enabled\n ? { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds, followStatus: target.followStatus }\n : null,\n });\n if (outcome.kind === \"failed\") {\n return { status: 500, body: { received: true, error: outcome.reason } };\n }\n // After the inbox row is written: iFood's 202 means \"recorded\" (FUT-5984).\n return { status, body: { received: true, outcome: outcome.kind } };\n}\n\n/**\n * The store a delivery to the APP's single address belongs to, and its\n * connection: resolved from the merchant the payload names, then proved by\n * the signature (FUT-5613). The payload is read before it is verified only to\n * find whose key verifies it; nothing of it is acted on until it is.\n */\nasync function admitApp(\n config: MarketplaceApiConfig,\n request: WireRequest<unknown>,\n): Promise<Admitted | WireResponse> {\n const { provider = \"\" } = request.params;\n if (!config.engine.knows(provider)) return { status: 404, body: { error: \"unknown_provider\" } };\n const raw = request.request;\n if (!raw) return { status: 400, body: { error: \"raw_request_required\" } };\n const rawBody = await raw.text();\n const payload = parsedJson(rawBody);\n if (payload === undefined) return { status: 400, body: { error: \"invalid_json\" } };\n // A presence heartbeat names no store: proved by the app's own key, with no statement (FUT-5984).\n const probe = config.engine.presence(provider, payload);\n if (probe) {\n const signature = config.engine.readSignature(provider, (name) => raw.headers.get(name));\n return (await config.engine.signedByApp(provider, rawBody, signature)) ? presenceAnswer(probe) : UNAUTHORIZED;\n }\n const found = await appConnection(config, provider, payload);\n if (\"status\" in found) return found;\n // The app's address never takes an unsigned delivery, whatever the store's own setting.\n const signature = config.engine.readSignature(provider, (name) => raw.headers.get(name));\n const secret = found.target.webhookSecret;\n if (!secret || !config.engine.verifySignature(provider, rawBody, signature, secret)) {\n config.logger.warn(`marketplace.webhook: app ${provider} delivery for ${found.clientId} refused`);\n return UNAUTHORIZED;\n }\n return { ...found, provider, payload };\n}\n\n/** A JSON body, or undefined when it is not JSON. */\nfunction parsedJson(rawBody: string): unknown {\n try {\n return JSON.parse(rawBody) as unknown;\n } catch {\n return undefined;\n }\n}\n\n/** The store whose live connection holds the merchant a delivery names, or the 401. */\nasync function appConnection(\n config: MarketplaceApiConfig,\n provider: string,\n payload: unknown,\n): Promise<{ clientId: string; target: IngestionTarget } | WireResponse> {\n const merchantId = config.engine.normalize(provider, payload)?.externalMerchantId ?? null;\n const clientId = merchantId === null ? null : await config.engine.tenantFor(provider, merchantId);\n if (!clientId) return UNAUTHORIZED;\n try {\n const target = await config.engine.target(clientId, provider);\n return target ? { clientId, target } : UNAUTHORIZED;\n } catch (error) {\n config.logger.error(`marketplace.webhook: app ${provider} key of ${clientId} unavailable: ${String(error)}`);\n return UNAUTHORIZED;\n }\n}\n\n/**\n * `POST /webhooks/marketplace/:provider` — the ONE address the software's own\n * app registers with a marketplace, for every store linked through it\n * (FUT-5613). The store is found by the merchant id the delivery names, and\n * the delivery must carry a valid signature: unsigned is refused here.\n */\nexport function appWebhookRoute(config: MarketplaceApiConfig): WireRoute<unknown> {\n return {\n method: \"POST\",\n path: \"/webhooks/marketplace/:provider\",\n kind: \"webhook\",\n handle: async (request) => {\n const admitted = await admitApp(config, request);\n return \"status\" in admitted ? admitted : deliverAdmitted(config, admitted);\n },\n };\n}\n\n/** The webhook descriptor. Raw body required: signatures are computed over bytes. */\nexport function webhookRoute(config: MarketplaceApiConfig): WireRoute<unknown> {\n return {\n method: \"POST\",\n path: \"/webhooks/marketplace/:tenantSlug/:provider\",\n kind: \"webhook\",\n handle: (request) => handleWebhook(config, request),\n };\n}\n","import type { WireResponse, WireRoute } from \"@12-apps/wiring\";\n\nimport type { BulkProblem } from \"../core/bulk\";\nimport type { DecisionProblem } from \"../core/cancellation\";\nimport type { MarketplaceIntegrationView } from \"../core/integration\";\nimport type { MarketplaceMenuLinkView } from \"../core/menu-links\";\nimport { MARKETPLACE_DECIDE, MARKETPLACE_MANAGE } from \"./contribution\";\nimport type { MarketplaceServerCopy } from \"./copy\";\nimport { iso, ok, parse, refuse, type MarketplaceActor, type MarketplaceApiConfig } from \"./http\";\nimport {\n decideMarketplaceOrdersBody,\n listMarketplaceAcceptancesQuery,\n listMarketplaceIntegrationsQuery,\n listMarketplaceMenuLinksQuery,\n upsertMarketplaceIntegrationsBody,\n upsertMarketplaceMenuLinksBody,\n} from \"./mcp\";\nimport { linkRoutes } from \"./link-routes\";\nimport { appWebhookRoute, webhookRoute } from \"./webhook\";\n\n/**\n * The marketplace HTTP surface as framework-neutral wiring descriptors: the\n * webhook every marketplace posts to, and, per entity, one read and one bulk\n * write — connections, SKU links, decisions — for a store's staff and its MCP\n * tools alike.\n *\n * There is no authentication, tenant resolution or RBAC in here: each\n * descriptor DECLARES the permission it needs and the host's guard answers it;\n * the actor arrives already resolved. Paths are relative to the host's mount.\n */\n\nexport type MarketplaceRoute = WireRoute<MarketplaceActor> | WireRoute<unknown>;\n\nconst BASE = \"/admin/:tenantSlug/marketplace\";\n\n/** The 409 code of a decision on an order that is no longer on the clock. */\nexport const ORDER_NOT_PENDING_CODE = \"MARKETPLACE_ORDER_NOT_PENDING\";\n\nconst NOT_PENDING = new Set([\"NOT_FOUND\", \"ALREADY_DECIDED\", \"EXPIRED\", \"CONFLICT\"]);\n\n/** A connection as the read returns it: dates as ISO, the adapter's half beside it. */\nfunction integrationOut(config: MarketplaceApiConfig, row: MarketplaceIntegrationView) {\n const adapter = config.engine.adapter(row.provider);\n return {\n ...row,\n lastEventAt: iso(row.lastEventAt),\n lastVerifiedAt: iso(row.lastVerifiedAt),\n archivedAt: iso(row.archivedAt),\n capabilities: adapter ? adapter.capabilities : null,\n reasons: adapter ? [...adapter.cancellationReasons()] : [],\n };\n}\n\nfunction linkOut(link: MarketplaceMenuLinkView) {\n return { ...link, lastSeenAt: link.lastSeenAt.toISOString() };\n}\n\n/** Each problem with its sentence; a host refusal keeps the host's own words. */\nfunction problemsOut(copy: MarketplaceServerCopy, problems: readonly (BulkProblem | DecisionProblem)[]) {\n return problems.map((problem) => {\n const host = \"host\" in problem ? problem.host : undefined;\n return {\n ...problem,\n message: host?.message ?? (problem.code === \"MERCHANT_TAKEN\" ? (copy.link?.problems.MERCHANT_TAKEN ?? problem.code) : copy.problems[problem.code]),\n ...(host ? { hostCode: host.code, details: host.details } : {}),\n };\n });\n}\n\n/** A refused bulk write: 422, nothing saved, every problem with its path. */\nfunction refusedBulk(copy: MarketplaceServerCopy, problems: readonly BulkProblem[]): WireResponse {\n return refuse(422, copy.nothingSaved, { problems: problemsOut(copy, problems) });\n}\n\n/**\n * A refused decision call. The host's own refusal is a 409 carrying ITS code\n * (`MARKETPLACE_STOCK_ASK` and the short lines in `details`); an order no\n * longer on the clock a 409; anything else (a reason, an item) a 422.\n */\nfunction refusedDecisions(copy: MarketplaceServerCopy, problems: readonly DecisionProblem[]): WireResponse {\n const out = problemsOut(copy, problems);\n const host = problems.find((problem) => problem.code === \"HOST_REFUSED\")?.host;\n if (host) return refuse(409, host.message, { code: host.code, details: host.details, problems: out });\n if (problems.some((problem) => NOT_PENDING.has(problem.code))) {\n return refuse(409, copy.orderNoLongerPending, { code: ORDER_NOT_PENDING_CODE, problems: out });\n }\n return refuse(422, copy.nothingSaved, { problems: out });\n}\n\nfunction integrationRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceIntegrationsQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const rows = await engine.integrations(actor.clientId, {\n providers: parsed.value.ids,\n includeArchived: parsed.value.includeArchived === \"true\",\n });\n return ok(rows.map((row) => integrationOut(config, row)));\n },\n },\n {\n method: \"PUT\",\n path: BASE,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(upsertMarketplaceIntegrationsBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.upsertIntegrations({\n clientId: actor.clientId,\n actorId: actor.userId ?? null,\n validateOnly: parsed.value.validateOnly,\n rows: parsed.value.integrations.map((row) =>\n \"credentials\" in row && row.credentials\n ? { ...row, credentials: { ...row.credentials, webhookSecret: row.credentials.webhookSecret ?? null } }\n : row,\n ) as Parameters<typeof engine.upsertIntegrations>[0][\"rows\"],\n });\n if (result.kind === \"refused\") return refusedBulk(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, integrations: result.rows.map((row) => integrationOut(config, row)) });\n },\n },\n ];\n}\n\nfunction menuLinkRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: `${BASE}/menu-links`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceMenuLinksQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const links = await engine.menuLinks({\n clientId: actor.clientId,\n provider: parsed.value.provider,\n unmappedOnly: parsed.value.unmapped === \"true\",\n ids: parsed.value.ids,\n });\n return ok(links.map(linkOut));\n },\n },\n {\n method: \"PUT\",\n path: `${BASE}/menu-links`,\n permission: MARKETPLACE_MANAGE,\n handle: async ({ actor, body }) => {\n const parsed = parse(upsertMarketplaceMenuLinksBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.upsertMenuLinks({\n clientId: actor.clientId,\n rows: parsed.value.links,\n validateOnly: parsed.value.validateOnly,\n });\n if (result.kind === \"refused\") return refusedBulk(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, links: result.rows.map(linkOut) });\n },\n },\n ];\n}\n\nfunction acceptanceRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {\n const { engine, copy } = config;\n return [\n {\n method: \"GET\",\n path: `${BASE}/acceptances`,\n permission: MARKETPLACE_DECIDE,\n handle: async ({ actor, query }) => {\n const parsed = parse(listMarketplaceAcceptancesQuery, query, copy);\n if (!parsed.ok) return parsed.response;\n const pending = await engine.pending(actor.clientId, parsed.value.ids);\n return ok(\n pending.map((order) => ({\n ...order,\n acknowledgeBy: iso(order.acknowledgeBy),\n externalDueAt: iso(order.externalDueAt),\n })),\n );\n },\n },\n {\n method: \"POST\",\n path: `${BASE}/acceptances`,\n permission: MARKETPLACE_DECIDE,\n handle: async ({ actor, body }) => {\n const parsed = parse(decideMarketplaceOrdersBody, body, copy);\n if (!parsed.ok) return parsed.response;\n const result = await engine.decideMany({\n clientId: actor.clientId,\n decisions: parsed.value.decisions,\n validateOnly: parsed.value.validateOnly,\n });\n if (result.kind === \"refused\") return refusedDecisions(copy, result.problems);\n return ok({ validateOnly: result.validateOnly, decisions: result.rows });\n },\n },\n ];\n}\n\n/** The whole surface, in mount order. */\nexport function marketplaceRoutes(config: MarketplaceApiConfig): MarketplaceRoute[] {\n return [\n webhookRoute(config),\n appWebhookRoute(config),\n ...integrationRoutes(config),\n ...linkRoutes(config),\n ...menuLinkRoutes(config),\n ...acceptanceRoutes(config),\n ];\n}\n","import type { JobsContribution, WireJobBlueprint } from \"@12-apps/wiring\";\n\nimport type { MarketplaceEngine } from \"../core/engine\";\nimport { CatalogueRetryError, type CatalogueJobPayload } from \"../core/catalogue-job\";\nimport { AcknowledgeRetryError, type AcknowledgeJobPayload } from \"../core/acknowledge\";\nimport { FetchOrderRetryError, type FetchOrderJobPayload } from \"../core/fetch-order\";\nimport { CancellationReasonsRetryError, type CancellationReasonsJobPayload } from \"../core/order-reasons\";\nimport { OutboundRetryError } from \"../core/outbound\";\nimport type { OutboundJobPayload } from \"../core/outbound-queue\";\nimport { AvailabilityRetryError } from \"../core/pause-job\";\nimport { DisputeAnswerRetryError, type DisputeAnswerJobPayload } from \"../core/dispute-job\";\nimport type { AvailabilityJobPayload } from \"../core/pause-store\";\n\n/**\n * The engine's eleven jobs, declared here because every number in them is the\n * engine's knowledge, not a host's:\n *\n * - `expire-acceptances`, every minute: the unit being measured is minutes (a\n * default window is five), so a coarser tick would make \"expired\" mean\n * anywhere from five to twenty.\n * - `reconcile-inbox`, every five minutes: nothing races a deadline here, and\n * each pass re-runs real ingestion work; the engine's attempt bound retires\n * a payload that will never succeed.\n * - `outbound`, on demand: one call to a marketplace, three attempts with\n * backoff. Its idempotency is the ROW's (the engine re-reads it), never the\n * queue's dedupe alone.\n * - `fetch-order`, on demand: one GET of an order a marketplace's event only\n * announced (`orderToFetch`), then the one ingest path. Three attempts with\n * backoff; the reconciliation sweep re-queues a row still owed.\n * - `acknowledge`, on demand: tells the marketplace a store's recorded events\n * were received (FUT-5984, iFood). Three attempts with backoff; the\n * reconcile pass re-queues a store still owing some.\n * - `cancellation-reasons`, on demand: reads one order's own cancellation\n * reasons once, after its ingest (FUT-5984, iFood). Three attempts; the\n * static list stays the fallback.\n * - `catalogue`, on demand: one publish or withdraw of one product on one\n * marketplace's catalogue (FUT-4768). Three attempts with backoff; the\n * last one stamps FAILED with a failure code.\n * - `outbound-sweep`, every five minutes: re-queues every call a row still\n * owes (a PENDING request, an accept with no confirm stamp, a catalogue\n * publish or withdraw on its way) once it is older than the job's own retry\n * span, so a refused enqueue or a dead process loses nothing.\n * - `availability`, on demand: brings one marketplace in line with the host's\n * last pause or resume ask for one store (FUT-4851). Three attempts with\n * backoff; the last one stamps FAILED with a failure code.\n * - `dispute-answer`, on demand: sends one store's answer to a buyer's\n * dispute (FUT-6099). Three attempts with backoff; the last gives the\n * answer back OPEN, and the outbound sweep re-queues one still owed.\n * - `availability-sweep`, every five minutes: resumes a pause past its\n * `until` (the host stopped renewing it), re-queues an ask still owed, and\n * gives up on one older than a day.\n *\n * What stays the host's: whether to run them at all, on which runtime, and the\n * lease implementation. A host with no worker declines `jobs` in writing.\n *\n * Bound with `{ engine }`, these arrive at a runner as\n * `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,\n * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.acknowledge`,\n * `marketplace.cancellation-reasons`, `marketplace.catalogue`,\n * `marketplace.outbound-sweep`, `marketplace.availability`,\n * `marketplace.availability-sweep`, `marketplace.link-check` and\n * `marketplace.dispute-answer`.\n */\n\n/** What the host closes over at bind time: the mounted engine. */\nexport interface MarketplaceJobDeps {\n engine: Pick<\n MarketplaceEngine,\n | \"expireLapsed\"\n | \"retryable\"\n | \"reprocess\"\n | \"runOutbound\"\n | \"runFetchOrder\"\n | \"runAcknowledge\"\n | \"sweepAcknowledgements\"\n | \"runCancellationReasons\"\n | \"runCatalogue\"\n | \"sweepOutbound\"\n | \"runAvailability\"\n | \"sweepAvailability\"\n | \"sweepLinks\"\n | \"runDisputeAnswer\"\n >;\n}\n\n/** The single-flight queue name (`@12-apps/jobs`' `SWEEP_QUEUE`), as a literal. */\nexport const MARKETPLACE_SWEEP_QUEUE = \"sweeps\";\n\n/** How long one sweep pass may hold its name. */\nconst SWEEP_LEASE_MS = 5 * 60_000;\n\n/** The outbound job's attempts: the last one stamps the failure. */\nexport const MARKETPLACE_OUTBOUND_ATTEMPTS = 3;\n\nconst expireAcceptances: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"expire-acceptances\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"* * * * *\", timezone: \"UTC\" },\n // Never retried by the queue: the next tick re-finds everything from the rows.\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.expireLapsed();\n if (result.expired === 0) return;\n context.logger.info(\n `marketplace.expire-acceptances: expired ${result.expired} order(s) across ${result.tenants} tenant(s).`,\n );\n },\n};\n\nconst reconcileInbox: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"reconcile-inbox\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const pending = await deps.engine.retryable();\n let ingested = 0;\n // One event's failure never wedges the batch: `reprocess` never throws.\n for (const event of pending) {\n const outcome = await deps.engine.reprocess(event);\n if (outcome.kind === \"ingested\") ingested += 1;\n }\n // The events still owed an acknowledgment are re-queued, one job per store (FUT-5984).\n const { requeued } = await deps.engine.sweepAcknowledgements();\n if (pending.length === 0 && requeued === 0) return;\n context.logger.info(\n `marketplace.reconcile-inbox: re-ran ${pending.length} stored delivery(ies), ${ingested} became order(s); ` +\n `re-queued the acknowledgment of ${requeued} store(s).`,\n );\n },\n};\n\nconst outbound: WireJobBlueprint<OutboundJobPayload, MarketplaceJobDeps> = {\n name: \"outbound\",\n attempts: MARKETPLACE_OUTBOUND_ATTEMPTS,\n backoff: { type: \"exponential\", delayMs: 30_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runOutbound(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.outbound: ${payload.action} ${payload.orderId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof OutboundRetryError) context.logger.warn(`marketplace.outbound: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The fetch job's attempts: the last one settles the inbox row FAILED. */\nexport const MARKETPLACE_FETCH_ORDER_ATTEMPTS = 3;\n\nconst fetchOrder: WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps> = {\n name: \"fetch-order\",\n attempts: MARKETPLACE_FETCH_ORDER_ATTEMPTS,\n // Short: an order waiting for its body is on the store's acceptance clock.\n backoff: { type: \"exponential\", delayMs: 5_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runFetchOrder(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.fetch-order: inbox ${payload.inboxId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof FetchOrderRetryError) context.logger.warn(`marketplace.fetch-order: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The acknowledgment's attempts: the last one leaves the events owed, for the reconcile pass. */\nconst MARKETPLACE_ACKNOWLEDGE_ATTEMPTS = 3;\n\nconst acknowledge: WireJobBlueprint<AcknowledgeJobPayload, MarketplaceJobDeps> = {\n name: \"acknowledge\",\n attempts: MARKETPLACE_ACKNOWLEDGE_ATTEMPTS,\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runAcknowledge(payload, { attempt: context.attempt, maxAttempts: context.maxAttempts });\n if (outcome.kind === \"skipped\") context.logger.info(`marketplace.acknowledge: ${payload.provider} ${payload.clientId} skipped: ${outcome.reason}`);\n } catch (error) {\n if (error instanceof AcknowledgeRetryError) context.logger.warn(`marketplace.acknowledge: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The reasons read's attempts: the last one leaves the static list in place. */\nconst MARKETPLACE_CANCELLATION_REASONS_ATTEMPTS = 3;\n\nconst cancellationReasons: WireJobBlueprint<CancellationReasonsJobPayload, MarketplaceJobDeps> = {\n name: \"cancellation-reasons\",\n attempts: MARKETPLACE_CANCELLATION_REASONS_ATTEMPTS,\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runCancellationReasons(payload, { attempt: context.attempt, maxAttempts: context.maxAttempts });\n if (outcome.kind === \"skipped\") context.logger.info(`marketplace.cancellation-reasons: ${payload.orderId} skipped: ${outcome.reason}`);\n } catch (error) {\n if (error instanceof CancellationReasonsRetryError) context.logger.warn(`marketplace.cancellation-reasons: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The catalogue job's attempts: the last one stamps FAILED. */\nconst MARKETPLACE_CATALOGUE_ATTEMPTS = 3;\n\nconst catalogue: WireJobBlueprint<CatalogueJobPayload, MarketplaceJobDeps> = {\n name: \"catalogue\",\n attempts: MARKETPLACE_CATALOGUE_ATTEMPTS,\n // Short: a person is watching the switch say \"sending\".\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runCatalogue(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.catalogue: ${payload.action} ${payload.publicationId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof CatalogueRetryError) context.logger.warn(`marketplace.catalogue: ${error.message}`);\n throw error;\n }\n },\n};\n\nconst outboundSweep: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"outbound-sweep\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.sweepOutbound();\n const idle = result.requeued + result.givenUp + result.timedOut + result.catalogueRequeued === 0;\n if (idle) return;\n context.logger.info(\n `marketplace.outbound-sweep: re-queued ${result.requeued} call(s) and ${result.catalogueRequeued} catalogue ` +\n `call(s), timed out ${result.timedOut} cancellation request(s), gave up on ${result.givenUp}.`,\n );\n },\n};\n\n/** The availability job's attempts: the last one stamps FAILED. */\nexport const MARKETPLACE_AVAILABILITY_ATTEMPTS = 3;\n\nconst availability: WireJobBlueprint<AvailabilityJobPayload, MarketplaceJobDeps> = {\n name: \"availability\",\n attempts: MARKETPLACE_AVAILABILITY_ATTEMPTS,\n // Short: a store is open on the marketplace while the kitchen is paused.\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runAvailability(payload, {\n attempt: context.attempt,\n maxAttempts: context.maxAttempts,\n });\n if (outcome.kind === \"skipped\") {\n context.logger.info(`marketplace.availability: ${payload.provider} ${payload.clientId} skipped: ${outcome.reason}`);\n }\n } catch (error) {\n if (error instanceof AvailabilityRetryError) context.logger.warn(`marketplace.availability: ${error.message}`);\n throw error;\n }\n },\n};\n\nconst availabilitySweep: WireJobBlueprint<void, MarketplaceJobDeps> = {\n name: \"availability-sweep\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"*/5 * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (_payload, deps, context) => {\n const result = await deps.engine.sweepAvailability();\n if (result.expired + result.requeued + result.givenUp === 0) return;\n context.logger.info(\n `marketplace.availability-sweep: resumed ${result.expired} expired pause(s), re-queued ${result.requeued}, ` +\n `gave up on ${result.givenUp}.`,\n );\n },\n};\n\n/**\n * `link-check` (FUT-5798), each minute and once more half a minute later\n * (queued by the tick, only while a store waits): every centralized link\n * attempt still waiting asks the app's list, and a store whose authorization\n * arrived is hinted. Never retried: the next pass re-finds it from the rows.\n */\nconst linkCheck: WireJobBlueprint<{ half?: boolean } | undefined, MarketplaceJobDeps> = {\n name: \"link-check\",\n queue: MARKETPLACE_SWEEP_QUEUE,\n concurrency: 1,\n schedule: { pattern: \"* * * * *\", timezone: \"UTC\" },\n attempts: 1,\n lease: { ttlMs: SWEEP_LEASE_MS },\n handle: async (payload, deps, context) => {\n const result = await deps.engine.sweepLinks({ half: payload?.half === true });\n if (result.seen.length === 0) return;\n context.logger.info(`marketplace.link-check: saw the authorization of ${result.seen.length} store(s); ${result.waiting} still waiting.`);\n },\n};\n\n/** The dispute answer's attempts: the last one gives the answer back for a person to send again. */\nconst MARKETPLACE_DISPUTE_ANSWER_ATTEMPTS = 3;\n\nconst disputeAnswer: WireJobBlueprint<DisputeAnswerJobPayload, MarketplaceJobDeps> = {\n name: \"dispute-answer\",\n attempts: MARKETPLACE_DISPUTE_ANSWER_ATTEMPTS,\n // Short: the marketplace's deadline is minutes, and a person waits on the card.\n backoff: { type: \"exponential\", delayMs: 10_000 },\n handle: async (payload, deps, context) => {\n try {\n const outcome = await deps.engine.runDisputeAnswer(payload, { attempt: context.attempt, maxAttempts: context.maxAttempts });\n if (outcome.kind === \"skipped\") context.logger.info(`marketplace.dispute-answer: ${payload.disputeId} skipped: ${outcome.reason}`);\n } catch (error) {\n if (error instanceof DisputeAnswerRetryError) context.logger.warn(`marketplace.dispute-answer: ${error.message}`);\n throw error;\n }\n },\n};\n\n/** The jobs contribution. */\nexport const MARKETPLACE_JOBS = {\n namespace: \"marketplace\",\n blueprints: {\n \"expire-acceptances\": expireAcceptances,\n \"reconcile-inbox\": reconcileInbox,\n outbound,\n \"fetch-order\": fetchOrder,\n acknowledge,\n \"cancellation-reasons\": cancellationReasons,\n catalogue,\n \"outbound-sweep\": outboundSweep,\n availability,\n \"availability-sweep\": availabilitySweep,\n \"link-check\": linkCheck,\n \"dispute-answer\": disputeAnswer,\n },\n} as const satisfies JobsContribution<MarketplaceJobDeps>;\n","import type { MarketplaceEngine } from \"../core/engine\";\nimport type { MarketplaceApiConfig } from \"./http\";\nimport { marketplaceRoutes, type MarketplaceRoute } from \"./routes\";\n\n/**\n * `@12-apps/marketplace/server` — the engine's HTTP surface, jobs, MCP tools\n * and permissions, as wiring-contract values.\n *\n * ```ts\n * const engine = createMarketplaceEngine({ …ports, adapters });\n * const api = createApiMarketplace({ engine, copy, tenantBySlug, logger });\n * // api.routes: mount under `/api` (the hono adapter does it in one line)\n * ```\n */\n\n/** What `createApiMarketplace` hands back: the routes, and the engine they serve. */\nexport interface ApiMarketplace {\n routes: MarketplaceRoute[];\n engine: MarketplaceEngine;\n}\n\n/** Build the route table over a mounted engine. */\nexport function createApiMarketplace(config: MarketplaceApiConfig): ApiMarketplace {\n if (!config.logger) {\n throw new Error(\"@12-apps/marketplace: the observability namespace needs a logger; pass `logger`.\");\n }\n return { routes: marketplaceRoutes(config), engine: config.engine };\n}\n\nexport type { MarketplaceActor, MarketplaceApiConfig } from \"./http\";\nexport type { MarketplaceRoute } from \"./routes\";\nexport type { MarketplaceLinkCopy, MarketplaceServerCopy } from \"./copy\";\nexport {\n MARKETPLACE_DECIDE,\n MARKETPLACE_MANAGE,\n MARKETPLACE_PERMISSIONS,\n} from \"./contribution\";\nexport {\n MARKETPLACE_AVAILABILITY_ATTEMPTS,\n MARKETPLACE_FETCH_ORDER_ATTEMPTS,\n MARKETPLACE_JOBS,\n MARKETPLACE_OUTBOUND_ATTEMPTS,\n MARKETPLACE_SWEEP_QUEUE,\n type MarketplaceJobDeps,\n} from \"./jobs\";\nexport {\n MARKETPLACE_MCP_TOOLS,\n decideMarketplaceOrdersBody,\n listMarketplaceAcceptancesQuery,\n listMarketplaceIntegrationsQuery,\n listMarketplaceMenuLinksQuery,\n marketplaceParams,\n upsertMarketplaceIntegrationsBody,\n upsertMarketplaceMenuLinksBody,\n} from \"./mcp\";\nexport { ORDER_NOT_PENDING_CODE } from \"./routes\";\nexport type { MarketplaceProblemCode } from \"./copy\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCO,SAAS,GAAG,MAA6B;AAC9C,SAAO,EAAE,QAAQ,KAAK,MAAM,EAAE,KAAK,EAAE;AACvC;AAFgB;AAKT,SAAS,OAAO,QAAgB,OAAe,QAAiC,CAAC,GAAiB;AACvG,SAAO,EAAE,QAAQ,MAAM,EAAE,OAAO,GAAG,MAAM,EAAE;AAC7C;AAFgB;AAKT,SAAS,MACd,QACA,OACA,MACgE;AAChE,QAAM,SAAS,OAAO,UAAU,SAAS,CAAC,CAAC;AAC3C,MAAI,OAAO,QAAS,QAAO,EAAE,IAAI,MAAM,OAAO,OAAO,KAAK;AAC1D,QAAM,WAAW,OAAO,MAAM,OAAO,IAAI,CAAC,WAAW;AAAA,IACnD,MAAM,M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