@12-apps/marketplace 1.10.0 → 1.11.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 (71) hide show
  1. package/ADOPTING.md +36 -0
  2. package/README.md +63 -0
  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-CD0SfdVS.d.ts} +124 -1
  6. package/dist/{chunk-PYHNM47K.js → chunk-DCWOQ5PN.js} +2 -2
  7. package/dist/{chunk-WVZ2IXFH.js → chunk-OS4TSIFU.js} +190 -12
  8. package/dist/chunk-OS4TSIFU.js.map +1 -0
  9. package/dist/chunk-SGOTN5PX.js +345 -0
  10. package/dist/chunk-SGOTN5PX.js.map +1 -0
  11. package/dist/{chunk-HEXLCTOG.js → chunk-TVZU4HNT.js} +1 -1
  12. package/dist/chunk-TVZU4HNT.js.map +1 -0
  13. package/dist/{chunk-2BA2EHNF.js → chunk-YWMEIMO3.js} +206 -22
  14. package/dist/chunk-YWMEIMO3.js.map +1 -0
  15. package/dist/{client-B4EQCRD_.d.ts → client-11sncog4.d.ts} +1 -1
  16. package/dist/{engine-DK3iV_Kk.d.ts → engine-C_3RK8wC.d.ts} +116 -4
  17. package/dist/hono/index.d.ts +2 -2
  18. package/dist/hono/index.js +3 -3
  19. package/dist/ifood/index.d.ts +5 -2
  20. package/dist/ifood/index.js +125 -7
  21. package/dist/ifood/index.js.map +1 -1
  22. package/dist/index.d.ts +23 -4
  23. package/dist/index.js +264 -21
  24. package/dist/index.js.map +1 -1
  25. package/dist/keeta/index.d.ts +2 -2
  26. package/dist/keeta/index.js +2 -2
  27. package/dist/manifest/index.d.ts +219 -1
  28. package/dist/manifest/index.js +1 -1
  29. package/dist/manifest/server.d.ts +2 -2
  30. package/dist/manifest/server.js +3 -3
  31. package/dist/rappi/index.d.ts +1 -1
  32. package/dist/rappi/index.js +1 -1
  33. package/dist/server/en-US.d.ts +13 -0
  34. package/dist/server/en-US.js +13 -0
  35. package/dist/server/en-US.js.map +1 -1
  36. package/dist/server/index.d.ts +241 -7
  37. package/dist/server/index.js +3 -3
  38. package/dist/server/pt-BR.d.ts +13 -0
  39. package/dist/server/pt-BR.js +13 -0
  40. package/dist/server/pt-BR.js.map +1 -1
  41. package/package.json +1 -1
  42. package/prisma/marketplace.prisma +41 -0
  43. package/prisma/migrations/20261127090000_marketplace_app_link/migration.sql +81 -0
  44. package/src/core/adapter.ts +21 -0
  45. package/src/core/bulk.ts +43 -8
  46. package/src/core/engine.ts +59 -3
  47. package/src/core/integration.ts +60 -32
  48. package/src/core/link-store.ts +170 -0
  49. package/src/core/linking-port.ts +100 -0
  50. package/src/core/linking.ts +363 -0
  51. package/src/core/merchant-claim.ts +106 -0
  52. package/src/core/ports.ts +3 -0
  53. package/src/ifood/index.ts +4 -0
  54. package/src/ifood/linking.ts +170 -0
  55. package/src/ifood/outbound.ts +10 -3
  56. package/src/index.ts +14 -0
  57. package/src/server/copy.ts +20 -2
  58. package/src/server/en-US.ts +13 -0
  59. package/src/server/index.ts +1 -1
  60. package/src/server/link-routes.ts +140 -0
  61. package/src/server/mcp-link.ts +103 -0
  62. package/src/server/mcp.ts +6 -2
  63. package/src/server/pt-BR.ts +13 -0
  64. package/src/server/routes.ts +5 -2
  65. package/src/server/webhook.ts +86 -0
  66. package/dist/chunk-2BA2EHNF.js.map +0 -1
  67. package/dist/chunk-HEXLCTOG.js.map +0 -1
  68. package/dist/chunk-WVZ2IXFH.js.map +0 -1
  69. package/dist/chunk-ZO4S3LF4.js +0 -254
  70. package/dist/chunk-ZO4S3LF4.js.map +0 -1
  71. /package/dist/{chunk-PYHNM47K.js.map → chunk-DCWOQ5PN.js.map} +0 -0
