mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-23 00:53:38 +02:00
Harden plugin action invocation scope
This commit is contained in:
1 parent
c91a062326
commit
ad685d2de8
15 files changed
+937
-37
No files matched your search
@@ -73,6 +73,21 @@ export class CapabilityDeniedError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when a worker→host call tries to escape the company scope attached to
|
||||
* the current host invocation.
|
||||
*/
|
||||
export class InvocationScopeDeniedError extends Error {
|
||||
override readonly name = "InvocationScopeDeniedError";
|
||||
readonly code = PLUGIN_RPC_ERROR_CODES.CAPABILITY_DENIED;
|
||||
|
||||
constructor(pluginId: string, method: string, requestedCompanyId: string, allowedCompanyId: string) {
|
||||
super(
|
||||
`Plugin "${pluginId}" cannot call "${method}" for company "${requestedCompanyId}" during invocation scoped to company "${allowedCompanyId}"`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Host service interfaces
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -292,8 +307,17 @@ export interface HostClientFactoryOptions {
|
||||
*/
|
||||
type HostHandler<M extends WorkerToHostMethodName> = (
|
||||
params: WorkerToHostMethods[M][0],
|
||||
context?: HostHandlerContext,
|
||||
) => Promise<WorkerToHostMethods[M][1]>;
|
||||
|
||||
export interface HostInvocationScope {
|
||||
companyId?: string | null;
|
||||
}
|
||||
|
||||
export interface HostHandlerContext {
|
||||
invocationScope?: HostInvocationScope | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A complete map of all worker→host method handlers.
|
||||
*
|
||||
@@ -474,6 +498,43 @@ export function createHostClientHandlers(
|
||||
throw new CapabilityDeniedError(pluginId, method, required);
|
||||
}
|
||||
|
||||
function nonEmptyString(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
||||
}
|
||||
|
||||
function invocationCompanyId(context: HostHandlerContext | undefined): string | null {
|
||||
return nonEmptyString(context?.invocationScope?.companyId);
|
||||
}
|
||||
|
||||
function requestedCompanyId(params: unknown): string | null {
|
||||
if (!params || typeof params !== "object") return null;
|
||||
const record = params as Record<string, unknown>;
|
||||
const directCompanyId = nonEmptyString(record.companyId);
|
||||
if (directCompanyId) return directCompanyId;
|
||||
if (record.scopeKind === "company") return nonEmptyString(record.scopeId);
|
||||
return null;
|
||||
}
|
||||
|
||||
function assertInvocationCompanyScope(
|
||||
method: WorkerToHostMethodName,
|
||||
params: unknown,
|
||||
context: HostHandlerContext | undefined,
|
||||
): void {
|
||||
const allowedCompanyId = invocationCompanyId(context);
|
||||
if (!allowedCompanyId) return;
|
||||
const companyId = requestedCompanyId(params);
|
||||
if (!companyId || companyId === allowedCompanyId) return;
|
||||
throw new InvocationScopeDeniedError(pluginId, method, companyId, allowedCompanyId);
|
||||
}
|
||||
|
||||
function filterCompaniesToInvocationScope<T extends { id: string }>(
|
||||
rows: T[],
|
||||
context: HostHandlerContext | undefined,
|
||||
): T[] {
|
||||
const companyId = invocationCompanyId(context);
|
||||
return companyId ? rows.filter((row) => row.id === companyId) : rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a capability-gated proxy handler for a method.
|
||||
*
|
||||
@@ -485,9 +546,10 @@ export function createHostClientHandlers(
|
||||
method: M,
|
||||
handler: HostHandler<M>,
|
||||
): HostHandler<M> {
|
||||
return async (params: WorkerToHostMethods[M][0]) => {
|
||||
return async (params: WorkerToHostMethods[M][0], context?: HostHandlerContext) => {
|
||||
requireCapability(method);
|
||||
return handler(params);
|
||||
assertInvocationCompanyScope(method, params, context);
|
||||
return handler(params, context);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -591,8 +653,8 @@ export function createHostClientHandlers(
|
||||
}),
|
||||
|
||||
// Companies
|
||||
"companies.list": gated("companies.list", async (params) => {
|
||||
return services.companies.list(params);
|
||||
"companies.list": gated("companies.list", async (params, context) => {
|
||||
return filterCompaniesToInvocationScope(await services.companies.list(params), context);
|
||||
}),
|
||||
"companies.get": gated("companies.get", async (params) => {
|
||||
return services.companies.get(params);
|
||||
|
||||
@@ -58,6 +58,7 @@ export {
|
||||
createHostClientHandlers,
|
||||
getRequiredCapability,
|
||||
CapabilityDeniedError,
|
||||
InvocationScopeDeniedError,
|
||||
} from "./host-client-factory.js";
|
||||
|
||||
// JSON-RPC protocol helpers and constants
|
||||
@@ -128,6 +129,8 @@ export type {
|
||||
// JSON-RPC protocol types
|
||||
export type {
|
||||
JsonRpcId,
|
||||
JsonRpcInvocationScope,
|
||||
JsonRpcInvocationContext,
|
||||
JsonRpcRequest,
|
||||
JsonRpcSuccessResponse,
|
||||
JsonRpcError,
|
||||
@@ -145,6 +148,9 @@ export type {
|
||||
RunJobParams,
|
||||
GetDataParams,
|
||||
PerformActionParams,
|
||||
PluginPerformActionActorType,
|
||||
PluginPerformActionActorContext,
|
||||
PluginPerformActionContext,
|
||||
ExecuteToolParams,
|
||||
PluginEnvironmentDiagnostic,
|
||||
PluginEnvironmentDriverBaseParams,
|
||||
|
||||
@@ -79,6 +79,19 @@ export const JSONRPC_VERSION = "2.0" as const;
|
||||
*/
|
||||
export type JsonRpcId = string | number;
|
||||
|
||||
/**
|
||||
* Host-owned scope attached to a host→worker invocation. Workers may echo the
|
||||
* invocation id on nested worker→host calls, but they never author this scope.
|
||||
*/
|
||||
export interface JsonRpcInvocationScope {
|
||||
readonly companyId?: string | null;
|
||||
}
|
||||
|
||||
export interface JsonRpcInvocationContext {
|
||||
readonly id: string;
|
||||
readonly scope: JsonRpcInvocationScope;
|
||||
}
|
||||
|
||||
/**
|
||||
* A JSON-RPC 2.0 request message.
|
||||
*
|
||||
@@ -96,6 +109,10 @@ export interface JsonRpcRequest<
|
||||
readonly method: TMethod;
|
||||
/** Structured parameters for the method call. */
|
||||
readonly params: TParams;
|
||||
/** Host-owned invocation metadata sent only from host→worker requests. */
|
||||
readonly paperclipInvocation?: JsonRpcInvocationContext;
|
||||
/** Invocation id echoed by SDK worker→host calls made inside that request. */
|
||||
readonly paperclipInvocationId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -313,11 +330,35 @@ export interface GetDataParams {
|
||||
*
|
||||
* @see PLUGIN_SPEC.md §13.9 — `performAction`
|
||||
*/
|
||||
export type PluginPerformActionActorType = "user" | "agent" | "system";
|
||||
|
||||
export interface PluginPerformActionActorContext {
|
||||
/** Authenticated principal type resolved by the Paperclip host. */
|
||||
type: PluginPerformActionActorType;
|
||||
/** Authenticated board user id when `type === "user"`, otherwise null. */
|
||||
userId: string | null;
|
||||
/** Authenticated agent id when `type === "agent"`, otherwise null. */
|
||||
agentId: string | null;
|
||||
/** Authenticated heartbeat/run id when available. */
|
||||
runId: string | null;
|
||||
/** Company id authorized by the host bridge for this action, when applicable. */
|
||||
companyId: string | null;
|
||||
}
|
||||
|
||||
export interface PluginPerformActionContext {
|
||||
/** Immutable authenticated actor context supplied by the host. */
|
||||
actor: Readonly<PluginPerformActionActorContext>;
|
||||
/** Convenience alias for `actor.companyId`. */
|
||||
companyId: string | null;
|
||||
}
|
||||
|
||||
export interface PerformActionParams {
|
||||
/** Plugin-defined action key (e.g. `"resync"`). */
|
||||
key: string;
|
||||
/** Action parameters from the UI. */
|
||||
params: Record<string, unknown>;
|
||||
/** Authenticated actor context resolved by the host, never by caller params. */
|
||||
actorContext?: PluginPerformActionActorContext | null;
|
||||
/** Optional launcher/container metadata from the host render environment. */
|
||||
renderEnvironment?: PluginLauncherRenderContextSnapshot | null;
|
||||
}
|
||||
|
||||
@@ -53,6 +53,8 @@ import type {
|
||||
PluginEnvironmentRealizeWorkspaceResult,
|
||||
PluginEnvironmentExecuteParams,
|
||||
PluginEnvironmentExecuteResult,
|
||||
PluginPerformActionActorContext,
|
||||
PluginPerformActionContext,
|
||||
} from "./protocol.js";
|
||||
|
||||
export interface TestHarnessOptions {
|
||||
@@ -70,6 +72,20 @@ export interface TestHarnessLogEntry {
|
||||
meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface TestHarnessPerformActionOptions {
|
||||
/**
|
||||
* Authenticated actor context to expose to the action handler. Omitted fields
|
||||
* default to null, and `type` defaults to `system`.
|
||||
*/
|
||||
actor?: Partial<PluginPerformActionActorContext> | null;
|
||||
/**
|
||||
* Host-authorized company scope. When provided, this is injected into
|
||||
* `params.companyId` so tests match the production bridge's anti-spoofing
|
||||
* behavior.
|
||||
*/
|
||||
companyId?: string | null;
|
||||
}
|
||||
|
||||
export interface TestHarness {
|
||||
/** Fully-typed in-memory plugin context passed to `plugin.setup(ctx)`. */
|
||||
ctx: PluginContext;
|
||||
@@ -92,7 +108,11 @@ export interface TestHarness {
|
||||
/** Invoke a `ctx.data.register(...)` handler by key. */
|
||||
getData<T = unknown>(key: string, params?: Record<string, unknown>): Promise<T>;
|
||||
/** Invoke a `ctx.actions.register(...)` handler by key. */
|
||||
performAction<T = unknown>(key: string, params?: Record<string, unknown>): Promise<T>;
|
||||
performAction<T = unknown>(
|
||||
key: string,
|
||||
params?: Record<string, unknown>,
|
||||
options?: TestHarnessPerformActionOptions,
|
||||
): Promise<T>;
|
||||
/** Execute a registered tool handler via `ctx.tools.execute(...)`. */
|
||||
executeTool<T = ToolResult>(name: string, params: unknown, runCtx?: Partial<ToolRunContext>): Promise<T>;
|
||||
/** Read raw in-memory state for assertions. */
|
||||
@@ -452,7 +472,10 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness {
|
||||
const jobs = new Map<string, (job: PluginJobContext) => Promise<void>>();
|
||||
const launchers = new Map<string, PluginLauncherRegistration>();
|
||||
const dataHandlers = new Map<string, (params: Record<string, unknown>) => Promise<unknown>>();
|
||||
const actionHandlers = new Map<string, (params: Record<string, unknown>) => Promise<unknown>>();
|
||||
const actionHandlers = new Map<
|
||||
string,
|
||||
(params: Record<string, unknown>, context: PluginPerformActionContext) => Promise<unknown>
|
||||
>();
|
||||
const toolHandlers = new Map<string, (params: unknown, runCtx: ToolRunContext) => Promise<ToolResult>>();
|
||||
|
||||
function localFolderKey(companyId: string, folderKey: string): string {
|
||||
@@ -463,6 +486,41 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness {
|
||||
return `${localFolderKey(companyId, folderKey)}:${relativePath}`;
|
||||
}
|
||||
|
||||
function stringOrNull(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
||||
}
|
||||
|
||||
function actorTypeOrSystem(value: unknown): PluginPerformActionActorContext["type"] {
|
||||
return value === "user" || value === "agent" || value === "system" ? value : "system";
|
||||
}
|
||||
|
||||
function actionContextFor(
|
||||
params: Record<string, unknown>,
|
||||
options?: TestHarnessPerformActionOptions,
|
||||
): PluginPerformActionContext {
|
||||
const actorInput = options?.actor ?? null;
|
||||
const companyId = stringOrNull(options?.companyId) ?? stringOrNull(actorInput?.companyId) ?? stringOrNull(params.companyId);
|
||||
const actor = Object.freeze({
|
||||
type: actorTypeOrSystem(actorInput?.type),
|
||||
userId: stringOrNull(actorInput?.userId),
|
||||
agentId: stringOrNull(actorInput?.agentId),
|
||||
runId: stringOrNull(actorInput?.runId),
|
||||
companyId,
|
||||
});
|
||||
return Object.freeze({ actor, companyId });
|
||||
}
|
||||
|
||||
function paramsWithHostCompanyScope(
|
||||
params: Record<string, unknown>,
|
||||
context: PluginPerformActionContext,
|
||||
options?: TestHarnessPerformActionOptions,
|
||||
): Record<string, unknown> {
|
||||
if (Object.prototype.hasOwnProperty.call(options ?? {}, "companyId")) {
|
||||
return context.companyId ? { ...params, companyId: context.companyId } : { ...params };
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
function normalizeLocalFolderRelativePath(relativePath: string): string {
|
||||
const parts: string[] = [];
|
||||
for (const segment of relativePath.split(/[\\/]+/)) {
|
||||
@@ -2107,10 +2165,15 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness {
|
||||
if (!handler) throw new Error(`No data handler registered for '${key}'`);
|
||||
return await handler(params) as T;
|
||||
},
|
||||
async performAction<T = unknown>(key: string, params: Record<string, unknown> = {}) {
|
||||
async performAction<T = unknown>(
|
||||
key: string,
|
||||
params: Record<string, unknown> = {},
|
||||
options?: TestHarnessPerformActionOptions,
|
||||
) {
|
||||
const handler = actionHandlers.get(key);
|
||||
if (!handler) throw new Error(`No action handler registered for '${key}'`);
|
||||
return await handler(params) as T;
|
||||
const context = actionContextFor(params, options);
|
||||
return await handler(paramsWithHostCompanyScope(params, context, options), context) as T;
|
||||
},
|
||||
async executeTool<T = ToolResult>(name: string, params: unknown, runCtx: Partial<ToolRunContext> = {}) {
|
||||
const handler = toolHandlers.get(name);
|
||||
|
||||
@@ -40,6 +40,7 @@ import type {
|
||||
Agent,
|
||||
Goal,
|
||||
} from "@paperclipai/shared";
|
||||
import type { PluginPerformActionContext } from "./protocol.js";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Re-exports from @paperclipai/shared (plugin authors import from one place)
|
||||
@@ -945,9 +946,12 @@ export interface PluginActionsClient {
|
||||
* Register a handler for a plugin-defined action key.
|
||||
*
|
||||
* @param key - Stable string identifier for this action (e.g. `"resync"`)
|
||||
* @param handler - Async function that receives action params and returns a result
|
||||
* @param handler - Async function that receives action params plus immutable host actor context and returns a result
|
||||
*/
|
||||
register(key: string, handler: (params: Record<string, unknown>) => Promise<unknown>): void;
|
||||
register(
|
||||
key: string,
|
||||
handler: (params: Record<string, unknown>, context: PluginPerformActionContext) => Promise<unknown>,
|
||||
): void;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
*/
|
||||
|
||||
import fs from "node:fs";
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
import path from "node:path";
|
||||
import { createInterface, type Interface as ReadlineInterface } from "node:readline";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -76,6 +77,8 @@ import type {
|
||||
RunJobParams,
|
||||
GetDataParams,
|
||||
PerformActionParams,
|
||||
PluginPerformActionActorContext,
|
||||
PluginPerformActionContext,
|
||||
ExecuteToolParams,
|
||||
PluginEnvironmentAcquireLeaseParams,
|
||||
PluginEnvironmentDestroyLeaseParams,
|
||||
@@ -285,7 +288,10 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
|
||||
const jobHandlers = new Map<string, (job: PluginJobContext) => Promise<void>>();
|
||||
const launcherRegistrations = new Map<string, PluginLauncherRegistration>();
|
||||
const dataHandlers = new Map<string, (params: Record<string, unknown>) => Promise<unknown>>();
|
||||
const actionHandlers = new Map<string, (params: Record<string, unknown>) => Promise<unknown>>();
|
||||
const actionHandlers = new Map<
|
||||
string,
|
||||
(params: Record<string, unknown>, context: PluginPerformActionContext) => Promise<unknown>
|
||||
>();
|
||||
const toolHandlers = new Map<string, {
|
||||
declaration: Pick<import("@paperclipai/shared").PluginToolDeclaration, "displayName" | "description" | "parametersSchema">;
|
||||
fn: (params: unknown, runCtx: ToolRunContext) => Promise<ToolResult>;
|
||||
@@ -301,6 +307,7 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
|
||||
}>();
|
||||
let nextOutboundId = 1;
|
||||
const MAX_OUTBOUND_ID = Number.MAX_SAFE_INTEGER - 1;
|
||||
const invocationStorage = new AsyncLocalStorage<string | null>();
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Outbound messaging (worker → host)
|
||||
@@ -366,7 +373,8 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
|
||||
|
||||
try {
|
||||
const request = createRequest(method, params, id);
|
||||
sendMessage(request);
|
||||
const invocationId = invocationStorage.getStore();
|
||||
sendMessage(invocationId ? { ...request, paperclipInvocationId: invocationId } : request);
|
||||
} catch (err) {
|
||||
settle(reject, err instanceof Error ? err : new Error(String(err)));
|
||||
}
|
||||
@@ -1093,7 +1101,10 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
|
||||
},
|
||||
|
||||
actions: {
|
||||
register(key: string, handler: (params: Record<string, unknown>) => Promise<unknown>): void {
|
||||
register(
|
||||
key: string,
|
||||
handler: (params: Record<string, unknown>, context: PluginPerformActionContext) => Promise<unknown>,
|
||||
): void {
|
||||
actionHandlers.set(key, handler);
|
||||
},
|
||||
},
|
||||
@@ -1173,22 +1184,33 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
|
||||
*/
|
||||
async function handleHostRequest(request: JsonRpcRequest): Promise<void> {
|
||||
const { id, method, params } = request;
|
||||
const invocationId = typeof request.paperclipInvocation?.id === "string"
|
||||
? request.paperclipInvocation.id
|
||||
: null;
|
||||
|
||||
try {
|
||||
const result = await dispatchMethod(method, params);
|
||||
sendMessage(createSuccessResponse(id, result ?? null));
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : String(err);
|
||||
// Propagate specific error codes from handler errors (e.g.
|
||||
// METHOD_NOT_FOUND, METHOD_NOT_IMPLEMENTED) — fall back to
|
||||
// WORKER_ERROR for untyped exceptions.
|
||||
const errorCode =
|
||||
typeof (err as any)?.code === "number"
|
||||
? (err as any).code
|
||||
: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR;
|
||||
const execute = async (): Promise<void> => {
|
||||
try {
|
||||
const result = await dispatchMethod(method, params);
|
||||
sendMessage(createSuccessResponse(id, result ?? null));
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : String(err);
|
||||
// Propagate specific error codes from handler errors (e.g.
|
||||
// METHOD_NOT_FOUND, METHOD_NOT_IMPLEMENTED) — fall back to
|
||||
// WORKER_ERROR for untyped exceptions.
|
||||
const errorCode =
|
||||
typeof (err as any)?.code === "number"
|
||||
? (err as any).code
|
||||
: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR;
|
||||
|
||||
sendMessage(createErrorResponse(id, errorCode, errorMessage));
|
||||
sendMessage(createErrorResponse(id, errorCode, errorMessage));
|
||||
}
|
||||
};
|
||||
|
||||
if (invocationId) {
|
||||
await invocationStorage.run(invocationId, execute);
|
||||
return;
|
||||
}
|
||||
await execute();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1420,6 +1442,32 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
|
||||
);
|
||||
}
|
||||
|
||||
function stringOrNull(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
||||
}
|
||||
|
||||
function actorTypeOrSystem(value: unknown): PluginPerformActionActorContext["type"] {
|
||||
return value === "user" || value === "agent" || value === "system" ? value : "system";
|
||||
}
|
||||
|
||||
function actionContextFromParams(params: PerformActionParams): PluginPerformActionContext {
|
||||
const rawActor = params.actorContext && typeof params.actorContext === "object"
|
||||
? params.actorContext
|
||||
: null;
|
||||
const legacyCompanyId = stringOrNull(params.params.companyId);
|
||||
const actor = Object.freeze({
|
||||
type: actorTypeOrSystem(rawActor?.type),
|
||||
userId: stringOrNull(rawActor?.userId),
|
||||
agentId: stringOrNull(rawActor?.agentId),
|
||||
runId: stringOrNull(rawActor?.runId),
|
||||
companyId: stringOrNull(rawActor?.companyId) ?? legacyCompanyId,
|
||||
});
|
||||
return Object.freeze({
|
||||
actor,
|
||||
companyId: actor.companyId,
|
||||
});
|
||||
}
|
||||
|
||||
async function handlePerformAction(params: PerformActionParams): Promise<unknown> {
|
||||
const handler = actionHandlers.get(params.key);
|
||||
if (!handler) {
|
||||
@@ -1429,6 +1477,7 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
|
||||
params.renderEnvironment === undefined
|
||||
? params.params
|
||||
: { ...params.params, renderEnvironment: params.renderEnvironment },
|
||||
actionContextFromParams(params),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { HostServices } from "../src/host-client-factory.js";
|
||||
import {
|
||||
createHostClientHandlers,
|
||||
InvocationScopeDeniedError,
|
||||
} from "../src/host-client-factory.js";
|
||||
|
||||
describe("createHostClientHandlers invocation company scope", () => {
|
||||
it("rejects company-scoped host calls outside the current invocation company", async () => {
|
||||
const projectsList = vi.fn(async () => []);
|
||||
const services = {
|
||||
projects: {
|
||||
list: projectsList,
|
||||
},
|
||||
} as unknown as HostServices;
|
||||
|
||||
const handlers = createHostClientHandlers({
|
||||
pluginId: "paperclip.test",
|
||||
capabilities: ["projects.read"],
|
||||
services,
|
||||
});
|
||||
|
||||
await expect(
|
||||
handlers["projects.list"](
|
||||
{ companyId: "company-b" },
|
||||
{ invocationScope: { companyId: "company-a" } },
|
||||
),
|
||||
).rejects.toBeInstanceOf(InvocationScopeDeniedError);
|
||||
expect(projectsList).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("filters companies.list to the current invocation company", async () => {
|
||||
const services = {
|
||||
companies: {
|
||||
list: vi.fn(async () => [
|
||||
{ id: "company-a", name: "Company A" },
|
||||
{ id: "company-b", name: "Company B" },
|
||||
]),
|
||||
},
|
||||
} as unknown as HostServices;
|
||||
|
||||
const handlers = createHostClientHandlers({
|
||||
pluginId: "paperclip.test",
|
||||
capabilities: ["companies.read"],
|
||||
services,
|
||||
});
|
||||
|
||||
await expect(
|
||||
handlers["companies.list"](
|
||||
{},
|
||||
{ invocationScope: { companyId: "company-a" } },
|
||||
),
|
||||
).resolves.toEqual([{ id: "company-a", name: "Company A" }]);
|
||||
});
|
||||
|
||||
it("rejects company-scope store access for a different company", async () => {
|
||||
const stateGet = vi.fn(async () => null);
|
||||
const services = {
|
||||
state: {
|
||||
get: stateGet,
|
||||
},
|
||||
} as unknown as HostServices;
|
||||
|
||||
const handlers = createHostClientHandlers({
|
||||
pluginId: "paperclip.test",
|
||||
capabilities: ["plugin.state.read"],
|
||||
services,
|
||||
});
|
||||
|
||||
await expect(
|
||||
handlers["state.get"](
|
||||
{ scopeKind: "company", scopeId: "company-b", stateKey: "settings" },
|
||||
{ invocationScope: { companyId: "company-a" } },
|
||||
),
|
||||
).rejects.toBeInstanceOf(InvocationScopeDeniedError);
|
||||
expect(stateGet).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestHarness } from "../src/testing.js";
|
||||
import type { PaperclipPluginManifestV1 } from "../src/types.js";
|
||||
|
||||
const manifest = {
|
||||
id: "paperclip.test-actions",
|
||||
apiVersion: 1,
|
||||
version: "1.0.0",
|
||||
displayName: "Test Actions",
|
||||
description: "Test plugin",
|
||||
author: "Paperclip",
|
||||
categories: ["automation"],
|
||||
capabilities: [],
|
||||
entrypoints: {},
|
||||
} satisfies PaperclipPluginManifestV1;
|
||||
|
||||
describe("createTestHarness action context", () => {
|
||||
it("passes immutable authenticated actor context and overrides caller company scope", async () => {
|
||||
const harness = createTestHarness({ manifest });
|
||||
|
||||
harness.ctx.actions.register("inspect", async (params, context) => ({
|
||||
paramsCompanyId: params.companyId,
|
||||
actor: context.actor,
|
||||
companyId: context.companyId,
|
||||
contextFrozen: Object.isFrozen(context),
|
||||
actorFrozen: Object.isFrozen(context.actor),
|
||||
}));
|
||||
|
||||
const result = await harness.performAction<{
|
||||
paramsCompanyId: unknown;
|
||||
actor: {
|
||||
type: string;
|
||||
userId: string | null;
|
||||
agentId: string | null;
|
||||
runId: string | null;
|
||||
companyId: string | null;
|
||||
};
|
||||
companyId: string | null;
|
||||
contextFrozen: boolean;
|
||||
actorFrozen: boolean;
|
||||
}>(
|
||||
"inspect",
|
||||
{ companyId: "spoofed-company", value: true },
|
||||
{
|
||||
companyId: "host-company",
|
||||
actor: {
|
||||
type: "user",
|
||||
userId: "board-user-1",
|
||||
runId: "run-1",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.paramsCompanyId).toBe("host-company");
|
||||
expect(result.companyId).toBe("host-company");
|
||||
expect(result.actor).toEqual({
|
||||
type: "user",
|
||||
userId: "board-user-1",
|
||||
agentId: null,
|
||||
runId: "run-1",
|
||||
companyId: "host-company",
|
||||
});
|
||||
expect(result.contextFrozen).toBe(true);
|
||||
expect(result.actorFrozen).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps existing one-argument action handlers compatible", async () => {
|
||||
const harness = createTestHarness({ manifest });
|
||||
harness.ctx.actions.register("legacy", async (params) => ({ ok: params.ok }));
|
||||
|
||||
await expect(harness.performAction("legacy", { ok: true })).resolves.toEqual({ ok: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
const readline = require("node:readline");
|
||||
|
||||
let nextRequestId = 1;
|
||||
const pendingNested = new Map();
|
||||
|
||||
function send(message) {
|
||||
process.stdout.write(`${JSON.stringify(message)}\n`);
|
||||
}
|
||||
|
||||
function sendNestedHostRequest(originalRequest, invocationId) {
|
||||
const nestedId = `nested-${nextRequestId++}`;
|
||||
const params = originalRequest.params?.params ?? {};
|
||||
const mode = params.mode;
|
||||
const requestedCompanyId = params.requestedCompanyId;
|
||||
const nestedRequest = {
|
||||
jsonrpc: "2.0",
|
||||
id: nestedId,
|
||||
method: "companies.get",
|
||||
params: {
|
||||
companyId: requestedCompanyId,
|
||||
},
|
||||
};
|
||||
|
||||
if (mode === "echo") {
|
||||
nestedRequest.paperclipInvocationId = invocationId;
|
||||
} else if (mode === "unknown") {
|
||||
nestedRequest.paperclipInvocationId = "unknown-invocation";
|
||||
}
|
||||
|
||||
pendingNested.set(nestedId, originalRequest.id);
|
||||
send(nestedRequest);
|
||||
}
|
||||
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
crlfDelay: Infinity,
|
||||
});
|
||||
|
||||
rl.on("line", (line) => {
|
||||
if (!line.trim()) return;
|
||||
const message = JSON.parse(line);
|
||||
|
||||
if (message.id && pendingNested.has(message.id)) {
|
||||
const originalId = pendingNested.get(message.id);
|
||||
pendingNested.delete(message.id);
|
||||
if (message.error) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: originalId,
|
||||
error: message.error,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: originalId,
|
||||
result: message.result,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const method = message && typeof message.method === "string" ? message.method : null;
|
||||
|
||||
if (method === "initialize") {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: message.id,
|
||||
result: {
|
||||
ok: true,
|
||||
supportedMethods: ["getData", "performAction"],
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "getData" || method === "performAction") {
|
||||
sendNestedHostRequest(message, message.paperclipInvocation?.id);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "shutdown") {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: message.id,
|
||||
result: {},
|
||||
});
|
||||
setImmediate(() => process.exit(0));
|
||||
return;
|
||||
}
|
||||
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: message.id,
|
||||
error: {
|
||||
code: -32601,
|
||||
message: `Unhandled method: ${method}`,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -773,6 +773,8 @@ describeEmbeddedPostgres("issueService.list participantAgentId", () => {
|
||||
const normalIssueId = randomUUID();
|
||||
const pluginVisibleIssueId = randomUUID();
|
||||
const operationIssueId = randomUUID();
|
||||
const typedOperationIssueId = randomUUID();
|
||||
const legacyContentMachineOperationIssueId = randomUUID();
|
||||
|
||||
await db.insert(companies).values({
|
||||
id: companyId,
|
||||
@@ -826,12 +828,36 @@ describeEmbeddedPostgres("issueService.list participantAgentId", () => {
|
||||
originKind: "plugin:paperclip.missions:operation",
|
||||
originId: "mission-alpha:operation-1",
|
||||
},
|
||||
{
|
||||
id: typedOperationIssueId,
|
||||
companyId,
|
||||
projectId,
|
||||
title: "Typed plugin operation issue",
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: agentId,
|
||||
originKind: "plugin:paperclip.missions:operation:evaluation",
|
||||
originId: "mission-alpha:operation-2",
|
||||
},
|
||||
{
|
||||
id: legacyContentMachineOperationIssueId,
|
||||
companyId,
|
||||
projectId,
|
||||
title: "Legacy Content Machine operation issue",
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
assigneeAgentId: agentId,
|
||||
originKind: "plugin:paperclipai.content-machine:evaluation",
|
||||
originId: "content-machine-operation-1",
|
||||
},
|
||||
]);
|
||||
|
||||
const defaultIssueIds = (await svc.list(companyId)).map((issue) => issue.id);
|
||||
expect(defaultIssueIds).toContain(normalIssueId);
|
||||
expect(defaultIssueIds).toContain(pluginVisibleIssueId);
|
||||
expect(defaultIssueIds).not.toContain(operationIssueId);
|
||||
expect(defaultIssueIds).not.toContain(typedOperationIssueId);
|
||||
expect(defaultIssueIds).not.toContain(legacyContentMachineOperationIssueId);
|
||||
|
||||
const inboxIssueIds = (await svc.list(companyId, {
|
||||
assigneeAgentId: agentId,
|
||||
@@ -840,17 +866,28 @@ describeEmbeddedPostgres("issueService.list participantAgentId", () => {
|
||||
})).map((issue) => issue.id);
|
||||
expect(inboxIssueIds).toContain(normalIssueId);
|
||||
expect(inboxIssueIds).not.toContain(operationIssueId);
|
||||
expect(inboxIssueIds).not.toContain(typedOperationIssueId);
|
||||
expect(inboxIssueIds).not.toContain(legacyContentMachineOperationIssueId);
|
||||
|
||||
await expect(svc.list(companyId, { originKind: "plugin:paperclip.missions:operation" }))
|
||||
.resolves.toEqual([expect.objectContaining({ id: operationIssueId })]);
|
||||
await expect(svc.list(companyId, { originId: "mission-alpha:operation-1" }))
|
||||
.resolves.toEqual([expect.objectContaining({ id: operationIssueId })]);
|
||||
await expect(svc.list(companyId, { originKindPrefix: "plugin:paperclip.missions:operation" }))
|
||||
.resolves.toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ id: operationIssueId }),
|
||||
expect.objectContaining({ id: typedOperationIssueId }),
|
||||
]));
|
||||
|
||||
const projectIssueIds = (await svc.list(companyId, { projectId })).map((issue) => issue.id);
|
||||
expect(projectIssueIds).toContain(operationIssueId);
|
||||
expect(projectIssueIds).toContain(typedOperationIssueId);
|
||||
expect(projectIssueIds).toContain(legacyContentMachineOperationIssueId);
|
||||
|
||||
const advancedIssueIds = (await svc.list(companyId, { includePluginOperations: true })).map((issue) => issue.id);
|
||||
expect(advancedIssueIds).toContain(operationIssueId);
|
||||
expect(advancedIssueIds).toContain(typedOperationIssueId);
|
||||
expect(advancedIssueIds).toContain(legacyContentMachineOperationIssueId);
|
||||
});
|
||||
|
||||
it("excludes plugin operation issues from unread inbox counts", async () => {
|
||||
|
||||
@@ -114,6 +114,17 @@ function boardActor(overrides: Record<string, unknown> = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
function agentActor(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
type: "agent",
|
||||
agentId: agentA,
|
||||
companyId: companyA,
|
||||
runId: runA,
|
||||
source: "agent_jwt",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function readyPlugin() {
|
||||
mockRegistry.getById.mockResolvedValue({
|
||||
id: pluginId,
|
||||
@@ -634,10 +645,137 @@ describe.sequential("plugin tool and bridge authz", () => {
|
||||
expect(call).toHaveBeenCalledWith(pluginId, "performAction", {
|
||||
key: "sync",
|
||||
params: {},
|
||||
actorContext: {
|
||||
type: "user",
|
||||
userId: "admin-1",
|
||||
agentId: null,
|
||||
runId: null,
|
||||
companyId: null,
|
||||
},
|
||||
renderEnvironment: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("passes authenticated actor context and overrides spoofed company scope for plugin actions", async () => {
|
||||
readyPlugin();
|
||||
const call = vi.fn().mockResolvedValue({ ok: true });
|
||||
const { app } = await createApp(boardActor({ runId: runA }), {}, {
|
||||
bridgeDeps: {
|
||||
workerManager: { call },
|
||||
},
|
||||
});
|
||||
|
||||
const res = await request(app)
|
||||
.post(`/api/plugins/${pluginId}/actions/sync`)
|
||||
.send({
|
||||
companyId: companyA,
|
||||
params: {
|
||||
companyId: companyB,
|
||||
reviewerUserId: "spoofed-user",
|
||||
},
|
||||
});
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(call).toHaveBeenCalledWith(pluginId, "performAction", {
|
||||
key: "sync",
|
||||
params: {
|
||||
companyId: companyA,
|
||||
reviewerUserId: "spoofed-user",
|
||||
},
|
||||
actorContext: {
|
||||
type: "user",
|
||||
userId: "user-1",
|
||||
agentId: null,
|
||||
runId: runA,
|
||||
companyId: companyA,
|
||||
},
|
||||
renderEnvironment: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("allows agent-scoped plugin actions with authenticated actor context", async () => {
|
||||
readyPlugin();
|
||||
const call = vi.fn().mockResolvedValue({ ok: true });
|
||||
const { app } = await createApp(agentActor(), {}, {
|
||||
bridgeDeps: {
|
||||
workerManager: { call },
|
||||
},
|
||||
});
|
||||
|
||||
const res = await request(app)
|
||||
.post(`/api/plugins/${pluginId}/actions/sync`)
|
||||
.send({
|
||||
companyId: companyA,
|
||||
params: {
|
||||
companyId: companyB,
|
||||
reviewerAgentId: "spoofed-agent",
|
||||
},
|
||||
});
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(call).toHaveBeenCalledWith(pluginId, "performAction", {
|
||||
key: "sync",
|
||||
params: {
|
||||
companyId: companyA,
|
||||
reviewerAgentId: "spoofed-agent",
|
||||
},
|
||||
actorContext: {
|
||||
type: "agent",
|
||||
userId: null,
|
||||
agentId: agentA,
|
||||
runId: runA,
|
||||
companyId: companyA,
|
||||
},
|
||||
renderEnvironment: null,
|
||||
});
|
||||
|
||||
call.mockClear();
|
||||
const legacyRes = await request(app)
|
||||
.post(`/api/plugins/${pluginId}/bridge/action`)
|
||||
.send({
|
||||
key: "sync",
|
||||
companyId: companyA,
|
||||
params: {
|
||||
companyId: companyB,
|
||||
reviewerAgentId: "spoofed-agent",
|
||||
},
|
||||
});
|
||||
|
||||
expect(legacyRes.status).toBe(200);
|
||||
expect(call).toHaveBeenCalledWith(pluginId, "performAction", {
|
||||
key: "sync",
|
||||
params: {
|
||||
companyId: companyA,
|
||||
reviewerAgentId: "spoofed-agent",
|
||||
},
|
||||
actorContext: {
|
||||
type: "agent",
|
||||
userId: null,
|
||||
agentId: agentA,
|
||||
runId: runA,
|
||||
companyId: companyA,
|
||||
},
|
||||
renderEnvironment: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects agent plugin actions outside the authenticated company scope", async () => {
|
||||
readyPlugin();
|
||||
const call = vi.fn().mockResolvedValue({ ok: true });
|
||||
const { app } = await createApp(agentActor(), {}, {
|
||||
bridgeDeps: {
|
||||
workerManager: { call },
|
||||
},
|
||||
});
|
||||
|
||||
const res = await request(app)
|
||||
.post(`/api/plugins/${pluginId}/actions/sync`)
|
||||
.send({ companyId: companyB });
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(call).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("attaches worker bridge errors to the HTTP logger context", async () => {
|
||||
readyPlugin();
|
||||
const call = vi.fn().mockRejectedValue(new Error("missing source_objects column"));
|
||||
|
||||
@@ -3,6 +3,8 @@ import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { PaperclipPluginManifestV1 } from "@paperclipai/shared";
|
||||
import {
|
||||
createHostClientHandlers,
|
||||
type HostServices,
|
||||
JsonRpcCallError,
|
||||
type HostToWorkerMethods,
|
||||
} from "@paperclipai/plugin-sdk";
|
||||
@@ -15,6 +17,7 @@ import {
|
||||
const FIXTURES_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "fixtures");
|
||||
const DELAYED_WORKER_ENTRYPOINT = path.join(FIXTURES_DIR, "plugin-worker-delayed.cjs");
|
||||
const TERMINATED_WORKER_ENTRYPOINT = path.join(FIXTURES_DIR, "plugin-worker-terminated.cjs");
|
||||
const INVOCATION_SCOPE_WORKER_ENTRYPOINT = path.join(FIXTURES_DIR, "plugin-worker-invocation-scope.cjs");
|
||||
|
||||
const TEST_MANIFEST: PaperclipPluginManifestV1 = {
|
||||
id: "test.plugin",
|
||||
@@ -178,4 +181,145 @@ describe("plugin-worker-manager stderr failure context", () => {
|
||||
await handle.stop().catch(() => undefined);
|
||||
}
|
||||
});
|
||||
|
||||
it("passes performAction invocation scope to nested worker host calls", async () => {
|
||||
const companiesGet = vi.fn(async (
|
||||
params: { companyId: string },
|
||||
context?: { invocationScope?: { companyId?: string | null } | null },
|
||||
) => ({
|
||||
id: params.companyId,
|
||||
scopedCompanyId: context?.invocationScope?.companyId ?? null,
|
||||
}));
|
||||
const handle = createPluginWorkerHandle("test.plugin", {
|
||||
entrypointPath: INVOCATION_SCOPE_WORKER_ENTRYPOINT,
|
||||
manifest: TEST_MANIFEST,
|
||||
config: {},
|
||||
instanceInfo: {
|
||||
instanceId: "instance-1",
|
||||
hostVersion: "1.0.0",
|
||||
},
|
||||
apiVersion: 1,
|
||||
hostHandlers: {
|
||||
"companies.get": companiesGet as never,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await handle.start();
|
||||
|
||||
await expect(handle.call("performAction", {
|
||||
key: "probe",
|
||||
params: {
|
||||
mode: "echo",
|
||||
requestedCompanyId: "company-a",
|
||||
},
|
||||
actorContext: {
|
||||
type: "agent",
|
||||
userId: null,
|
||||
agentId: "agent-1",
|
||||
runId: "run-1",
|
||||
companyId: "company-a",
|
||||
},
|
||||
renderEnvironment: null,
|
||||
})).resolves.toEqual({
|
||||
id: "company-a",
|
||||
scopedCompanyId: "company-a",
|
||||
});
|
||||
expect(companiesGet).toHaveBeenCalledWith(
|
||||
{ companyId: "company-a" },
|
||||
{ invocationScope: { companyId: "company-a" } },
|
||||
);
|
||||
} finally {
|
||||
await handle.stop().catch(() => undefined);
|
||||
}
|
||||
});
|
||||
|
||||
it("applies the active performAction scope when a nested worker host call omits the invocation id", async () => {
|
||||
const handlers = createHostClientHandlers({
|
||||
pluginId: "test.plugin",
|
||||
capabilities: ["companies.read"],
|
||||
services: {
|
||||
companies: {
|
||||
list: vi.fn(async () => []),
|
||||
get: vi.fn(async (params: { companyId: string }) => ({ id: params.companyId })),
|
||||
},
|
||||
} as unknown as HostServices,
|
||||
});
|
||||
const handle = createPluginWorkerHandle("test.plugin", {
|
||||
entrypointPath: INVOCATION_SCOPE_WORKER_ENTRYPOINT,
|
||||
manifest: TEST_MANIFEST,
|
||||
config: {},
|
||||
instanceInfo: {
|
||||
instanceId: "instance-1",
|
||||
hostVersion: "1.0.0",
|
||||
},
|
||||
apiVersion: 1,
|
||||
hostHandlers: handlers,
|
||||
});
|
||||
|
||||
try {
|
||||
await handle.start();
|
||||
|
||||
await expect(handle.call("performAction", {
|
||||
key: "probe",
|
||||
params: {
|
||||
requestedCompanyId: "company-b",
|
||||
},
|
||||
actorContext: {
|
||||
type: "agent",
|
||||
userId: null,
|
||||
agentId: "agent-1",
|
||||
runId: "run-1",
|
||||
companyId: "company-a",
|
||||
},
|
||||
renderEnvironment: null,
|
||||
})).rejects.toMatchObject({
|
||||
message: expect.stringContaining("scoped to company \"company-a\""),
|
||||
});
|
||||
} finally {
|
||||
await handle.stop().catch(() => undefined);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects nested worker host calls that forge an unknown invocation id", async () => {
|
||||
const companiesGet = vi.fn(async (params: { companyId: string }) => ({ id: params.companyId }));
|
||||
const handle = createPluginWorkerHandle("test.plugin", {
|
||||
entrypointPath: INVOCATION_SCOPE_WORKER_ENTRYPOINT,
|
||||
manifest: TEST_MANIFEST,
|
||||
config: {},
|
||||
instanceInfo: {
|
||||
instanceId: "instance-1",
|
||||
hostVersion: "1.0.0",
|
||||
},
|
||||
apiVersion: 1,
|
||||
hostHandlers: {
|
||||
"companies.get": companiesGet as never,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await handle.start();
|
||||
|
||||
await expect(handle.call("performAction", {
|
||||
key: "probe",
|
||||
params: {
|
||||
mode: "unknown",
|
||||
requestedCompanyId: "company-a",
|
||||
},
|
||||
actorContext: {
|
||||
type: "agent",
|
||||
userId: null,
|
||||
agentId: "agent-1",
|
||||
runId: "run-1",
|
||||
companyId: "company-a",
|
||||
},
|
||||
renderEnvironment: null,
|
||||
})).rejects.toMatchObject({
|
||||
message: expect.stringContaining("unknown or expired invocation scope"),
|
||||
});
|
||||
expect(companiesGet).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await handle.stop().catch(() => undefined);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -55,7 +55,7 @@ import type { PluginJobStore } from "../services/plugin-job-store.js";
|
||||
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
|
||||
import type { PluginStreamBus } from "../services/plugin-stream-bus.js";
|
||||
import type { PluginToolDispatcher } from "../services/plugin-tool-dispatcher.js";
|
||||
import type { ToolRunContext } from "@paperclipai/plugin-sdk";
|
||||
import type { PluginPerformActionActorContext, ToolRunContext } from "@paperclipai/plugin-sdk";
|
||||
import { JsonRpcCallError, PLUGIN_RPC_ERROR_CODES } from "@paperclipai/plugin-sdk";
|
||||
import {
|
||||
assertAuthenticated,
|
||||
@@ -572,6 +572,43 @@ export function pluginRoutes(
|
||||
return companyId;
|
||||
}
|
||||
|
||||
function performActionActorContext(req: Request, companyId: string | undefined): PluginPerformActionActorContext {
|
||||
const scopedCompanyId = companyId ?? null;
|
||||
if (req.actor.type === "agent") {
|
||||
return {
|
||||
type: "agent",
|
||||
userId: null,
|
||||
agentId: req.actor.agentId ?? null,
|
||||
runId: req.actor.runId ?? null,
|
||||
companyId: scopedCompanyId,
|
||||
};
|
||||
}
|
||||
if (req.actor.type === "board") {
|
||||
return {
|
||||
type: "user",
|
||||
userId: req.actor.userId ?? "board",
|
||||
agentId: null,
|
||||
runId: req.actor.runId ?? null,
|
||||
companyId: scopedCompanyId,
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: "system",
|
||||
userId: null,
|
||||
agentId: null,
|
||||
runId: req.actor.runId ?? null,
|
||||
companyId: scopedCompanyId,
|
||||
};
|
||||
}
|
||||
|
||||
function actionParamsWithAuthorizedCompanyScope(
|
||||
params: Record<string, unknown> | undefined,
|
||||
companyId: string | undefined,
|
||||
): Record<string, unknown> {
|
||||
const base = params ?? {};
|
||||
return companyId === undefined ? base : { ...base, companyId };
|
||||
}
|
||||
|
||||
async function validateToolRunContextScope(runContext: ToolRunContext): Promise<string | null> {
|
||||
const [agent] = await db
|
||||
.select({ companyId: agents.companyId })
|
||||
@@ -1170,7 +1207,7 @@ export function pluginRoutes(
|
||||
* @see PLUGIN_SPEC.md §19.7 — Error Propagation Through The Bridge
|
||||
*/
|
||||
router.post("/plugins/:pluginId/bridge/action", async (req, res) => {
|
||||
assertBoardOrgAccess(req);
|
||||
assertAuthenticated(req);
|
||||
|
||||
if (!bridgeDeps) {
|
||||
res.status(501).json({ error: "Plugin bridge is not enabled" });
|
||||
@@ -1208,7 +1245,7 @@ export function pluginRoutes(
|
||||
return;
|
||||
}
|
||||
|
||||
assertPluginBridgeScope(req, body.companyId);
|
||||
const companyId = assertPluginBridgeScope(req, body.companyId);
|
||||
|
||||
try {
|
||||
const result = await bridgeDeps.workerManager.call(
|
||||
@@ -1216,7 +1253,8 @@ export function pluginRoutes(
|
||||
"performAction",
|
||||
{
|
||||
key: body.key,
|
||||
params: body.params ?? {},
|
||||
params: actionParamsWithAuthorizedCompanyScope(body.params, companyId),
|
||||
actorContext: performActionActorContext(req, companyId),
|
||||
renderEnvironment: body.renderEnvironment ?? null,
|
||||
},
|
||||
);
|
||||
@@ -1352,7 +1390,7 @@ export function pluginRoutes(
|
||||
* @see PLUGIN_SPEC.md §19.7 — Error Propagation Through The Bridge
|
||||
*/
|
||||
router.post("/plugins/:pluginId/actions/:key", async (req, res) => {
|
||||
assertBoardOrgAccess(req);
|
||||
assertAuthenticated(req);
|
||||
|
||||
if (!bridgeDeps) {
|
||||
res.status(501).json({ error: "Plugin bridge is not enabled" });
|
||||
@@ -1390,7 +1428,7 @@ export function pluginRoutes(
|
||||
renderEnvironment?: PluginLauncherRenderContextSnapshot | null;
|
||||
} | undefined;
|
||||
|
||||
assertPluginBridgeScope(req, body?.companyId);
|
||||
const companyId = assertPluginBridgeScope(req, body?.companyId);
|
||||
|
||||
try {
|
||||
const result = await bridgeDeps.workerManager.call(
|
||||
@@ -1398,7 +1436,8 @@ export function pluginRoutes(
|
||||
"performAction",
|
||||
{
|
||||
key,
|
||||
params: body?.params ?? {},
|
||||
params: actionParamsWithAuthorizedCompanyScope(body?.params, companyId),
|
||||
actorContext: performActionActorContext(req, companyId),
|
||||
renderEnvironment: body?.renderEnvironment ?? null,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -683,14 +683,25 @@ function inboxVisibleForUserCondition(companyId: string, userId: string) {
|
||||
`;
|
||||
}
|
||||
|
||||
const LEGACY_PLUGIN_OPERATION_ORIGIN_KINDS = [
|
||||
"plugin:paperclipai.content-machine:case",
|
||||
"plugin:paperclipai.content-machine:evaluation",
|
||||
"plugin:paperclipai.content-machine:source-sync",
|
||||
] as const;
|
||||
|
||||
function nonPluginOperationIssueCondition() {
|
||||
return sql<boolean>`NOT (${issues.originKind} LIKE 'plugin:%:operation' OR ${issues.originKind} LIKE 'plugin:%:operation:%')`;
|
||||
return sql<boolean>`NOT (
|
||||
${issues.originKind} LIKE 'plugin:%:operation'
|
||||
OR ${issues.originKind} LIKE 'plugin:%:operation:%'
|
||||
OR ${inArray(issues.originKind, LEGACY_PLUGIN_OPERATION_ORIGIN_KINDS)}
|
||||
)`;
|
||||
}
|
||||
|
||||
function shouldIncludePluginOperationIssues(filters: IssueFilters | undefined) {
|
||||
return Boolean(
|
||||
filters?.includePluginOperations ||
|
||||
filters?.originKind ||
|
||||
filters?.originKindPrefix ||
|
||||
filters?.originId ||
|
||||
filters?.projectId,
|
||||
);
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
*/
|
||||
|
||||
import { fork, type ChildProcess } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { createInterface, type Interface as ReadlineInterface } from "node:readline";
|
||||
import type { PaperclipPluginManifestV1 } from "@paperclipai/shared";
|
||||
@@ -102,12 +103,21 @@ export type WorkerStatus =
|
||||
| "crashed"
|
||||
| "backoff";
|
||||
|
||||
export interface WorkerInvocationScope {
|
||||
companyId?: string | null;
|
||||
}
|
||||
|
||||
export interface WorkerToHostHandlerContext {
|
||||
invocationScope?: WorkerInvocationScope | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Worker-to-host method handler. The host registers these to service calls
|
||||
* that the plugin worker makes back to the host (e.g. state.get, events.emit).
|
||||
*/
|
||||
export type WorkerToHostHandler<M extends WorkerToHostMethodName> = (
|
||||
params: WorkerToHostMethods[M][0],
|
||||
context?: WorkerToHostHandlerContext,
|
||||
) => Promise<WorkerToHostMethods[M][1]>;
|
||||
|
||||
/**
|
||||
@@ -199,6 +209,8 @@ interface PendingRequest {
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
/** Timestamp when the request was sent. */
|
||||
sentAt: number;
|
||||
/** Active host-owned invocation id attached to this host→worker call. */
|
||||
invocationId?: string;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -379,6 +391,7 @@ export function createPluginWorkerHandle(
|
||||
// Pending RPC requests awaiting a response
|
||||
const pendingRequests = new Map<string | number, PendingRequest>();
|
||||
let nextRequestId = 1;
|
||||
const activeInvocationScopes = new Map<string, WorkerInvocationScope>();
|
||||
|
||||
// Optional methods reported by the worker during initialization
|
||||
let supportedMethods: string[] = [];
|
||||
@@ -424,6 +437,38 @@ export function createPluginWorkerHandle(
|
||||
childProcess.stdin.write(serialized);
|
||||
}
|
||||
|
||||
function stringOrNull(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
||||
}
|
||||
|
||||
function invocationScopeForCall(
|
||||
method: HostToWorkerMethodName,
|
||||
params: unknown,
|
||||
): WorkerInvocationScope | null {
|
||||
if (method !== "performAction" || !params || typeof params !== "object") return null;
|
||||
const actorContext = (params as { actorContext?: { companyId?: unknown } | null }).actorContext;
|
||||
const companyId = stringOrNull(actorContext?.companyId);
|
||||
return companyId ? { companyId } : null;
|
||||
}
|
||||
|
||||
function invocationContextForWorkerRequest(request: JsonRpcRequest): WorkerToHostHandlerContext | undefined {
|
||||
const invocationId = stringOrNull(request.paperclipInvocationId);
|
||||
if (invocationId) {
|
||||
const invocationScope = activeInvocationScopes.get(invocationId);
|
||||
if (!invocationScope) {
|
||||
throw new Error("Worker host request referenced an unknown or expired invocation scope");
|
||||
}
|
||||
return { invocationScope };
|
||||
}
|
||||
if (activeInvocationScopes.size === 1) {
|
||||
return { invocationScope: [...activeInvocationScopes.values()][0] };
|
||||
}
|
||||
if (activeInvocationScopes.size > 1) {
|
||||
throw new Error("Worker host request omitted invocation scope while multiple scoped invocations are active");
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Incoming message handling
|
||||
// -----------------------------------------------------------------------
|
||||
@@ -481,7 +526,7 @@ export function createPluginWorkerHandle(
|
||||
async function handleWorkerRequest(request: JsonRpcRequest): Promise<void> {
|
||||
const method = request.method as WorkerToHostMethodName;
|
||||
const handler = options.hostHandlers[method] as
|
||||
| ((params: unknown) => Promise<unknown>)
|
||||
| ((params: unknown, context?: WorkerToHostHandlerContext) => Promise<unknown>)
|
||||
| undefined;
|
||||
|
||||
if (!handler) {
|
||||
@@ -501,7 +546,7 @@ export function createPluginWorkerHandle(
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await handler(request.params);
|
||||
const result = await handler(request.params, invocationContextForWorkerRequest(request));
|
||||
sendMessage({
|
||||
jsonrpc: JSONRPC_VERSION,
|
||||
id: request.id,
|
||||
@@ -751,6 +796,7 @@ export function createPluginWorkerHandle(
|
||||
function rejectAllPending(error: Error): void {
|
||||
for (const [id, pending] of pendingRequests) {
|
||||
clearTimeout(pending.timer);
|
||||
if (pending.invocationId) activeInvocationScopes.delete(pending.invocationId);
|
||||
pending.resolve(
|
||||
createErrorResponse(
|
||||
pending.id,
|
||||
@@ -760,6 +806,7 @@ export function createPluginWorkerHandle(
|
||||
);
|
||||
}
|
||||
pendingRequests.clear();
|
||||
activeInvocationScopes.clear();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
@@ -1020,6 +1067,9 @@ export function createPluginWorkerHandle(
|
||||
|
||||
const id = nextRequestId++;
|
||||
const timeout = Math.min(timeoutMs ?? rpcTimeoutMs, MAX_RPC_TIMEOUT_MS);
|
||||
const invocationScope = invocationScopeForCall(method, params);
|
||||
const invocation = invocationScope ? { id: randomUUID(), scope: invocationScope } : null;
|
||||
if (invocation) activeInvocationScopes.set(invocation.id, invocation.scope);
|
||||
|
||||
// Guard against double-settlement. When a process exits all pending
|
||||
// requests are rejected via rejectAllPending(), but the timeout timer
|
||||
@@ -1032,6 +1082,7 @@ export function createPluginWorkerHandle(
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
pendingRequests.delete(id);
|
||||
if (invocation) activeInvocationScopes.delete(invocation.id);
|
||||
fn(value);
|
||||
};
|
||||
|
||||
@@ -1059,16 +1110,18 @@ export function createPluginWorkerHandle(
|
||||
},
|
||||
timer,
|
||||
sentAt: Date.now(),
|
||||
invocationId: invocation?.id,
|
||||
};
|
||||
|
||||
pendingRequests.set(id, pending);
|
||||
|
||||
try {
|
||||
const request = createRequest(method, params, id);
|
||||
sendMessage(request);
|
||||
sendMessage(invocation ? { ...request, paperclipInvocation: invocation } : request);
|
||||
} catch (err) {
|
||||
clearTimeout(timer);
|
||||
pendingRequests.delete(id);
|
||||
if (invocation) activeInvocationScopes.delete(invocation.id);
|
||||
reject(
|
||||
new Error(
|
||||
`Failed to send "${method}" to worker: ${
|
||||
|
||||
Reference in new issue
Block a user