-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathmarketplace.ts
More file actions
422 lines (383 loc) · 14.4 KB
/
Copy pathmarketplace.ts
File metadata and controls
422 lines (383 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
/**
* Marketplace API client
*
* Calls the site-side proxy endpoints (/_emdash/api/admin/plugins/marketplace/*)
* which forward to the marketplace Worker. This avoids CORS issues since the
* admin UI doesn't need to know the marketplace URL.
*/
import { i18n } from "@lingui/core";
import { msg } from "@lingui/core/macro";
import { API_BASE, apiFetch, parseApiResponse, throwResponseError } from "./client.js";
// ---------------------------------------------------------------------------
// Types — matches the marketplace REST API response shapes
// ---------------------------------------------------------------------------
export interface MarketplaceAuthor {
name: string;
verified: boolean;
}
export interface MarketplaceAuditSummary {
verdict: "pass" | "warn" | "fail";
riskScore: number;
}
export interface MarketplaceImageAuditSummary {
verdict: "pass" | "warn" | "fail";
}
export interface MarketplaceVersion {
version: string;
minEmDashVersion?: string;
bundleSize: number;
changelog?: string;
readme?: string;
screenshotUrls?: string[];
audit?: MarketplaceAuditSummary;
imageAudit?: MarketplaceImageAuditSummary;
publishedAt: string;
}
/** Summary shown in browse cards */
export interface MarketplacePluginSummary {
id: string;
name: string;
description?: string;
author: MarketplaceAuthor;
capabilities: string[];
keywords?: string[];
installCount: number;
iconUrl?: string;
latestVersion?: {
version: string;
audit?: MarketplaceAuditSummary;
imageAudit?: MarketplaceImageAuditSummary;
};
createdAt: string;
updatedAt: string;
}
/** Full detail returned by GET /plugins/:id */
export interface MarketplacePluginDetail extends MarketplacePluginSummary {
license?: string;
repositoryUrl?: string;
homepageUrl?: string;
latestVersion?: MarketplaceVersion;
}
export interface MarketplaceSearchResult {
items: MarketplacePluginSummary[];
nextCursor?: string;
}
export interface MarketplaceSearchOpts {
q?: string;
capability?: string;
sort?: "installs" | "updated" | "created" | "name";
cursor?: string;
limit?: number;
}
/** Update check result per plugin */
export interface PluginUpdateInfo {
pluginId: string;
installed: string;
latest: string;
hasCapabilityChanges: boolean;
}
/** Install request body */
export interface InstallPluginOpts {
version?: string;
confirmMcpTools?: boolean;
}
export interface PluginMcpConsentTool {
name: string;
description: string;
route: string;
permission: string;
destructive: boolean;
}
export class PluginMcpConsentRequiredError extends Error {
constructor(readonly tools: PluginMcpConsentTool[]) {
super(i18n._(msg`Plugin MCP tools require explicit consent`));
this.name = "PluginMcpConsentRequiredError";
}
}
export class MarketplaceUpdateEscalationError extends Error {
readonly code: "CAPABILITY_ESCALATION" | "ROUTE_VISIBILITY_ESCALATION";
readonly capabilityChanges: { added: string[]; removed: string[] };
readonly routeVisibilityChanges?: { newlyPublic: string[] };
readonly mcpTools: PluginMcpConsentTool[];
constructor(
code: "CAPABILITY_ESCALATION" | "ROUTE_VISIBILITY_ESCALATION",
message: string,
capabilityChanges: { added: string[]; removed: string[] },
routeVisibilityChanges?: { newlyPublic: string[] },
mcpTools: PluginMcpConsentTool[] = [],
) {
super(message);
this.name = "MarketplaceUpdateEscalationError";
this.code = code;
this.capabilityChanges = capabilityChanges;
this.routeVisibilityChanges = routeVisibilityChanges;
this.mcpTools = mcpTools;
}
}
export class MarketplaceUpdateMcpConsentRequiredError extends PluginMcpConsentRequiredError {
constructor(
tools: PluginMcpConsentTool[],
readonly capabilityChanges: { added: string[]; removed: string[] },
readonly routeVisibilityChanges?: { newlyPublic: string[] },
) {
super(tools);
this.name = "MarketplaceUpdateMcpConsentRequiredError";
}
}
function isPluginMcpConsentTool(value: unknown): value is PluginMcpConsentTool {
if (!value || typeof value !== "object") return false;
return (
typeof Reflect.get(value, "name") === "string" &&
typeof Reflect.get(value, "description") === "string" &&
typeof Reflect.get(value, "route") === "string" &&
typeof Reflect.get(value, "permission") === "string" &&
typeof Reflect.get(value, "destructive") === "boolean"
);
}
function getMcpConsentTools(body: unknown): PluginMcpConsentTool[] | null {
if (!body || typeof body !== "object") return null;
const error = Reflect.get(body, "error");
if (!error || typeof error !== "object") return null;
if (Reflect.get(error, "code") !== "MCP_TOOL_CONSENT_REQUIRED") return null;
const details = Reflect.get(error, "details");
if (!details || typeof details !== "object") return null;
const tools = Reflect.get(details, "mcpTools");
if (!Array.isArray(tools) || tools.length === 0) return null;
const valid = tools.filter(isPluginMcpConsentTool);
return valid.length > 0 ? valid : null;
}
function normaliseStringArray(value: unknown): string[] {
return Array.isArray(value)
? value.filter((item): item is string => typeof item === "string")
: [];
}
function getMarketplaceUpdateEscalation(body: unknown): MarketplaceUpdateEscalationError | null {
if (!body || typeof body !== "object") return null;
const error = Reflect.get(body, "error");
if (!error || typeof error !== "object") return null;
const code = Reflect.get(error, "code");
if (code !== "CAPABILITY_ESCALATION" && code !== "ROUTE_VISIBILITY_ESCALATION") return null;
const details = Reflect.get(error, "details");
if (!details || typeof details !== "object") return null;
const capabilityChanges = Reflect.get(details, "capabilityChanges");
if (!capabilityChanges || typeof capabilityChanges !== "object") return null;
const added = normaliseStringArray(Reflect.get(capabilityChanges, "added"));
const removed = normaliseStringArray(Reflect.get(capabilityChanges, "removed"));
const routeVisibilityChanges = Reflect.get(details, "routeVisibilityChanges");
const newlyPublic =
routeVisibilityChanges && typeof routeVisibilityChanges === "object"
? normaliseStringArray(Reflect.get(routeVisibilityChanges, "newlyPublic"))
: [];
const message = Reflect.get(error, "message");
const mcpTools = Reflect.get(details, "mcpTools");
const validMcpTools = Array.isArray(mcpTools) ? mcpTools.filter(isPluginMcpConsentTool) : [];
return new MarketplaceUpdateEscalationError(
code,
typeof message === "string" ? message : i18n._(msg`Plugin update requires re-consent`),
{ added, removed },
newlyPublic.length > 0 ? { newlyPublic } : undefined,
validMcpTools,
);
}
function getMarketplaceUpdateMcpConsent(
body: unknown,
): MarketplaceUpdateMcpConsentRequiredError | null {
const tools = getMcpConsentTools(body);
if (!tools || !body || typeof body !== "object") return null;
const error = Reflect.get(body, "error");
if (!error || typeof error !== "object") return null;
const details = Reflect.get(error, "details");
if (!details || typeof details !== "object") return null;
const capabilityChanges = Reflect.get(details, "capabilityChanges");
const added =
capabilityChanges && typeof capabilityChanges === "object"
? normaliseStringArray(Reflect.get(capabilityChanges, "added"))
: [];
const removed =
capabilityChanges && typeof capabilityChanges === "object"
? normaliseStringArray(Reflect.get(capabilityChanges, "removed"))
: [];
const routeVisibilityChanges = Reflect.get(details, "routeVisibilityChanges");
const newlyPublic =
routeVisibilityChanges && typeof routeVisibilityChanges === "object"
? normaliseStringArray(Reflect.get(routeVisibilityChanges, "newlyPublic"))
: [];
return new MarketplaceUpdateMcpConsentRequiredError(
tools,
{ added, removed },
newlyPublic.length > 0 ? { newlyPublic } : undefined,
);
}
/** Update request body */
export interface UpdatePluginOpts {
/** Exact version reviewed by the user */
version?: string;
/** User has confirmed new capabilities */
confirmCapabilityChanges?: boolean;
/** User has confirmed newly public routes */
confirmRouteVisibilityChanges?: boolean;
confirmMcpTools?: boolean;
}
/** Uninstall request body */
export interface UninstallPluginOpts {
/** Delete plugin storage data */
deleteData?: boolean;
}
// ---------------------------------------------------------------------------
// API functions — proxy through site endpoints
// ---------------------------------------------------------------------------
const MARKETPLACE_BASE = `${API_BASE}/admin/plugins/marketplace`;
/**
* Search the marketplace catalog.
* Proxied through /_emdash/api/admin/plugins/marketplace
*/
export async function searchMarketplace(
opts: MarketplaceSearchOpts = {},
): Promise<MarketplaceSearchResult> {
const params = new URLSearchParams();
if (opts.q) params.set("q", opts.q);
if (opts.capability) params.set("capability", opts.capability);
if (opts.sort) params.set("sort", opts.sort);
if (opts.cursor) params.set("cursor", opts.cursor);
if (opts.limit) params.set("limit", String(opts.limit));
const qs = params.toString();
const url = `${MARKETPLACE_BASE}${qs ? `?${qs}` : ""}`;
const response = await apiFetch(url);
return parseApiResponse<MarketplaceSearchResult>(response, "Marketplace search failed");
}
/**
* Get full plugin detail.
* Proxied through /_emdash/api/admin/plugins/marketplace/:id
*/
export async function fetchMarketplacePlugin(id: string): Promise<MarketplacePluginDetail> {
const response = await apiFetch(`${MARKETPLACE_BASE}/${encodeURIComponent(id)}`);
if (response.status === 404) {
throw new Error(`Plugin "${id}" not found in marketplace`);
}
return parseApiResponse<MarketplacePluginDetail>(response, "Failed to fetch plugin");
}
/**
* Install a plugin from the marketplace.
* POST /_emdash/api/admin/plugins/marketplace/:id/install
*/
export async function installMarketplacePlugin(
id: string,
opts: InstallPluginOpts = {},
): Promise<void> {
const response = await apiFetch(`${MARKETPLACE_BASE}/${encodeURIComponent(id)}/install`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(opts),
});
if (!response.ok) {
const body: unknown = await response
.clone()
.json()
.catch(() => null);
const mcpTools = getMcpConsentTools(body);
if (mcpTools) throw new PluginMcpConsentRequiredError(mcpTools);
await throwResponseError(response, i18n._(msg`Failed to install plugin`));
}
}
/**
* Update a marketplace plugin to a newer version.
* POST /_emdash/api/admin/plugins/:id/update
*/
export async function updateMarketplacePlugin(
id: string,
opts: UpdatePluginOpts = {},
): Promise<void> {
const response = await apiFetch(`${API_BASE}/admin/plugins/${encodeURIComponent(id)}/update`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(opts),
});
if (!response.ok) {
const body: unknown = await response
.clone()
.json()
.catch(() => null);
const escalation = getMarketplaceUpdateEscalation(body);
if (escalation) throw escalation;
const mcpConsent = getMarketplaceUpdateMcpConsent(body);
if (mcpConsent) throw mcpConsent;
await throwResponseError(response, i18n._(msg`Failed to update plugin`));
}
}
/**
* Uninstall a marketplace plugin.
* POST /_emdash/api/admin/plugins/:id/uninstall
*/
export async function uninstallMarketplacePlugin(
id: string,
opts: UninstallPluginOpts = {},
): Promise<void> {
const response = await apiFetch(`${API_BASE}/admin/plugins/${encodeURIComponent(id)}/uninstall`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(opts),
});
if (!response.ok) await throwResponseError(response, i18n._(msg`Failed to uninstall plugin`));
}
/**
* Check all marketplace plugins for available updates.
* GET /_emdash/api/admin/plugins/updates
*/
export async function checkPluginUpdates(): Promise<PluginUpdateInfo[]> {
const response = await apiFetch(`${API_BASE}/admin/plugins/updates`);
const result = await parseApiResponse<{ items: PluginUpdateInfo[] }>(
response,
"Failed to check for updates",
);
return result.items;
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/**
* Human-readable labels for plugin capabilities.
*
* Canonical names are the keys; legacy names alias to the same labels so
* old manifests still render meaningful copy until they're republished.
*/
import type { MessageDescriptor } from "@lingui/core";
export const CAPABILITY_LABELS: Record<string, MessageDescriptor> = {
// Canonical
"content:read": msg`Read your content`,
"content:write": msg`Create, update, and delete content`,
"comments:read": msg`Read comment bodies, author email addresses, pseudonymous IP hashes, user agents, and moderation metadata`,
"comments:moderate": msg`Approve comments and mark them as pending or spam`,
"taxonomies:read": msg`Read your taxonomies and terms`,
"media:read": msg`Access your media library`,
"media:write": msg`Upload and manage media`,
"users:read": msg`Read user accounts`,
"network:request": msg`Make network requests`,
"network:request:unrestricted": msg`Make network requests to any host (unrestricted)`,
// Legacy aliases (still emitted by older installed manifests)
"read:content": msg`Read your content`,
"write:content": msg`Create, update, and delete content`,
"read:media": msg`Access your media library`,
"write:media": msg`Upload and manage media`,
"read:users": msg`Read user accounts`,
"network:fetch": msg`Make network requests`,
"network:fetch:any": msg`Make network requests to any host (unrestricted)`,
};
/** Capability names that grant scoped network access (legacy + canonical). */
const NETWORK_REQUEST_CAPABILITIES = new Set(["network:request", "network:fetch"]);
/**
* Get a human-readable description for a capability.
* For scoped network capabilities, appends the allowed hosts if provided.
*
* Module-scope so calls outside React components work; uses the global i18n
* instance for translation. Components that have access to `useLingui` can
* also resolve `CAPABILITY_LABELS[capability]` directly with `t(...)` if they
* need the translated string without the host suffix.
*/
export function describeCapability(capability: string, allowedHosts?: string[]): string {
const descriptor = CAPABILITY_LABELS[capability];
const base = descriptor ? i18n._(descriptor) : capability;
if (NETWORK_REQUEST_CAPABILITIES.has(capability) && allowedHosts && allowedHosts.length > 0) {
return i18n._(msg`${base} to: ${allowedHosts.join(", ")}`);
}
return base;
}