fix(dashboard): scope areas and responsibilities to each user (#22513)

This commit is contained in:
scotttong authored and GitHub committed 2026-11-21 13:59:00 -08:00
1 parent 558dbb0132
commit 856f14e507
68 files changed
+2708 -559

No files matched your search

+4 -1
View File
@@ -240,6 +240,7 @@ export function activityRoutes(db: Db) {
entityId: req.query.entityId as string | undefined,
limit: normalizeActivityLimit(Number(req.query.limit)),
readCondition: await issueReadSqlCondition(db, req.actor),
dashboardUserId: req.actor.type === "board" ? req.actor.userId : null,
caseReadCondition: await caseActivityReadSqlCondition(db, req.actor),
};
const result = await svc.list(filters);
@@ -267,6 +268,7 @@ export function activityRoutes(db: Db) {
}
if (parsedQuery.data.actorScope === "agents") {
const result = await agentAudit.list({ companyId, ...parsedQuery.data,
dashboardUserId: req.actor.type === "board" ? req.actor.userId : null,
caseReadCondition: await caseActivityReadSqlCondition(db, req.actor) });
res.json({ ...result, accessTier: "full" });
return;
@@ -277,6 +279,7 @@ export function activityRoutes(db: Db) {
throw forbidden("Audit filters require permission: audit:view_agent_actions");
}
const result = await agentAudit.list({ companyId, ...parsedQuery.data,
dashboardUserId: req.actor.type === "board" ? req.actor.userId : null,
caseReadCondition: await caseActivityReadSqlCondition(db, req.actor) });
res.json({
...(canViewAttribution ? result : stripAuditAttribution(result)),
@@ -298,7 +301,7 @@ export function activityRoutes(db: Db) {
const rows: Awaited<ReturnType<typeof agentAudit.list>>["items"] = [];
let cursor: string | undefined;
do {
const page = await agentAudit.list({ companyId, ...filters, cursor, limit: AUDIT_CSV_PAGE_SIZE, caseReadCondition });
const page = await agentAudit.list({ companyId, ...filters, cursor, limit: AUDIT_CSV_PAGE_SIZE, dashboardUserId: req.actor.userId, caseReadCondition });
for (const item of page.items) {
if (rows.length >= AUDIT_CSV_EXPORT_MAX_ROWS) break;
rows.push(item);
+2 -5
View File
@@ -81,15 +81,12 @@ export async function agentPersonInCompany(db: Db, req: Request, companyId: stri
}
/**
* The writer rule for an agent on a person's responsibilities: it acts for
* the person who directed its run and may change what that person could, so
* it manages that person's own responsibilities, and anyone's when that person
* is a company owner or admin. Returns that person's user id, or null.
* A directed agent run may manage the dashboard of the person who directed it.
*/
export async function agentActsForResponsibilityOwner(db: Db, req: Request, companyId: string, ownerUserId: string): Promise<string | null> {
const person = await agentPersonInCompany(db, req, companyId);
if (!person) return null;
return person.userId === ownerUserId || person.role === "owner" || person.role === "admin" ? person.userId : null;
return person.userId === ownerUserId && (!req.actor.authorizingUserId || req.actor.authorizingUserId === ownerUserId) ? person.userId : null;
}
/** Why an agent may not act for a person here, for its error messages. */
+3 -2
View File
@@ -3,6 +3,7 @@ import type { SecretBindingTargetType } from "@paperclipai/shared";
import { forbidden, HttpError, unauthorized } from "../errors.js";
import { logger } from "../middleware/logger.js";
import { responsibleUserAuthzShadowMode } from "../services/authorization.js";
import { dashboardConversationReadable, type DashboardConversationFields } from "../services/responsibility-privacy.js";
import { getHiddenSettings } from "../services/settings-visibility.js";
function throwOrShadowResponsibleUserCompanyAccessDeny(
@@ -315,7 +316,7 @@ export function hasCompanyAccess(req: Request, companyId: string): boolean {
* Routes with bespoke not-found behavior (legacy `200 []` contracts,
* audit-logged denials) should still compose `hasCompanyAccess` directly.
*/
export async function getAccessibleResource<T extends { companyId: string }>(
export async function getAccessibleResource<T extends { companyId: string } & DashboardConversationFields>(
req: Request,
res: Response,
resource: T | null | undefined | Promise<T | null | undefined>,
@@ -323,7 +324,7 @@ export async function getAccessibleResource<T extends { companyId: string }>(
notFoundBody: Record<string, unknown> = { error: notFoundMessage },
): Promise<T | null> {
const resolved = await resource;
if (!resolved || !hasCompanyAccess(req, resolved.companyId)) {
if (!resolved || !hasCompanyAccess(req, resolved.companyId) || !dashboardConversationReadable(req.actor, resolved)) {
res.status(404).json(notFoundBody);
return null;
}
+17 -58
View File
@@ -1,3 +1,4 @@
import { agentMayReportFor, dashboardOwner } from "./responsibility-owner.js";
import { Router, type NextFunction, type Request, type Response } from "express";
import type { Db } from "@paperclipai/db";
import {
@@ -72,27 +73,8 @@ function linkTarget(body: LinkResponsibility | ResponsibilityLinkLookupQuery): R
return { kind: "routine", id: body.routineId! };
}
/**
* The writer rule: a board user manages their own responsibilities; company
* owners/admins and instance admins manage anyone's.
*/
export function boardCanManageResponsibilityOwner(req: Request, companyId: string, ownerUserId: string) {
if (req.actor.type !== "board") return false;
if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return true;
if (req.actor.userId && req.actor.userId === ownerUserId) return true;
const membership = req.actor.memberships?.find((item) => item.companyId === companyId && item.status === "active");
return membership?.membershipRole === "owner" || membership?.membershipRole === "admin";
}
/**
* Whose responsibilities a request means when it names no owner: a board user
* means their own, and an agent means the person its run works for (the
* person chatting, or the task's responsible person).
*/
export function defaultResponsibilityOwnerUserId(req: Request): string | undefined {
if (req.actor.type === "board") return req.actor.userId ?? undefined;
if (req.actor.type === "agent") return req.actor.onBehalfOfUserId ?? undefined;
return undefined;
export function boardCanManageResponsibilityOwner(req: Request, _companyId: string, ownerUserId: string) {
return req.actor.type === "board" && req.actor.userId === ownerUserId;
}
export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignmentWakeupDeps } = {}) {
@@ -157,14 +139,15 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
function assertBoardCanManage(req: Request, row: { companyId: string; ownerUserId: string }) {
if (!boardCanManageOwner(req, row.companyId, row.ownerUserId)) {
throw forbidden("Only the person who owns this responsibility, or a company admin, can change it");
throw forbidden("Only the person who owns this responsibility can change it");
}
}
async function loadForRead(req: Request, res: Response) {
async function loadForRead(req: Request, res: Response, reporting = false) {
const row = await getAccessibleResource(req, res, svc.getById(req.params.id as string), NOT_FOUND);
if (!row) return null;
await assertCompanyRead(req, row.companyId);
if (!(reporting && agentMayReportFor(req, row.ownerUserId) && row.status === "active")) await dashboardOwner(db, req, row.companyId, row.ownerUserId);
return row;
}
@@ -191,7 +174,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
}
const personUserId = await agentActsForResponsibilityOwner(db, req, row.companyId, row.ownerUserId);
if (!personUserId) {
throw forbidden(`Only the person who owns this responsibility, or a company admin, can change it, and this agent's run does not act for such a person. ${AGENT_PERSON_RULE}.`);
throw forbidden(`Only the person who owns this responsibility can change it, and this agent's run does not act for such a person. ${AGENT_PERSON_RULE}.`);
}
return { personUserId, agentId: getActorInfo(req).actorId };
}
@@ -294,12 +277,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
const companyId = req.params.companyId as string;
await assertCompanyRead(req, companyId);
const query = listResponsibilitiesQuerySchema.parse(req.query);
const ownerUserId = query.ownerUserId ?? defaultResponsibilityOwnerUserId(req);
if (!ownerUserId) {
throw unprocessable(req.actor.type === "agent"
? "ownerUserId is required: this run works for no person, so name the person whose responsibilities to read"
: "ownerUserId is required");
}
const ownerUserId = await dashboardOwner(db, req, companyId, query.ownerUserId);
res.json(await svc.overview(companyId, ownerUserId, {
includeLetGo: query.includeLetGo,
scope: await readScope(req, companyId),
@@ -311,28 +289,8 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
const companyId = req.params.companyId as string;
await assertCompanyRead(req, companyId);
const actor = getActorInfo(req);
let ownerUserId: string;
// An agent acting for someone who may manage the owner creates what that person could.
let actsFor: string | null = null;
if (req.actor.type === "agent") {
const owner = req.body.ownerUserId ?? defaultResponsibilityOwnerUserId(req);
if (!owner) {
throw unprocessable("ownerUserId is required: this run works for no person, so name the person in this company the responsibility is for");
}
ownerUserId = owner;
if (!(await svc.isCompanyMember(companyId, ownerUserId))) throw notFound("Owner is not a member of this company");
actsFor = await agentActsForResponsibilityOwner(db, req, companyId, ownerUserId);
} else {
const self = req.actor.userId;
ownerUserId = req.body.ownerUserId ?? self ?? "";
if (!ownerUserId) throw unprocessable("ownerUserId is required");
if (ownerUserId !== self) {
if (!boardCanManageOwner(req, companyId, ownerUserId)) {
throw forbidden("Only a company admin can create a responsibility for another person");
}
if (!(await svc.isCompanyMember(companyId, ownerUserId))) throw notFound("Owner is not a member of this company");
}
}
const ownerUserId = await dashboardOwner(db, req, companyId, req.body.ownerUserId);
const actsFor = req.actor.type === "agent" ? ownerUserId : null;
const { areaTitle, ...body } = req.body as typeof req.body & { areaTitle?: string };
if (areaTitle && body.areaId) throw unprocessable("Send areaId or areaTitle, not both");
const { responsibility: created, activatedArea, created: isNew, newArea } = await inChange(req, res, {
@@ -341,7 +299,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
createdAreaIds: (result) => (result.newArea ? [result.newArea.id] : []),
}, async ({ svc: scoped, areas }: ScopedServices) => {
// The area by title is made in the same transaction, so a refused create leaves no area behind.
const area = areaTitle ? await areas.create(companyId, { title: areaTitle }, areaActorFor(req, actsFor)) : null;
const area = areaTitle ? await areas.create(companyId, ownerUserId, { title: areaTitle }, areaActorFor(req, actsFor)) : null;
const result = await scoped.create(
companyId,
{ ...body, ...(area ? { areaId: area.area.id } : {}) },
@@ -379,7 +337,8 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
router.patch("/responsibilities/:id", validate(updateResponsibilitySchema), async (req, res) => {
await assertResponsibilitiesEnabled();
const row = await loadForWrite(req, res);
const reporting = req.body.metricCurrent !== undefined && Object.keys(req.body).length === 1;
const row = await loadForRead(req, res, reporting);
if (!row) return;
const scope = await readScope(req, row.companyId);
const actsFor = req.actor.type === "agent" ? await agentActsForResponsibilityOwner(db, req, row.companyId, row.ownerUserId) : null;
@@ -391,7 +350,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
createdAreaIds: (result) => (result.newArea ? [result.newArea.id] : []),
}, async ({ svc: scoped, areas }: ScopedServices) => {
// The area by title is made in the same transaction, so a refused change leaves no area behind.
const area = areaTitle ? await areas.create(row.companyId, { title: areaTitle }, areaActorFor(req, actsFor)) : null;
const area = areaTitle ? await areas.create(row.companyId, row.ownerUserId, { title: areaTitle }, areaActorFor(req, actsFor)) : null;
if (area) patch.areaId = area.area.id;
const result = await scoped.update(
row,
@@ -523,7 +482,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
moveFromIds = await svc.liveIdsOfOwner(row.companyId, row.ownerUserId, row.id);
} else if (req.body.moveFrom && req.body.moveFrom !== row.id) {
const source = await svc.getById(req.body.moveFrom);
if (!source || source.companyId !== row.companyId) throw notFound("Responsibility to move from not found");
if (!source || source.companyId !== row.companyId || source.ownerUserId !== row.ownerUserId) throw notFound("Responsibility to move from not found");
await assertWriter(req, source);
moveFromIds = [source.id];
owners.add(source.ownerUserId);
@@ -612,7 +571,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
action: "issue.created",
entityType: "issue",
entityId: issue.id,
details: { title: issue.title, identifier: issue.identifier, responsibilityId: row.id },
details: { title: issue.title, identifier: issue.identifier },
});
await logMutation(req, row.companyId, "responsibility.delegated", row.id, {
issueId: issue.id,
@@ -639,7 +598,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
const companyId = req.params.companyId as string;
await assertCompanyRead(req, companyId);
const query = responsibilityLinkLookupQuerySchema.parse(req.query);
const responsibilities = await svc.lookup(companyId, linkTarget(query), await readScope(req, companyId));
const responsibilities = await svc.lookup(companyId, await dashboardOwner(db, req, companyId), linkTarget(query), await readScope(req, companyId));
res.json({ responsibilities });
});
+11 -21
View File
@@ -1,3 +1,4 @@
import { dashboardOwner } from "./responsibility-owner.js";
import { Router, type Request, type Response } from "express";
import type { Db } from "@paperclipai/db";
import {
@@ -19,11 +20,7 @@ import { assertBoardOrAgent, assertCompanyAccess, getAccessibleResource, getActo
const NOT_FOUND = "Area not found";
/**
* Responsibility areas (experimental, `enableResponsibilities`). Areas have no
* owner: any board user with write access to the company manages them. An
* agent acting for a member of the company may do the same, each change saved
* as a version of that person's Dashboard they can undo (a delete only after
* the person accepts a confirmation card); other agents can only propose one.
* An owner or a run they directed can manage their areas. Agent changes are versioned.
*/
export function responsibilityAreaRoutes(db: Db) {
const router = Router();
@@ -55,6 +52,8 @@ export function responsibilityAreaRoutes(db: Db) {
async function loadForBoardWrite(req: Request, res: Response) {
const row = await getAccessibleResource(req, res, svc.getById(req.params.id as string), NOT_FOUND);
if (!row) return null;
await assertCompanyRead(req, row.companyId);
await dashboardOwner(db, req, row.companyId, row.ownerUserId);
return row;
}
@@ -90,7 +89,7 @@ export function responsibilityAreaRoutes(db: Db) {
const companyId = req.params.companyId as string;
await assertCompanyRead(req, companyId);
const query = listResponsibilityAreasQuerySchema.parse(req.query);
res.json(await svc.list(companyId, { includeArchived: query.includeArchived }));
res.json(await svc.list(companyId, await dashboardOwner(db, req, companyId), { includeArchived: query.includeArchived }));
});
router.post("/companies/:companyId/responsibility-areas", validate(createResponsibilityAreaSchema), async (req, res) => {
@@ -99,8 +98,9 @@ export function responsibilityAreaRoutes(db: Db) {
await assertCompanyRead(req, companyId);
const actor = getActorInfo(req);
const person = await agentPersonInCompany(db, req, companyId);
const ownerUserId = await dashboardOwner(db, req, companyId);
const create = (tx: Db) => responsibilityAreaService(tx).create(
companyId,
companyId, ownerUserId,
req.body,
req.actor.type !== "agent" ? { type: "board" }
: person ? { type: "board", viaAgentId: actor.actorId }
@@ -131,20 +131,9 @@ export function responsibilityAreaRoutes(db: Db) {
const row = await loadForBoardWrite(req, res);
if (!row) return;
const writer = await assertAreaWriter(req, row.companyId);
// On an area other people's proposed or active responsibilities share (the same test restore
// uses), Undo never changes the name, description or order, and of status changes only brings
// an archived area back. A change it cannot reverse saves no version, so no Dashboard offers an
// Undo that would do nothing; it stays in the activity log.
const sharedChange = Boolean(writer)
&& (await svc.ownersInArea(row.companyId, row.id, ["proposed", "active"])).some((owner) => owner !== writer!.personUserId)
&& ((req.body.title !== undefined && req.body.title !== row.title)
|| (req.body.description !== undefined && req.body.description !== row.description)
|| (req.body.sortOrder !== undefined && req.body.sortOrder !== row.sortOrder)
|| (req.body.status !== undefined && req.body.status !== row.status && !(row.status === "active" && req.body.status === "archived")));
// Otherwise everyone whose Dashboard shows the area gets a version.
const updated = writer && !sharedChange
const updated = writer
? await agentChanges.record({
companyId: row.companyId, ownerUserIds: [writer.personUserId, ...await svc.ownersInArea(row.companyId, row.id)],
companyId: row.companyId, ownerUserIds: [writer.personUserId],
agentId: writer.agentId, touchedAreaIds: [row.id],
onVersion: reportVersionOf(res, writer.personUserId),
}, (tx) => responsibilityAreaService(tx).update(row, req.body))
@@ -172,6 +161,7 @@ export function responsibilityAreaRoutes(db: Db) {
agentId: writer.agentId,
interactionId: query.confirmationId,
key: responsibilityDeletionKey("area", row.id),
ownerUserId: writer.personUserId,
});
confirmationId = card.id;
}
@@ -179,7 +169,7 @@ export function responsibilityAreaRoutes(db: Db) {
// Moving its responsibilities changes their owners' Dashboards too.
const removed = writer
? await agentChanges.record({
companyId: row.companyId, ownerUserIds: [writer.personUserId, ...await svc.ownersInArea(row.companyId, row.id)],
companyId: row.companyId, ownerUserIds: [writer.personUserId],
agentId: writer.agentId,
touchedAreaIds: [row.id, ...(query.moveResponsibilitiesTo ? [query.moveResponsibilitiesTo] : [])],
onVersion: reportVersionOf(res, writer.personUserId),
+5 -10
View File
@@ -1,3 +1,4 @@
import { dashboardOwner } from "./responsibility-owner.js";
import { Router, type Request } from "express";
import type { Db } from "@paperclipai/db";
import {
@@ -35,7 +36,6 @@ import { automationConversationService } from "../services/responsibility-automa
import { standingCheckService } from "../services/routine-standing-checks.js";
import { routineSuggestionService, type RoutineSuggestionResponsibilityFiling } from "../services/routine-suggestions.js";
import { assertBoard, assertCompanyAccess, getAccessibleResource, getActorInfo } from "./authz.js";
import { defaultResponsibilityOwnerUserId } from "./responsibilities.js";
import { getReadableIssue } from "./readable-issue.js";
const automationQuerySchema = listResponsibilitiesQuerySchema.pick({ ownerUserId: true });
@@ -147,12 +147,7 @@ export function responsibilityAutomationRoutes(
const companyId = req.params.companyId as string;
await assertCompanyRead(req, companyId);
const query = automationQuerySchema.parse(req.query);
const ownerUserId = query.ownerUserId ?? defaultResponsibilityOwnerUserId(req);
if (!ownerUserId) {
throw unprocessable(req.actor.type === "agent"
? "ownerUserId is required: this run works for no person, so name the person whose responsibilities to read"
: "ownerUserId is required");
}
const ownerUserId = await dashboardOwner(db, req, companyId, query.ownerUserId);
res.json(await automation.overview(companyId, ownerUserId, { scope: await readScope(req) }));
});
@@ -161,7 +156,7 @@ export function responsibilityAutomationRoutes(
const issue = await getReadableIssue(access, req, res, issues.getById(req.params.id as string), ISSUE_NOT_FOUND);
if (!issue) return;
assertBoard(req);
res.json(await conversations.conversationFor(issue));
res.json(await conversations.conversationFor(issue, boardUserId(req)));
});
router.post("/issues/:id/automation-conversation", validate(startAutomationConversationSchema), async (req, res) => {
@@ -171,7 +166,7 @@ export function responsibilityAutomationRoutes(
assertBoard(req);
await assertBoardCanAssignTasks(req, source.companyId);
const actor = getActorInfo(req);
const agentId = req.body.agentId ?? await conversations.defaultAgentId(source, req.body.responsibilityId);
const agentId = req.body.agentId ?? await conversations.defaultAgentId(source, boardUserId(req), req.body.responsibilityId);
if (agentId) {
// The same assignment permission the delegate route checks.
const decision = await access.decide({
@@ -224,7 +219,7 @@ export function responsibilityAutomationRoutes(
requestedByActorId: actor.actorId,
});
}
const body = await conversations.conversation(source);
const body = await conversations.conversation(source, boardUserId(req));
if (created) {
res.status(201).json(body);
return;
+4 -2
View File
@@ -1,3 +1,4 @@
import { dashboardOwner } from "./responsibility-owner.js";
import { Router, type Request } from "express";
import type { Db } from "@paperclipai/db";
import {
@@ -71,10 +72,10 @@ export function responsibilityBarRoutes(db: Db, opts: { heartbeat?: IssueAssignm
};
}
/** The writer rule of the responsibilities routes: the owner, or a company admin. */
/** The writer rule of the responsibilities routes: the owner. */
function assertWriter(req: Request, row: { companyId: string; ownerUserId: string }) {
if (!boardCanManageResponsibilityOwner(req, row.companyId, row.ownerUserId)) {
throw forbidden("Only the person who owns this responsibility, or a company admin, can change its bar");
throw forbidden("Only the person who owns this responsibility can change its bar");
}
}
@@ -95,6 +96,7 @@ export function responsibilityBarRoutes(db: Db, opts: { heartbeat?: IssueAssignm
const row = await getAccessibleResource(req, res, responsibilitiesSvc.getById(req.params.id as string), NOT_FOUND);
if (!row) return;
assertBoard(req);
await dashboardOwner(db, req, row.companyId, row.ownerUserId);
res.json(await svc.conversation(row));
});
+7 -22
View File
@@ -1,3 +1,4 @@
import { dashboardOwner } from "./responsibility-owner.js";
import { Router, type Request } from "express";
import type { Db } from "@paperclipai/db";
import {
@@ -22,10 +23,9 @@ import {
toDashboardVersionSummary,
type DashboardActivityEvent,
} from "../services/responsibility-dashboard-versions.js";
import { responsibilityService } from "../services/responsibilities.js";
import { assertBoard, assertCompanyAccess, getAccessibleResource, getActorInfo } from "./authz.js";
import { getReadableIssue } from "./readable-issue.js";
import { boardCanManageResponsibilityOwner, defaultResponsibilityOwnerUserId } from "./responsibilities.js";
import { boardCanManageResponsibilityOwner } from "./responsibilities.js";
const ISSUE_NOT_FOUND = "Issue not found";
const VERSION_NOT_FOUND = "Version not found";
@@ -35,7 +35,7 @@ const VERSION_NOT_FOUND = "Version not found";
* applied change saved as a version (experimental `enableResponsibilities`).
* Reads follow the responsibilities overview: board users read their own by
* default, agents name the person. A person who may edit that person's
* responsibilities (themselves, or a company admin) starts the conversation,
* responsibilities starts the conversation,
* applies the agent's proposed changes and restores versions; only the agent
* in the conversation proposes.
*/
@@ -44,7 +44,6 @@ export function responsibilityDashboardRoutes(db: Db, opts: { heartbeat?: IssueA
const access = accessService(db);
const svc = responsibilityDashboardService(db);
const versions = responsibilityDashboardVersionService(db);
const responsibilitiesSvc = responsibilityService(db);
const issues = issueService(db);
const references = issueReferenceService(db);
const heartbeat = opts.heartbeat ?? heartbeatService(db);
@@ -83,20 +82,9 @@ export function responsibilityDashboardRoutes(db: Db, opts: { heartbeat?: IssueA
}
}
/** The overview route's ownerUserId rule: board users default to themselves, agents to the person their run works for. */
function ownerFrom(req: Request, ownerUserId: string | undefined) {
const owner = ownerUserId ?? defaultResponsibilityOwnerUserId(req);
if (!owner) {
throw unprocessable(req.actor.type === "agent"
? "ownerUserId is required: this run works for no person, so name the person whose dashboard to read"
: "ownerUserId is required");
}
return owner;
}
function assertWriter(req: Request, companyId: string, ownerUserId: string) {
if (!boardCanManageResponsibilityOwner(req, companyId, ownerUserId)) {
throw forbidden("Only the person whose dashboard this is, or a company admin, can change it");
throw notFound("Dashboard item not found");
}
}
@@ -121,7 +109,7 @@ export function responsibilityDashboardRoutes(db: Db, opts: { heartbeat?: IssueA
const companyId = req.params.companyId as string;
await assertCompanyRead(req, companyId);
const query = responsibilityDashboardQuerySchema.parse(req.query);
res.json(await svc.state(companyId, ownerFrom(req, query.ownerUserId)));
res.json(await svc.state(companyId, await dashboardOwner(db, req, companyId, query.ownerUserId)));
});
router.get("/companies/:companyId/responsibility-dashboard/versions", async (req, res) => {
@@ -129,7 +117,7 @@ export function responsibilityDashboardRoutes(db: Db, opts: { heartbeat?: IssueA
const companyId = req.params.companyId as string;
await assertCompanyRead(req, companyId);
const query = responsibilityDashboardQuerySchema.parse(req.query);
const ownerUserId = ownerFrom(req, query.ownerUserId);
const ownerUserId = await dashboardOwner(db, req, companyId, query.ownerUserId);
// Someone who may change this dashboard saves it as it is first, so the list starts with what they see.
const writer = boardCanManageResponsibilityOwner(req, companyId, ownerUserId);
const { list, saved } = await versions.list(companyId, ownerUserId, writer ? { checkpointBy: getActorInfo(req).actorId } : {});
@@ -150,11 +138,8 @@ export function responsibilityDashboardRoutes(db: Db, opts: { heartbeat?: IssueA
const companyId = req.params.companyId as string;
assertBoard(req);
assertCompanyAccess(req, companyId);
const ownerUserId = ownerFrom(req, req.body.ownerUserId);
const ownerUserId = await dashboardOwner(db, req, companyId, req.body.ownerUserId);
assertWriter(req, companyId, ownerUserId);
if (ownerUserId !== req.actor.userId && !(await responsibilitiesSvc.isCompanyMember(companyId, ownerUserId))) {
throw notFound("Owner is not a member of this company");
}
const actor = getActorInfo(req);
const agentId = req.body.agentId ?? await svc.defaultAgentId(companyId);
if (agentId) {
+5 -3
View File
@@ -1,3 +1,4 @@
import { agentMayReportFor, dashboardOwner } from "./responsibility-owner.js";
import { Router, type Request, type Response } from "express";
import type { Db } from "@paperclipai/db";
import {
@@ -38,7 +39,7 @@ export function responsibilityMetricRoutes(db: Db) {
}
/** The detail route's read rule: company access, board or agent, and agents inside the company-scope boundary. */
async function loadForRead(req: Request, res: Response) {
async function loadForRead(req: Request, res: Response, reporting = false) {
const row = await getAccessibleResource(req, res, responsibilitiesSvc.getById(req.params.id as string), NOT_FOUND);
if (!row) return null;
if (req.actor.type !== "board" && req.actor.type !== "agent") throw forbidden("Board or agent access required");
@@ -48,12 +49,13 @@ export function responsibilityMetricRoutes(db: Db) {
throw forbidden("Responsibilities are outside this agent's authorization boundary", authorizationDeniedDetails(decision));
}
}
if (!(reporting && agentMayReportFor(req, row.ownerUserId))) await dashboardOwner(db, req, row.companyId, row.ownerUserId);
return row;
}
function assertOwnerOrAdmin(req: Request, row: { companyId: string; ownerUserId: string }) {
if (!boardCanManageResponsibilityOwner(req, row.companyId, row.ownerUserId)) {
throw forbidden("Only the person who owns this responsibility, or a company admin, can change its metrics");
throw forbidden("Only the person who owns this responsibility can change its metrics");
}
}
@@ -129,7 +131,7 @@ export function responsibilityMetricRoutes(db: Db) {
validate(recordResponsibilityMetricReadingSchema),
async (req, res) => {
await svc.assertEnabled();
const row = await loadForRead(req, res);
const row = await loadForRead(req, res, true);
if (!row) return;
const scope = await readScope(req);
const actor = getActorInfo(req);
+22
View File
@@ -0,0 +1,22 @@
import type { Request } from "express";
import type { Db } from "@paperclipai/db";
import { forbidden, notFound } from "../errors.js";
import { agentPersonInCompany } from "./agent-person-authz.js";
/** A dashboard belongs to the signed-in person or the person who directed this agent run. */
export async function dashboardOwner(db: Db, req: Request, companyId: string, requested?: string | null): Promise<string> {
const userId = req.actor.type === "board"
? req.actor.userId
: (await agentPersonInCompany(db, req, companyId))?.userId;
if (!userId) throw forbidden("A personal dashboard requires a user or a run directed by that user");
if (req.actor.authorizingUserId && req.actor.authorizingUserId !== userId) throw forbidden("Dashboard access requires the authorizing user");
if (requested !== undefined && userId !== requested) throw notFound("Dashboard item not found");
return userId;
}
/** Reporting permissions apply only within the user scope of the agent's credentials or run. */
export function agentMayReportFor(req: Request, ownerUserId: string) {
return req.actor.type === "agent"
&& (!req.actor.authorizingUserId || req.actor.authorizingUserId === ownerUserId)
&& (!req.actor.onBehalfOfUserId || req.actor.onBehalfOfUserId === ownerUserId);
}
+2
View File
@@ -1,3 +1,4 @@
import { dashboardOwner } from "./responsibility-owner.js";
import { Router, type Request, type Response } from "express";
import type { Db } from "@paperclipai/db";
import { forbidden } from "../errors.js";
@@ -39,6 +40,7 @@ export function responsibilityRunRoutes(db: Db) {
throw forbidden("Responsibilities are outside this agent's authorization boundary", authorizationDeniedDetails(decision));
}
}
await dashboardOwner(db, req, row.companyId, row.ownerUserId);
return row;
}
@@ -1,3 +1,4 @@
import { agentMayReportFor, dashboardOwner } from "./responsibility-owner.js";
import { Router, type Request, type Response } from "express";
import type { Db } from "@paperclipai/db";
import {
@@ -51,10 +52,11 @@ export function responsibilityStatusReportRoutes(db: Db, opts: { heartbeat?: Iss
}
}
async function loadForRead(req: Request, res: Response) {
async function loadForRead(req: Request, res: Response, reporting = false) {
const row = await getAccessibleResource(req, res, responsibilitiesSvc.getById(req.params.id as string), NOT_FOUND);
if (!row) return null;
await assertCompanyRead(req, row.companyId);
if (!(reporting && agentMayReportFor(req, row.ownerUserId))) await dashboardOwner(db, req, row.companyId, row.ownerUserId);
return row;
}
@@ -79,12 +81,7 @@ export function responsibilityStatusReportRoutes(db: Db, opts: { heartbeat?: Iss
const companyId = req.params.companyId as string;
await assertCompanyRead(req, companyId);
const query = ownerQuerySchema.parse(req.query);
const ownerUserId = query.ownerUserId ?? (req.actor.type === "board" ? req.actor.userId : undefined);
if (!ownerUserId) {
throw unprocessable(req.actor.type === "agent"
? "ownerUserId is required: name the person whose responsibilities to read"
: "ownerUserId is required");
}
const ownerUserId = await dashboardOwner(db, req, companyId, query.ownerUserId);
res.json(await svc.overview(companyId, ownerUserId));
});
@@ -97,7 +94,7 @@ export function responsibilityStatusReportRoutes(db: Db, opts: { heartbeat?: Iss
router.post("/responsibilities/:id/status-report", validate(writeResponsibilityStatusReportSchema), async (req, res) => {
await svc.assertEnabled();
const row = await loadForRead(req, res);
const row = await loadForRead(req, res, true);
if (!row) return;
let author: StatusReportAuthor;
if (req.actor.type === "agent") {
@@ -130,7 +127,7 @@ export function responsibilityStatusReportRoutes(db: Db, opts: { heartbeat?: Iss
if (!row) return;
assertBoard(req);
if (!boardCanManageResponsibilityOwner(req, row.companyId, row.ownerUserId)) {
throw forbidden("Only the person who owns this responsibility, or a company admin, can ask for an update");
throw forbidden("Only the person who owns this responsibility can ask for an update");
}
const reporter = await svc.reporterOf(row);
if (reporter) {
@@ -1,3 +1,4 @@
import { dashboardOwner } from "./responsibility-owner.js";
import { Router, type Request } from "express";
import type { Db } from "@paperclipai/db";
import { listResponsibilitiesQuerySchema } from "@paperclipai/shared";
@@ -15,7 +16,6 @@ import {
type ResponsibilitySummaryServiceOptions,
} from "../services/responsibility-summaries.js";
import { assertCompanyAccess, getAccessibleResource } from "./authz.js";
import { defaultResponsibilityOwnerUserId } from "./responsibilities.js";
const NOT_FOUND = "Responsibility not found";
const summaryQuerySchema = listResponsibilitiesQuerySchema.pick({ ownerUserId: true });
@@ -67,12 +67,7 @@ export function responsibilitySummaryRoutes(db: Db, opts: { summaries?: Responsi
const companyId = req.params.companyId as string;
await assertCompanyRead(req, companyId);
const query = summaryQuerySchema.parse(req.query);
const ownerUserId = query.ownerUserId ?? defaultResponsibilityOwnerUserId(req);
if (!ownerUserId) {
throw unprocessable(req.actor.type === "agent"
? "ownerUserId is required: this run works for no person, so name the person whose responsibilities to summarize"
: "ownerUserId is required");
}
const ownerUserId = await dashboardOwner(db, req, companyId, query.ownerUserId);
const overview = await responsibilities.overview(companyId, ownerUserId, {
includeLetGo: false,
scope: await readScope(req),
@@ -85,6 +80,7 @@ export function responsibilitySummaryRoutes(db: Db, opts: { summaries?: Responsi
const row = await getAccessibleResource(req, res, responsibilities.getById(req.params.id as string), NOT_FOUND);
if (!row) return;
await assertCompanyRead(req, row.companyId);
await dashboardOwner(db, req, row.companyId, row.ownerUserId);
const detail = await responsibilities.detail(row, await readScope(req), { actor: req.actor });
res.json(await summaries.affectingTheNumber({ detail, actor: req.actor }));
});
+3 -1
View File
@@ -19,6 +19,7 @@ import { trackRoutineCreated } from "@paperclipai/shared/telemetry";
import { validate, validateIssueMutationBody } from "../middleware/validate.js";
import { accessService, documentAnnotationService, instanceSettingsService, logActivity, routineService } from "../services/index.js";
import { instanceSettingsService as experimentSettings } from "../services/instance-settings.js";
import { dashboardOwner } from "./responsibility-owner.js";
import { responsibilitiesDisabledError } from "../services/responsibilities-disabled.js";
import { agentPersonInCompany } from "./agent-person-authz.js";
import { assertCompanyAccess, getAccessibleResource, getActorInfo, hasCompanyAccess } from "./authz.js";
@@ -207,7 +208,8 @@ export function routineRoutes(
&& (await experimentSettings(db).getExperimental()).enableResponsibilities !== true) {
throw responsibilitiesDisabledError();
}
const result = await svc.list(companyId, { ...filters, ...(q ? { query: q } : {}), ...(unfiled === "true" ? { unfiled: true } : {}) });
const ownerUserId = filters.responsibilityId || unfiled === "true" ? await dashboardOwner(db, req, companyId) : undefined;
const result = await svc.list(companyId, { ...filters, ownerUserId, ...(q ? { query: q } : {}), ...(unfiled === "true" ? { unfiled: true } : {}) });
res.json(result);
});