@12-apps/marketplace 1.10.0 → 1.12.0

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.
Files changed (84) hide show
  1. package/ADOPTING.md +126 -1
  2. package/README.md +100 -1
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-CYJzu1c9.d.ts → adapter-nUyZpLzz.d.ts} +448 -173
  6. package/dist/{chunk-2BA2EHNF.js → chunk-45ZVN5XI.js} +316 -42
  7. package/dist/chunk-45ZVN5XI.js.map +1 -0
  8. package/dist/{chunk-PYHNM47K.js → chunk-L6FG6T4S.js} +2 -2
  9. package/dist/{chunk-HEXLCTOG.js → chunk-LACBT6NC.js} +1 -1
  10. package/dist/chunk-LACBT6NC.js.map +1 -0
  11. package/dist/{chunk-WVZ2IXFH.js → chunk-MIPNQ7X5.js} +190 -12
  12. package/dist/chunk-MIPNQ7X5.js.map +1 -0
  13. package/dist/chunk-SGOTN5PX.js +345 -0
  14. package/dist/chunk-SGOTN5PX.js.map +1 -0
  15. package/dist/{client-B4EQCRD_.d.ts → client-Ctas7WCS.d.ts} +1 -1
  16. package/dist/{engine-DK3iV_Kk.d.ts → engine-CIy9P7Cq.d.ts} +149 -8
  17. package/dist/hono/index.d.ts +2 -2
  18. package/dist/hono/index.js +3 -3
  19. package/dist/ifood/index.d.ts +10 -2
  20. package/dist/ifood/index.js +297 -25
  21. package/dist/ifood/index.js.map +1 -1
  22. package/dist/index.d.ts +23 -4
  23. package/dist/index.js +424 -84
  24. package/dist/index.js.map +1 -1
  25. package/dist/keeta/index.d.ts +2 -18
  26. package/dist/keeta/index.js +12 -3
  27. package/dist/keeta/index.js.map +1 -1
  28. package/dist/manifest/index.d.ts +219 -1
  29. package/dist/manifest/index.js +1 -1
  30. package/dist/manifest/server.d.ts +2 -2
  31. package/dist/manifest/server.js +3 -3
  32. package/dist/rappi/index.d.ts +1 -1
  33. package/dist/rappi/index.js +1 -1
  34. package/dist/server/en-US.d.ts +13 -0
  35. package/dist/server/en-US.js +13 -0
  36. package/dist/server/en-US.js.map +1 -1
  37. package/dist/server/index.d.ts +241 -7
  38. package/dist/server/index.js +3 -3
  39. package/dist/server/pt-BR.d.ts +13 -0
  40. package/dist/server/pt-BR.js +13 -0
  41. package/dist/server/pt-BR.js.map +1 -1
  42. package/package.json +1 -1
  43. package/prisma/marketplace.prisma +41 -0
  44. package/prisma/migrations/20261127090000_marketplace_app_link/migration.sql +81 -0
  45. package/src/core/adapter.ts +27 -0
  46. package/src/core/bulk.ts +43 -8
  47. package/src/core/courier-port.ts +100 -0
  48. package/src/core/courier.ts +153 -0
  49. package/src/core/engine.ts +63 -4
  50. package/src/core/integration.ts +60 -32
  51. package/src/core/lifecycle.ts +27 -4
  52. package/src/core/link-store.ts +170 -0
  53. package/src/core/linking-port.ts +100 -0
  54. package/src/core/linking.ts +363 -0
  55. package/src/core/merchant-claim.ts +106 -0
  56. package/src/core/outbound-queue.ts +24 -11
  57. package/src/core/outbound.ts +8 -6
  58. package/src/core/pickup-code.ts +136 -0
  59. package/src/core/pipeline.ts +15 -6
  60. package/src/core/ports.ts +26 -1
  61. package/src/core/status-store.ts +2 -3
  62. package/src/core/types.ts +56 -4
  63. package/src/ifood/courier.ts +210 -0
  64. package/src/ifood/index.ts +8 -0
  65. package/src/ifood/linking.ts +170 -0
  66. package/src/ifood/normalize.ts +7 -0
  67. package/src/ifood/outbound.ts +10 -3
  68. package/src/index.ts +30 -0
  69. package/src/keeta/normalize.ts +21 -6
  70. package/src/server/copy.ts +20 -2
  71. package/src/server/en-US.ts +13 -0
  72. package/src/server/index.ts +1 -1
  73. package/src/server/link-routes.ts +140 -0
  74. package/src/server/mcp-link.ts +103 -0
  75. package/src/server/mcp.ts +6 -2
  76. package/src/server/pt-BR.ts +13 -0
  77. package/src/server/routes.ts +5 -2
  78. package/src/server/webhook.ts +86 -0
  79. package/dist/chunk-2BA2EHNF.js.map +0 -1
  80. package/dist/chunk-HEXLCTOG.js.map +0 -1
  81. package/dist/chunk-WVZ2IXFH.js.map +0 -1
  82. package/dist/chunk-ZO4S3LF4.js +0 -254
  83. package/dist/chunk-ZO4S3LF4.js.map +0 -1
  84. /package/dist/{chunk-PYHNM47K.js.map → chunk-L6FG6T4S.js.map} +0 -0
