@12-apps/marketplace 1.9.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 (75) hide show
  1. package/ADOPTING.md +63 -1
  2. package/README.md +64 -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-CD0SfdVS.d.ts} +124 -1
  6. package/dist/{chunk-PYHNM47K.js → chunk-DCWOQ5PN.js} +2 -2
  7. package/dist/{chunk-6N2HEV3U.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-BMCERPQX.js → chunk-YWMEIMO3.js} +221 -27
  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-wmW-VuBL.d.ts → engine-C_3RK8wC.d.ts} +207 -64
  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 +280 -26
  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 +223 -2
  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 +246 -8
  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 +47 -0
  43. package/prisma/migrations/20261126230000_marketplace_menu_link_variation/migration.sql +11 -0
  44. package/prisma/migrations/20261127090000_marketplace_app_link/migration.sql +81 -0
  45. package/src/core/adapter.ts +21 -0
  46. package/src/core/bulk.ts +77 -15
  47. package/src/core/engine.ts +59 -3
  48. package/src/core/ingest.ts +2 -1
  49. package/src/core/integration.ts +60 -32
  50. package/src/core/link-store.ts +170 -0
  51. package/src/core/linking-port.ts +100 -0
  52. package/src/core/linking.ts +363 -0
  53. package/src/core/menu-links.ts +36 -6
  54. package/src/core/merchant-claim.ts +106 -0
  55. package/src/core/order-types.ts +74 -0
  56. package/src/core/ports.ts +26 -65
  57. package/src/ifood/index.ts +4 -0
  58. package/src/ifood/linking.ts +170 -0
  59. package/src/ifood/outbound.ts +10 -3
  60. package/src/index.ts +14 -0
  61. package/src/server/copy.ts +20 -2
  62. package/src/server/en-US.ts +13 -0
  63. package/src/server/index.ts +1 -1
  64. package/src/server/link-routes.ts +140 -0
  65. package/src/server/mcp-link.ts +103 -0
  66. package/src/server/mcp.ts +13 -4
  67. package/src/server/pt-BR.ts +13 -0
  68. package/src/server/routes.ts +5 -2
  69. package/src/server/webhook.ts +86 -0
  70. package/dist/chunk-6N2HEV3U.js.map +0 -1
  71. package/dist/chunk-BMCERPQX.js.map +0 -1
  72. package/dist/chunk-HEXLCTOG.js.map +0 -1
  73. package/dist/chunk-NP4EYKPO.js +0 -252
  74. package/dist/chunk-NP4EYKPO.js.map +0 -1
  75. /package/dist/{chunk-PYHNM47K.js.map → chunk-DCWOQ5PN.js.map} +0 -0
package/src/core/bulk.ts CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  type MarketplaceIntegrationView,
5
5
  type SaveMarketplaceIntegrationInput,
6
6
  } from "./integration";
7
+ import { MarketplaceMerchantTakenError, isUniqueViolation, merchantHeldElsewhere } from "./merchant-claim";
7
8
  import { upsertLink, type MarketplaceMenuLinkView } from "./menu-links";
8
9
  import type { EngineContext, MarketplaceAuditEntry, MarketplaceDb } from "./ports";
9
10
 
@@ -24,7 +25,9 @@ export type BulkProblemCode =
24
25
  | "UNKNOWN_PROVIDER"
25
26
  | "NOTHING_TO_UPDATE"
26
27
  | "NOT_FOUND"
27
- | "CATALOG_ITEM_NOT_FOUND";
28
+ | "CATALOG_ITEM_NOT_FOUND"
29
+ /** Another store's live connection holds the merchant id this row sets, or revives (FUT-5613). */
30
+ | "MERCHANT_TAKEN";
28
31
 
