@12-apps/marketplace 1.10.0 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ADOPTING.md +126 -1
- package/README.md +100 -1
- package/dist/99food/index.d.ts +2 -2
- package/dist/99food/index.js +2 -2
- package/dist/{adapter-CYJzu1c9.d.ts → adapter-nUyZpLzz.d.ts} +448 -173
- package/dist/{chunk-2BA2EHNF.js → chunk-45ZVN5XI.js} +316 -42
- package/dist/chunk-45ZVN5XI.js.map +1 -0
- package/dist/{chunk-PYHNM47K.js → chunk-L6FG6T4S.js} +2 -2
- package/dist/{chunk-HEXLCTOG.js → chunk-LACBT6NC.js} +1 -1
- package/dist/chunk-LACBT6NC.js.map +1 -0
- package/dist/{chunk-WVZ2IXFH.js → chunk-MIPNQ7X5.js} +190 -12
- package/dist/chunk-MIPNQ7X5.js.map +1 -0
- package/dist/chunk-SGOTN5PX.js +345 -0
- package/dist/chunk-SGOTN5PX.js.map +1 -0
- package/dist/{client-B4EQCRD_.d.ts → client-Ctas7WCS.d.ts} +1 -1
- package/dist/{engine-DK3iV_Kk.d.ts → engine-CIy9P7Cq.d.ts} +149 -8
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +3 -3
- package/dist/ifood/index.d.ts +10 -2
- package/dist/ifood/index.js +297 -25
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +23 -4
- package/dist/index.js +424 -84
- package/dist/index.js.map +1 -1
- package/dist/keeta/index.d.ts +2 -18
- package/dist/keeta/index.js +12 -3
- package/dist/keeta/index.js.map +1 -1
- package/dist/manifest/index.d.ts +219 -1
- package/dist/manifest/index.js +1 -1
- package/dist/manifest/server.d.ts +2 -2
- package/dist/manifest/server.js +3 -3
- package/dist/rappi/index.d.ts +1 -1
- package/dist/rappi/index.js +1 -1
- package/dist/server/en-US.d.ts +13 -0
- package/dist/server/en-US.js +13 -0
- package/dist/server/en-US.js.map +1 -1
- package/dist/server/index.d.ts +241 -7
- package/dist/server/index.js +3 -3
- package/dist/server/pt-BR.d.ts +13 -0
- package/dist/server/pt-BR.js +13 -0
- package/dist/server/pt-BR.js.map +1 -1
- package/package.json +1 -1
- package/prisma/marketplace.prisma +41 -0
- package/prisma/migrations/20261127090000_marketplace_app_link/migration.sql +81 -0
- package/src/core/adapter.ts +27 -0
- package/src/core/bulk.ts +43 -8
- package/src/core/courier-port.ts +100 -0
- package/src/core/courier.ts +153 -0
- package/src/core/engine.ts +63 -4
- package/src/core/integration.ts +60 -32
- package/src/core/lifecycle.ts +27 -4
- package/src/core/link-store.ts +170 -0
- package/src/core/linking-port.ts +100 -0
- package/src/core/linking.ts +363 -0
- package/src/core/merchant-claim.ts +106 -0
- package/src/core/outbound-queue.ts +24 -11
- package/src/core/outbound.ts +8 -6
- package/src/core/pickup-code.ts +136 -0
- package/src/core/pipeline.ts +15 -6
- package/src/core/ports.ts +26 -1
- package/src/core/status-store.ts +2 -3
- package/src/core/types.ts +56 -4
- package/src/ifood/courier.ts +210 -0
- package/src/ifood/index.ts +8 -0
- package/src/ifood/linking.ts +170 -0
- package/src/ifood/normalize.ts +7 -0
- package/src/ifood/outbound.ts +10 -3
- package/src/index.ts +30 -0
- package/src/keeta/normalize.ts +21 -6
- package/src/server/copy.ts +20 -2
- package/src/server/en-US.ts +13 -0
- package/src/server/index.ts +1 -1
- package/src/server/link-routes.ts +140 -0
- package/src/server/mcp-link.ts +103 -0
- package/src/server/mcp.ts +6 -2
- package/src/server/pt-BR.ts +13 -0
- package/src/server/routes.ts +5 -2
- package/src/server/webhook.ts +86 -0
- package/dist/chunk-2BA2EHNF.js.map +0 -1
- package/dist/chunk-HEXLCTOG.js.map +0 -1
- package/dist/chunk-WVZ2IXFH.js.map +0 -1
- package/dist/chunk-ZO4S3LF4.js +0 -254
- package/dist/chunk-ZO4S3LF4.js.map +0 -1
- /package/dist/{chunk-PYHNM47K.js.map → chunk-L6FG6T4S.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
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { StatusStep } from "./adapter";
|
|
1
|
+
import type { MarketplaceAdapter, StatusStep } from "./adapter";
|
|
2
2
|
import type { EngineContext } from "./ports";
|
|
3
3
|
import type { MarketplaceProvider } from "./types";
|
|
4
4
|
|
|
@@ -16,10 +16,11 @@ import type { MarketplaceProvider } from "./types";
|
|
|
16
16
|
export const MARKETPLACE_OUTBOUND_JOB = "marketplace.outbound";
|
|
17
17
|
|
|
18
18
|
/**
|
|
19
|
-
* What goes out: the store's aceite, the store's cancellation request,
|
|
20
|
-
* step of the order the store reached (`status`, FUT-4653)
|
|
19
|
+
* What goes out: the store's aceite, the store's cancellation request, a
|
|
20
|
+
* step of the order the store reached (`status`, FUT-4653), or the pickup code
|
|
21
|
+
* the store checked at the hand-over (`validatePickupCode`, FUT-5665).
|
|
21
22
|
*/
|
|
22
|
-
export type OutboundAction = "confirm" | "requestCancellation" | "status";
|
|
23
|
+
export type OutboundAction = "confirm" | "requestCancellation" | "status" | "validatePickupCode";
|
|
23
24
|
|
|
24
25
|
/** The outbound job's payload. Identifiers only. */
|
|
25
26
|
export interface OutboundJobPayload {
|
|
@@ -33,6 +34,12 @@ export interface OutboundJobPayload {
|
|
|
33
34
|
* belongs to: the owner of its SENDING claim. Absent on every other action.
|
|
34
35
|
*/
|
|
35
36
|
claimKey?: string;
|
|
37
|
+
/**
|
|
38
|
+
* OPTIONAL. The pickup code a `validatePickupCode` call sends; absent on every
|
|
39
|
+
* other action. The one non-identifier in the payload: a short-lived code the
|
|
40
|
+
* job needs to send, which no log line prints.
|
|
41
|
+
*/
|
|
42
|
+
code?: string;
|
|
36
43
|
}
|
|
37
44
|
|
|
38
45
|
/** The dedupe key: at most one queued call per (order, action). */
|
|
@@ -45,6 +52,18 @@ export function statusDedupeKey(step: StatusStep, orderId: string, at: Date): st
|
|
|
45
52
|
return `${MARKETPLACE_OUTBOUND_JOB}:status:${step}:${orderId}:${at.getTime()}`;
|
|
46
53
|
}
|
|
47
54
|
|
|
55
|
+
/** Whether the adapter's marketplace can take this call at all. */
|
|
56
|
+
function ableTo(adapter: MarketplaceAdapter, payload: OutboundJobPayload): boolean {
|
|
57
|
+
switch (payload.action) {
|
|
58
|
+
case "status":
|
|
59
|
+
return Boolean(payload.step && adapter.capabilities.statusSteps?.includes(payload.step));
|
|
60
|
+
case "confirm":
|
|
61
|
+
return adapter.capabilities.apiConfirm;
|
|
62
|
+
default:
|
|
63
|
+
return adapter.capabilities.apiCancel;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
48
67
|
/**
|
|
49
68
|
* Queue one outbound call, when the marketplace's API can take it at all.
|
|
50
69
|
*
|
|
@@ -65,13 +84,7 @@ export async function enqueueOutbound(
|
|
|
65
84
|
): Promise<boolean> {
|
|
66
85
|
const adapter = ctx.registry.get(provider);
|
|
67
86
|
if (!adapter) return false;
|
|
68
|
-
|
|
69
|
-
payload.action === "status"
|
|
70
|
-
? Boolean(payload.step && adapter.capabilities.statusSteps?.includes(payload.step))
|
|
71
|
-
: payload.action === "confirm"
|
|
72
|
-
? adapter.capabilities.apiConfirm
|
|
73
|
-
: adapter.capabilities.apiCancel;
|
|
74
|
-
if (!able) return false;
|
|
87
|
+
if (!ableTo(adapter, payload)) return false;
|
|
75
88
|
const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });
|
|
76
89
|
if (!outcome.enqueued) {
|
|
77
90
|
ctx.ports.logger.warn(
|
package/src/core/outbound.ts
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
} from "./cancellation-outcome";
|
|
10
10
|
import { readOutboundConnection, type OutboundConnection } from "./integration";
|
|
11
11
|
import type { OutboundJobPayload } from "./outbound-queue";
|
|
12
|
+
import { runPickupCode, tellPickupCode } from "./pickup-code";
|
|
12
13
|
import { failStatusRow, runStatus } from "./status-job";
|
|
13
14
|
import { failAsTimeout } from "./outbound-sweep";
|
|
14
15
|
import type { CancellationFailureReason, EngineContext } from "./ports";
|
|
@@ -334,9 +335,10 @@ async function runCancellation(
|
|
|
334
335
|
*/
|
|
335
336
|
async function stampLastAttemptFailure(ctx: EngineContext, payload: OutboundJobPayload, error: unknown): Promise<OutboundOutcome> {
|
|
336
337
|
const reason = error instanceof Error ? error.message : String(error);
|
|
337
|
-
if (payload.action === "status") {
|
|
338
|
-
await failStatusRow(ctx, payload);
|
|
339
|
-
ctx
|
|
338
|
+
if (payload.action === "status" || payload.action === "validatePickupCode") {
|
|
339
|
+
if (payload.action === "status") await failStatusRow(ctx, payload);
|
|
340
|
+
else await tellPickupCode(ctx, payload, "UNVERIFIED");
|
|
341
|
+
ctx.ports.logger.error(`marketplace.outbound: ${payload.action}${payload.step ? ` ${payload.step}` : ""} for order ${payload.orderId} failed: ${reason}`);
|
|
340
342
|
return { kind: "failed", action: payload.action, reason };
|
|
341
343
|
}
|
|
342
344
|
const db = await ctx.ports.db();
|
|
@@ -366,9 +368,9 @@ async function runOnce(ctx: EngineContext, payload: OutboundJobPayload, attempt:
|
|
|
366
368
|
if (!row) return { kind: "skipped", reason: "no acceptance for this order" };
|
|
367
369
|
const adapter = ctx.registry.get(row.provider);
|
|
368
370
|
if (!adapter) return { kind: "skipped", reason: `no adapter for ${row.provider}` };
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
371
|
+
const deps = { attempt, ref: refOf(row), retryError: (m: string) => new OutboundRetryError(m) };
|
|
372
|
+
if (payload.action === "status") return runStatus(ctx, payload, row, adapter, deps);
|
|
373
|
+
if (payload.action === "validatePickupCode") return runPickupCode(ctx, payload, row, adapter, deps);
|
|
372
374
|
return payload.action === "confirm"
|
|
373
375
|
? runConfirm(ctx, payload, row, adapter, attempt)
|
|
374
376
|
: runCancellation(ctx, payload, row, adapter, attempt);
|