@extenshi/mcp
Version:
Extenshi MCP server — bring the extension catalog (search, security, market research) and pre-publish scanning into your AI tools
236 lines • 12.4 kB
JavaScript
/**
* Multi-store publishing for the MCP `publish_extension` tool.
*
* Thin wrapper over @extenshi/publisher: credentials come from the MCP
* client's environment (same env vars as `extenshi publish`, defined once in
* the publisher's STORE_ENV), the upload goes straight from this machine to
* the store APIs. FREE — no Extenshi API key, nothing passes through Extenshi
* servers. Chrome takes the author's own service account key.
*/
import * as fs from 'node:fs';
import path from 'node:path';
import { isPlaceholderGeckoId, isValidGeckoId } from '@extenshi/contracts';
import { ChromeAPI, configuredStores, EdgeAPI, FirefoxAPI, publishToStores, readStoreCredentialsFromEnv, retiredStoreCredentials, STORE_ENV, } from '@extenshi/publisher';
import { assertValidArtifact } from './validate-artifact.js';
import { assertInsideWorkspace, WorkspacePathError } from './workspace-path.js';
export const ENV_DOCS = STORE_ENV;
/**
* Store credentials, with an explicitly stated AMO add-on id filling
* FIREFOX_ADDON_GUID when the environment has none. A different environment
* value is refused: one run publishes to one add-on id.
*/
export function storeCredentialsFor(addonId, env = process.env, stores) {
return readStoreCredentials(credentialsEnv(addonId, env), stores);
}
/** The environment with an explicitly stated AMO add-on id filled in. */
function credentialsEnv(addonId, env = process.env) {
if (addonId && env.FIREFOX_ADDON_GUID && env.FIREFOX_ADDON_GUID !== addonId)
throw new PublishSetupError(`addon_id (${addonId}) differs from FIREFOX_ADDON_GUID (${env.FIREFOX_ADDON_GUID}); state one add-on id.`);
return addonId && !env.FIREFOX_ADDON_GUID ? { ...env, FIREFOX_ADDON_GUID: addonId } : env;
}
/** Credentials for `stores` (all stores when empty); key files are read only for those. */
export function readStoreCredentials(env = process.env, stores) {
try {
return readStoreCredentialsFromEnv(env, stores?.length ? stores : undefined);
}
catch (err) {
throw new PublishSetupError(err instanceof Error ? err.message : String(err));
}
}
export function credentialsHelp(stores, env = process.env) {
const retired = retiredStoreCredentials(env);
return stores
.map((s) => ` ${s}: ${ENV_DOCS[s].join(', ')}${retired[s] ? `\n ${retired[s]}` : ''}`)
.join('\n');
}
export class PublishSetupError extends Error {
}
/**
* Whether this call may CREATE a new AMO add-on. With a project, its
* owner-decided `amo.addonId` governs (and a different FIREFOX_ADDON_GUID is
* refused). Without one, `allowNewAddon` is the switch and `addonId` has to
* state the id explicitly — it is never taken silently from the environment.
* Mirrors the CLI's gate.
*/
export function amoCreateAllowed(opts) {
if (opts.addonId !== undefined && opts.addonId !== opts.addonGuid)
throw new PublishSetupError(`addon_id (${opts.addonId}) differs from FIREFOX_ADDON_GUID (${opts.addonGuid}); state one add-on id.`);
if (!opts.projectId) {
if (!opts.allowNewAddon)
return false;
if (!opts.addonId)
throw new PublishSetupError('allow_new_addon without project_id needs addon_id: the AMO add-on id to create, stated explicitly. ' +
'It becomes permanent at the first upload and is never invented. With project_id the owner decides it in Dojo instead.');
if (!isValidGeckoId(opts.addonId))
throw new PublishSetupError(`addon_id ${opts.addonId} is not an AMO add-on id: use a braced GUID ({xxxxxxxx-xxxx-…}) or name@domain.`);
if (isPlaceholderGeckoId(opts.addonId))
throw new PublishSetupError(`addon_id ${opts.addonId} is a placeholder; AMO would bind the new add-on to it forever. State the real id.`);
return true;
}
if (opts.decision?.status === 'decided') {
if (opts.decision.value !== opts.addonGuid)
throw new PublishSetupError(`FIREFOX_ADDON_GUID (${opts.addonGuid}) differs from the add-on id the project owner decided (${String(opts.decision.value)}). ` +
'Set the manifest gecko.id and FIREFOX_ADDON_GUID to the decided id; AMO never renames an add-on.');
return true;
}
if (opts.allowNewAddon)
throw new PublishSetupError(`The owner of project ${opts.projectId} has not decided amo.addonId, and creating the AMO add-on fixes it permanently. ` +
'Propose it with propose_decision; the owner decides it on the Dojo project page.');
return false;
}
/**
* An MCP installed with an older @extenshi/publisher would drop reviewer notes
* without a word (its options schema strips unknown keys), so refuse instead.
* Read through the namespace: a missing named export would fail the import.
*/
export function requireReviewerNotesSupport(firefox = FirefoxAPI) {
if (typeof firefox.AMO_APPROVAL_NOTES_MAX !== 'number')
throw new PublishSetupError("This installation's @extenshi/publisher predates reviewer_notes. Reinstall @extenshi/mcp to update it.");
}
/**
* An MCP installed with an older @extenshi/publisher would create the version and
* drop the source archive without a word (it ignores sourceFilePath without a
* listing), and AMO rejects a bundled version that has no source. Refuse instead.
*/
export function requireSourceWithoutListingSupport(firefox = FirefoxAPI) {
if (firefox.AMO_SOURCE_WITHOUT_LISTING !== true)
throw new PublishSetupError("This installation's @extenshi/publisher predates source_path without listing_path. Reinstall @extenshi/mcp to update it.");
}
/**
* Load the Firefox extras. With a listing: the listing, source and screenshots
* of a listed AMO submission. Source alone: only `sourceFilePath`, for the new
* version of an existing add-on.
*/
export function loadFirefoxListing(listing) {
if (listing.screenshotsDir && !listing.listingPath)
throw new PublishSetupError('screenshots_dir needs listing_path, the AMO listing the previews belong to.');
if (!listing.listingPath && !listing.sourcePath)
return undefined;
try {
const sourceFilePath = listing.sourcePath ? path.resolve(listing.sourcePath) : undefined;
if (sourceFilePath) {
if (!fs.existsSync(sourceFilePath))
throw new Error(`Source archive not found: ${listing.sourcePath}`);
FirefoxAPI.assertSourceArchive(sourceFilePath);
}
if (!listing.listingPath) {
requireSourceWithoutListingSupport();
return { sourceFilePath };
}
if (typeof FirefoxAPI.submitListing !== 'function' || typeof FirefoxAPI.loadAmoListing !== 'function')
throw new PublishSetupError("This installation's @extenshi/publisher predates AMO listing submission. Reinstall @extenshi/mcp to update it.");
const parsed = FirefoxAPI.loadAmoListing(path.resolve(listing.listingPath));
const screenshotPaths = listing.screenshotsDir
? FirefoxAPI.listScreenshots(path.resolve(listing.screenshotsDir), parsed.defaultLocale)
: undefined;
if (screenshotPaths && !screenshotPaths.length)
throw new Error(`No .png, .jpg or .gif screenshots in ${listing.screenshotsDir}`);
return {
listing: parsed,
sourceFilePath,
screenshotPaths,
allowCreate: listing.allowCreate ?? false,
replaceScreenshots: listing.replaceScreenshots ?? false,
};
}
catch (err) {
if (err instanceof PublishSetupError)
throw err;
throw new PublishSetupError(err instanceof Error ? err.message : String(err));
}
}
export async function publishArtifact(args) {
// Confine artifacts to the workspace before anything reads them: the
// paths arrive as tool arguments, and publishing an arbitrary build
// from elsewhere on disk (under the user's store credentials and
// trusted listings) is exactly the prompt-injection endgame. The
// resolved realpaths replace the raw inputs for everything below.
try {
args = {
...args,
artifactPath: assertInsideWorkspace(args.artifactPath, args.workspaceRoot),
...(args.firefoxArtifactPath
? { firefoxArtifactPath: assertInsideWorkspace(args.firefoxArtifactPath, args.workspaceRoot) }
: {}),
};
}
catch (err) {
if (err instanceof WorkspacePathError)
throw new PublishSetupError(err.message);
throw err;
}
if (!fs.existsSync(args.artifactPath)) {
throw new PublishSetupError(`Artifact not found: ${args.artifactPath}`);
}
if (args.firefoxArtifactPath && !fs.existsSync(args.firefoxArtifactPath)) {
throw new PublishSetupError(`Firefox artifact not found: ${args.firefoxArtifactPath}`);
}
// Refuse to upload anything that isn't a real extension package.
try {
assertValidArtifact(args.artifactPath);
if (args.firefoxArtifactPath)
assertValidArtifact(args.firefoxArtifactPath);
}
catch (err) {
throw new PublishSetupError(err instanceof Error ? err.message : String(err));
}
const reviewerNotes = args.reviewerNotes?.trim() || undefined;
if (reviewerNotes)
requireReviewerNotesSupport();
const env = credentialsEnv(args.addonId);
const stores = args.stores?.length ? args.stores : configuredStores(env);
// Only the selected stores: an unrelated broken Chrome key path must not
// stop a Firefox- or Edge-only publish.
const creds = readStoreCredentials(env, stores);
if (!stores.length) {
throw new PublishSetupError('No store credentials found in the environment. Publishing is free and runs locally — ' +
'add credentials for at least one store to the MCP server env:\n' +
credentialsHelp(['chrome', 'firefox', 'edge']));
}
const missing = stores.filter((s) => !creds[s]);
if (missing.length) {
throw new PublishSetupError(`Missing credentials for: ${missing.join(', ')}\n${credentialsHelp(missing)}`);
}
if (args.firefoxListing && !stores.includes('firefox'))
throw new PublishSetupError('listing_path, source_path and screenshots_dir apply to Firefox (AMO); include firefox in stores.');
const firefoxListing = args.firefoxListing ? loadFirefoxListing(args.firefoxListing) : undefined;
return publishToStores({
extensionId: creds.chrome?.appId ?? creds.firefox?.addonGuid ?? creds.edge?.productId ?? 'extension',
stores,
packagePaths: {
chrome: stores.includes('chrome') ? args.artifactPath : undefined,
firefox: stores.includes('firefox') ? (args.firefoxArtifactPath ?? args.artifactPath) : undefined,
edge: stores.includes('edge') ? args.artifactPath : undefined,
},
storeConfigs: {
chrome: creds.chrome,
firefox: creds.firefox ? { ...creds.firefox, ...(firefoxListing ?? {}) } : undefined,
edge: creds.edge,
},
releaseNotes: args.releaseNotes,
reviewerNotes,
parallel: true,
});
}
export async function validateStoreCredentials(stores) {
const targets = stores?.length ? stores : ['chrome', 'firefox', 'edge'];
const creds = readStoreCredentials(process.env, targets);
return Promise.all(targets.map(async (store) => {
if (store === 'chrome' && creds.chrome) {
// The item id proves the service account is added to the publisher
// and the item belongs to it, not only that the key signs.
const valid = await ChromeAPI.validateCredentials(creds.chrome, creds.chrome.appId);
return { store, configured: true, valid };
}
if (store === 'firefox' && creds.firefox) {
const valid = await FirefoxAPI.validateCredentials(creds.firefox.jwtIssuer, creds.firefox.jwtSecret);
return { store, configured: true, valid };
}
if (store === 'edge' && creds.edge) {
const valid = await EdgeAPI.validateCredentials(creds.edge, creds.edge.productId);
return { store, configured: true, valid };
}
return { store, configured: false, valid: false };
}));
}
//# sourceMappingURL=publish.js.map