29
32
  export interface BulkProblem {
30
33
  path: (string | number)[];
@@ -40,12 +43,17 @@ export type IntegrationRowInput =
40
43
  | ({ operation?: "upsert" } & Omit<SaveMarketplaceIntegrationInput, "clientId">)
41
44
  | { operation: "archive" | "unarchive"; provider: string; reason?: string | null };
42
45
 
43
- /** One SKU link: map it to a catalog id, or unmap it with `menuItemId: null`. */
46
+ /**
47
+ * One SKU link: map it to a catalog id, or unmap it with `menuItemId: null`.
48
+ * `variationId` narrows the mapping to one variation of that id (FUT-4927);
49
+ * absent or null maps the item alone, and it may not be set on an unmap.
50
+ */
44
51
  export interface MenuLinkRowInput {
45
52
  provider: string;
46
53
  externalSku: string;
47
54
  externalName?: string;
48
55
  menuItemId: string | null;
56
+ variationId?: string | null;
49
57
  }
50
58
 
51
59
  /** The key of each row seen twice, as problems. */
@@ -82,6 +90,29 @@ function integrationRowProblems(
82
90
  return changes ? [] : [{ path: ["integrations", index], code: "NOTHING_TO_UPDATE" }];
83
91
  }
84
92
 
93
+ /**
94
+ * The rows that would give a merchant id another store's live connection
95
+ * holds: an upsert setting it (refused at the merchant field), or an
96
+ * unarchive reviving it (refused at the provider).
97
+ */
98
+ async function merchantProblems(
99
+ ctx: EngineContext,
100
+ clientId: string,
101
+ rows: readonly IntegrationRowInput[],
102
+ merchantOf: ReadonlyMap<string, string | null>,
103
+ ): Promise<BulkProblem[]> {
104
+ const db = await ctx.ports.db();
105
+ const problems: BulkProblem[] = [];
106
+ for (const [index, row] of rows.entries()) {
107
+ const unarchive = row.operation === "unarchive";
108
+ const merchantId = unarchive ? merchantOf.get(row.provider) : "externalMerchantId" in row ? row.externalMerchantId : null;
109
+ if (row.operation === "archive" || !merchantId) continue;
110
+ if (!(await merchantHeldElsewhere(db, clientId, row.provider, merchantId))) continue;
111
+ problems.push({ path: ["integrations", index, unarchive ? "provider" : "externalMerchantId"], code: "MERCHANT_TAKEN" });
112
+ }
113
+ return problems;
114
+ }
115
+
85
116
  /** Thrown inside the transaction to roll a `validateOnly` call back. */
86
117
  class ValidateOnly extends Error {
87
118
  constructor() {
@@ -131,14 +162,15 @@ export async function upsertIntegrations(
131
162
  ctx: EngineContext,
132
163
  input: { clientId: string; actorId: string | null; rows: readonly IntegrationRowInput[]; validateOnly?: boolean },
133
164
  ): Promise<BulkResult<MarketplaceIntegrationView>> {
134
- const existing = new Set(
135
- (await listMarketplaceIntegrations(ctx, input.clientId, { includeArchived: true })).map((row) => row.provider),
136
- );
165
+ const stored = await listMarketplaceIntegrations(ctx, input.clientId, { includeArchived: true });
166
+ const existing = new Set(stored.map((row) => row.provider));
167
+ const merchantOf = new Map(stored.map((row) => [row.provider as string, row.externalMerchantId]));
137
168
  const problems = [
138
169
  ...duplicates(input.rows, (row) => row.provider, "integrations", "provider"),
139
170
  ...unknownProviders(ctx, input.rows, "integrations"),
140
171
  ...input.rows.flatMap((row, index) => integrationRowProblems(row, index, existing)),
141
172
  ];
173
+ if (problems.length === 0) problems.push(...(await merchantProblems(ctx, input.clientId, input.rows, merchantOf)));
142
174
  if (problems.length > 0) return { kind: "refused", problems };
143
175
 
144
176
  const validateOnly = input.validateOnly === true;
@@ -146,10 +178,18 @@ export async function upsertIntegrations(
146
178
  // The audit lines are written INSIDE the archive's transaction, through its
147
179
  // client: an archive never lands without its line, and an audit that fails
148
180
  // rolls the archive back. A `validateOnly` call rolls both back.
149
- await inTransaction(ctx, validateOnly, async (db) => {
150
- for (const row of input.rows) await writeIntegration(ctx, db, input.clientId, row, now);
151
- await auditArchives(ctx, db, input, now);
152
- });
181
+ try {
182
+ await inTransaction(ctx, validateOnly, async (db) => {
183
+ for (const row of input.rows) await writeIntegration(ctx, db, input.clientId, row, now);
184
+ await auditArchives(ctx, db, input, now);
185
+ });
186
+ } catch (error) {
187
+ // A race lost to another store's write of the same merchant, seen by the save's own check or the unique index.
188
+ const raced = error instanceof MarketplaceMerchantTakenError || isUniqueViolation(error);
189
+ const lost = raced ? await merchantProblems(ctx, input.clientId, input.rows, merchantOf) : [];
190
+ if (lost.length === 0) throw error;
191
+ return { kind: "refused", problems: lost };
192
+ }
153
193
  const providers = input.rows.map((row) => row.provider);
154
194
  const rows = validateOnly
155
195
  ? []
@@ -177,7 +217,33 @@ async function auditArchives(
177
217
  }
178
218
  }
179
219
 
180
- /** Map or unmap many SKUs at once; every catalog id must be the store's. */
220
+ /**
221
+ * The catalog half of one link row: the item must be the store's, and a named
222
+ * variation must be one of that item's, as the host answers. A variation on an
223
+ * unmap, or with a host that cannot answer for variations, is refused at the
224
+ * variation, and the item is not asked about it.
225
+ */
226
+ async function linkRowProblems(
227
+ ctx: EngineContext,
228
+ clientId: string,
229
+ row: MenuLinkRowInput,
230
+ index: number,
231
+ ): Promise<BulkProblem[]> {
232
+ const variationPath = ["links", index, "variationId"];
233
+ const variationId = row.variationId ?? null;
234
+ if (row.menuItemId === null) {
235
+ return variationId === null ? [] : [{ path: variationPath, code: "CATALOG_ITEM_NOT_FOUND" }];
236
+ }
237
+ if (!(await ctx.ports.order.catalogHas(clientId, row.menuItemId))) {
238
+ return [{ path: ["links", index, "menuItemId"], code: "CATALOG_ITEM_NOT_FOUND" }];
239
+ }
240
+ if (variationId === null) return [];
241
+ const order = ctx.ports.order;
242
+ const belongs = order.catalogHasVariation ? await order.catalogHasVariation(clientId, row.menuItemId, variationId) : false;
243
+ return belongs ? [] : [{ path: variationPath, code: "CATALOG_ITEM_NOT_FOUND" }];
244
+ }
245
+
246
+ /** Map or unmap many SKUs at once; every catalog id (and variation) must be the store's. */
181
247
  export async function upsertMenuLinks(
182
248
  ctx: EngineContext,
183
249
  input: { clientId: string; rows: readonly MenuLinkRowInput[]; validateOnly?: boolean },
@@ -186,11 +252,7 @@ export async function upsertMenuLinks(
186
252
  ...duplicates(input.rows, (row) => `${row.provider}\u0000${row.externalSku}`, "links", "externalSku"),
187
253
  ...unknownProviders(ctx, input.rows, "links"),
188
254
  ];
189
- for (const [index, row] of input.rows.entries()) {
190
- if (row.menuItemId !== null && !(await ctx.ports.order.catalogHas(input.clientId, row.menuItemId))) {
191
- problems.push({ path: ["links", index, "menuItemId"], code: "CATALOG_ITEM_NOT_FOUND" });
192
- }
193
- }
255
+ for (const [index, row] of input.rows.entries()) problems.push(...(await linkRowProblems(ctx, input.clientId, row, index)));
194
256
  if (problems.length > 0) return { kind: "refused", problems };
195
257
 
196
258
  const validateOnly = input.validateOnly === true;
@@ -52,12 +52,23 @@ import { ingestMarketplaceOrder, type IngestResult, type IngestSettings } from "
52
52
  import {
53
53
  listMarketplaceIntegrations,
54
54
  resolveIngestionTarget,
55
- resolveTenantByMerchant,
56
55
  saveMarketplaceIntegration,
57
56
  type IngestionTarget,
58
57
  type MarketplaceIntegrationView,
59
58
  type SaveMarketplaceIntegrationInput,
60
59
  } from "./integration";
60
+ import {
61
+ finishLink,
62
+ linkState,
63
+ linkedMerchants,
64
+ selectLinkedMerchant,
65
+ startLink,
66
+ type LinkFailure,
67
+ type LinkFinished,
68
+ type LinkPendingView,
69
+ } from "./linking";
70
+ import type { LinkedMerchant } from "./linking-port";
71
+ import { guardMerchantClaim, resolveTenantByMerchant } from "./merchant-claim";
61
72
  import { listMarketplaceMenuLinks, type MarketplaceMenuLinkView } from "./menu-links";
62
73
  import { runOutbound, type OutboundAttempt, type OutboundOutcome } from "./outbound";
63
74
  import { informStatus, type InformStatusInput } from "./status-inform";
@@ -131,7 +142,7 @@ export interface MarketplaceEngine {
131
142
  clientId: string,
132
143
  options?: { providers?: readonly string[]; includeArchived?: boolean },
133
144
  ): Promise<MarketplaceIntegrationView[]>;
134
- /** Create or patch ONE connection (the bulk call's single-row form, with no audit). */
145
+ /** Create or patch ONE connection (the bulk call's single-row form, with no audit). Throws MarketplaceMerchantTakenError. */
135
146
  saveIntegration(input: SaveMarketplaceIntegrationInput): Promise<MarketplaceIntegrationView>;
136
147
  /** Create, patch, archive or unarchive many connections, all-or-nothing. */
137
148
  upsertIntegrations(input: {
@@ -141,6 +152,43 @@ export interface MarketplaceEngine {
141
152
  validateOnly?: boolean;
142
153
  }): Promise<BulkResult<MarketplaceIntegrationView>>;
143
154
 
155
+ /**
156
+ * Whether this store can link this marketplace through the software's own
157
+ * app (FUT-5613), and the linking it left in progress. `available` is false
158
+ * when the adapter links nothing, the host configured no app for it, or the
159
+ * link table is not composed: the store's own credentials still work.
160
+ */
161
+ linkState(input: {
162
+ clientId: string;
163
+ provider: MarketplaceProvider;
164
+ environment?: "SANDBOX" | "PRODUCTION";
165
+ }): Promise<{ available: boolean; pending: LinkPendingView | null }>;
166
+ /** Ask for the portal code; the verifier stays sealed server-side. Replaces an earlier attempt. */
167
+ startLink(input: {
168
+ clientId: string;
169
+ provider: MarketplaceProvider;
170
+ environment?: "SANDBOX" | "PRODUCTION";
171
+ }): Promise<{ kind: "started"; pending: LinkPendingView } | LinkFailure>;
172
+ /** Exchange the pasted authorization code for the store's tokens; select the merchant when only one. */
173
+ finishLink(input: {
174
+ clientId: string;
175
+ provider: MarketplaceProvider;
176
+ authorizationCode: string;
177
+ actorId: string | null;
178
+ enabled?: boolean;
179
+ }): Promise<LinkFinished | LinkFailure>;
180
+ /** The merchants a linked connection's grant covers. */
181
+ linkedMerchants(input: {
182
+ clientId: string;
183
+ provider: MarketplaceProvider;
184
+ }): Promise<{ kind: "listed"; merchants: LinkedMerchant[] } | LinkFailure>;
185
+ /** Choose the marketplace store of a linked connection whose grant covers several. */
186
+ selectLinkedMerchant(input: {
187
+ clientId: string;
188
+ provider: MarketplaceProvider;
189
+ merchantId: string;
190
+ }): Promise<{ kind: "selected"; integration: MarketplaceIntegrationView } | LinkFailure>;
191
+
144
192
  /** The SKU map. `unmappedOnly` is the store's attention list; `ids` narrows. */
145
193
  menuLinks(input: {
146
194
  clientId: string;
@@ -295,8 +343,16 @@ export function createMarketplaceEngine(config: MarketplaceEngineConfig): Market
295
343
  deliver: (input) => processDelivery(ctx, input),
296
344
 
297
345
  integrations: (clientId, options) => listMarketplaceIntegrations(ctx, clientId, options),
298
- saveIntegration: async (input) => saveMarketplaceIntegration(ctx, input, await ports.db()),
346
+ saveIntegration: (input) =>
347
+ guardMerchantClaim(ctx, { ...input, merchantId: input.externalMerchantId }, async () =>
348
+ saveMarketplaceIntegration(ctx, input, await ports.db()),
349
+ ),
299
350
  upsertIntegrations: (input) => upsertIntegrations(ctx, input),
351
+ linkState: (input) => linkState(ctx, input),
352
+ startLink: (input) => startLink(ctx, input),
353
+ finishLink: (input) => finishLink(ctx, input),
354
+ linkedMerchants: (input) => linkedMerchants(ctx, input),
355
+ selectLinkedMerchant: (input) => selectLinkedMerchant(ctx, input),
300
356
 
301
357
  menuLinks: (input) => listMarketplaceMenuLinks(ctx, input),
302
358
  upsertMenuLinks: (input) => upsertMenuLinks(ctx, input),
@@ -78,7 +78,8 @@ async function composeLines(
78
78
  quantity: line.quantity,
79
79
  unitPriceCents: line.unitPriceCents,
80
80
  note: line.note,
81
- subjectRef: mapping.get(line.externalSku) ?? null,
81
+ subjectRef: mapping.get(line.externalSku)?.menuItemId ?? null,
82
+ variationRef: mapping.get(line.externalSku)?.variationId ?? null,
82
83
  }));
83
84
  }
84
85
 
@@ -1,4 +1,6 @@
1
- import type { MarketplaceCredentials } from "./adapter";
1
+ import type { AdapterGrant, MarketplaceCredentials } from "./adapter";
2
+ import { appCredentialsOf, linkGrant, openLinkRefreshToken, type MarketplaceAuthMode } from "./link-store";
3
+ import { assertMerchantFree } from "./merchant-claim";
2
4
  import type { EngineContext, MarketplaceDb } from "./ports";
3
5
  import type { MarketplaceProvider } from "./types";
4
6
 
@@ -37,6 +39,12 @@ export interface MarketplaceIntegrationView {
37
39
  lastVerifiedAt: Date | null;
38
40
  /** Archived connections ingest nothing; null while live. */
39
41
  archivedAt: Date | null;
42
+ /**
43
+ * How the connection authenticates (FUT-5613): CREDENTIALS, the store's own
44
+ * app; LINKED, the software's app the store authorized. Always set by this
45
+ * version; optional in the type so a view built by hand against 1.x compiles.
46
+ */
47
+ authMode?: MarketplaceAuthMode;
40
48
  }
41
49
 
42
50
  interface IntegrationRow {
@@ -52,6 +60,7 @@ interface IntegrationRow {
52
60
  lastEventAt: Date | null;
53
61
  lastVerifiedAt: Date | null;
54
62
  archivedAt: Date | null;
63
+ authMode?: string;
55
64
  }
56
65
 
57
66
  const VIEW_SELECT = {
@@ -67,6 +76,7 @@ const VIEW_SELECT = {
67
76
  lastEventAt: true,
68
77
  lastVerifiedAt: true,
69
78
  archivedAt: true,
79
+ authMode: true,
70
80
  } as const;
71
81
 
72
82
  function toView(row: IntegrationRow): MarketplaceIntegrationView {
@@ -83,6 +93,7 @@ function toView(row: IntegrationRow): MarketplaceIntegrationView {
83
93
  lastEventAt: row.lastEventAt,
84
94
  lastVerifiedAt: row.lastVerifiedAt,
85
95
  archivedAt: row.archivedAt ?? null,
96
+ authMode: row.authMode === "LINKED" ? "LINKED" : "CREDENTIALS",
86
97
  };
87
98
  }
88
99
 
@@ -139,12 +150,16 @@ export interface SaveMarketplaceIntegrationInput {
139
150
  * Re-entering credentials resets `status` to UNVERIFIED. The stored status is a
140
151
  * claim about a specific secret; carrying VERIFIED across a credential change
141
152
  * would assert that a probe which never ran had passed.
153
+ *
154
+ * A merchant id another store's live connection holds is refused with
155
+ * `MarketplaceMerchantTakenError`: the app's webhook routes by it.
142
156
  */
143
157
  export async function saveMarketplaceIntegration(
144
158
  ctx: EngineContext,
145
159
  input: SaveMarketplaceIntegrationInput,
146
160
  db: MarketplaceDb,
147
161
  ): Promise<MarketplaceIntegrationView> {
162
+ await assertMerchantFree(db, input.clientId, input.provider, input.externalMerchantId);
148
163
  const sealed = input.credentials
149
164
  ? ctx.ports.secrets.seal(JSON.stringify(input.credentials))
150
165
  : undefined;
@@ -157,7 +172,8 @@ export async function saveMarketplaceIntegration(
157
172
  ...(input.autoAccept === undefined ? {} : { autoAccept: input.autoAccept }),
158
173
  ...(input.followStatus === undefined ? {} : { followStatus: input.followStatus }),
159
174
  ...(input.ackSlaSeconds === undefined ? {} : { ackSlaSeconds: input.ackSlaSeconds }),
160
- ...(sealed === undefined ? {} : { credentials: sealed, status: "UNVERIFIED" }),
175
+ // Typed credentials make the connection the store's own app again.
176
+ ...(sealed === undefined ? {} : { credentials: sealed, status: "UNVERIFIED", authMode: "CREDENTIALS" }),
161
177
  };
162
178
  const row = (await db.marketplaceIntegration.upsert({
163
179
  where: { clientId_provider: { clientId: input.clientId, provider: input.provider } },
@@ -230,8 +246,12 @@ export async function resolveIngestionTarget(
230
246
  credentials: true,
231
247
  archivedAt: true,
232
248
  externalMerchantId: true,
249
+ authMode: true,
250
+ environment: true,
233
251
  },
234
252
  })) as {
253
+ authMode?: string;
254
+ environment?: string;
235
255
  externalMerchantId: string | null;
236
256
  enabled: boolean;
237
257
  autoAccept: boolean;
@@ -251,11 +271,35 @@ export async function resolveIngestionTarget(
251
271
  // An unopenable blob must not read as "no secret configured" — that would
252
272
  // turn a key-rotation problem into an endpoint that accepts unsigned
253
273
  // deliveries. The secrets port throws instead, and the caller answers 401.
254
- webhookSecret:
255
- row.credentials === "" ? null : openCredentials(ctx, row.credentials).webhookSecret,
274
+ webhookSecret: await webhookSecretOf(ctx, provider, row),
256
275
  };
257
276
  }
258
277
 
278
+ /**
279
+ * The key a connection's deliveries are verified against: the store's own,
280
+ * or, for a linked connection, the software's app's (FUT-5613). A linked
281
+ * connection whose app is no longer configured THROWS, like a blob that will
282
+ * not open: it must never read as "no secret, accept unsigned".
283
+ */
284
+ async function webhookSecretOf(
285
+ ctx: EngineContext,
286
+ provider: MarketplaceProvider,
287
+ row: { credentials: string; authMode?: string; environment?: string },
288
+ ): Promise<string | null> {
289
+ if (row.authMode !== "LINKED") {
290
+ return row.credentials === "" ? null : openCredentials(ctx, row.credentials).webhookSecret;
291
+ }
292
+ const app = await appCredentialsOf(ctx, provider, environmentOf(row.environment));
293
+ if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
294
+ // The marketplace signs with the app's client secret unless the host names another key.
295
+ const secret = app.webhookSecret || app.clientSecret;
296
+ if (!secret) throw new Error(`No webhook key is configured for ${provider}.`);
297
+ return secret;
298
+ }
299
+
300
+ const environmentOf = (value: string | undefined): "SANDBOX" | "PRODUCTION" =>
301
+ value === "PRODUCTION" ? "PRODUCTION" : "SANDBOX";
302
+
259
303
  /**
260
304
  * Open a stored credential set.
261
305
  *
@@ -281,28 +325,6 @@ function openCredentials(
281
325
  };
282
326
  }
283
327
 
284
- /**
285
- * Which tenant a delivery belongs to, resolved from the merchant id the
286
- * marketplace names.
287
- *
288
- * Matched against the column OUTSIDE the ciphertext, which is the whole reason
289
- * `externalMerchantId` lives there: attributing a delivery must not require
290
- * decrypting every store's secrets to find the match.
291
- */
292
- export async function resolveTenantByMerchant(
293
- ctx: EngineContext,
294
- provider: MarketplaceProvider,
295
- externalMerchantId: string,
296
- ): Promise<string | null> {
297
- const db = await ctx.ports.db();
298
- const rows = (await db.marketplaceIntegration.findMany({
299
- where: { provider, externalMerchantId, archivedAt: null },
300
- select: { clientId: true },
301
- take: 1,
302
- })) as { clientId: string }[];
303
- return rows[0]?.clientId ?? null;
304
- }
305
-
306
328
  /** Stamp the connection's liveness marker. Best-effort; never blocks ingestion. */
307
329
  export async function markMarketplaceEventSeen(
308
330
  db: MarketplaceDb,
@@ -320,6 +342,8 @@ export async function markMarketplaceEventSeen(
320
342
  export interface OutboundConnection {
321
343
  environment: "SANDBOX" | "PRODUCTION";
322
344
  credentials: MarketplaceCredentials;
345
+ /** A linked connection's token source (FUT-5613); absent for the store's own credentials. */
346
+ grant?: AdapterGrant;
323
347
  }
324
348
 
325
349
  /**
@@ -336,11 +360,15 @@ export async function readOutboundConnection(
336
360
  const db = await ctx.ports.db();
337
361
  const row = (await db.marketplaceIntegration.findUnique({
338
362
  where: { clientId_provider: { clientId, provider } },
339
- select: { environment: true, credentials: true },
340
- })) as { environment: string; credentials: string } | null;
363
+ select: { environment: true, credentials: true, authMode: true },
364
+ })) as { environment: string; credentials: string; authMode?: string } | null;
341
365
  if (!row || row.credentials === "") return null;
342
- return {
343
- environment: row.environment === "PRODUCTION" ? "PRODUCTION" : "SANDBOX",
344
- credentials: openCredentials(ctx, row.credentials),
345
- };
366
+ const environment = environmentOf(row.environment);
367
+ if (row.authMode !== "LINKED") return { environment, credentials: openCredentials(ctx, row.credentials) };
368
+ // Linked: the software's app speaks for the store, with the store's refresh token.
369
+ const app = await appCredentialsOf(ctx, provider, environment);
370
+ if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
371
+ const refreshToken = openLinkRefreshToken(ctx, row.credentials);
372
+ const link = { clientId, provider, environment, refreshToken, app, sealed: row.credentials };
373
+ return { environment, credentials: app, grant: linkGrant(ctx, link) };
346
374
  }
@@ -0,0 +1,170 @@
1
+ import type { AdapterGrant, AdapterTokenCache, MarketplaceCredentials, OutboundResult } from "./adapter";
2
+ import type { LinkGrant } from "./linking-port";
3
+ import type { EngineContext } from "./ports";
4
+ import type { MarketplaceProvider } from "./types";
5
+
6
+ /**
7
+ * A LINKED connection's secrets and tokens (FUT-5613).
8
+ *
9
+ * The sealed `credentials` blob of a linked connection holds the store's
10
+ * refresh token and nothing of the app: the app's client id and secret are
11
+ * the host's configuration (`appCredentials`), read at each use so a rotation
12
+ * there reaches every store at once. The access token lives in the engine's
13
+ * per-process token cache only, like every other marketplace token.
14
+ */
15
+
16
+ /** How a connection authenticates. */
17
+ export type MarketplaceAuthMode = "CREDENTIALS" | "LINKED";
18
+
19
+ /** A token is renewed this long before the marketplace says it expires. */
20
+ const TOKEN_MARGIN_MS = 60_000;
21
+
22
+ /** The blob a linked connection stores, sealed. The empty app fields keep 1.x readers' shape. */
23
+ export function sealLink(ctx: EngineContext, refreshToken: string): string {
24
+ return ctx.ports.secrets.seal(JSON.stringify({ clientId: "", clientSecret: "", webhookSecret: null, refreshToken }));
25
+ }
26
+
27
+ /** The refresh token a linked connection's blob holds. Throws when it holds none, or will not open. */
28
+ export function openLinkRefreshToken(ctx: EngineContext, sealed: string): string {
29
+ const parsed: unknown = JSON.parse(ctx.ports.secrets.open(sealed));
30
+ const token = typeof parsed === "object" && parsed !== null ? (parsed as { refreshToken?: unknown }).refreshToken : null;
31
+ if (typeof token !== "string" || token === "") throw new Error("The linked connection holds no refresh token.");
32
+ return token;
33
+ }
34
+
35
+ /** The software's own app on this marketplace, or null when the host configured none. */
36
+ export async function appCredentialsOf(
37
+ ctx: EngineContext,
38
+ provider: MarketplaceProvider,
39
+ environment: "SANDBOX" | "PRODUCTION",
40
+ ): Promise<MarketplaceCredentials | null> {
41
+ const port = ctx.ports.appCredentials;
42
+ if (!port) return null;
43
+ const credentials = await port(provider, environment);
44
+ return credentials && credentials.clientId !== "" && credentials.clientSecret !== "" ? credentials : null;
45
+ }
46
+
47
+ /** Where a linked connection's access token sits in the cache: per store, never per app. */
48
+ export const linkTokenKey = (provider: string, environment: string, clientId: string): string =>
49
+ `LINK:${provider}:${environment}:${clientId}`;
50
+
51
+ /** The row a token belongs to, and the sealed blob it was read with: the compare-and-set's version. */
52
+ interface LinkVersion {
53
+ clientId: string;
54
+ provider: string;
55
+ sealed: string;
56
+ }
57
+
58
+ /**
59
+ * Put a fresh access token in the cache, only while the connection still
60
+ * holds the blob it was bought with: a grant a re-link replaced caches nothing.
61
+ */
62
+ export async function cacheLinkToken(ctx: EngineContext, link: LinkVersion, key: string, grant: LinkGrant): Promise<boolean> {
63
+ const db = await ctx.ports.db();
64
+ const row = (await db.marketplaceIntegration.findUnique({
65
+ where: { clientId_provider: { clientId: link.clientId, provider: link.provider } },
66
+ select: { credentials: true },
67
+ })) as { credentials: string } | null;
68
+ if (row?.credentials !== link.sealed) return false;
69
+ setToken(ctx, key, grant);
70
+ return true;
71
+ }
72
+
73
+ function setToken(ctx: EngineContext, key: string, grant: LinkGrant): void {
74
+ const expiresAt = ctx.ports.clock.now().getTime() + Math.max(grant.expiresInSeconds, 1) * 1000;
75
+ ctx.tokens.set(key, { token: grant.accessToken, expiresAt });
76
+ }
77
+
78
+ /** One refresh per connection at a time, per token cache (that is, per engine). */
79
+ const inflight = new WeakMap<AdapterTokenCache, Map<string, Promise<{ token: string } | OutboundResult>>>();
80
+
81
+ /** Who a grant is for. */
82
+ interface LinkedConnection extends LinkVersion {
83
+ clientId: string;
84
+ provider: MarketplaceProvider;
85
+ environment: "SANDBOX" | "PRODUCTION";
86
+ refreshToken: string;
87
+ app: MarketplaceCredentials;
88
+ }
89
+
90
+ /** Store a rotated refresh token back on the live connection, unless a re-link replaced the blob it was read with. */
91
+ async function storeRotated(ctx: EngineContext, link: LinkedConnection, refreshToken: string): Promise<boolean> {
92
+ const db = await ctx.ports.db();
93
+ const { count } = await db.marketplaceIntegration.updateMany({
94
+ where: { clientId: link.clientId, provider: link.provider, authMode: "LINKED", archivedAt: null, credentials: link.sealed },
95
+ data: { credentials: sealLink(ctx, refreshToken) },
96
+ });
97
+ return count > 0;
98
+ }
99
+
100
+ /**
101
+ * The marketplace no longer honours the refresh token: the store must link
102
+ * again. The connection reads FAILED, which is what the screen shows; a
103
+ * connection linked again since the token was read is left alone.
104
+ */
105
+ async function markLinkFailed(ctx: EngineContext, link: LinkedConnection): Promise<boolean> {
106
+ const db = await ctx.ports.db();
107
+ const { count } = await db.marketplaceIntegration.updateMany({
108
+ where: { clientId: link.clientId, provider: link.provider, authMode: "LINKED", credentials: link.sealed },
109
+ data: { status: "FAILED" },
110
+ });
111
+ if (count > 0) ctx.ports.publishChanged(link.clientId);
112
+ return count > 0;
113
+ }
114
+
115
+ /** What a refresh that lost the race to a re-link answers: the caller reads the new link and tries again. */
116
+ const RELINKED: OutboundResult = { kind: "retry", reason: "the connection was linked again during the refresh" };
117
+
118
+ async function refreshOnce(ctx: EngineContext, link: LinkedConnection, key: string): Promise<{ token: string } | OutboundResult> {
119
+ const linking = ctx.registry.get(link.provider)?.linking;
120
+ if (!linking) return { kind: "refused", status: 0, message: "this marketplace links no store", own: true };
121
+ const answer = await linking.refresh(
122
+ { http: ctx.ports.http, credentials: link.app, environment: link.environment, now: ctx.ports.clock.now() },
123
+ { refreshToken: link.refreshToken },
124
+ );
125
+ if (answer.kind === "retry") return answer;
126
+ if (answer.kind === "refused") return (await markLinkFailed(ctx, link)) ? { ...answer, own: true } : RELINKED;
127
+ const rotated = answer.value.refreshToken;
128
+ if (rotated === null || rotated === link.refreshToken) {
129
+ return (await cacheLinkToken(ctx, link, key, answer.value)) ? { token: answer.value.accessToken } : RELINKED;
130
+ }
131
+ // The new token is already in hand; a failed write costs a re-link only if
132
+ // the marketplace also revoked the old one, so it is logged, never thrown.
133
+ const stored = await storeRotated(ctx, link, rotated).catch((error: unknown) => {
134
+ ctx.ports.logger.error(
135
+ `marketplace.link: ${link.provider} rotated refresh token of ${link.clientId} not stored: ` +
136
+ (error instanceof Error ? error.message : String(error)),
137
+ );
138
+ return null;
139
+ });
140
+ if (stored === false) return RELINKED;
141
+ setToken(ctx, key, answer.value);
142
+ return { token: answer.value.accessToken };
143
+ }
144
+
145
+ /** The grant an outbound call of a linked connection is handed. */
146
+ export function linkGrant(ctx: EngineContext, link: LinkedConnection): AdapterGrant {
147
+ const key = linkTokenKey(link.provider, link.environment, link.clientId);
148
+ return {
149
+ key,
150
+ accessToken: async () => {
151
+ const cached = ctx.tokens.get(key);
152
+ if (cached && cached.expiresAt > ctx.ports.clock.now().getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
153
+ let running = inflight.get(ctx.tokens);
154
+ if (!running) {
155
+ running = new Map();
156
+ inflight.set(ctx.tokens, running);
157
+ }
158
+ const pending = running.get(key);
159
+ if (pending) return pending;
160
+ const call = refreshOnce(ctx, link, key)
161
+ .catch((error: unknown): OutboundResult => ({
162
+ kind: "retry",
163
+ reason: error instanceof Error ? error.message : String(error),
164
+ }))
165
+ .finally(() => running.delete(key));
166
+ running.set(key, call);
167
+ return call;
168
+ },
169
+ };
170
+ }