@@ -0,0 +1,170 @@
1
+ import { outboundResultOf, type MarketplaceHttpRequest } from "../core/adapter";
2
+ import type { LinkCallContext, LinkCode, LinkGrant, LinkResult, LinkedMerchant, MarketplaceLinking } from "../core/linking-port";
3
+ import { asString, pick } from "../core/payload-read";
4
+ import { IFOOD_API } from "./outbound";
5
+
6
+ /**
7
+ * iFood's DISTRIBUTED-APP authentication, the wire format only (FUT-5613).
8
+ * Read 2026-11-26 off iFood's own pages, served as Markdown at
9
+ * https://developer.ifood.com.br/pt-BR/docs/guides/modules/authentication/distributed.md
10
+ * and .../merchant/endpoints.md:
11
+ *
12
+ * - `POST /authentication/v1.0/oauth/userCode`, form `clientId` → 200
13
+ * `{ userCode, authorizationCodeVerifier, verificationUrl,
14
+ * verificationUrlComplete, expiresIn }` ("valid for 10 minutes", 600).
15
+ * - `POST /authentication/v1.0/oauth/token`, form `grantType=authorization_code`,
16
+ * `clientId`, `clientSecret`, `authorizationCode`, `authorizationCodeVerifier`
17
+ * → 200 `{ accessToken, type: "bearer", expiresIn }` (6 hours by default)
18
+ * and a refresh token ("returns an access token and a refresh token").
19
+ * - The same URL, `grantType=refresh_token`, `clientId`, `clientSecret`,
20
+ * `refreshToken`.
21
+ * - `GET /merchant/v1.0/merchants?page=&size=` (size default 100) → 200
22
+ * `[{ id, name, corporateName }]`: every store the token covers.
23
+ *
24
+ * ESTIMATED, not settled by those pages:
25
+ * - the refresh token's FIELD name in the token answer: the page's table
26
+ * lists only `accessToken`, `type`, `expiresIn`; `refreshToken` (the name
27
+ * the request takes) is read, and the snake-case twin as a fallback;
28
+ * - whether a refresh ROTATES the refresh token: a new one is stored when
29
+ * answered, the old one kept when not;
30
+ * - the refresh token's own lifetime (unstated: "if the refreshToken
31
+ * expires, the user must authorize again"): a refused refresh marks the
32
+ * connection FAILED for the store to link again;
33
+ * - the status of a wrong or used authorization code: any final 4xx is
34
+ * `refused`.
35
+ */
36
+
37
+ const USER_CODE_URL = `${IFOOD_API}/authentication/v1.0/oauth/userCode`;
38
+ const TOKEN_URL = `${IFOOD_API}/authentication/v1.0/oauth/token`;
39
+ const MERCHANTS_URL = `${IFOOD_API}/merchant/v1.0/merchants`;
40
+
41
+ /** iFood's documented lifetime of a user code, used when the answer states none. */
42
+ const USER_CODE_SECONDS = 600;
43
+ /** iFood's documented default lifetime of an access token: 6 hours. */
44
+ const ACCESS_TOKEN_SECONDS = 21_600;
45
+ /** One page of the merchant list; iFood's documented default. */
46
+ const MERCHANT_PAGE_SIZE = 100;
47
+ /** A ceiling on pages read, so a misbehaving answer cannot loop. */
48
+ const MAX_MERCHANT_PAGES = 20;
49
+
50
+ const FORM = { "Content-Type": "application/x-www-form-urlencoded" };
51
+
52
+ function json(body: string): unknown {
53
+ try {
54
+ return body === "" ? null : (JSON.parse(body) as unknown);
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+
60
+ /** One call whose 2xx body `read` turns into the value; anything else ends it. */
61
+ async function call<T>(
62
+ ctx: LinkCallContext,
63
+ request: MarketplaceHttpRequest,
64
+ read: (body: unknown) => T | null,
65
+ ): Promise<LinkResult<T>> {
66
+ try {
67
+ const response = await ctx.http(request);
68
+ const result = outboundResultOf(response);
69
+ if (result.kind !== "accepted") return result;
70
+ const value = read(json(response.body));
71
+ return value === null
72
+ ? { kind: "refused", status: response.status, message: "iFood's answer is not the documented shape" }
73
+ : { kind: "ok", value };
74
+ } catch (error) {
75
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
76
+ }
77
+ }
78
+
79
+ const positive = (value: unknown, fallback: number): number =>
80
+ typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
81
+
82
+ function codeOf(body: unknown): LinkCode | null {
83
+ const userCode = asString(pick(body, "userCode"));
84
+ const verifier = asString(pick(body, "authorizationCodeVerifier"));
85
+ const verificationUrl = asString(pick(body, "verificationUrl"));
86
+ if (!userCode || !verifier || !verificationUrl) return null;
87
+ return {
88
+ userCode,
89
+ verifier,
90
+ verificationUrl,
91
+ verificationUrlComplete: asString(pick(body, "verificationUrlComplete")) ?? verificationUrl,
92
+ expiresInSeconds: positive(pick(body, "expiresIn"), USER_CODE_SECONDS),
93
+ };
94
+ }
95
+
96
+ function grantOf(body: unknown, requireRefresh: boolean): LinkGrant | null {
97
+ const accessToken = asString(pick(body, "accessToken"));
98
+ const refreshToken = asString(pick(body, "refreshToken")) ?? asString(pick(body, "refresh_token"));
99
+ if (!accessToken || (requireRefresh && !refreshToken)) return null;
100
+ return { accessToken, refreshToken, expiresInSeconds: positive(pick(body, "expiresIn"), ACCESS_TOKEN_SECONDS) };
101
+ }
102
+
103
+ function merchantsOf(body: unknown): LinkedMerchant[] | null {
104
+ if (!Array.isArray(body)) return null;
105
+ return body.flatMap((raw: unknown) => {
106
+ const id = asString(pick(raw, "id"));
107
+ return id ? [{ id, name: asString(pick(raw, "name")), corporateName: asString(pick(raw, "corporateName")) }] : [];
108
+ });
109
+ }
110
+
111
+ const tokenRequest = (fields: Record<string, string>): MarketplaceHttpRequest => ({
112
+ method: "POST",
113
+ url: TOKEN_URL,
114
+ headers: FORM,
115
+ body: new URLSearchParams(fields).toString(),
116
+ });
117
+
118
+ /** Every merchant the token covers, page by page until a short page. */
119
+ async function listMerchants(ctx: LinkCallContext, accessToken: string): Promise<LinkResult<LinkedMerchant[]>> {
120
+ const all: LinkedMerchant[] = [];
121
+ for (let page = 1; page <= MAX_MERCHANT_PAGES; page += 1) {
122
+ const answer = await call(
123
+ ctx,
124
+ {
125
+ method: "GET",
126
+ url: `${MERCHANTS_URL}?page=${page}&size=${MERCHANT_PAGE_SIZE}`,
127
+ headers: { Authorization: `Bearer ${accessToken}` },
128
+ },
129
+ merchantsOf,
130
+ );
131
+ if (answer.kind !== "ok") return answer;
132
+ all.push(...answer.value);
133
+ if (answer.value.length < MERCHANT_PAGE_SIZE) break;
134
+ }
135
+ return { kind: "ok", value: all };
136
+ }
137
+
138
+ /** The iFood adapter's linking half. */
139
+ export const IFOOD_LINKING: MarketplaceLinking = {
140
+ requestCode: (ctx) =>
141
+ call(
142
+ ctx,
143
+ { method: "POST", url: USER_CODE_URL, headers: FORM, body: new URLSearchParams({ clientId: ctx.credentials.clientId }).toString() },
144
+ codeOf,
145
+ ),
146
+ exchange: (ctx, input) =>
147
+ call(
148
+ ctx,
149
+ tokenRequest({
150
+ grantType: "authorization_code",
151
+ clientId: ctx.credentials.clientId,
152
+ clientSecret: ctx.credentials.clientSecret,
153
+ authorizationCode: input.authorizationCode,
154
+ authorizationCodeVerifier: input.verifier,
155
+ }),
156
+ (body) => grantOf(body, true),
157
+ ),
158
+ refresh: (ctx, input) =>
159
+ call(
160
+ ctx,
161
+ tokenRequest({
162
+ grantType: "refresh_token",
163
+ clientId: ctx.credentials.clientId,
164
+ clientSecret: ctx.credentials.clientSecret,
165
+ refreshToken: input.refreshToken,
166
+ }),
167
+ (body) => grantOf(body, false),
168
+ ),
169
+ merchants: (ctx, input) => listMerchants(ctx, input.accessToken),
170
+ };
@@ -38,8 +38,13 @@ export const IFOOD_PORTAL_URL = "https://portal.ifood.com.br/";
38
38
  /** A token is renewed this long before iFood says it expires. */
39
39
  const TOKEN_MARGIN_MS = 60_000;
40
40
 
41
- /** The token cache key: per environment and merchant app. */
42
- export const ifoodTokenKey = (ctx: AdapterCallContext): string => `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`;
41
+ /**
42
+ * The token cache key: per environment and merchant app, or, for a store
43
+ * linked through the software's app (FUT-5613), the store's own grant key, so
44
+ * deleting it after a 401 forgets that store's token and nobody else's.
45
+ */
46
+ export const ifoodTokenKey = (ctx: AdapterCallContext): string =>
47
+ ctx.grant ? ctx.grant.key : `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`;
43
48
 
44
49
  /** iFood's OAuth answer, read defensively: a missing field is "no token". */
45
50
  function tokenOf(body: string): { token: string; expiresInSeconds: number } | null {
@@ -55,10 +60,12 @@ function tokenOf(body: string): { token: string; expiresInSeconds: number } | nu
55
60
 
56
61
  /**
57
62
  * A bearer token for this merchant app, from the per-process cache or a fresh
58
- * client-credentials grant. Keyed by the app's client id, so two stores with
63
+ * client-credentials grant (or, linked, the store's grant). Keyed by the app's client id, so two stores with
59
64
  * two apps never share one. The token lives in memory only.
60
65
  */
61
66
  export async function bearer(ctx: AdapterCallContext): Promise<{ token: string } | OutboundResult> {
67
+ // A linked store: its refresh token buys the token, never a client-credentials grant.
68
+ if (ctx.grant) return ctx.grant.accessToken();
62
69
  const key = ifoodTokenKey(ctx);
63
70
  const cached = ctx.tokens.get(key);
64
71
  if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
package/src/index.ts CHANGED
@@ -28,6 +28,7 @@ export {
28
28
  outboundResultOf,
29
29
  tokenGrantResultOf,
30
30
  type AdapterCallContext,
31
+ type AdapterGrant,
31
32
  type AdapterTokenCache,
32
33
  type CancellationReason,
33
34
  type CancellationRequestInput,
@@ -120,6 +121,7 @@ export type {
120
121
  MarketplaceIntegrationView,
121
122
  SaveMarketplaceIntegrationInput,
122
123
  } from "./core/integration";
124
+ export { MarketplaceMerchantTakenError } from "./core/merchant-claim";
123
125
  export type { MarketplaceMenuLinkView } from "./core/menu-links";
124
126
  export {
125
127
  OutboundRetryError,
@@ -218,3 +220,15 @@ export {
218
220
  type StorePauseWanted,
219
221
  } from "./core/pause-store";
220
222
  export type { AvailabilitySweepResult } from "./core/pause-sweep";
223
+ export type {
224
+ LinkCallContext,
225
+ LinkCode,
226
+ LinkGrant,
227
+ LinkResult,
228
+ LinkedMerchant,
229
+ MarketplaceAppCredentialsPort,
230
+ MarketplaceLinkAttemptDelegate,
231
+ MarketplaceLinking,
232
+ } from "./core/linking-port";
233
+ export type { LinkFailure, LinkFinished, LinkPendingView, LinkRefusalCode } from "./core/linking";
234
+ export type { MarketplaceAuthMode } from "./core/link-store";
@@ -1,8 +1,13 @@
1
1
  import type { BulkProblemCode } from "../core/bulk";
2
2
  import type { DecisionProblemCode } from "../core/cancellation";
3
+ import type { LinkRefusalCode } from "../core/linking";
3
4
 
4
- /** Every problem code a route can answer, decisions and bulk writes alike. */
5
- export type MarketplaceProblemCode = DecisionProblemCode | BulkProblemCode;
5
+ /**
6
+ * Every problem code a route words from `problems`, decisions and bulk writes
7
+ * alike. MERCHANT_TAKEN is worded by `link.problems` instead (FUT-5613), so a
8
+ * host's own pack written against 1.x still compiles.
9
+ */
10
+ export type MarketplaceProblemCode = DecisionProblemCode | Exclude<BulkProblemCode, "MERCHANT_TAKEN">;
6
11
 
7
12
  /**
8
13
  * Every sentence the marketplace routes answer with. Required, no defaults
@@ -22,4 +27,17 @@ export interface MarketplaceServerCopy {
22
27
  orderNoLongerPending: string;
23
28
  /** One sentence per problem code, for each `problems[].message`. */
24
29
  problems: Readonly<Record<MarketplaceProblemCode, string>>;
30
+ /**
31
+ * OPTIONAL in the type, so a host's own pack written against 1.x still
32
+ * compiles: the sentences of the linking routes (FUT-5613). Absent, those
33
+ * routes answer the machine code as `error`. Both shipped packs carry it.
34
+ */
35
+ link?: MarketplaceLinkCopy;
36
+ }
37
+
38
+ /** What the linking routes say: one sentence per refusal, and one for "try again". */
39
+ export interface MarketplaceLinkCopy {
40
+ problems: Readonly<Record<LinkRefusalCode, string>>;
41
+ /** The marketplace did not answer (a timeout, a 5xx, a rate limit). */
42
+ tryAgain: string;
25
43
  }
@@ -19,4 +19,17 @@ export const MARKETPLACE_SERVER_COPY_EN_US = {
19
19
  NOTHING_TO_UPDATE: "Nothing to update.",
20
20
  CATALOG_ITEM_NOT_FOUND: "Product not found.",
21
21
  },
22
+ link: {
23
+ problems: {
24
+ UNAVAILABLE: "Connecting through the app is not available for this marketplace.",
25
+ NO_LINK_IN_PROGRESS: "No connection is in progress. Start again from the first step.",
26
+ LINK_EXPIRED: "The code has expired. Get a new code and repeat the steps.",
27
+ CODE_REFUSED: "The marketplace refused the authorization code. Check the code and paste it again.",
28
+ MARKETPLACE_REFUSED: "The marketplace refused the connection request.",
29
+ NOT_LINKED: "This store is not connected through the app. Connect it again.",
30
+ UNKNOWN_MERCHANT: "This store is not among the ones authorized on the marketplace.",
31
+ MERCHANT_TAKEN: "This marketplace store is already connected to another account.",
32
+ },
33
+ tryAgain: "The marketplace did not answer. Try again in a moment.",
34
+ },
22
35
  } as const satisfies MarketplaceServerCopy;
@@ -29,7 +29,7 @@ export function createApiMarketplace(config: MarketplaceApiConfig): ApiMarketpla
29
29
 
30
30
  export type { MarketplaceActor, MarketplaceApiConfig } from "./http";
31
31
  export type { MarketplaceRoute } from "./routes";
32
- export type { MarketplaceServerCopy } from "./copy";
32
+ export type { MarketplaceLinkCopy, MarketplaceServerCopy } from "./copy";
33
33
  export {
34
34
  MARKETPLACE_DECIDE,
35
35
  MARKETPLACE_MANAGE,
@@ -0,0 +1,140 @@
1
+ import type { WireResponse, WireRoute } from "@12-apps/wiring";
2
+
3
+ import type { MarketplaceIntegrationView } from "../core/integration";
4
+ import type { LinkFailure, LinkPendingView, LinkRefusalCode } from "../core/linking";
5
+ import { MARKETPLACE_MANAGE } from "./contribution";
6
+ import { iso, ok, parse, refuse, type MarketplaceActor, type MarketplaceApiConfig } from "./http";
7
+ import { finishLinkBody, linkMerchantsQuery, linkStateQuery, selectLinkMerchantBody, startLinkBody } from "./mcp-link";
8
+
9
+ /**
10
+ * Linking a store through the software's own marketplace app (FUT-5613), as
11
+ * HTTP, beside the connection routes and behind the same permission:
12
+ *
13
+ * - `GET …/marketplace/link?provider=` — whether linking is available, and the code in progress;
14
+ * - `POST …/marketplace/link/start` — a new portal code (the verifier stays on the server);
15
+ * - `POST …/marketplace/link/finish` — the pasted authorization code, for the store's tokens;
16
+ * - `GET …/marketplace/link/merchants?provider=` — the marketplace stores the grant covers;
17
+ * - `PUT …/marketplace/link/merchant` — which of them this store is.
18
+ *
19
+ * No answer ever carries a token, a verifier or the app's credentials.
20
+ */
21
+
22
+ const BASE = "/admin/:tenantSlug/marketplace/link";
23
+
24
+ /** The HTTP status each refusal answers. */
25
+ const STATUS: Readonly<Record<LinkRefusalCode, number>> = {
26
+ UNAVAILABLE: 409,
27
+ NO_LINK_IN_PROGRESS: 409,
28
+ LINK_EXPIRED: 409,
29
+ CODE_REFUSED: 422,
30
+ MARKETPLACE_REFUSED: 502,
31
+ NOT_LINKED: 409,
32
+ UNKNOWN_MERCHANT: 422,
33
+ MERCHANT_TAKEN: 409,
34
+ };
35
+
36
+ /** A failure as the routes answer it: the host's sentence, the code, and the marketplace's own words. */
37
+ function failed(config: MarketplaceApiConfig, failure: LinkFailure): WireResponse {
38
+ const words = config.copy.link;
39
+ if (failure.kind === "retry") {
40
+ return refuse(503, words?.tryAgain ?? "MARKETPLACE_UNREACHABLE", { code: "MARKETPLACE_UNREACHABLE" });
41
+ }
42
+ return refuse(STATUS[failure.code], words?.problems[failure.code] ?? failure.code, {
43
+ code: failure.code,
44
+ ...(failure.message === null ? {} : { marketplaceStatus: failure.status, marketplaceMessage: failure.message }),
45
+ });
46
+ }
47
+
48
+ const pendingOut = (pending: LinkPendingView | null) => (pending ? { ...pending, expiresAt: pending.expiresAt.toISOString() } : null);
49
+
50
+ function connectionOut(row: MarketplaceIntegrationView) {
51
+ return { ...row, lastEventAt: iso(row.lastEventAt), lastVerifiedAt: iso(row.lastVerifiedAt), archivedAt: iso(row.archivedAt) };
52
+ }
53
+
54
+ /** An unknown provider, before anything is asked of the engine. */
55
+ function unknown(config: MarketplaceApiConfig, id: string): WireResponse | null {
56
+ return config.engine.knows(id) ? null : refuse(422, config.copy.problems.UNKNOWN_PROVIDER, { code: "UNKNOWN_PROVIDER" });
57
+ }
58
+
59
+ function readRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {
60
+ const { engine, copy } = config;
61
+ return [
62
+ {
63
+ method: "GET",
64
+ path: BASE,
65
+ permission: MARKETPLACE_MANAGE,
66
+ handle: async ({ actor, query }) => {
67
+ const parsed = parse(linkStateQuery, query, copy);
68
+ if (!parsed.ok) return parsed.response;
69
+ const refusal = unknown(config, parsed.value.provider);
70
+ if (refusal) return refusal;
71
+ const state = await engine.linkState({ clientId: actor.clientId, ...parsed.value });
72
+ return ok({ available: state.available, pending: pendingOut(state.pending) });
73
+ },
74
+ },
75
+ {
76
+ method: "GET",
77
+ path: `${BASE}/merchants`,
78
+ permission: MARKETPLACE_MANAGE,
79
+ handle: async ({ actor, query }) => {
80
+ const parsed = parse(linkMerchantsQuery, query, copy);
81
+ if (!parsed.ok) return parsed.response;
82
+ const refusal = unknown(config, parsed.value.provider);
83
+ if (refusal) return refusal;
84
+ const result = await engine.linkedMerchants({ clientId: actor.clientId, provider: parsed.value.provider });
85
+ return result.kind === "listed" ? ok(result.merchants) : failed(config, result);
86
+ },
87
+ },
88
+ ];
89
+ }
90
+
91
+ function writeRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {
92
+ const { engine, copy } = config;
93
+ return [
94
+ {
95
+ method: "POST",
96
+ path: `${BASE}/start`,
97
+ permission: MARKETPLACE_MANAGE,
98
+ handle: async ({ actor, body }) => {
99
+ const parsed = parse(startLinkBody, body, copy);
100
+ if (!parsed.ok) return parsed.response;
101
+ const refusal = unknown(config, parsed.value.provider);
102
+ if (refusal) return refusal;
103
+ const result = await engine.startLink({ clientId: actor.clientId, ...parsed.value });
104
+ return result.kind === "started" ? ok(pendingOut(result.pending)) : failed(config, result);
105
+ },
106
+ },
107
+ {
108
+ method: "POST",
109
+ path: `${BASE}/finish`,
110
+ permission: MARKETPLACE_MANAGE,
111
+ handle: async ({ actor, body }) => {
112
+ const parsed = parse(finishLinkBody, body, copy);
113
+ if (!parsed.ok) return parsed.response;
114
+ const refusal = unknown(config, parsed.value.provider);
115
+ if (refusal) return refusal;
116
+ const result = await engine.finishLink({ clientId: actor.clientId, actorId: actor.userId ?? null, ...parsed.value });
117
+ if (result.kind !== "linked") return failed(config, result);
118
+ return ok({ integration: connectionOut(result.integration), merchants: result.merchants });
119
+ },
120
+ },
121
+ {
122
+ method: "PUT",
123
+ path: `${BASE}/merchant`,
124
+ permission: MARKETPLACE_MANAGE,
125
+ handle: async ({ actor, body }) => {
126
+ const parsed = parse(selectLinkMerchantBody, body, copy);
127
+ if (!parsed.ok) return parsed.response;
128
+ const refusal = unknown(config, parsed.value.provider);
129
+ if (refusal) return refusal;
130
+ const result = await engine.selectLinkedMerchant({ clientId: actor.clientId, ...parsed.value });
131
+ return result.kind === "selected" ? ok({ integration: connectionOut(result.integration) }) : failed(config, result);
132
+ },
133
+ },
134
+ ];
135
+ }
136
+
137
+ /** The linking routes, in mount order. */
138
+ export function linkRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {
139
+ return [...readRoutes(config), ...writeRoutes(config)];
140
+ }
@@ -0,0 +1,103 @@
1
+ import { z } from "zod";
2
+
3
+ import type { WireMcpTool } from "@12-apps/wiring";
4
+
5
+ /**
6
+ * The linking tools (FUT-5613), one per linking route, authored once and
7
+ * reused as the routes' validators. Every input is STRICT. No answer carries a
8
+ * token, a verifier or the app's credentials.
9
+ */
10
+
11
+ const provider = z.string().regex(/^[A-Z][A-Z0-9_]*$/u);
12
+ const environment = z.enum(["SANDBOX", "PRODUCTION"]);
13
+
14
+ /** Whether linking is available, and the code in progress. */
15
+ export const linkStateQuery = z.strictObject({ provider, environment: environment.optional() });
16
+ /** Start a linking: a new portal code. */
17
+ export const startLinkBody = z.strictObject({ provider, environment: environment.optional() });
18
+ /** Finish it with the authorization code the person pasted. */
19
+ export const finishLinkBody = z.strictObject({
20
+ provider,
21
+ authorizationCode: z.string().trim().min(1).max(512),
22
+ enabled: z.boolean().optional(),
23
+ });
24
+ /** The marketplace stores a linked connection's grant covers. */
25
+ export const linkMerchantsQuery = z.strictObject({ provider });
26
+ /** Which of them this store is. */
27
+ export const selectLinkMerchantBody = z.strictObject({ provider, merchantId: z.string().trim().min(1).max(200) });
28
+
29
+ const pendingSchema = z.object({
30
+ userCode: z.string(),
31
+ verificationUrl: z.string(),
32
+ verificationUrlComplete: z.string(),
33
+ expiresAt: z.string(),
34
+ });
35
+
36
+ const merchantSchema = z.object({ id: z.string(), name: z.string().nullable(), corporateName: z.string().nullable() });
37
+
38
+ const BASE = "/admin/{tenantSlug}/marketplace/link";
39
+
40
+ /** The five linking tools, over the connection schema the connection tools answer. */
41
+ export function marketplaceLinkTools<P extends z.ZodType, I extends z.ZodType>(params: P, integration: I) {
42
+ return [
43
+ {
44
+ operationId: "getMarketplaceLink",
45
+ method: "GET",
46
+ path: BASE,
47
+ summary:
48
+ "Read in one call whether a store can connect a marketplace through the software's own app (no credentials typed), and the portal code still in progress, if any: `userCode`, the portal link that already carries it, and when it expires.",
49
+ tags: ["marketplace"],
50
+ params,
51
+ query: linkStateQuery,
52
+ response: z.object({ data: z.object({ available: z.boolean(), pending: pendingSchema.nullable() }) }),
53
+ annotations: { readOnly: true },
54
+ },
55
+ {
56
+ operationId: "listMarketplaceLinkMerchants",
57
+ method: "GET",
58
+ path: `${BASE}/merchants`,
59
+ summary: "List the marketplace stores a linked connection's authorization covers, to choose which one this store is.",
60
+ tags: ["marketplace"],
61
+ params,
62
+ query: linkMerchantsQuery,
63
+ response: z.object({ data: z.array(merchantSchema) }),
64
+ annotations: { readOnly: true, openWorld: true },
65
+ },
66
+ {
67
+ operationId: "startMarketplaceLink",
68
+ method: "POST",
69
+ path: `${BASE}/start`,
70
+ summary:
71
+ "Start connecting a marketplace through the software's own app in one call: answers the code the person types on the marketplace's portal and the portal link that already carries it (valid ten minutes on iFood). Replaces a code in progress. 409 UNAVAILABLE when the software has no app on that marketplace.",
72
+ tags: ["marketplace"],
73
+ params,
74
+ body: startLinkBody,
75
+ response: z.object({ data: pendingSchema }),
76
+ annotations: { readOnly: false, destructive: false, openWorld: true },
77
+ },
78
+ {
79
+ operationId: "finishMarketplaceLink",
80
+ method: "POST",
81
+ path: `${BASE}/finish`,
82
+ summary:
83
+ "Finish connecting, in one call, with the authorization code the marketplace's portal showed the person. Stores the connection as LINKED and selects the marketplace store when the authorization covers only one; `merchants` lists them (null when they could not be listed). 422 CODE_REFUSED for a wrong code (the code in progress stays, paste again); 409 LINK_EXPIRED past its ten minutes.",
84
+ tags: ["marketplace"],
85
+ params,
86
+ body: finishLinkBody,
87
+ response: z.object({ data: z.object({ integration, merchants: z.array(merchantSchema).nullable() }) }),
88
+ annotations: { readOnly: false, destructive: false, openWorld: true },
89
+ },
90
+ {
91
+ operationId: "selectMarketplaceLinkMerchant",
92
+ method: "PUT",
93
+ path: `${BASE}/merchant`,
94
+ summary:
95
+ "Choose in one call which marketplace store a linked connection is, among those its authorization covers. 422 UNKNOWN_MERCHANT for one it does not cover; 409 MERCHANT_TAKEN when another store's connection holds it.",
96
+ tags: ["marketplace"],
97
+ params,
98
+ body: selectLinkMerchantBody,
99
+ response: z.object({ data: z.object({ integration }) }),
100
+ annotations: { readOnly: false, destructive: false, openWorld: true },
101
+ },
102
+ ] as const satisfies readonly WireMcpTool<z.ZodType>[];
103
+ }
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
  ];