@12-apps/marketplace 1.10.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ADOPTING.md +36 -0
- package/README.md +63 -0
- 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-WVZ2IXFH.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-2BA2EHNF.js → chunk-YWMEIMO3.js} +206 -22
- package/dist/chunk-YWMEIMO3.js.map +1 -0
- package/dist/{client-B4EQCRD_.d.ts → client-11sncog4.d.ts} +1 -1
- package/dist/{engine-DK3iV_Kk.d.ts → engine-C_3RK8wC.d.ts} +116 -4
- 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 +264 -21
- 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 +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 +21 -0
- package/src/core/bulk.ts +43 -8
- package/src/core/engine.ts +59 -3
- 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/merchant-claim.ts +106 -0
- package/src/core/ports.ts +3 -0
- 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 +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-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)[];
|
|
@@ -87,6 +90,29 @@ function integrationRowProblems(
|
|
|
87
90
|
return changes ? [] : [{ path: ["integrations", index], code: "NOTHING_TO_UPDATE" }];
|
|
88
91
|
}
|
|
89
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
|
+
|
|
90
116
|
/** Thrown inside the transaction to roll a `validateOnly` call back. */
|
|
91
117
|
class ValidateOnly extends Error {
|
|
92
118
|
constructor() {
|
|
@@ -136,14 +162,15 @@ export async function upsertIntegrations(
|
|
|
136
162
|
ctx: EngineContext,
|
|
137
163
|
input: { clientId: string; actorId: string | null; rows: readonly IntegrationRowInput[]; validateOnly?: boolean },
|
|
138
164
|
): Promise<BulkResult<MarketplaceIntegrationView>> {
|
|
139
|
-
const
|
|
140
|
-
|
|
141
|
-
);
|
|
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]));
|
|
142
168
|
const problems = [
|
|
143
169
|
...duplicates(input.rows, (row) => row.provider, "integrations", "provider"),
|
|
144
170
|
...unknownProviders(ctx, input.rows, "integrations"),
|
|
145
171
|
...input.rows.flatMap((row, index) => integrationRowProblems(row, index, existing)),
|
|
146
172
|
];
|
|
173
|
+
if (problems.length === 0) problems.push(...(await merchantProblems(ctx, input.clientId, input.rows, merchantOf)));
|
|
147
174
|
if (problems.length > 0) return { kind: "refused", problems };
|
|
148
175
|
|
|
149
176
|
const validateOnly = input.validateOnly === true;
|
|
@@ -151,10 +178,18 @@ export async function upsertIntegrations(
|
|
|
151
178
|
// The audit lines are written INSIDE the archive's transaction, through its
|
|
152
179
|
// client: an archive never lands without its line, and an audit that fails
|
|
153
180
|
// rolls the archive back. A `validateOnly` call rolls both back.
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
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
|
+
}
|
|
158
193
|
const providers = input.rows.map((row) => row.provider);
|
|
159
194
|
const rows = validateOnly
|
|
160
195
|
? []
|
package/src/core/engine.ts
CHANGED
|
@@ -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:
|
|
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),
|
package/src/core/integration.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
343
|
-
|
|
344
|
-
|
|
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
|
+
}
|
|
@@ -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
|
+
}
|