@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,363 @@
1
+ import { listMarketplaceIntegrations, readOutboundConnection, type MarketplaceIntegrationView } from "./integration";
2
+ import { appCredentialsOf, cacheLinkToken, linkTokenKey, sealLink } from "./link-store";
3
+ import type { LinkCallContext, LinkedMerchant, MarketplaceLinking } from "./linking-port";
4
+ import { MarketplaceMerchantTakenError, guardMerchantClaim, isUniqueViolation, merchantHeldElsewhere } from "./merchant-claim";
5
+ import type { EngineContext, MarketplaceDb } from "./ports";
6
+ import type { MarketplaceProvider } from "./types";
7
+
8
+ /**
9
+ * Linking a store through the software's own app (FUT-5613), as the host
10
+ * calls it: start (the portal code), finish (the authorization code the store
11
+ * pastes back), and choose the marketplace store when the grant covers more
12
+ * than one. The wire format is the adapter's `linking`; the rows, the sealing
13
+ * and the rules are here.
14
+ *
15
+ * The verifier never leaves the server: `start` keeps it sealed in the
16
+ * store's link attempt and answers only what a person reads.
17
+ */
18
+
19
+ type Environment = "SANDBOX" | "PRODUCTION";
20
+
21
+ /** Why a linking call did nothing. Vocabulary, not copy: the host words each. */
22
+ export type LinkRefusalCode =
23
+ /** No app configured for this marketplace, the adapter links nothing, or the host has no link table. */
24
+ | "UNAVAILABLE"
25
+ /** `finish` with no `start` before it (or after another finish used it). */
26
+ | "NO_LINK_IN_PROGRESS"
27
+ /** The portal code's ten minutes are over: start again. */
28
+ | "LINK_EXPIRED"
29
+ /** The marketplace refused the authorization code (wrong, used, or for another code). */
30
+ | "CODE_REFUSED"
31
+ /** The marketplace refused another call (the code request, the merchant list). */
32
+ | "MARKETPLACE_REFUSED"
33
+ /** `selectMerchant` on a connection that is not linked, or is archived. */
34
+ | "NOT_LINKED"
35
+ /** The merchant is not one the grant covers. */
36
+ | "UNKNOWN_MERCHANT"
37
+ /** Another store's live connection already holds that merchant. */
38
+ | "MERCHANT_TAKEN";
39
+
40
+ /** A linking call that did nothing: refused for good, or worth trying again. */
41
+ export type LinkFailure =
42
+ | { kind: "refused"; code: LinkRefusalCode; status: number | null; message: string | null }
43
+ | { kind: "retry"; reason: string };
44
+
45
+ /** A linking in progress, as a person sees it: never the verifier. */
46
+ export interface LinkPendingView {
47
+ userCode: string;
48
+ verificationUrl: string;
49
+ verificationUrlComplete: string;
50
+ expiresAt: Date;
51
+ }
52
+
53
+ interface AttemptRow {
54
+ environment: string;
55
+ /** Sealed; a new `start` seals a new one, so it tells this attempt from a later one. */
56
+ verifier: string;
57
+ userCode: string;
58
+ verificationUrl: string;
59
+ verificationUrlComplete: string;
60
+ expiresAt: Date;
61
+ }
62
+
63
+ const refused = (code: LinkRefusalCode, status: number | null = null, message: string | null = null): LinkFailure => ({
64
+ kind: "refused",
65
+ code,
66
+ status,
67
+ message,
68
+ });
69
+
70
+ const pendingOf = (row: AttemptRow): LinkPendingView => ({
71
+ userCode: row.userCode,
72
+ verificationUrl: row.verificationUrl,
73
+ verificationUrlComplete: row.verificationUrlComplete,
74
+ expiresAt: row.expiresAt,
75
+ });
76
+
77
+ /** What a linking call needs, or null when linking is unavailable here. */
78
+ async function linkingOf(
79
+ ctx: EngineContext,
80
+ provider: MarketplaceProvider,
81
+ environment: Environment,
82
+ ): Promise<{ linking: MarketplaceLinking; call: LinkCallContext; attempts: NonNullable<MarketplaceDb["marketplaceLinkAttempt"]> } | null> {
83
+ const linking = ctx.registry.get(provider)?.linking;
84
+ if (!linking) return null;
85
+ const attempts = (await ctx.ports.db()).marketplaceLinkAttempt;
86
+ if (!attempts) return null;
87
+ const app = await appCredentialsOf(ctx, provider, environment);
88
+ if (!app) return null;
89
+ return { linking, attempts, call: { http: ctx.ports.http, credentials: app, environment, now: ctx.ports.clock.now() } };
90
+ }
91
+
92
+ const keyOf = (clientId: string, provider: string) => ({ clientId_provider: { clientId, provider } });
93
+
94
+ /** Whether this store can link this marketplace, and the linking it left in progress, if still live. */
95
+ export async function linkState(
96
+ ctx: EngineContext,
97
+ input: { clientId: string; provider: MarketplaceProvider; environment?: Environment },
98
+ ): Promise<{ available: boolean; pending: LinkPendingView | null }> {
99
+ const ready = await linkingOf(ctx, input.provider, input.environment ?? "PRODUCTION");
100
+ if (!ready) return { available: false, pending: null };
101
+ const row = (await ready.attempts.findUnique({ where: keyOf(input.clientId, input.provider) })) as AttemptRow | null;
102
+ const live = row && row.expiresAt.getTime() > ctx.ports.clock.now().getTime();
103
+ return { available: true, pending: live ? pendingOf(row) : null };
104
+ }
105
+
106
+ /** Ask the marketplace for a portal code; keep its verifier, sealed, for this store. Replaces any earlier one. */
107
+ export async function startLink(
108
+ ctx: EngineContext,
109
+ input: { clientId: string; provider: MarketplaceProvider; environment?: Environment },
110
+ ): Promise<{ kind: "started"; pending: LinkPendingView } | LinkFailure> {
111
+ const environment = input.environment ?? "PRODUCTION";
112
+ const ready = await linkingOf(ctx, input.provider, environment);
113
+ if (!ready) return refused("UNAVAILABLE");
114
+ const answer = await ready.linking.requestCode(ready.call);
115
+ if (answer.kind === "retry") return answer;
116
+ if (answer.kind === "refused") return refused("MARKETPLACE_REFUSED", answer.status, answer.message);
117
+ const code = answer.value;
118
+ const row = {
119
+ environment,
120
+ verifier: ctx.ports.secrets.seal(code.verifier),
121
+ userCode: code.userCode,
122
+ verificationUrl: code.verificationUrl,
123
+ verificationUrlComplete: code.verificationUrlComplete,
124
+ expiresAt: new Date(ready.call.now.getTime() + code.expiresInSeconds * 1000),
125
+ };
126
+ await ready.attempts.upsert({
127
+ where: keyOf(input.clientId, input.provider),
128
+ create: { clientId: input.clientId, provider: input.provider, ...row },
129
+ update: row,
130
+ });
131
+ return { kind: "started", pending: pendingOf(row) };
132
+ }
133
+
134
+ /**
135
+ * Which merchant a fresh link selects: the only one the grant covers, else
136
+ * the one the connection already named if the grant still covers it, else
137
+ * none (the host asks). A merchant another store holds is never selected.
138
+ */
139
+ async function chooseMerchant(
140
+ db: MarketplaceDb,
141
+ input: { clientId: string; provider: string },
142
+ merchants: readonly LinkedMerchant[] | null,
143
+ current: string | null,
144
+ ): Promise<string | null> {
145
+ if (!merchants) return current;
146
+ const candidate =
147
+ merchants.length === 1 ? merchants[0]!.id : merchants.some((merchant) => merchant.id === current) ? current : null;
148
+ if (candidate === null) return null;
149
+ return (await merchantHeldElsewhere(db, input.clientId, input.provider, candidate)) ? null : candidate;
150
+ }
151
+
152
+ /** A link to save: its tokens, the merchants its grant covers, and the sealed verifier of the attempt it used. */
153
+ interface LinkToSave {
154
+ environment: Environment;
155
+ refreshToken: string;
156
+ merchants: readonly LinkedMerchant[] | null;
157
+ verifier: string;
158
+ }
159
+
160
+ /**
161
+ * Save the linked connection, unarchiving it (with its audit line) when the
162
+ * store had disconnected, and remove the attempt it used: only that one, so a
163
+ * `start` that landed meanwhile keeps its code. Answers the sealed blob saved.
164
+ */
165
+ async function saveLink(
166
+ ctx: EngineContext,
167
+ input: { clientId: string; provider: string; actorId: string | null; enabled?: boolean },
168
+ link: LinkToSave,
169
+ ): Promise<string> {
170
+ const now = ctx.ports.clock.now();
171
+ const credentials = sealLink(ctx, link.refreshToken);
172
+ await ctx.ports.transaction(async (db) => {
173
+ const existing = (await db.marketplaceIntegration.findUnique({
174
+ where: keyOf(input.clientId, input.provider),
175
+ select: { archivedAt: true, externalMerchantId: true },
176
+ })) as { archivedAt: Date | null; externalMerchantId: string | null } | null;
177
+ const data = {
178
+ credentials,
179
+ authMode: "LINKED",
180
+ environment: link.environment,
181
+ status: "VERIFIED",
182
+ lastVerifiedAt: now,
183
+ archivedAt: null,
184
+ externalMerchantId: await chooseMerchant(db, input, link.merchants, existing?.externalMerchantId ?? null),
185
+ ...(input.enabled === undefined ? {} : { enabled: input.enabled }),
186
+ };
187
+ await db.marketplaceIntegration.upsert({
188
+ where: keyOf(input.clientId, input.provider),
189
+ create: { clientId: input.clientId, provider: input.provider, ackSlaSeconds: ctx.ports.defaultAckSlaSeconds, ...data },
190
+ update: data,
191
+ });
192
+ if (existing?.archivedAt) {
193
+ await ctx.ports.audit.record(
194
+ {
195
+ clientId: input.clientId,
196
+ actorId: input.actorId,
197
+ action: "marketplace.integration.unarchive",
198
+ provider: input.provider,
199
+ reason: "linked again",
200
+ at: now,
201
+ },
202
+ db,
203
+ );
204
+ }
205
+ await db.marketplaceLinkAttempt!.deleteMany({ where: { clientId: input.clientId, provider: input.provider, verifier: link.verifier } });
206
+ });
207
+ return credentials;
208
+ }
209
+
210
+ /**
211
+ * {@link saveLink}, and once more with no merchant chosen when another
212
+ * store's write of the same merchant won the race (the unique index refused
213
+ * this one): the code is spent, so the tokens are kept whatever happens to the
214
+ * merchant, and the store chooses one afterwards.
215
+ */
216
+ async function saveLinkKeepingTokens(
217
+ ctx: EngineContext,
218
+ input: { clientId: string; provider: string; actorId: string | null; enabled?: boolean },
219
+ link: LinkToSave,
220
+ ): Promise<string> {
221
+ try {
222
+ return await saveLink(ctx, input, link);
223
+ } catch (error) {
224
+ if (!isUniqueViolation(error)) throw error;
225
+ ctx.ports.logger.warn(`marketplace.link: ${input.provider} merchant of ${input.clientId} taken meanwhile; none chosen`);
226
+ return saveLink(ctx, input, { ...link, merchants: [] });
227
+ }
228
+ }
229
+
230
+ /** The connection as every read surface sees it, after a link wrote it. */
231
+ async function viewOf(ctx: EngineContext, clientId: string, provider: string): Promise<MarketplaceIntegrationView> {
232
+ const [view] = await listMarketplaceIntegrations(ctx, clientId, { providers: [provider] });
233
+ if (!view) throw new Error(`The ${provider} connection of ${clientId} was not saved.`);
234
+ return view;
235
+ }
236
+
237
+ /** What `finishLink` answers: the connection, and the merchants the grant covers (null when they could not be listed). */
238
+ export interface LinkFinished {
239
+ kind: "linked";
240
+ integration: MarketplaceIntegrationView;
241
+ merchants: LinkedMerchant[] | null;
242
+ }
243
+
244
+ /**
245
+ * Exchange the authorization code the store pasted, with the verifier kept at
246
+ * `start`, for its tokens; store them on the connection (LINKED, VERIFIED,
247
+ * unarchived) and select the merchant when the grant covers only one. A
248
+ * refused code keeps the attempt, so the person can paste again inside the
249
+ * ten minutes.
250
+ */
251
+ export async function finishLink(
252
+ ctx: EngineContext,
253
+ input: { clientId: string; provider: MarketplaceProvider; authorizationCode: string; actorId: string | null; enabled?: boolean },
254
+ ): Promise<LinkFinished | LinkFailure> {
255
+ const opened = await openAttempt(ctx, input);
256
+ if ("kind" in opened) return opened;
257
+ const { ready, environment, verifier, sealedVerifier } = opened;
258
+ const exchanged = await ready.linking.exchange(ready.call, { authorizationCode: input.authorizationCode.trim(), verifier });
259
+ if (exchanged.kind === "retry") return exchanged;
260
+ if (exchanged.kind === "refused") return refused("CODE_REFUSED", exchanged.status, exchanged.message);
261
+ const grant = exchanged.value;
262
+ if (grant.refreshToken === null) return refused("CODE_REFUSED", null, "the marketplace answered no refresh token");
263
+
264
+ // The code is spent: from here on the tokens are saved whatever the merchant list says.
265
+ const listed = await ready.linking.merchants(ready.call, { accessToken: grant.accessToken });
266
+ const merchants = listed.kind === "ok" ? listed.value : null;
267
+ if (listed.kind !== "ok") {
268
+ ctx.ports.logger.warn(`marketplace.link: ${input.provider} merchants of ${input.clientId} not listed (${listed.kind})`);
269
+ }
270
+ const sealed = await saveLinkKeepingTokens(ctx, input, { environment, refreshToken: grant.refreshToken, merchants, verifier: sealedVerifier });
271
+ await cacheLinkToken(ctx, { ...input, sealed }, linkTokenKey(input.provider, environment, input.clientId), grant);
272
+ ctx.ports.publishChanged(input.clientId);
273
+ return { kind: "linked", integration: await viewOf(ctx, input.clientId, input.provider), merchants };
274
+ }
275
+
276
+ type Ready = NonNullable<Awaited<ReturnType<typeof linkingOf>>>;
277
+
278
+ /** The store's live attempt, opened: its verifier and the app to exchange it with. */
279
+ async function openAttempt(
280
+ ctx: EngineContext,
281
+ input: { clientId: string; provider: MarketplaceProvider },
282
+ ): Promise<{ ready: Ready; environment: Environment; verifier: string; sealedVerifier: string } | LinkFailure> {
283
+ const attempts = (await ctx.ports.db()).marketplaceLinkAttempt;
284
+ if (!attempts) return refused("UNAVAILABLE");
285
+ const attempt = (await attempts.findUnique({ where: keyOf(input.clientId, input.provider) })) as AttemptRow | null;
286
+ if (!attempt) return refused("NO_LINK_IN_PROGRESS");
287
+ const environment: Environment = attempt.environment === "SANDBOX" ? "SANDBOX" : "PRODUCTION";
288
+ const ready = await linkingOf(ctx, input.provider, environment);
289
+ if (!ready) return refused("UNAVAILABLE");
290
+ if (attempt.expiresAt.getTime() <= ready.call.now.getTime()) return refused("LINK_EXPIRED");
291
+ return { ready, environment, verifier: ctx.ports.secrets.open(attempt.verifier), sealedVerifier: attempt.verifier };
292
+ }
293
+
294
+ /** A linked connection's call context and a live access token, through its own grant. */
295
+ async function grantCall(
296
+ ctx: EngineContext,
297
+ clientId: string,
298
+ provider: MarketplaceProvider,
299
+ ): Promise<{ call: LinkCallContext; accessToken: string } | LinkFailure> {
300
+ const views = await listMarketplaceIntegrations(ctx, clientId, { providers: [provider] });
301
+ if (views[0]?.authMode !== "LINKED") return refused("NOT_LINKED");
302
+ const connection = await readOutboundConnection(ctx, clientId, provider).catch(() => null);
303
+ if (!connection?.grant) return refused("UNAVAILABLE");
304
+ const token = await connection.grant.accessToken();
305
+ if ("token" in token) {
306
+ const call = { http: ctx.ports.http, credentials: connection.credentials, environment: connection.environment, now: ctx.ports.clock.now() };
307
+ return { call, accessToken: token.token };
308
+ }
309
+ if (token.kind === "retry") return token;
310
+ return token.kind === "refused" ? refused("NOT_LINKED", token.status, token.message) : refused("NOT_LINKED");
311
+ }
312
+
313
+ /** The merchants a linked connection's grant covers, listed through the grant itself. */
314
+ async function grantMerchants(
315
+ ctx: EngineContext,
316
+ clientId: string,
317
+ provider: MarketplaceProvider,
318
+ ): Promise<LinkedMerchant[] | LinkFailure> {
319
+ const linking = ctx.registry.get(provider)?.linking;
320
+ if (!linking) return refused("UNAVAILABLE");
321
+ const granted = await grantCall(ctx, clientId, provider);
322
+ if ("kind" in granted) return granted;
323
+ const listed = await linking.merchants(granted.call, { accessToken: granted.accessToken });
324
+ if (listed.kind === "ok") return listed.value;
325
+ return listed.kind === "retry" ? listed : refused("MARKETPLACE_REFUSED", listed.status, listed.message);
326
+ }
327
+
328
+ /** The merchants a linked connection covers, for the screen's choice. */
329
+ export async function linkedMerchants(
330
+ ctx: EngineContext,
331
+ input: { clientId: string; provider: MarketplaceProvider },
332
+ ): Promise<{ kind: "listed"; merchants: LinkedMerchant[] } | LinkFailure> {
333
+ const merchants = await grantMerchants(ctx, input.clientId, input.provider);
334
+ return Array.isArray(merchants) ? { kind: "listed", merchants } : merchants;
335
+ }
336
+
337
+ /** Choose which marketplace store a linked connection is (the grant covers more than one). */
338
+ export async function selectLinkedMerchant(
339
+ ctx: EngineContext,
340
+ input: { clientId: string; provider: MarketplaceProvider; merchantId: string },
341
+ ): Promise<{ kind: "selected"; integration: MarketplaceIntegrationView } | LinkFailure> {
342
+ const merchants = await grantMerchants(ctx, input.clientId, input.provider);
343
+ if (!Array.isArray(merchants)) return merchants;
344
+ if (!merchants.some((merchant) => merchant.id === input.merchantId)) return refused("UNKNOWN_MERCHANT");
345
+ const db = await ctx.ports.db();
346
+ if (await merchantHeldElsewhere(db, input.clientId, input.provider, input.merchantId)) return refused("MERCHANT_TAKEN");
347
+ // A race lost between the check and the write: the unique index refuses it, read as the same refusal.
348
+ const write = () =>
349
+ db.marketplaceIntegration.updateMany({
350
+ where: { clientId: input.clientId, provider: input.provider, authMode: "LINKED", archivedAt: null },
351
+ data: { externalMerchantId: input.merchantId },
352
+ });
353
+ const taken = await guardMerchantClaim(ctx, { ...input, merchantId: input.merchantId }, write).then(
354
+ () => false,
355
+ (error: unknown) => {
356
+ if (error instanceof MarketplaceMerchantTakenError) return true;
357
+ throw error;
358
+ },
359
+ );
360
+ if (taken) return refused("MERCHANT_TAKEN");
361
+ ctx.ports.publishChanged(input.clientId);
362
+ return { kind: "selected", integration: await viewOf(ctx, input.clientId, input.provider) };
363
+ }
@@ -0,0 +1,106 @@
1
+ import type { EngineContext, MarketplaceDb } from "./ports";
2
+
3
+ /**
4
+ * One marketplace store, one live connection (FUT-5613).
5
+ *
6
+ * The app's single webhook address finds the store a delivery belongs to by
7
+ * the merchant id it names, so a merchant id held by two live connections of
8
+ * one marketplace would hand one store's orders to another. Every write that
9
+ * sets or revives a merchant id refuses one another store's live connection
10
+ * holds, and the migration's partial unique index
11
+ * (`marketplace_integrations_live_merchant_key`) closes the race between the
12
+ * check and the write: the loser's unique violation reads as the same refusal.
13
+ */
14
+
15
+ /** Thrown by a single save whose merchant id another store's live connection holds. */
16
+ export class MarketplaceMerchantTakenError extends Error {
17
+ readonly code = "MERCHANT_TAKEN" as const;
18
+ /** The field the refusal is about, as a problem path. */
19
+ readonly path = ["externalMerchantId"] as const;
20
+ constructor(provider: string, merchantId: string) {
21
+ super(`The ${provider} merchant ${merchantId} is already held by another store's live connection.`);
22
+ this.name = "MarketplaceMerchantTakenError";
23
+ }
24
+ }
25
+
26
+ /** A unique violation, as Prisma (`P2002`) or Postgres (`23505`) reports it. */
27
+ export function isUniqueViolation(error: unknown): boolean {
28
+ const code = (error as { code?: unknown } | null)?.code;
29
+ return code === "P2002" || code === "23505";
30
+ }
31
+
32
+ /** Whether another store's live connection to this marketplace already holds this merchant. */
33
+ export async function merchantHeldElsewhere(
34
+ db: MarketplaceDb,
35
+ clientId: string,
36
+ provider: string,
37
+ merchantId: string,
38
+ ): Promise<boolean> {
39
+ const rows = (await db.marketplaceIntegration.findMany({
40
+ where: { provider, externalMerchantId: merchantId, archivedAt: null },
41
+ select: { clientId: true },
42
+ })) as { clientId: string }[];
43
+ return rows.some((row) => row.clientId !== clientId);
44
+ }
45
+
46
+ /** Throw {@link MarketplaceMerchantTakenError} when a write would set a merchant id another store's live connection holds. */
47
+ export async function assertMerchantFree(
48
+ db: MarketplaceDb,
49
+ clientId: string,
50
+ provider: string,
51
+ merchantId: string | null | undefined,
52
+ ): Promise<void> {
53
+ if (merchantId && (await merchantHeldElsewhere(db, clientId, provider, merchantId))) {
54
+ throw new MarketplaceMerchantTakenError(provider, merchantId);
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Run a write that sets `merchantId` on this store's connection. A unique
60
+ * violation it raises is the merchant index's when, read again on a fresh
61
+ * client (the write's transaction is gone), another store holds the merchant:
62
+ * it is thrown as {@link MarketplaceMerchantTakenError}. Anything else is thrown
63
+ * as it came.
64
+ */
65
+ export async function guardMerchantClaim<T>(
66
+ ctx: EngineContext,
67
+ claim: { clientId: string; provider: string; merchantId: string | null | undefined },
68
+ write: () => Promise<T>,
69
+ ): Promise<T> {
70
+ try {
71
+ return await write();
72
+ } catch (error) {
73
+ const { merchantId } = claim;
74
+ if (!isUniqueViolation(error) || !merchantId) throw error;
75
+ if (!(await merchantHeldElsewhere(await ctx.ports.db(), claim.clientId, claim.provider, merchantId))) throw error;
76
+ throw new MarketplaceMerchantTakenError(claim.provider, merchantId);
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Which tenant a delivery belongs to, resolved from the merchant id the
82
+ * marketplace names.
83
+ *
84
+ * Matched against the column OUTSIDE the ciphertext, which is the whole reason
85
+ * `externalMerchantId` lives there: attributing a delivery must not require
86
+ * decrypting every store's secrets to find the match. A merchant two live
87
+ * connections hold (rows a host wrote before the unique index) attributes to
88
+ * nobody: picking one would hand one store's orders to another.
89
+ */
90
+ export async function resolveTenantByMerchant(
91
+ ctx: EngineContext,
92
+ provider: string,
93
+ externalMerchantId: string,
94
+ ): Promise<string | null> {
95
+ const db = await ctx.ports.db();
96
+ const rows = (await db.marketplaceIntegration.findMany({
97
+ where: { provider, externalMerchantId, archivedAt: null },
98
+ select: { clientId: true },
99
+ take: 2,
100
+ })) as { clientId: string }[];
101
+ if (rows.length > 1) {
102
+ ctx.ports.logger.warn(`marketplace: ${provider} merchant ${externalMerchantId} is held by several live connections`);
103
+ return null;
104
+ }
105
+ return rows[0]?.clientId ?? null;
106
+ }
package/src/core/ports.ts CHANGED
@@ -2,6 +2,7 @@ import type { AdapterRegistry } from "./registry";
2
2
  import type { AdapterTokenCache, MarketplaceAdapter, MarketplaceHttp, StatusStep } from "./adapter";
3
3
  import type { CatalogueImage, CatalogueItem } from "./catalogue-port";
4
4
  import type { MarketplaceLifecycleAnswer, MarketplaceLifecycleFacts } from "./lifecycle-port";
5
+ import type { MarketplaceAppCredentialsPort, MarketplaceLinkAttemptDelegate } from "./linking-port";
5
6
  import type {
6
7
  CancellationFailureReason,
7
8
  MarketplaceAdmission,
@@ -110,6 +111,7 @@ export interface MarketplaceDb {
110
111
  create(args: unknown): Promise<unknown>;
111
112
  updateMany(args: unknown): Promise<{ count: number }>;
112
113
  };
114
+ marketplaceLinkAttempt?: MarketplaceLinkAttemptDelegate; // OPTIONAL, as above; absent: no linking (FUT-5613).
113
115
  }
114
116
 
115
117
  /** One decision as the host's admission sees it, BEFORE the claim commits. */
@@ -333,6 +335,7 @@ export interface MarketplacePorts {
333
335
  * catalogue. Absent: every catalogue call answers `UNSUPPORTED`.
334
336
  */
335
337
  catalogue?: MarketplaceCataloguePort;
338
+ appCredentials?: MarketplaceAppCredentialsPort; // OPTIONAL. The software's own app, to link a store (FUT-5613).
336
339
  /** The acceptance window a connection gets when it does not state its own. */
337
340
  defaultAckSlaSeconds: number;
338
341
  /** How many stored deliveries one reconciliation pass re-runs. */
@@ -2,6 +2,7 @@ import type { CancellationReason, MarketplaceAdapter } from "../core/adapter";
2
2
  import { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from "./copy";
3
3
  import { IFOOD_CATALOGUE } from "./catalogue";
4
4
  import { IFOOD_CATALOGUE_READER } from "./catalogue-read";
5
+ import { IFOOD_LINKING } from "./linking";
5
6
  import { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
6
7
  import { IFOOD_PORTAL_URL, ifoodConfirm, ifoodInformStatus, ifoodRequestCancellation, ifoodStatusSupported } from "./outbound";
7
8
  import { IFOOD_AVAILABILITY } from "./pause";
@@ -79,6 +80,8 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
79
80
  informStatus: ifoodInformStatus,
80
81
  // The Merchant API's interruptions: an id and an end per closure (FUT-4851).
81
82
  availability: IFOOD_AVAILABILITY,
83
+ // The distributed-app authorization: a store links the software's own app (FUT-5613).
84
+ linking: IFOOD_LINKING,
82
85
  // No per-order deep link is known, so the portal, where a live order is
83
86
  // on the first screen.
84
87
  appLink: () => IFOOD_PORTAL_URL,
@@ -89,5 +92,6 @@ export { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from
89
92
  export { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
90
93
  export { IFOOD_CATALOGUE, ifoodItemBody, ifoodItemId, ifoodProductId } from "./catalogue";
91
94
  export { IFOOD_CATALOGUE_READER } from "./catalogue-read";
95
+ export { IFOOD_LINKING } from "./linking";
92
96
  export { IFOOD_IMAGE_BASE_URL } from "./catalogue-snapshot";
93
97
  export { IFOOD_AVAILABILITY, ifoodLocalTime, ifoodPause, ifoodResume } from "./pause";