Files
orca/src/main/plugins/plugin-bundled-bootstrap.ts
T

222 lines
7.6 KiB
TypeScript

import { readFile, realpath, stat } from 'node:fs/promises'
import { isAbsolute, join, relative, sep } from 'node:path'
import { z } from 'zod'
import { isQualifiedPluginKey } from '../../shared/plugins/manifest/plugin-manifest'
import { pluginRelativeDirectorySchema } from '../../shared/plugins/manifest/plugin-manifest-fields'
import { hasOfficialPluginPublisher } from '../../shared/plugins/catalog/plugin-marketplace'
import { getPluginsDataDir, getUserPluginsDir } from './plugin-discovery'
import {
installBundledPlugin,
readPluginLockfile,
retireBundledPlugin
} from './installation/plugin-install'
import { inspectPluginInstallTree } from './installation/plugin-install-staging'
import { readPluginCurrentPointer } from './installation/plugin-current-pointer'
import { hashPluginTree } from './plugin-content-hash'
export const BUNDLED_PLUGIN_INDEX_FILENAME = 'bundled-plugins.json'
const BUNDLED_PLUGIN_INDEX_MAX_BYTES = 64 * 1024
const bundledPluginIndexSchema = z
.object({
version: z.literal(1),
plugins: z
.array(
z
.object({
pluginKey: z
.string()
.refine(isQualifiedPluginKey, 'invalid qualified plugin identity')
.refine(
hasOfficialPluginPublisher,
'bundled plugins must use the official publisher'
),
path: pluginRelativeDirectorySchema,
contentHash: z.string().regex(/^[0-9a-f]{64}$/)
})
.strict()
)
.max(32)
})
.strict()
.superRefine((index, ctx) => {
const keys = new Set<string>()
for (const [entryIndex, plugin] of index.plugins.entries()) {
if (keys.has(plugin.pluginKey)) {
ctx.addIssue({
code: 'custom',
path: ['plugins', entryIndex, 'pluginKey'],
message: 'duplicate bundled plugin identity'
})
}
keys.add(plugin.pluginKey)
}
})
export type PluginBundledBootstrapResult = {
installed: string[]
unchanged: string[]
/** Previously bundled plugins this release stopped shipping, now uninstalled. */
retired: string[]
errors: { pluginKey: string; error: string }[]
}
export function resolveBundledPluginRoot(options: {
isPackaged: boolean
resourcesPath: string
appPath: string
}): string {
return options.isPackaged
? join(options.resourcesPath, 'plugins', 'launch')
: join(options.appPath, 'resources', 'plugins', 'launch')
}
/** The running app's bundled plugin root. */
export function bundledPluginRootForApp(app: {
isPackaged: boolean
getAppPath(): string
}): string {
return resolveBundledPluginRoot({
isPackaged: app.isPackaged,
resourcesPath: process.resourcesPath,
appPath: app.getAppPath()
})
}
async function readBundledPluginIndex(
root: string
): Promise<z.infer<typeof bundledPluginIndexSchema>> {
const indexPath = join(root, BUNDLED_PLUGIN_INDEX_FILENAME)
const metadata = await stat(indexPath)
if (!metadata.isFile() || metadata.size > BUNDLED_PLUGIN_INDEX_MAX_BYTES) {
throw new Error(`bundled plugin index exceeds ${BUNDLED_PLUGIN_INDEX_MAX_BYTES} bytes`)
}
return bundledPluginIndexSchema.parse(JSON.parse(await readFile(indexPath, 'utf8')))
}
/** Whether this release ships the plugin; false when the index can't be read. */
export async function isBundledPluginKey(root: string, pluginKey: string): Promise<boolean> {
if (!hasOfficialPluginPublisher(pluginKey)) {
return false
}
const index = await readBundledPluginIndex(root).catch(() => null)
return index?.plugins.some((entry) => entry.pluginKey === pluginKey) ?? false
}
async function resolveBundlePath(root: string, path: string): Promise<string> {
const [resolvedRoot, resolvedPath] = await Promise.all([
realpath(root),
realpath(join(root, path))
])
const fromRoot = relative(resolvedRoot, resolvedPath)
if (!fromRoot || fromRoot === '..' || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot)) {
throw new Error('bundled plugin path escapes the resource root')
}
return resolvedPath
}
async function bundledInstallIsIntact(
pluginsDir: string,
pluginKey: string,
contentHash: string
): Promise<boolean> {
const pluginDir = join(pluginsDir, pluginKey)
if ((await readPluginCurrentPointer(pluginDir).catch(() => null)) !== contentHash) {
return false
}
const hashed = await hashPluginTree(join(pluginDir, contentHash))
return hashed.ok && hashed.hash === contentHash
}
export async function bootstrapBundledPlugins(options: {
root: string
userDataPath: string
hostVersion: string
blockedPluginReason?: (pluginKey: string) => string | null
/** Runs before a retired plugin's files are deleted, e.g. to revoke its consent. */
beforeRetire?: (pluginKey: string) => void | Promise<void>
/** Runs after a retired plugin's files are gone, e.g. to clear its frame storage. */
afterRetire?: (pluginKey: string) => void | Promise<void>
}): Promise<PluginBundledBootstrapResult> {
const index = await readBundledPluginIndex(options.root)
const pluginsDir = getUserPluginsDir(options.userDataPath)
const lock = await readPluginLockfile(pluginsDir)
const result: PluginBundledBootstrapResult = {
installed: [],
unchanged: [],
retired: [],
errors: []
}
for (const entry of index.plugins) {
const locked = lock.plugins[entry.pluginKey]
// Why: a catalog install or update of the same plugin is the user's choice; never downgrade it.
if (locked && locked.source.kind !== 'bundled') {
continue
}
if (
locked?.source.kind === 'bundled' &&
locked.source.bundleId === entry.pluginKey &&
locked.contentHash === entry.contentHash &&
(await bundledInstallIsIntact(pluginsDir, entry.pluginKey, entry.contentHash))
) {
result.unchanged.push(entry.pluginKey)
continue
}
try {
const sourcePath = await resolveBundlePath(options.root, entry.path)
const inspection = await inspectPluginInstallTree({
rootDir: sourcePath,
hostVersion: options.hostVersion,
identity: { pluginKey: entry.pluginKey }
})
if (!inspection.ok) {
throw new Error(inspection.error)
}
if (inspection.contentHash !== entry.contentHash) {
throw new Error('bundled plugin content does not match its release index')
}
const installed = await installBundledPlugin({
pluginsDir,
sourcePath,
hostVersion: options.hostVersion,
expectedPluginKey: entry.pluginKey,
blockedPluginReason: options.blockedPluginReason
})
if (!installed.ok) {
throw new Error(installed.error)
}
result.installed.push(entry.pluginKey)
} catch (error) {
result.errors.push({
pluginKey: entry.pluginKey,
error: error instanceof Error ? error.message : String(error)
})
}
}
// Why: a release that drops a bundled plugin must not leave it installed but unremovable.
const shipped = new Set(index.plugins.map((entry) => entry.pluginKey))
for (const [pluginKey, locked] of Object.entries(lock.plugins)) {
if (locked.source.kind !== 'bundled' || shipped.has(pluginKey)) {
continue
}
try {
const retired = await retireBundledPlugin({
pluginsDir,
pluginsDataDir: getPluginsDataDir(options.userDataPath),
pluginKey,
beforeRemove: () => options.beforeRetire?.(pluginKey)
})
if (retired) {
result.retired.push(pluginKey)
await options.afterRetire?.(pluginKey)
}
} catch (error) {
result.errors.push({
pluginKey,
error: error instanceof Error ? error.message : String(error)
})
}
}
return result
}