Files
outline/server/utils/PluginManager.ts
Tom Moor 6d7cd455e9 chore: Decouple core plugins (#14340)
* chore: Move plugin-specific integration code into plugins

Core no longer imports from or names the settings of individual plugins.
Plugins now register mention providers, issue status icons, instance URLs,
settings keys, settings and import schemas, and OAuth clients through hooks.

* fix: Recompute embed instance URLs after plugins load and match legacy issue icons by URL

* fix: Skip logo upload jobs queued without a settings path

* chore: Choose issue status icons from the unfurl state
2026-11-02 19:42:48 -05:00

213 lines
6.9 KiB
TypeScript

import path from "node:path";
import { glob } from "glob";
import type Router from "@koa/router";
import { isArray, sortBy } from "es-toolkit/compat";
import type { z } from "zod";
import type {
Concrete,
EmbedIntegrationSettings,
IntegrationService,
LinkedAccountIntegrationSettings,
} from "@shared/types";
import type BaseEmail from "@server/emails/templates/BaseEmail";
import type { ImportsCreateBody } from "@server/routes/api/imports/schema";
import env from "@server/env";
import Logger from "@server/logging/Logger";
import type BaseProcessor from "@server/queues/processors/BaseProcessor";
import type { BaseTask } from "@server/queues/tasks/base/BaseTask";
import type {
MentionSignature,
UnfurlSignature,
UninstallSignature,
} from "@server/types";
import type OAuthClient from "./oauth";
import type { BaseIssueProvider } from "./BaseIssueProvider";
import type { GroupSyncProvider } from "./GroupSyncProvider";
import type { BaseSearchProvider } from "./BaseSearchProvider";
/**
* The priority of a plugin, used to determine the order in which plugins of
* the same type are evaluated. Lower values are higher priority.
*/
export enum PluginPriority {
VeryHigh = 0,
High = 100,
Normal = 200,
Low = 300,
VeryLow = 500,
}
/**
* The different types of server plugins that can be registered.
*/
export enum Hook {
API = "api",
AuthProvider = "authProvider",
EmailTemplate = "emailTemplate",
ImportSchema = "importSchema",
IntegrationSettings = "integrationSettings",
IssueProvider = "issueProvider",
Processor = "processor",
SearchProvider = "searchProvider",
MentionProvider = "mentionProvider",
Task = "task",
UnfurlProvider = "unfurl",
Uninstall = "uninstall",
GroupSyncProvider = "groupSyncProvider",
}
/**
* A map of plugin types to their values, for example an API plugin would have a value of type
* Router. Registering an API plugin causes the router to be mounted.
*/
type PluginValueMap = {
[Hook.API]: Router;
[Hook.AuthProvider]: {
router: Router | Promise<Router>;
id: string;
/**
* Whether a verified email from another tenant of the provider, eg a
* different Google Workspace domain, can sign in to a matching account.
*/
allowEmailMatch?: boolean;
/** Creates a client to validate and refresh the provider's access tokens. */
oauthClient?: () => OAuthClient;
};
// oxlint-disable-next-line @typescript-eslint/no-explicit-any -- typeof BaseEmail<EmailProps> isn't assignable from BaseEmail<Subtype>; plugins register heterogeneous template Props.
[Hook.EmailTemplate]: Concrete<typeof BaseEmail<any>>;
[Hook.ImportSchema]: z.ZodType<ImportsCreateBody>;
[Hook.IntegrationSettings]: {
/** The integration service that the settings belong to. */
service: IntegrationService;
/** The settings keys that are presented to clients. */
keys: (
| keyof EmbedIntegrationSettings
| keyof LinkedAccountIntegrationSettings
)[];
/** Whether guests can see the keys, which only render and edit embeds. */
visibleToGuests?: boolean;
/** A schema to validate settings given through the integrations API. */
schema?: z.ZodType<EmbedIntegrationSettings>;
};
[Hook.IssueProvider]: BaseIssueProvider;
[Hook.MentionProvider]: MentionSignature;
[Hook.Processor]: Concrete<typeof BaseProcessor>;
[Hook.SearchProvider]: BaseSearchProvider;
[Hook.Task]: Concrete<typeof BaseTask<object>>;
[Hook.Uninstall]: UninstallSignature;
[Hook.UnfurlProvider]: { unfurl: UnfurlSignature; cacheExpiry: number };
[Hook.GroupSyncProvider]: { id: string; provider: GroupSyncProvider };
};
export type Plugin<T extends Hook> = {
/** Plugin type */
type: T;
/** The plugin's display name */
name?: string;
/** A brief description of the plugin */
description?: string;
/** The plugin content */
value: PluginValueMap[T];
/** Priority will affect order in menus and execution. Lower is earlier. */
priority?: number;
};
/**
* Server plugin manager.
*/
export class PluginManager {
private static plugins = new Map<Hook, Plugin<Hook>[]>();
/**
* Add plugins to the manager.
*
* @param plugins
*/
public static add(plugins: Array<Plugin<Hook>> | Plugin<Hook>) {
if (isArray(plugins)) {
return plugins.forEach((plugin) => this.register(plugin));
}
this.register(plugins);
}
private static register<T extends Hook>(plugin: Plugin<T>) {
if (!this.plugins.has(plugin.type)) {
this.plugins.set(plugin.type, []);
}
this.plugins
.get(plugin.type)!
.push({ ...plugin, priority: plugin.priority ?? PluginPriority.Normal });
// Do not log plugin registration in forked worker processes, one log from the master process
// is enough. This can be detected by the presence of `process.send`.
if (process.send === undefined) {
Logger.debug(
"plugins",
`Plugin(type=${plugin.type}) registered ${
"name" in plugin.value && typeof plugin.value.name === "string"
? plugin.value.name
: ""
} ${plugin.description ? `(${plugin.description})` : ""}`
);
}
}
/**
* Returns all the plugins of a given type in order of priority.
* Triggers loading of all plugins from disk if not already loaded.
*
* @param type - the type of plugin to filter by.
* @returns a list of plugins.
*/
public static getHooks<T extends Hook>(type: T) {
this.loadPlugins();
return sortBy(this.plugins.get(type) || [], "priority") as Plugin<T>[];
}
/**
* Returns the GroupSyncProvider for the given authentication provider name.
*
* @param name - the authentication provider name (e.g. "oidc", "google").
* @returns the GroupSyncProvider if one is registered, undefined otherwise.
*/
public static getGroupSyncProvider(
name: string
): GroupSyncProvider | undefined {
const hooks = this.getHooks(Hook.GroupSyncProvider);
return hooks.find((h) => h.value.id === name)?.value.provider;
}
/**
* Load plugin server components. Each plugin registers itself from a single
* `server/index` entry point, which imports any other modules it needs, so
* only the entry point is loaded here.
*/
public static loadPlugins() {
if (this.loaded) {
return;
}
const rootDir = env.ENVIRONMENT === "test" ? "" : "build";
glob
.sync(path.join(rootDir, "plugins/*/server/index.[jt]s"))
.forEach((filePath: string) => {
try {
// oxlint-disable-next-line typescript/no-require-imports -- path is only known at runtime
require(path.join(process.cwd(), filePath));
} catch (err) {
// Isolate failures so a single broken plugin cannot prevent the rest
// of the application from starting.
Logger.error(
`Failed to load plugin at ${filePath}`,
err instanceof Error ? err : new Error(String(err))
);
}
});
this.loaded = true;
}
private static loaded = false;
}