@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.
- package/ADOPTING.md +63 -1
- package/README.md +64 -1
- package/dist/99food/index.d.ts +2 -2
- package/dist/99food/index.js +2 -2
- package/dist/{adapter-CYJzu1c9.d.ts → adapter-CD0SfdVS.d.ts} +124 -1
- package/dist/{chunk-PYHNM47K.js → chunk-DCWOQ5PN.js} +2 -2
- package/dist/{chunk-6N2HEV3U.js → chunk-OS4TSIFU.js} +190 -12
- package/dist/chunk-OS4TSIFU.js.map +1 -0
- package/dist/chunk-SGOTN5PX.js +345 -0
- package/dist/chunk-SGOTN5PX.js.map +1 -0
- package/dist/{chunk-HEXLCTOG.js → chunk-TVZU4HNT.js} +1 -1
- package/dist/chunk-TVZU4HNT.js.map +1 -0
- package/dist/{chunk-BMCERPQX.js → chunk-YWMEIMO3.js} +221 -27
- package/dist/chunk-YWMEIMO3.js.map +1 -0
- package/dist/{client-B4EQCRD_.d.ts → client-11sncog4.d.ts} +1 -1
- package/dist/{engine-wmW-VuBL.d.ts → engine-C_3RK8wC.d.ts} +207 -64
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +3 -3
- package/dist/ifood/index.d.ts +5 -2
- package/dist/ifood/index.js +125 -7
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +23 -4
- package/dist/index.js +280 -26
- package/dist/index.js.map +1 -1
- package/dist/keeta/index.d.ts +2 -2
- package/dist/keeta/index.js +2 -2
- package/dist/manifest/index.d.ts +223 -2
- 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 +246 -8
- 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 +47 -0
- package/prisma/migrations/20261126230000_marketplace_menu_link_variation/migration.sql +11 -0
- package/prisma/migrations/20261127090000_marketplace_app_link/migration.sql +81 -0
- package/src/core/adapter.ts +21 -0
- package/src/core/bulk.ts +77 -15
- package/src/core/engine.ts +59 -3
- package/src/core/ingest.ts +2 -1
- package/src/core/integration.ts +60 -32
- 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/menu-links.ts +36 -6
- package/src/core/merchant-claim.ts +106 -0
- package/src/core/order-types.ts +74 -0
- package/src/core/ports.ts +26 -65
- package/src/ifood/index.ts +4 -0
- package/src/ifood/linking.ts +170 -0
- package/src/ifood/outbound.ts +10 -3
- package/src/index.ts +14 -0
- 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 +13 -4
- 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-6N2HEV3U.js.map +0 -1
- package/dist/chunk-BMCERPQX.js.map +0 -1
- package/dist/chunk-HEXLCTOG.js.map +0 -1
- package/dist/chunk-NP4EYKPO.js +0 -252
- package/dist/chunk-NP4EYKPO.js.map +0 -1
- /package/dist/{chunk-PYHNM47K.js.map → chunk-DCWOQ5PN.js.map} +0 -0
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import type { MarketplaceCredentials, MarketplaceHttp, OutboundResult } from "./adapter";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* LINKING a store through the software's OWN marketplace app (FUT-5613): the
|
|
5
|
+
* store authorizes the software's app on the marketplace's portal, and never
|
|
6
|
+
* types a client id, a secret, a webhook key or a webhook address.
|
|
7
|
+
*
|
|
8
|
+
* The flow, as an adapter states it (iFood's "distributed app"):
|
|
9
|
+
*
|
|
10
|
+
* 1. `requestCode`: the app asks for a short code the store types (or a link
|
|
11
|
+
* that already carries it) on the marketplace's portal, plus a VERIFIER the
|
|
12
|
+
* engine keeps server-side for that store and never hands the browser.
|
|
13
|
+
* 2. The store authorizes the app on the portal and is shown an
|
|
14
|
+
* AUTHORIZATION CODE, which it pastes back.
|
|
15
|
+
* 3. `exchange`: the code plus the verifier buy an access token and a refresh
|
|
16
|
+
* token, stored sealed on the store's connection.
|
|
17
|
+
* 4. `merchants`: which of the marketplace's stores the grant covers; one is
|
|
18
|
+
* selected at once.
|
|
19
|
+
* 5. `refresh`: a new access token from the refresh token, whenever the
|
|
20
|
+
* cached one is gone. A rotated refresh token is stored back.
|
|
21
|
+
*
|
|
22
|
+
* The app's own credentials are the HOST's configuration, one pair per
|
|
23
|
+
* marketplace and environment ({@link MarketplaceAppCredentialsPort}), never a
|
|
24
|
+
* store's.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
/** What a linking call is handed: the APP's credentials, never a store's. */
|
|
28
|
+
export interface LinkCallContext {
|
|
29
|
+
http: MarketplaceHttp;
|
|
30
|
+
credentials: MarketplaceCredentials;
|
|
31
|
+
environment: "SANDBOX" | "PRODUCTION";
|
|
32
|
+
now: Date;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The code a store types on the marketplace's portal, and the verifier kept for it. */
|
|
36
|
+
export interface LinkCode {
|
|
37
|
+
/** Shown to the person: they type it on the portal. */
|
|
38
|
+
userCode: string;
|
|
39
|
+
/** The portal page the code is typed on. */
|
|
40
|
+
verificationUrl: string;
|
|
41
|
+
/** The same page with the code already in it: the link the screen opens. */
|
|
42
|
+
verificationUrlComplete: string;
|
|
43
|
+
/** How long the code lives, in seconds. */
|
|
44
|
+
expiresInSeconds: number;
|
|
45
|
+
/** Kept server-side for this store until the exchange. NEVER sent to a browser. */
|
|
46
|
+
verifier: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** What an exchange or a refresh buys. */
|
|
50
|
+
export interface LinkGrant {
|
|
51
|
+
accessToken: string;
|
|
52
|
+
/** How long the access token lives, in seconds. */
|
|
53
|
+
expiresInSeconds: number;
|
|
54
|
+
/**
|
|
55
|
+
* The refresh token. An exchange always answers one; a refresh answers one
|
|
56
|
+
* when the marketplace rotates it, and null when the old one stays valid.
|
|
57
|
+
*/
|
|
58
|
+
refreshToken: string | null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** One marketplace store the grant covers. */
|
|
62
|
+
export interface LinkedMerchant {
|
|
63
|
+
id: string;
|
|
64
|
+
name: string | null;
|
|
65
|
+
corporateName: string | null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* A linking call's answer: the value, or why there is none. `refused` is
|
|
70
|
+
* final (the marketplace judged the request: a wrong or used code, a refresh
|
|
71
|
+
* token it no longer honours); `retry` is the network, a 5xx, a rate limit.
|
|
72
|
+
*/
|
|
73
|
+
export type LinkResult<T> = { kind: "ok"; value: T } | Exclude<OutboundResult, { kind: "accepted" }>;
|
|
74
|
+
|
|
75
|
+
/** The adapter's half: the marketplace's wire format for each step, and nothing else. */
|
|
76
|
+
export interface MarketplaceLinking {
|
|
77
|
+
requestCode(ctx: LinkCallContext): Promise<LinkResult<LinkCode>>;
|
|
78
|
+
exchange(ctx: LinkCallContext, input: { authorizationCode: string; verifier: string }): Promise<LinkResult<LinkGrant>>;
|
|
79
|
+
refresh(ctx: LinkCallContext, input: { refreshToken: string }): Promise<LinkResult<LinkGrant>>;
|
|
80
|
+
merchants(ctx: LinkCallContext, input: { accessToken: string }): Promise<LinkResult<LinkedMerchant[]>>;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The host's configuration of its OWN app on a marketplace: client id, client
|
|
85
|
+
* secret, and the key the marketplace signs the app's webhook deliveries with.
|
|
86
|
+
* Null (or the port not bound) means the software has no app there, and the
|
|
87
|
+
* linking flow reports itself unavailable; a store's own credentials keep
|
|
88
|
+
* working unchanged either way.
|
|
89
|
+
*/
|
|
90
|
+
export type MarketplaceAppCredentialsPort = (
|
|
91
|
+
provider: string,
|
|
92
|
+
environment: "SANDBOX" | "PRODUCTION",
|
|
93
|
+
) => MarketplaceCredentials | null | Promise<MarketplaceCredentials | null>;
|
|
94
|
+
|
|
95
|
+
/** The link-attempt delegate the engine reads and writes (the `MarketplaceLinkAttempt` model). */
|
|
96
|
+
export interface MarketplaceLinkAttemptDelegate {
|
|
97
|
+
findUnique(args: unknown): Promise<unknown>;
|
|
98
|
+
upsert(args: unknown): Promise<unknown>;
|
|
99
|
+
deleteMany(args: unknown): Promise<{ count: number }>;
|
|
100
|
+
}
|
|
@@ -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
|
+
}
|
package/src/core/menu-links.ts
CHANGED
|
@@ -14,6 +14,13 @@ import type { MarketplaceProvider } from "./types";
|
|
|
14
14
|
* The package never dereferences `menuItemId`. It asks the host whether the id
|
|
15
15
|
* is theirs (`order.catalogHas`, in `./bulk.ts`) and stores it; what the id
|
|
16
16
|
* MEANS is the host's.
|
|
17
|
+
*
|
|
18
|
+
* A link may narrow the mapping to ONE variation of that id (`variationId`,
|
|
19
|
+
* FUT-4927): a marketplace SKU usually names one flavour or size, and the
|
|
20
|
+
* host's order line is then the item plus that variation. `variationId` null
|
|
21
|
+
* is the item alone, exactly as before it existed; it is never set without
|
|
22
|
+
* `menuItemId`, and the host answers whether it belongs to the item
|
|
23
|
+
* (`order.catalogHasVariation`).
|
|
17
24
|
*/
|
|
18
25
|
|
|
19
26
|
/** A link as every read surface sees it. */
|
|
@@ -24,15 +31,24 @@ export interface MarketplaceMenuLinkView {
|
|
|
24
31
|
externalName: string;
|
|
25
32
|
/** The host catalog id, or null while the SKU is unmapped. */
|
|
26
33
|
menuItemId: string | null;
|
|
34
|
+
/** The variation of `menuItemId` the SKU names, or null for the item alone. */
|
|
35
|
+
variationId: string | null;
|
|
27
36
|
lastSeenAt: Date;
|
|
28
37
|
}
|
|
29
38
|
|
|
39
|
+
/** What one SKU resolves to on the ingest path; both null while it is unmapped. */
|
|
40
|
+
interface ResolvedSku {
|
|
41
|
+
menuItemId: string | null;
|
|
42
|
+
variationId: string | null;
|
|
43
|
+
}
|
|
44
|
+
|
|
30
45
|
const LINK_SELECT = {
|
|
31
46
|
id: true,
|
|
32
47
|
provider: true,
|
|
33
48
|
externalSku: true,
|
|
34
49
|
externalName: true,
|
|
35
50
|
menuItemId: true,
|
|
51
|
+
variationId: true,
|
|
36
52
|
lastSeenAt: true,
|
|
37
53
|
} as const;
|
|
38
54
|
|
|
@@ -42,6 +58,7 @@ interface LinkRow {
|
|
|
42
58
|
externalSku: string;
|
|
43
59
|
externalName: string | null;
|
|
44
60
|
menuItemId: string | null;
|
|
61
|
+
variationId?: string | null;
|
|
45
62
|
lastSeenAt: Date;
|
|
46
63
|
}
|
|
47
64
|
|
|
@@ -52,6 +69,9 @@ function toView(row: LinkRow): MarketplaceMenuLinkView {
|
|
|
52
69
|
externalSku: row.externalSku,
|
|
53
70
|
externalName: row.externalName ?? row.externalSku,
|
|
54
71
|
menuItemId: row.menuItemId,
|
|
72
|
+
// A row with no variation key (a fake db) reads as the item alone. A Prisma client
|
|
73
|
+
// generated before the migration throws on `variationId` instead: sync, generate, migrate.
|
|
74
|
+
variationId: row.menuItemId === null ? null : (row.variationId ?? null),
|
|
55
75
|
lastSeenAt: row.lastSeenAt,
|
|
56
76
|
};
|
|
57
77
|
}
|
|
@@ -86,6 +106,10 @@ export async function listMarketplaceMenuLinks(
|
|
|
86
106
|
* transaction. The caller has already checked the id is this tenant's
|
|
87
107
|
* (`order.catalogHas`). Creates the link if the SKU has never been seen: an
|
|
88
108
|
* operator mapping ahead of the first order is doing the right thing.
|
|
109
|
+
*
|
|
110
|
+
* Every write sets BOTH halves: a mapping to the item alone (`variationId`
|
|
111
|
+
* absent or null) clears a variation an earlier mapping named, and an unmap
|
|
112
|
+
* clears both.
|
|
89
113
|
*/
|
|
90
114
|
export async function upsertLink(
|
|
91
115
|
db: MarketplaceDb,
|
|
@@ -95,8 +119,10 @@ export async function upsertLink(
|
|
|
95
119
|
externalSku: string;
|
|
96
120
|
externalName?: string;
|
|
97
121
|
menuItemId: string | null;
|
|
122
|
+
variationId?: string | null;
|
|
98
123
|
},
|
|
99
124
|
): Promise<MarketplaceMenuLinkView> {
|
|
125
|
+
const variationId = input.menuItemId === null ? null : (input.variationId ?? null);
|
|
100
126
|
const row = (await db.marketplaceMenuLink.upsert({
|
|
101
127
|
where: {
|
|
102
128
|
clientId_provider_externalSku: {
|
|
@@ -111,11 +137,12 @@ export async function upsertLink(
|
|
|
111
137
|
externalSku: input.externalSku,
|
|
112
138
|
externalName: input.externalName ?? input.externalSku,
|
|
113
139
|
menuItemId: input.menuItemId,
|
|
140
|
+
variationId,
|
|
114
141
|
},
|
|
115
142
|
// `externalName` is NOT rewritten here. It is the marketplace's snapshot of
|
|
116
143
|
// what it called the item, and an operator's typing is not a better record
|
|
117
144
|
// of that than the marketplace's own text.
|
|
118
|
-
update: { menuItemId: input.menuItemId },
|
|
145
|
+
update: { menuItemId: input.menuItemId, variationId },
|
|
119
146
|
select: LINK_SELECT,
|
|
120
147
|
})) as LinkRow;
|
|
121
148
|
return toView(row);
|
|
@@ -139,8 +166,8 @@ export async function resolveSkus(
|
|
|
139
166
|
skus: { externalSku: string; name: string }[];
|
|
140
167
|
seenAt: Date;
|
|
141
168
|
},
|
|
142
|
-
): Promise<Map<string,
|
|
143
|
-
const resolved = new Map<string,
|
|
169
|
+
): Promise<Map<string, ResolvedSku>> {
|
|
170
|
+
const resolved = new Map<string, ResolvedSku>();
|
|
144
171
|
for (const sku of input.skus) {
|
|
145
172
|
const row = (await db.marketplaceMenuLink.upsert({
|
|
146
173
|
where: {
|
|
@@ -158,9 +185,12 @@ export async function resolveSkus(
|
|
|
158
185
|
lastSeenAt: input.seenAt,
|
|
159
186
|
},
|
|
160
187
|
update: { lastSeenAt: input.seenAt },
|
|
161
|
-
select: { menuItemId: true },
|
|
162
|
-
})) as { menuItemId: string | null };
|
|
163
|
-
resolved.set(sku.externalSku,
|
|
188
|
+
select: { menuItemId: true, variationId: true },
|
|
189
|
+
})) as { menuItemId: string | null; variationId?: string | null };
|
|
190
|
+
resolved.set(sku.externalSku, {
|
|
191
|
+
menuItemId: row.menuItemId,
|
|
192
|
+
variationId: row.menuItemId === null ? null : (row.variationId ?? null),
|
|
193
|
+
});
|
|
164
194
|
}
|
|
165
195
|
return resolved;
|
|
166
196
|
}
|
|
@@ -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
|
+
}
|