mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
feat(dot): add guided invitations and persistent agent connections (#15581)
Add guided external-agent invitations with live Dot connection checks and ongoing access until revoked. Keep expired credentials invalid and enforce permissions for private avatar uploads. Preserve Runner recovery and remote launch boundaries. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
04de3132c2
commit
2b4a1d7073
61 files changed
+7529
-4422
No files matched your search
@@ -0,0 +1,156 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import express, { type Request, type ErrorRequestHandler } from "express";
|
||||
import request from "supertest";
|
||||
import sharp from "sharp";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, expect, it, vi } from "vitest";
|
||||
import { createDb, agents, companies, assets, activityLog, authUsers, companyMemberships, mcpOauthClients, mcpOauthGrants, dotAgentBindings, principalPermissionGrants } from "@paperclipai/db";
|
||||
import { appearanceForPalette, MAX_AGENT_AVATAR_BYTES } from "@paperclipai/shared";
|
||||
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js";
|
||||
import { createStorageService } from "../storage/service.js";
|
||||
import type { StorageService } from "../storage/types.js";
|
||||
import { normalizeAgentAvatar, setAgentProfileAvatar } from "../services/agent-profile-avatar.js";
|
||||
import { agentProfileAvatarRoutes } from "../routes/agent-profile-avatar.js";
|
||||
import { assetRoutes } from "../routes/assets.js";
|
||||
import { agentService } from "../services/agents.js";
|
||||
import { instanceSettingsService } from "../services/instance-settings.js";
|
||||
import { createDotRunnerMcpTools } from "../services/dot-runner-broker.js";
|
||||
import type { McpPrincipal } from "../services/public-mcp/oauth.js";
|
||||
import { isSecretSensitiveHttpRequest } from "../middleware/http-log-policy.js";
|
||||
|
||||
let storage: StorageService;
|
||||
vi.mock("../storage/index.js", () => ({ getStorageService: () => storage }));
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let root: string;
|
||||
let imageBase64: string;
|
||||
beforeAll(async () => {
|
||||
temporary = await startEmbeddedPostgresTestDatabase("paperclip-profile-avatar-");
|
||||
db = createDb(temporary.connectionString);
|
||||
root = await mkdtemp(join(tmpdir(), "profile-avatar-"));
|
||||
storage = createStorageService(createLocalDiskStorageProvider(root));
|
||||
imageBase64 = (await sharp({ create: { width: 800, height: 600, channels: 3, background: "orange" } }).png().toBuffer()).toString("base64");
|
||||
await instanceSettingsService(db).updateExperimental({ enablePublicMcp: true, enableOpenAiDot: true });
|
||||
}, 120000);
|
||||
afterAll(async () => { await temporary?.cleanup(); if (root) await rm(root, { recursive: true, force: true }); });
|
||||
async function fixture() {
|
||||
const [company] = await db.insert(companies).values({ name: "Avatar test", issuePrefix: randomUUID().slice(0, 8) }).returning();
|
||||
const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Dot", status: "active", adapterType: "paperclip_runner", appearance: appearanceForPalette("deep-tide") }).returning();
|
||||
const actor = { actorType: "agent" as const, actorId: agent!.id, agentId: agent!.id };
|
||||
return { company: company!, agent: agent!, actor };
|
||||
}
|
||||
function appFor(actor: Request["actor"]) {
|
||||
const app = express();
|
||||
app.use(express.json({ limit: "2mb" }));
|
||||
app.use((req, _res, next) => { req.actor = actor; next(); });
|
||||
app.use("/api", agentProfileAvatarRoutes(db, storage), assetRoutes(db, storage));
|
||||
app.use(((error, _req, res, _next) => res.status(error.status ?? 400).json({ error: error.message })) as ErrorRequestHandler);
|
||||
return app;
|
||||
}
|
||||
|
||||
it("uploads, normalizes, serves privately, retries without duplication, and resets the avatar", async () => {
|
||||
const f = await fixture();
|
||||
const app = appFor({ type: "agent", agentId: f.agent.id, companyId: f.company.id });
|
||||
const path = `/api/companies/${f.company.id}/agents/${f.agent.id}/avatar`;
|
||||
const upload = await request(app).put(path).send({ imageBase64 }).expect(200);
|
||||
expect(upload.body.appearance.paletteId).toBe(f.agent.appearance?.paletteId);
|
||||
const retry = await request(app).put(path).send({ imageBase64 }).expect(200);
|
||||
expect(retry.body).toEqual(upload.body);
|
||||
expect(await db.select().from(assets).where(eq(assets.companyId, f.company.id))).toHaveLength(1);
|
||||
const audit = await db.select().from(activityLog).where(eq(activityLog.companyId, f.company.id));
|
||||
expect(audit.filter(row => row.action === "agent.avatar_updated")).toHaveLength(1);
|
||||
expect(JSON.stringify(audit)).not.toContain(imageBase64);
|
||||
const content = await request(app).get(upload.body.avatarUrl).expect(200);
|
||||
expect(content.headers["cache-control"]).toContain("private");
|
||||
expect(await sharp(content.body).metadata()).toMatchObject({ format: "png", width: 512, height: 384 });
|
||||
expect((await agentService(db).getById(f.agent.id))?.avatarUrl).toBe(upload.body.avatarUrl);
|
||||
const reset = await request(app).put(path).send({ imageBase64: null }).expect(200);
|
||||
expect(reset.body.appearance).toEqual(f.agent.appearance);
|
||||
expect(reset.body.avatarUrl).toContain("/api/agent-avatars/");
|
||||
});
|
||||
|
||||
it("rejects other agents, companies, viewers, and foreign asset references", async () => {
|
||||
const f = await fixture(); const other = await fixture();
|
||||
const path = `/api/companies/${f.company.id}/agents/${f.agent.id}/avatar`;
|
||||
for (const actor of [
|
||||
{ type: "agent", agentId: other.agent.id, companyId: f.company.id },
|
||||
{ type: "agent", agentId: other.agent.id, companyId: other.company.id },
|
||||
{ type: "board", source: "session", companyIds: [f.company.id], memberships: [{ companyId: f.company.id, status: "active", membershipRole: "viewer" }] },
|
||||
] satisfies Request["actor"][]) await request(appFor(actor)).put(path).send({ imageBase64 }).expect(403);
|
||||
await request(appFor({ type: "none" })).put(path).send({ imageBase64 }).expect(401);
|
||||
const foreign = await setAgentProfileAvatar(db, storage, other.company.id, other.agent.id, { imageBase64 }, other.actor);
|
||||
await expect(agentService(db).update(f.agent.id, { appearance: foreign.appearance })).rejects.toThrow("avatar upload");
|
||||
await request(appFor({ type: "agent", agentId: f.agent.id, companyId: f.company.id })).get(foreign.avatarUrl).expect(404);
|
||||
});
|
||||
|
||||
it("requires an agent configuration grant for board avatar changes", async () => {
|
||||
const f = await fixture();
|
||||
const userId = randomUUID();
|
||||
await db.insert(authUsers).values({ id: userId, name: "Member", email: `${userId}@example.test`, createdAt: new Date(), updatedAt: new Date() });
|
||||
await db.insert(companyMemberships).values({ companyId: f.company.id, principalType: "user", principalId: userId, membershipRole: "member", status: "active" });
|
||||
const app = appFor({ type: "board", source: "session", userId, companyIds: [f.company.id], memberships: [{ companyId: f.company.id, status: "active", membershipRole: "member" }] });
|
||||
const path = `/api/companies/${f.company.id}/agents/${f.agent.id}/avatar`;
|
||||
await request(app).put(path).send({ imageBase64 }).expect(403);
|
||||
await request(app).put(path).send({ imageBase64: null }).expect(403);
|
||||
expect(await db.select().from(assets).where(eq(assets.companyId, f.company.id))).toHaveLength(0);
|
||||
await db.insert(principalPermissionGrants).values({ companyId: f.company.id, principalType: "user", principalId: userId, permissionKey: "agents:suggest-changes" });
|
||||
await request(app).put(path).send({ imageBase64 }).expect(403);
|
||||
await db.insert(principalPermissionGrants).values({ companyId: f.company.id, principalType: "user", principalId: userId, permissionKey: "agents:configure" });
|
||||
await request(app).put(path).send({ imageBase64 }).expect(200);
|
||||
await request(app).put(path).send({ imageBase64: null }).expect(200);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ kind: "task_bridge" as const, parentIssueId: randomUUID() },
|
||||
{ kind: "skill_test" as const, issueId: randomUUID() },
|
||||
])("rejects profile changes by restricted %s credentials", async keyScope => {
|
||||
const f = await fixture();
|
||||
const app = appFor({ type: "agent", agentId: f.agent.id, companyId: f.company.id, keyScope });
|
||||
const path = `/api/companies/${f.company.id}/agents/${f.agent.id}/avatar`;
|
||||
await request(app).put(path).send({ imageBase64 }).expect(403);
|
||||
await request(app).put(path).send({ imageBase64: null }).expect(403);
|
||||
expect(await db.select().from(assets).where(eq(assets.companyId, f.company.id))).toHaveLength(0);
|
||||
expect(await db.select().from(activityLog).where(eq(activityLog.companyId, f.company.id))).toHaveLength(0);
|
||||
expect((await agentService(db).getById(f.agent.id))?.appearance).toEqual(f.agent.appearance);
|
||||
});
|
||||
|
||||
it("rejects URLs, SVG, corrupt and oversized images, unsupported fields and inactive agents", async () => {
|
||||
for (const input of ["https://example.test/avatar.png", Buffer.from("<svg xmlns=\"http://www.w3.org/2000/svg\"/>").toString("base64"), Buffer.from("broken").toString("base64"), Buffer.alloc(MAX_AGENT_AVATAR_BYTES + 1).toString("base64")]) {
|
||||
await expect(normalizeAgentAvatar(input)).rejects.toThrow();
|
||||
}
|
||||
const tooManyPixels = await sharp({ create: { width: 5000, height: 5000, channels: 3, background: "white" } }).png().toBuffer();
|
||||
await expect(normalizeAgentAvatar(tooManyPixels.toString("base64"))).rejects.toThrow("16 megapixels");
|
||||
const f = await fixture();
|
||||
const app = appFor({ type: "agent", agentId: f.agent.id, companyId: f.company.id });
|
||||
await request(app).put(`/api/companies/${f.company.id}/agents/${f.agent.id}/avatar`).send({ imageBase64, agentId: randomUUID() }).expect(400);
|
||||
await db.update(agents).set({ status: "pending_approval" }).where(eq(agents.id, f.agent.id));
|
||||
await expect(setAgentProfileAvatar(db, storage, f.company.id, f.agent.id, { imageBase64 }, f.actor)).rejects.toThrow("current state");
|
||||
});
|
||||
|
||||
it("lets a paired Dot upload without an assignment, with feature and current grant authorization", async () => {
|
||||
const f = await fixture(); const userId = randomUUID(); const clientId = randomUUID();
|
||||
await db.insert(authUsers).values({ id: userId, name: "Owner", email: `${userId}@example.test`, createdAt: new Date(), updatedAt: new Date() });
|
||||
await db.insert(companyMemberships).values({ companyId: f.company.id, principalType: "user", principalId: userId, membershipRole: "owner", status: "active" });
|
||||
await db.insert(mcpOauthClients).values({ id: clientId, name: "Dot", redirectUris: [] });
|
||||
const [grant] = await db.insert(mcpOauthGrants).values({ companyId: f.company.id, userId, clientId, resource: "https://paperclip.example/mcp/runner", purpose: "agent", agentId: f.agent.id, scopes: ["paperclip:agent"] }).returning();
|
||||
await db.insert(dotAgentBindings).values({ companyId: f.company.id, agentId: f.agent.id, operatorId: userId, grantId: grant!.id, status: "connected" });
|
||||
const principal: McpPrincipal = { grant: grant!, company: f.company, actor: { type: "agent", companyId: f.company.id, agentId: f.agent.id } };
|
||||
const tools = createDotRunnerMcpTools(db);
|
||||
expect((await tools.listTools(principal)).find(tool => tool.name === "paperclip_dot_set_avatar")?.annotations).toMatchObject({ readOnlyHint: false });
|
||||
expect(await tools.callTool(principal, "paperclip_dot_set_avatar", { imageBase64 })).toMatchObject({ outcome: "completed", result: { agentId: f.agent.id } });
|
||||
await expect(tools.callTool(principal, "paperclip_dot_set_avatar", { imageBase64, agentId: randomUUID() })).rejects.toThrow();
|
||||
await instanceSettingsService(db).updateExperimental({ enableOpenAiDot: false });
|
||||
try { await expect(tools.callTool(principal, "paperclip_dot_set_avatar", { imageBase64 })).rejects.toThrow("disabled"); }
|
||||
finally { await instanceSettingsService(db).updateExperimental({ enableOpenAiDot: true }); }
|
||||
await db.update(mcpOauthGrants).set({ revokedAt: new Date() }).where(eq(mcpOauthGrants.id, grant!.id));
|
||||
await expect(tools.callTool(principal, "paperclip_dot_set_avatar", { imageBase64 })).rejects.toThrow("authority");
|
||||
});
|
||||
|
||||
it("redacts HTTP diagnostics containing image bytes", () => {
|
||||
expect(isSecretSensitiveHttpRequest("PUT", "/api/companies/company/agents/agent/avatar")).toBe(true);
|
||||
expect(isSecretSensitiveHttpRequest("POST", "/mcp/runner")).toBe(true);
|
||||
});
|
||||
@@ -4138,9 +4138,9 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
for (const canary of [configToken, signingSecret, clientSecret, f.token]) expect(publicState).not.toContain(canary);
|
||||
await request(f.app).patch(`/api/chat-endpoints/${f.endpoint.id}`).send({ slackApp: appDetails }).expect(409);
|
||||
});
|
||||
it("uploads avatar bytes without fetching a tenant-session-protected URL, after app credentials are durable", async () => {
|
||||
it.each([undefined, "22222222-2222-4222-8222-222222222222"])("uploads preset bytes after credentials are durable, even with private avatar %s", async customAvatarAssetId => {
|
||||
const f = await fixture();
|
||||
await db.update(agents).set({ appearance: { schemaVersion: 1, characterVersion: "cap-v1", paletteId: "cherry-pop" } }).where(eq(agents.id, f.assignedAgentId));
|
||||
await db.update(agents).set({ appearance: { schemaVersion: 1, characterVersion: "cap-v1", paletteId: "cherry-pop", customAvatarAssetId } }).where(eq(agents.id, f.assignedAgentId));
|
||||
f.state.beforeIcon = async () => {
|
||||
const row = (await f.service.slackRegistration.registration(f.endpoint.id))!;
|
||||
expect(row).toMatchObject({ status: "install", appId: f.appId });
|
||||
|
||||
@@ -91,7 +91,7 @@ async function createApp(actor: any, db: any = {} as any) {
|
||||
}
|
||||
|
||||
describe("cli auth routes", () => {
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
vi.resetModules();
|
||||
vi.doUnmock("../services/index.js");
|
||||
vi.doUnmock("../routes/authz.js");
|
||||
@@ -99,6 +99,9 @@ describe("cli auth routes", () => {
|
||||
vi.doUnmock("../middleware/index.js");
|
||||
registerModuleMocks();
|
||||
vi.resetAllMocks();
|
||||
// Cold route transforms are fixture setup, not HTTP request latency.
|
||||
// Use the hook budget while preserving the request tests' normal timeout.
|
||||
await Promise.all([import("../routes/access.js"), import("../middleware/index.js")]);
|
||||
});
|
||||
|
||||
it("creates a CLI auth challenge with approval metadata", async () => {
|
||||
|
||||
@@ -1727,20 +1727,30 @@ describe("company portability", () => {
|
||||
expect(exported.warnings.filter((warning) => warning.includes("could not be exported portably"))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("round-trips the saved visual persona through the portable bundle", async () => {
|
||||
it.each([undefined, "22222222-2222-4222-8222-222222222222"])("round-trips the preset without private avatar references (%s)", async customAvatarAssetId => {
|
||||
const appearance = { schemaVersion: 1, characterVersion: "cap-v1", paletteId: "arctic-blue" };
|
||||
const source = await agentSvc.list();
|
||||
agentSvc.list.mockResolvedValue(source.map((agent: Record<string, unknown>) => ({ ...agent, appearance })));
|
||||
agentSvc.list.mockResolvedValue(source.map((agent: Record<string, unknown>) => ({ ...agent, appearance: { ...appearance, ...(customAvatarAssetId ? { customAvatarAssetId } : {}) } })));
|
||||
const portability = companyPortabilityService({} as any);
|
||||
const include = { company: true, agents: true, projects: false, issues: false, skills: false };
|
||||
const exported = await portability.exportBundle("company-1", { include });
|
||||
expect(asTextFile(exported.files[".paperclip.yaml"])).toContain("arctic-blue");
|
||||
const extensionText = asTextFile(exported.files[".paperclip.yaml"]);
|
||||
expect(extensionText).not.toContain("customAvatarAssetId");
|
||||
if (customAvatarAssetId) {
|
||||
expect(exported.warnings.some(warning => warning.includes("uploaded avatar was omitted"))).toBe(true);
|
||||
// Even a hand-edited package must not carry another agent's private asset into import.
|
||||
exported.files[".paperclip.yaml"] = extensionText.replace(/^(\s*)paletteId:.*$/gm,
|
||||
match => `${match}\n${match.match(/^\s*/)?.[0]}customAvatarAssetId: ${customAvatarAssetId}`);
|
||||
expect(asTextFile(exported.files[".paperclip.yaml"])).toContain(customAvatarAssetId);
|
||||
}
|
||||
|
||||
agentSvc.list.mockResolvedValue([]);
|
||||
agentSvc.create.mockImplementation(async (_companyId: string, input: Record<string, unknown>) => ({ ...input, id: `imported-${input.name}` }));
|
||||
await portability.importBundle({ source: { type: "inline", files: exported.files, rootPath: exported.rootPath }, include,
|
||||
target: { mode: "new_company", newCompanyName: "Imported personas" }, collisionStrategy: "rename", agents: "all" }, "user-1");
|
||||
expect(agentSvc.create).toHaveBeenCalled();
|
||||
for (const [, input] of agentSvc.create.mock.calls) expect(input).toMatchObject({ appearance });
|
||||
for (const [, input] of agentSvc.create.mock.calls) expect(input.appearance).toEqual(appearance);
|
||||
});
|
||||
|
||||
it("reads env inputs back from .paperclip.yaml during preview import", async () => {
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { randomBytes, randomUUID } from "node:crypto";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, expect, it, vi } from "vitest";
|
||||
import { createDb, agents, approvals, principalPermissionGrants, authUsers, companies, companyMemberships, dotAgentBindings, activityLog } from "@paperclipai/db";
|
||||
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { dotInvitationService } from "../services/dot-invitations.js";
|
||||
import { dotRunnerBroker } from "../services/dot-runner-broker.js";
|
||||
import { dotRunnerRoutes } from "../routes/dot-runner.js";
|
||||
import { instanceSettingsService } from "../services/instance-settings.js";
|
||||
import { HttpError } from "../errors.js";
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let root: string;
|
||||
beforeAll(async () => {
|
||||
temporary = await startEmbeddedPostgresTestDatabase("dot-invitations-");
|
||||
db = createDb(temporary.connectionString);
|
||||
root = await mkdtemp(join(tmpdir(), "dot-invite-home-"));
|
||||
vi.stubEnv("PAPERCLIP_HOME", root);
|
||||
vi.stubEnv("PAPERCLIP_IN_WORKTREE", "false");
|
||||
await instanceSettingsService(db).updateExperimental({ enableOpenAiDot: true, enablePublicMcp: true });
|
||||
}, 120000);
|
||||
afterAll(async () => { await temporary?.cleanup(); if (root) await rm(root, { recursive: true, force: true }); vi.unstubAllEnvs(); });
|
||||
async function fixture(requireApproval = false) {
|
||||
const userId = randomUUID();
|
||||
await db.insert(authUsers).values({ id: userId, name: "Operator", email: `${userId}@example.test`, createdAt: new Date(), updatedAt: new Date() });
|
||||
const [company] = await db.insert(companies).values({ name: "Dot invitation", issuePrefix: "DI" + randomBytes(3).toString("hex"), requireBoardApprovalForNewAgents: requireApproval }).returning();
|
||||
await db.insert(companyMemberships).values({ companyId: company!.id, principalType: "user", principalId: userId, membershipRole: "owner", status: "active" });
|
||||
await db.insert(principalPermissionGrants).values({ companyId: company!.id, principalType: "user", principalId: userId, permissionKey: "agents:create" });
|
||||
return { userId, companyId: company!.id };
|
||||
}
|
||||
it("atomically resumes one pending invite across retries and never persists a pairing secret", async () => {
|
||||
const f = await fixture();
|
||||
const service = dotInvitationService(db);
|
||||
const [a, b] = await Promise.all([service.create(f.companyId, f.userId), service.create(f.companyId, f.userId)]);
|
||||
expect(a.agent.id).toBe(b.agent.id);
|
||||
expect(a.agent.status).toBe("idle");
|
||||
expect(await service.resume(f.companyId, f.userId)).toMatchObject({ agent: { id: a.agent.id } });
|
||||
expect(await service.resume(f.companyId, randomUUID())).toBeNull();
|
||||
expect(await db.select().from(agents).where(eq(agents.companyId, f.companyId))).toHaveLength(1);
|
||||
const code = await dotRunnerBroker(db).createPairing({ ...f, operatorId: f.userId, agentId: a.agent.id });
|
||||
const logs = await db.select().from(activityLog).where(eq(activityLog.companyId, f.companyId));
|
||||
expect(JSON.stringify(logs)).not.toContain(code.pairingCode);
|
||||
expect(JSON.stringify(await service.resume(f.companyId, f.userId))).not.toContain(code.pairingCode);
|
||||
});
|
||||
it("honors hiring approval before issuing a pairing capability", async () => {
|
||||
const f = await fixture(true);
|
||||
const invite = await dotInvitationService(db).create(f.companyId, f.userId);
|
||||
expect(invite.agent.status).toBe("pending_approval");
|
||||
expect(invite.approvalId).toBeTruthy();
|
||||
const [approval] = await db.select().from(approvals).where(eq(approvals.id, invite.approvalId!));
|
||||
expect(approval).toMatchObject({ status: "pending", type: "hire_agent", payload: { agentId: invite.agent.id } });
|
||||
await expect(dotRunnerBroker(db).createPairing({ ...f, operatorId: f.userId, agentId: invite.agent.id })).rejects.toThrow("approved");
|
||||
expect((await dotInvitationService(db).create(f.companyId, f.userId)).approvalId).toBe(invite.approvalId);
|
||||
});
|
||||
it("replaces only the named pending capability and refuses to revoke a connected binding", async () => {
|
||||
const f = await fixture(); const broker = dotRunnerBroker(db);
|
||||
const invite = await dotInvitationService(db).create(f.companyId, f.userId);
|
||||
const input = { companyId: f.companyId, agentId: invite.agent.id, operatorId: f.userId };
|
||||
const first = await broker.createPairing(input);
|
||||
const second = await broker.createPairing({ ...input, replaceBindingId: first.bindingId });
|
||||
expect(second.bindingId).not.toBe(first.bindingId);
|
||||
const [old] = await db.select().from(dotAgentBindings).where(eq(dotAgentBindings.id, first.bindingId));
|
||||
expect(old).toMatchObject({ status: "revoked", pairingCodeHash: null });
|
||||
await expect(broker.createPairing({ ...input, replaceBindingId: first.bindingId })).rejects.toThrow("changed");
|
||||
await db.update(dotAgentBindings).set({ status: "connected" }).where(eq(dotAgentBindings.id, second.bindingId));
|
||||
await expect(broker.createPairing({ ...input, replaceBindingId: second.bindingId })).rejects.toThrow("changed");
|
||||
});
|
||||
it("keeps invite routes company-scoped and denies viewers and agent actors", async () => {
|
||||
const f = await fixture();
|
||||
const app = express(); app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
const mode = req.headers["x-test-actor"];
|
||||
req.actor = mode === "agent" ? { type: "agent", agentId: randomUUID(), companyId: f.companyId }
|
||||
: { type: "board", source: "session", userId: f.userId, companyIds: [f.companyId],
|
||||
memberships: [{ companyId: f.companyId, membershipRole: mode === "viewer" ? "viewer" : "owner", status: "active" }] };
|
||||
next();
|
||||
});
|
||||
app.use(dotRunnerRoutes(db, "https://paperclip.example/mcp/runner"));
|
||||
app.use((error: Error, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
|
||||
res.status(error instanceof HttpError ? error.status : 500).json({ error: error.message });
|
||||
});
|
||||
const path = `/companies/${f.companyId}/dot-invitations`;
|
||||
for (const actor of ["viewer", "agent"]) expect((await request(app).post(path).set("x-test-actor", actor).send({})).status).toBe(403);
|
||||
expect((await request(app).post(`/companies/${randomUUID()}/dot-invitations`).send({})).status).toBe(403);
|
||||
const result = await request(app).post(path).send({});
|
||||
expect(result.status, JSON.stringify(result.body)).toBe(200);
|
||||
expect(result.body.agent.id).toBeTruthy();
|
||||
expect((await request(app).get(path)).body.agent.id).toBe(result.body.agent.id);
|
||||
expect(await db.select().from(agents).where(and(eq(agents.companyId, f.companyId), eq(agents.status, "idle")))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not trust editable agent metadata as an invitation ownership receipt", async () => {
|
||||
const f = await fixture();
|
||||
const [spoof] = await db.insert(agents).values({ companyId: f.companyId, name: "Unrelated agent", adapterType: "paperclip_runner",
|
||||
adapterConfig: { provider: "openai_dot" }, metadata: { dotInvitation: { operatorId: f.userId } } }).returning();
|
||||
const service = dotInvitationService(db);
|
||||
expect(await service.resume(f.companyId, f.userId)).toBeNull();
|
||||
expect((await service.create(f.companyId, f.userId)).agent.id).not.toBe(spoof!.id);
|
||||
});
|
||||
@@ -1,11 +1,12 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createDb, authUsers, companies, companyMemberships, agents, dotAgentBindings, mcpOauthGrants, mcpOauthRequests } from "@paperclipai/db";
|
||||
import { createDb, authUsers, companies, companyMemberships, agents, dotAgentBindings, mcpOauthGrants, mcpOauthRequests, mcpOauthTokens } from "@paperclipai/db";
|
||||
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { createPublicMcpOAuth, publicMcpConfig, DEVICE_GRANT } from "../services/public-mcp/oauth.js";
|
||||
import { createPublicMcpOAuth, publicMcpConfig, hashMcpSecret, DEVICE_GRANT } from "../services/public-mcp/oauth.js";
|
||||
import { instanceSettingsService } from "../services/instance-settings.js";
|
||||
import { dotRunnerBroker } from "../services/dot-runner-broker.js";
|
||||
import { publicMcpManagementRoutes, publicMcpIngressRoutes } from "../routes/public-mcp.js";
|
||||
@@ -26,7 +27,7 @@ describe("Dot onboarding with an operator-issued pairing capability", () => {
|
||||
await db.insert(authUsers).values({ id: userId, name: "Operator", email: userId + "@example.test", createdAt: new Date(), updatedAt: new Date() });
|
||||
const [company] = await db.insert(companies).values({ name: "Dot onboarding", issuePrefix: "DO" + randomBytes(3).toString("hex") }).returning();
|
||||
await db.insert(companyMemberships).values({ companyId: company!.id, principalType: "user", principalId: userId, membershipRole: "owner", status: "active" });
|
||||
const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Dot", adapterType: "paperclip_runner", status: "active" }).returning();
|
||||
const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Dot", adapterType: "paperclip_runner", adapterConfig: { provider: "openai_dot" }, status: "active" }).returning();
|
||||
const oauth = createPublicMcpOAuth(db, { ...config, ...(authorizationOrigin ? { authorizationOrigin } : {}) });
|
||||
const client = await oauth.register({ client_name: "Dot", redirect_uris: [callback], grant_types: ["authorization_code", "refresh_token", DEVICE_GRANT] }, randomUUID());
|
||||
const verifier = randomBytes(32).toString("base64url");
|
||||
@@ -37,6 +38,72 @@ describe("Dot onboarding with an operator-issued pairing capability", () => {
|
||||
const id = await begin();
|
||||
return { userId, company: company!, agent: agent!, oauth, client, verifier, input, pairing, id, begin };
|
||||
}
|
||||
async function connect(f: Awaited<ReturnType<typeof fixture>>) {
|
||||
const consent = await f.oauth.consentDotPairing(f.id, f.pairing.pairingCode);
|
||||
return f.oauth.token({ grant_type: "authorization_code", client_id: f.client.client_id,
|
||||
redirect_uri: callback, resource: config.resource, code: new URL(consent.redirectUrl).searchParams.get("code"), code_verifier: f.verifier });
|
||||
}
|
||||
it("refreshes a Dot connection after years of inactivity, still rotates and revokes on replay", async () => {
|
||||
const f = await fixture();
|
||||
const tokens = await connect(f);
|
||||
const [stored] = await db.select().from(mcpOauthTokens).where(eq(mcpOauthTokens.tokenHash, hashMcpSecret(tokens.refresh_token!)));
|
||||
expect(stored!.expiresAt).toBeNull();
|
||||
const refresh = { grant_type: "refresh_token", client_id: f.client.client_id, resource: config.resource, refresh_token: tokens.refresh_token };
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
try {
|
||||
vi.setSystemTime(new Date(Date.now() + 2 * 365 * 24 * 60 * 60_000));
|
||||
await expect(f.oauth.authenticate(tokens.access_token)).rejects.toThrow();
|
||||
const next = await f.oauth.token(refresh);
|
||||
expect(next.refresh_token).not.toBe(tokens.refresh_token);
|
||||
expect(next.expires_in).toBe(900);
|
||||
expect((await f.oauth.authenticate(next.access_token)).actor).toMatchObject({ type: "agent", agentId: f.agent.id });
|
||||
const [rotated] = await db.select().from(mcpOauthTokens).where(eq(mcpOauthTokens.tokenHash, hashMcpSecret(next.refresh_token!)));
|
||||
expect(rotated!.expiresAt).toBeNull();
|
||||
await expect(f.oauth.token(refresh)).rejects.toThrow();
|
||||
await expect(f.oauth.authenticate(next.access_token)).rejects.toThrow();
|
||||
expect(await dotRunnerBroker(db).bindingForAgent(f.company.id, f.agent.id)).toBeNull();
|
||||
} finally { vi.useRealTimers(); }
|
||||
});
|
||||
it("upgrades valid Dot refresh tokens without reviving expired, used or revoked credentials", async () => {
|
||||
const f = await fixture();
|
||||
const tokens = await connect(f);
|
||||
const grant = (await f.oauth.authenticate(tokens.access_token)).grant;
|
||||
const validExpiry = new Date(Date.now() + 30 * 24 * 60 * 60_000);
|
||||
await db.update(mcpOauthTokens).set({ expiresAt: validExpiry }).where(eq(mcpOauthTokens.tokenHash, hashMcpSecret(tokens.refresh_token!)));
|
||||
const stale = await fixture();
|
||||
const staleTokens = await connect(stale);
|
||||
const expired = new Date(0);
|
||||
await db.update(mcpOauthTokens).set({ expiresAt: expired }).where(eq(mcpOauthTokens.tokenHash, hashMcpSecret(staleTokens.refresh_token!)));
|
||||
const personalId = randomUUID();
|
||||
const revokedId = randomUUID();
|
||||
const usedHash = randomUUID();
|
||||
await db.insert(mcpOauthGrants).values([
|
||||
{ ...grant, id: personalId, purpose: "personal", agentId: null, resource: config.origin + "/mcp/paperclip" },
|
||||
{ ...grant, id: revokedId, revokedAt: new Date() },
|
||||
]);
|
||||
await db.insert(mcpOauthTokens).values([
|
||||
{ grantId: personalId, tokenHash: randomUUID(), kind: "refresh", expiresAt: validExpiry },
|
||||
{ grantId: revokedId, tokenHash: randomUUID(), kind: "refresh", expiresAt: validExpiry },
|
||||
{ grantId: grant.id, tokenHash: usedHash, kind: "refresh", expiresAt: validExpiry, usedAt: new Date() },
|
||||
]);
|
||||
const migration = await readFile(new URL("../../../packages/db/src/migrations/0319_heavy_captain_midlands.sql", import.meta.url), "utf8");
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
for (const statement of migration.split("--> statement-breakpoint")) await db.execute(sql.raw(statement));
|
||||
}
|
||||
const [personal] = await db.select().from(mcpOauthTokens).where(eq(mcpOauthTokens.grantId, personalId));
|
||||
const [revoked] = await db.select().from(mcpOauthTokens).where(eq(mcpOauthTokens.grantId, revokedId));
|
||||
const [used] = await db.select().from(mcpOauthTokens).where(eq(mcpOauthTokens.tokenHash, usedHash));
|
||||
const [staleToken] = await db.select().from(mcpOauthTokens).where(eq(mcpOauthTokens.tokenHash, hashMcpSecret(staleTokens.refresh_token!)));
|
||||
expect(personal!.expiresAt).toEqual(validExpiry);
|
||||
expect(revoked!.expiresAt).toEqual(validExpiry);
|
||||
expect(used!.expiresAt).toEqual(validExpiry);
|
||||
expect(staleToken!.expiresAt).toEqual(expired);
|
||||
await expect(stale.oauth.token({ grant_type: "refresh_token", client_id: stale.client.client_id, resource: config.resource, refresh_token: staleTokens.refresh_token })).rejects.toThrow();
|
||||
const next = await f.oauth.token({ grant_type: "refresh_token", client_id: f.client.client_id, resource: config.resource, refresh_token: tokens.refresh_token });
|
||||
expect((await f.oauth.authenticate(next.access_token)).actor).toMatchObject({ type: "agent", agentId: f.agent.id });
|
||||
await f.oauth.revokeToken(next.access_token, f.client.client_id);
|
||||
await expect(f.oauth.token({ grant_type: "refresh_token", client_id: f.client.client_id, resource: config.resource, refresh_token: next.refresh_token })).rejects.toThrow();
|
||||
});
|
||||
it("pins browser ingress without changing the issuer, resource or token endpoint", async () => {
|
||||
const browserOrigin = "https://paperclip-browser.example:10000";
|
||||
const f = await fixture(browserOrigin);
|
||||
@@ -75,6 +142,7 @@ describe("Dot onboarding with an operator-issued pairing capability", () => {
|
||||
expect((await request(app).post(path).send({ pairingCode: f.pairing.pairingCode })).status).toBe(403);
|
||||
const preview = await request(app).post(path + "/preview").set("Origin", config.origin).send({ pairingCode: f.pairing.pairingCode });
|
||||
expect(preview.status).toBe(200);
|
||||
expect(preview.body.accessDuration).toBe("Ongoing until revoked. This connection does not expire from inactivity.");
|
||||
expect(preview.body).toMatchObject({ company: { id: f.company.id, name: f.company.name }, agent: { id: f.agent.id, name: f.agent.name } });
|
||||
expect(JSON.stringify(preview.body)).not.toContain(f.pairing.pairingCode);
|
||||
expect(await db.select().from(mcpOauthGrants).where(eq(mcpOauthGrants.userId, f.userId))).toHaveLength(0);
|
||||
|
||||
@@ -10,7 +10,7 @@ import express, { type Request } from "express";
|
||||
import request from "supertest";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, authUsers, companies, companyMemberships, createDb, dotAgentBindings, dotMailboxItems, dotRunnerAssignments, dotRunnerOperations,
|
||||
heartbeatRuns, agentWakeupRequests, issueComments, issues, nativeRunResults, nativeRunFinalizations, completionContracts, mcpEventDeliveries, workspaceOperations, workAssessments, statusDecisions, issueThreadInteractions } from "@paperclipai/db";
|
||||
heartbeatRuns, agentWakeupRequests, issueComments, issues, nativeRunResults, nativeRunFinalizations, completionContracts, mcpEventDeliveries, mcpEventSubscriptions, workspaceOperations, workAssessments, statusDecisions, issueThreadInteractions } from "@paperclipai/db";
|
||||
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { createPublicMcpOAuth, DEVICE_GRANT } from "../services/public-mcp/oauth.js";
|
||||
import { createPublicMcpExecutor } from "../services/public-mcp/capabilities.js";
|
||||
@@ -125,7 +125,7 @@ describe("durable Dot Runner integration", () => {
|
||||
const events = createPublicMcpEvents(db, oauth, async () => { throw new Error("personal API dispatch forbidden"); }, { enableDotRunner: true, fetch: fetcher });
|
||||
const subscription = { name: "paperclip.dot.mailbox_updated", arguments: { companyId: company!.id, bindingId: pairing.bindingId }, delivery: { mode: "webhook", url: "https://example.com/dot-hook", secret } };
|
||||
await events.subscribe(principal, subscription);
|
||||
await broker.challenge(company!.id, agent!.id); await events.tick();
|
||||
await events.tick();
|
||||
if (!received.length) throw new Error("Dot readiness delivery missing: " + JSON.stringify(await db.select({ outcome: mcpEventDeliveries.outcome, event: mcpEventDeliveries.event }).from(mcpEventDeliveries)));
|
||||
expect(received.at(-1)?.data.kind).toBe("readiness_challenge");
|
||||
expect(received.at(-1)?.data).not.toHaveProperty("challenge");
|
||||
@@ -168,6 +168,25 @@ describe("durable Dot Runner integration", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["revoked binding", "removed subscription"])("handles an automatic event-test race with a %s", async change => {
|
||||
const f = await fixture();
|
||||
await db.update(dotAgentBindings).set({ readyAt: null, status: "connected" }).where(eq(dotAgentBindings.id, f.snapshot.bindingId));
|
||||
const readBinding = f.broker.bindingForAgent.bind(f.broker);
|
||||
const read = vi.spyOn(f.broker, "bindingForAgent").mockImplementationOnce(async (companyId, agentId) => {
|
||||
const state = await readBinding(companyId, agentId);
|
||||
if (change === "revoked binding") await db.update(dotAgentBindings).set({ revokedAt: new Date() }).where(eq(dotAgentBindings.id, f.snapshot.bindingId));
|
||||
else await db.update(mcpEventSubscriptions).set({ stoppedAt: new Date() }).where(eq(mcpEventSubscriptions.bindingId, f.snapshot.bindingId));
|
||||
return state;
|
||||
});
|
||||
try {
|
||||
await expect(f.broker.challenge(f.company.id, f.agent.id, { automatic: true, bindingId: f.snapshot.bindingId })).resolves.toEqual({ status: "unavailable" });
|
||||
await expect(f.broker.challenge(f.company.id, f.agent.id)).rejects.toThrow("Connect and subscribe");
|
||||
} finally {
|
||||
read.mockRestore();
|
||||
await f.events.unsubscribe(f.principal, f.subscription); await f.events.stop();
|
||||
}
|
||||
});
|
||||
|
||||
it("admits one durable idle intake without requiring a preassigned task", async () => {
|
||||
const f = await fixture();
|
||||
await db.update(companies).set({ defaultResponsibleUserId: f.userId }).where(eq(companies.id, f.company.id));
|
||||
|
||||
@@ -21,6 +21,7 @@ const apiPrefixes: Record<string, string> = {
|
||||
"agents.ts": "/api",
|
||||
"agent-commentary.ts": "/api",
|
||||
"agent-avatars.ts": "/api",
|
||||
"agent-profile-avatar.ts": "/api",
|
||||
"announcements.ts": "/api",
|
||||
"ai-connections.ts": "/api",
|
||||
"decision-models.ts": "/api",
|
||||
@@ -229,10 +230,13 @@ function loadActualRoutes() {
|
||||
}
|
||||
}
|
||||
if (file === "dot-runner.ts") {
|
||||
const basePath = /const path = "([^"]+)"/.exec(source)?.[1];
|
||||
if (!basePath) throw new Error("Dot binding route prefix is missing");
|
||||
for (const match of source.matchAll(/router\.(get|post|delete)\(path(?: \+ "([^"]+)")?/g)) {
|
||||
routes.add(`${match[1].toUpperCase()} ${normalizeExpressPath(prefix + basePath + (match[2] ?? ""))}`);
|
||||
for (const name of ["path", "invitePath"]) {
|
||||
const basePath = new RegExp(`const ${name} = "([^"]+)"`).exec(source)?.[1];
|
||||
if (!basePath) throw new Error(`Dot ${name} route prefix is missing`);
|
||||
const methods = new RegExp(`router\\.(get|post|delete)\\(${name}(?: \\+ "([^"]+)")?`, "g");
|
||||
for (const match of source.matchAll(methods)) {
|
||||
routes.add(`${match[1].toUpperCase()} ${normalizeExpressPath(prefix + basePath + (match[2] ?? ""))}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -858,6 +862,19 @@ describe("openapi routes", () => {
|
||||
expect(path.put.responses["422"]).toBeDefined();
|
||||
});
|
||||
|
||||
it("documents operator Dot invitations and current pairing and event-test fields", () => {
|
||||
const { spec } = loadSpecRoutes();
|
||||
const invitations = spec.paths["/api/companies/{companyId}/dot-invitations"];
|
||||
for (const operation of [invitations.get, invitations.post]) {
|
||||
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board" });
|
||||
expect(operation.responses["200"]).toBeDefined();
|
||||
}
|
||||
expect(invitations.post.requestBody.content["application/json"].schema.additionalProperties).toBe(false);
|
||||
const base = "/api/companies/{companyId}/agents/{agentId}/dot-binding";
|
||||
expect(spec.paths[base].post.requestBody.content["application/json"].schema.properties.replaceBindingId).toMatchObject({ type: "string", format: "uuid" });
|
||||
expect(spec.paths[base + "/event-test"].post.requestBody.content["application/json"].schema.properties.bindingId).toMatchObject({ type: "string", format: "uuid" });
|
||||
});
|
||||
|
||||
it("documents board-only repository discovery and selection", () => {
|
||||
const { spec } = loadSpecRoutes();
|
||||
const discovery = spec.paths["/api/companies/{companyId}/project-repositories"].get;
|
||||
|
||||
@@ -479,6 +479,15 @@ describe.skipIf(!support.supported)("public MCP OAuth and tool boundary", () =>
|
||||
await expect(oauth.authenticate(next.access_token)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it.each([new Date(0), null])("rejects personal refresh tokens with invalid expiry %s", async expiresAt => {
|
||||
const f = await fixture();
|
||||
const [stored] = await db.select().from(mcpOauthTokens).where(eq(mcpOauthTokens.tokenHash, hashMcpSecret(f.tokens.refresh_token!)));
|
||||
expect(stored!.expiresAt!.getTime() - Date.now()).toBeGreaterThan(29 * 24 * 60 * 60_000);
|
||||
await db.update(mcpOauthTokens).set({ expiresAt }).where(eq(mcpOauthTokens.id, stored!.id));
|
||||
await expect(oauth.token({ grant_type: "refresh_token", client_id: f.client.client_id,
|
||||
resource: config.resource, refresh_token: f.tokens.refresh_token })).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("rejects token expiry, revocation and membership loss on the next call", async () => {
|
||||
const f = await fixture();
|
||||
await db.update(mcpOauthTokens).set({ expiresAt: new Date(0) }).where(eq(mcpOauthTokens.tokenHash, hashMcpSecret(f.tokens.access_token)));
|
||||
|
||||
Reference in new issue
Block a user