package/src/server/mcp.ts CHANGED
@@ -2,6 +2,8 @@ import { z } from "zod";
2
2
 
3
3
  import type { WireMcpTool } from "@12-apps/wiring";
4
4
 
5
+ import { marketplaceLinkTools } from "./mcp-link";
6
+
5
7
  /**
6
8
  * The marketplace tool surface — authored ONCE, beside the route descriptors
7
9
  * it proxies to, and reused as the runtime validators. The advertised schema
@@ -197,6 +199,7 @@ const integrationSchema = z.object({
197
199
  lastEventAt: z.string().nullable(),
198
200
  lastVerifiedAt: z.string().nullable(),
199
201
  archivedAt: z.string().nullable(),
202
+ authMode: z.enum(["CREDENTIALS", "LINKED"]),
200
203
  capabilities: capabilitiesSchema.nullable(),
201
204
  reasons: z.array(reasonSchema),
202
205
  });
@@ -236,7 +239,7 @@ const decidedSchema = z.object({
236
239
 
237
240
  const BASE = "/admin/{tenantSlug}/marketplace";
238
241
 
239
- /** The six marketplace tools: a read and a bulk write per entity. */
242
+ /** The marketplace tools: a read and a bulk write per entity, and the five linking tools (FUT-5613). */
240
243
  export const MARKETPLACE_MCP_TOOLS = [
241
244
  {
242
245
  operationId: "listMarketplaceIntegrations",
@@ -255,7 +258,7 @@ export const MARKETPLACE_MCP_TOOLS = [
255
258
  method: "PUT",
256
259
  path: BASE,
257
260
  summary:
258
- "Create, update, archive or unarchive one or many marketplace connections in one all-or-nothing call. A row is keyed by `provider`; `operation` is `upsert` (default: any subset of the settings; omitting `credentials` keeps the stored secrets, sending them resets the status to UNVERIFIED), `archive` or `unarchive` (reversible, audited, with an optional `reason`). Any problem writes nothing and every problem comes back with its path. `validateOnly: true` checks without writing.",
261
+ "Create, update, archive or unarchive one or many marketplace connections in one all-or-nothing call. A row is keyed by `provider`; `operation` is `upsert` (default: any subset of the settings; omitting `credentials` keeps the stored secrets, sending them resets the status to UNVERIFIED), `archive` or `unarchive` (reversible, audited, with an optional `reason`). An `externalMerchantId` another store's live connection holds is refused `MERCHANT_TAKEN` at that field (an unarchive reviving one, at `provider`). Any problem writes nothing and every problem comes back with its path. `validateOnly: true` checks without writing.",
259
262
  tags: ["marketplace"],
260
263
  params: marketplaceParams,
261
264
  body: upsertMarketplaceIntegrationsBody,
@@ -310,4 +313,5 @@ export const MARKETPLACE_MCP_TOOLS = [
310
313
  response: z.object({ data: z.object({ validateOnly: z.boolean(), decisions: z.array(decidedSchema) }) }),
311
314
  annotations: { readOnly: false, destructive: true, openWorld: true },
312
315
  },
316
+ ...marketplaceLinkTools(marketplaceParams, integrationSchema),
313
317
  ] as const satisfies readonly WireMcpTool<z.ZodType>[];
@@ -19,4 +19,17 @@ export const MARKETPLACE_SERVER_COPY_PT_BR = {
19
19
  NOTHING_TO_UPDATE: "Nada para atualizar.",
20
20
  CATALOG_ITEM_NOT_FOUND: "Produto não encontrado.",
21
21
  },
22
+ link: {
23
+ problems: {
24
+ UNAVAILABLE: "A conexão pelo aplicativo não está disponível para este marketplace.",
25
+ NO_LINK_IN_PROGRESS: "Nenhuma conexão em andamento. Comece de novo pelo primeiro passo.",
26
+ LINK_EXPIRED: "O código expirou. Gere um código novo e repita os passos.",
27
+ CODE_REFUSED: "O marketplace recusou o código de autorização. Confira o código e cole de novo.",
28
+ MARKETPLACE_REFUSED: "O marketplace recusou o pedido de conexão.",
29
+ NOT_LINKED: "Esta loja não está conectada pelo aplicativo. Conecte de novo.",
30
+ UNKNOWN_MERCHANT: "Esta loja não está entre as autorizadas no marketplace.",
31
+ MERCHANT_TAKEN: "Esta loja do marketplace já está conectada a outra conta.",
32
+ },
33
+ tryAgain: "O marketplace não respondeu. Tente de novo em instantes.",
34
+ },
22
35
  } as const satisfies MarketplaceServerCopy;
@@ -15,7 +15,8 @@ import {
15
15
  upsertMarketplaceIntegrationsBody,
16
16
  upsertMarketplaceMenuLinksBody,
17
17
  } from "./mcp";
18
- import { webhookRoute } from "./webhook";
18
+ import { linkRoutes } from "./link-routes";
19
+ import { appWebhookRoute, webhookRoute } from "./webhook";
19
20
 
20
21
  /**
21
22
  * The marketplace HTTP surface as framework-neutral wiring descriptors: the
@@ -60,7 +61,7 @@ function problemsOut(copy: MarketplaceServerCopy, problems: readonly (BulkProble
60
61
  const host = "host" in problem ? problem.host : undefined;
61
62
  return {
62
63
  ...problem,
63
- message: host?.message ?? copy.problems[problem.code],
64
+ message: host?.message ?? (problem.code === "MERCHANT_TAKEN" ? (copy.link?.problems.MERCHANT_TAKEN ?? problem.code) : copy.problems[problem.code]),
64
65
  ...(host ? { hostCode: host.code, details: host.details } : {}),
65
66
  };
66
67
  });
@@ -208,7 +209,9 @@ function acceptanceRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceAc
208
209
  export function marketplaceRoutes(config: MarketplaceApiConfig): MarketplaceRoute[] {
209
210
  return [
210
211
  webhookRoute(config),
212
+ appWebhookRoute(config),
211
213
  ...integrationRoutes(config),
214
+ ...linkRoutes(config),
212
215
  ...menuLinkRoutes(config),
213
216
  ...acceptanceRoutes(config),
214
217
  ];
@@ -79,10 +79,22 @@ async function admit(
79
79
  }
80
80
  }
81
81
 
82
+ interface Admitted {
83
+ clientId: string;
84
+ provider: string;
85
+ payload: unknown;
86
+ target: IngestionTarget;
87
+ }
88
+
82
89
  /** Record and act on one verified delivery. */
83
90
  async function handleWebhook(config: MarketplaceApiConfig, request: WireRequest<unknown>): Promise<WireResponse> {
84
91
  const admitted = await admit(config, request);
85
92
  if ("status" in admitted) return admitted;
93
+ return deliverAdmitted(config, admitted);
94
+ }
95
+
96
+ /** Record and act on a delivery whose store and signature are proven. */
97
+ async function deliverAdmitted(config: MarketplaceApiConfig, admitted: Admitted): Promise<WireResponse> {
86
98
  const { clientId, provider, payload, target } = admitted;
87
99
  const { engine } = config;
88
100
 
@@ -109,6 +121,80 @@ async function handleWebhook(config: MarketplaceApiConfig, request: WireRequest<
109
121
  return { status: 200, body: { received: true, outcome: outcome.kind } };
110
122
  }
111
123
 
124
+ /**
125
+ * The store a delivery to the APP's single address belongs to, and its
126
+ * connection: resolved from the merchant the payload names, then proved by
127
+ * the signature (FUT-5613). The payload is read before it is verified only to
128
+ * find whose key verifies it; nothing of it is acted on until it is.
129
+ */
130
+ async function admitApp(
131
+ config: MarketplaceApiConfig,
132
+ request: WireRequest<unknown>,
133
+ ): Promise<Admitted | WireResponse> {
134
+ const { provider = "" } = request.params;
135
+ if (!config.engine.knows(provider)) return { status: 404, body: { error: "unknown_provider" } };
136
+ const raw = request.request;
137
+ if (!raw) return { status: 400, body: { error: "raw_request_required" } };
138
+ const rawBody = await raw.text();
139
+ const payload = parsedJson(rawBody);
140
+ if (payload === undefined) return { status: 400, body: { error: "invalid_json" } };
141
+ const found = await appConnection(config, provider, payload);
142
+ if ("status" in found) return found;
143
+ // The app's address never takes an unsigned delivery, whatever the store's own setting.
144
+ const signature = config.engine.readSignature(provider, (name) => raw.headers.get(name));
145
+ const secret = found.target.webhookSecret;
146
+ if (!secret || !config.engine.verifySignature(provider, rawBody, signature, secret)) {
147
+ config.logger.warn(`marketplace.webhook: app ${provider} delivery for ${found.clientId} refused`);
148
+ return UNAUTHORIZED;
149
+ }
150
+ return { ...found, provider, payload };
151
+ }
152
+
153
+ /** A JSON body, or undefined when it is not JSON. */
154
+ function parsedJson(rawBody: string): unknown {
155
+ try {
156
+ return JSON.parse(rawBody) as unknown;
157
+ } catch {
158
+ return undefined;
159
+ }
160
+ }
161
+
162
+ /** The store whose live connection holds the merchant a delivery names, or the 401. */
163
+ async function appConnection(
164
+ config: MarketplaceApiConfig,
165
+ provider: string,
166
+ payload: unknown,
167
+ ): Promise<{ clientId: string; target: IngestionTarget } | WireResponse> {
168
+ const merchantId = config.engine.normalize(provider, payload)?.externalMerchantId ?? null;
169
+ const clientId = merchantId === null ? null : await config.engine.tenantFor(provider, merchantId);
170
+ if (!clientId) return UNAUTHORIZED;
171
+ try {
172
+ const target = await config.engine.target(clientId, provider);
173
+ return target ? { clientId, target } : UNAUTHORIZED;
174
+ } catch (error) {
175
+ config.logger.error(`marketplace.webhook: app ${provider} key of ${clientId} unavailable: ${String(error)}`);
176
+ return UNAUTHORIZED;
177
+ }
178
+ }
179
+
180
+ /**
181
+ * `POST /webhooks/marketplace/:provider` — the ONE address the software's own
182
+ * app registers with a marketplace, for every store linked through it
183
+ * (FUT-5613). The store is found by the merchant id the delivery names, and
184
+ * the delivery must carry a valid signature: unsigned is refused here.
185
+ */
186
+ export function appWebhookRoute(config: MarketplaceApiConfig): WireRoute<unknown> {
187
+ return {
188
+ method: "POST",
189
+ path: "/webhooks/marketplace/:provider",
190
+ kind: "webhook",
191
+ handle: async (request) => {
192
+ const admitted = await admitApp(config, request);
193
+ return "status" in admitted ? admitted : deliverAdmitted(config, admitted);
194
+ },
195
+ };
196
+ }
197
+
112
198
  /** The webhook descriptor. Raw body required: signatures are computed over bytes. */
113
199
  export function webhookRoute(config: MarketplaceApiConfig): WireRoute<unknown> {
114
200
  return {