feat(server): integrate Better Auth, access control, and deployment mode startup

Wire up Better Auth for session-based authentication. Add actor middleware
that resolves local_trusted mode to an implicit board actor and authenticated
mode to Better Auth sessions. Add access service with membership, permission,
invite, and join-request management. Register access routes for member/invite/
join-request CRUD. Update health endpoint to report deployment mode and
bootstrap status. Enforce tasks:assign and agents:create permissions in issue
and agent routes. Add deployment mode validation at startup with guardrails
(loopback-only for local_trusted, auth config required for authenticated).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Forgotten
2026-02-23 14:40:32 -06:00
parent 60d6122271
commit e1f2be7ecf
24 changed files with 1530 additions and 49 deletions

View File

@@ -0,0 +1,268 @@
import { and, eq, inArray, sql } from "drizzle-orm";
import type { Db } from "@paperclip/db";
import {
companyMemberships,
instanceUserRoles,
principalPermissionGrants,
} from "@paperclip/db";
import type { PermissionKey, PrincipalType } from "@paperclip/shared";
type MembershipRow = typeof companyMemberships.$inferSelect;
type GrantInput = {
permissionKey: PermissionKey;
scope?: Record<string, unknown> | null;
};
export function accessService(db: Db) {
async function isInstanceAdmin(userId: string | null | undefined): Promise<boolean> {
if (!userId) return false;
const row = await db
.select({ id: instanceUserRoles.id })
.from(instanceUserRoles)
.where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin")))
.then((rows) => rows[0] ?? null);
return Boolean(row);
}
async function getMembership(
companyId: string,
principalType: PrincipalType,
principalId: string,
): Promise<MembershipRow | null> {
return db
.select()
.from(companyMemberships)
.where(
and(
eq(companyMemberships.companyId, companyId),
eq(companyMemberships.principalType, principalType),
eq(companyMemberships.principalId, principalId),
),
)
.then((rows) => rows[0] ?? null);
}
async function hasPermission(
companyId: string,
principalType: PrincipalType,
principalId: string,
permissionKey: PermissionKey,
): Promise<boolean> {
const membership = await getMembership(companyId, principalType, principalId);
if (!membership || membership.status !== "active") return false;
const grant = await db
.select({ id: principalPermissionGrants.id })
.from(principalPermissionGrants)
.where(
and(
eq(principalPermissionGrants.companyId, companyId),
eq(principalPermissionGrants.principalType, principalType),
eq(principalPermissionGrants.principalId, principalId),
eq(principalPermissionGrants.permissionKey, permissionKey),
),
)
.then((rows) => rows[0] ?? null);
return Boolean(grant);
}
async function canUser(
companyId: string,
userId: string | null | undefined,
permissionKey: PermissionKey,
): Promise<boolean> {
if (!userId) return false;
if (await isInstanceAdmin(userId)) return true;
return hasPermission(companyId, "user", userId, permissionKey);
}
async function listMembers(companyId: string) {
return db
.select()
.from(companyMemberships)
.where(eq(companyMemberships.companyId, companyId))
.orderBy(sql`${companyMemberships.createdAt} desc`);
}
async function setMemberPermissions(
companyId: string,
memberId: string,
grants: GrantInput[],
grantedByUserId: string | null,
) {
const member = await db
.select()
.from(companyMemberships)
.where(and(eq(companyMemberships.companyId, companyId), eq(companyMemberships.id, memberId)))
.then((rows) => rows[0] ?? null);
if (!member) return null;
await db.transaction(async (tx) => {
await tx
.delete(principalPermissionGrants)
.where(
and(
eq(principalPermissionGrants.companyId, companyId),
eq(principalPermissionGrants.principalType, member.principalType),
eq(principalPermissionGrants.principalId, member.principalId),
),
);
if (grants.length > 0) {
await tx.insert(principalPermissionGrants).values(
grants.map((grant) => ({
companyId,
principalType: member.principalType,
principalId: member.principalId,
permissionKey: grant.permissionKey,
scope: grant.scope ?? null,
grantedByUserId,
createdAt: new Date(),
updatedAt: new Date(),
})),
);
}
});
return member;
}
async function promoteInstanceAdmin(userId: string) {
const existing = await db
.select()
.from(instanceUserRoles)
.where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin")))
.then((rows) => rows[0] ?? null);
if (existing) return existing;
return db
.insert(instanceUserRoles)
.values({
userId,
role: "instance_admin",
})
.returning()
.then((rows) => rows[0]);
}
async function demoteInstanceAdmin(userId: string) {
return db
.delete(instanceUserRoles)
.where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin")))
.returning()
.then((rows) => rows[0] ?? null);
}
async function listUserCompanyAccess(userId: string) {
return db
.select()
.from(companyMemberships)
.where(and(eq(companyMemberships.principalType, "user"), eq(companyMemberships.principalId, userId)))
.orderBy(sql`${companyMemberships.createdAt} desc`);
}
async function setUserCompanyAccess(userId: string, companyIds: string[]) {
const existing = await listUserCompanyAccess(userId);
const existingByCompany = new Map(existing.map((row) => [row.companyId, row]));
const target = new Set(companyIds);
await db.transaction(async (tx) => {
const toDelete = existing.filter((row) => !target.has(row.companyId)).map((row) => row.id);
if (toDelete.length > 0) {
await tx.delete(companyMemberships).where(inArray(companyMemberships.id, toDelete));
}
for (const companyId of target) {
if (existingByCompany.has(companyId)) continue;
await tx.insert(companyMemberships).values({
companyId,
principalType: "user",
principalId: userId,
status: "active",
membershipRole: "member",
});
}
});
return listUserCompanyAccess(userId);
}
async function ensureMembership(
companyId: string,
principalType: PrincipalType,
principalId: string,
membershipRole: string | null = "member",
status: "pending" | "active" | "suspended" = "active",
) {
const existing = await getMembership(companyId, principalType, principalId);
if (existing) {
if (existing.status !== status || existing.membershipRole !== membershipRole) {
const updated = await db
.update(companyMemberships)
.set({ status, membershipRole, updatedAt: new Date() })
.where(eq(companyMemberships.id, existing.id))
.returning()
.then((rows) => rows[0] ?? null);
return updated ?? existing;
}
return existing;
}
return db
.insert(companyMemberships)
.values({
companyId,
principalType,
principalId,
status,
membershipRole,
})
.returning()
.then((rows) => rows[0]);
}
async function setPrincipalGrants(
companyId: string,
principalType: PrincipalType,
principalId: string,
grants: GrantInput[],
grantedByUserId: string | null,
) {
await db.transaction(async (tx) => {
await tx
.delete(principalPermissionGrants)
.where(
and(
eq(principalPermissionGrants.companyId, companyId),
eq(principalPermissionGrants.principalType, principalType),
eq(principalPermissionGrants.principalId, principalId),
),
);
if (grants.length === 0) return;
await tx.insert(principalPermissionGrants).values(
grants.map((grant) => ({
companyId,
principalType,
principalId,
permissionKey: grant.permissionKey,
scope: grant.scope ?? null,
grantedByUserId,
createdAt: new Date(),
updatedAt: new Date(),
})),
);
});
}
return {
isInstanceAdmin,
canUser,
hasPermission,
getMembership,
ensureMembership,
listMembers,
setMemberPermissions,
promoteInstanceAdmin,
demoteInstanceAdmin,
listUserCompanyAccess,
setUserCompanyAccess,
setPrincipalGrants,
};
}

View File

@@ -18,6 +18,10 @@ import {
approvals,
activityLog,
companySecrets,
joinRequests,
invites,
principalPermissionGrants,
companyMemberships,
} from "@paperclip/db";
export function companyService(db: Db) {
@@ -68,6 +72,10 @@ export function companyService(db: Db) {
await tx.delete(approvalComments).where(eq(approvalComments.companyId, id));
await tx.delete(approvals).where(eq(approvals.companyId, id));
await tx.delete(companySecrets).where(eq(companySecrets.companyId, id));
await tx.delete(joinRequests).where(eq(joinRequests.companyId, id));
await tx.delete(invites).where(eq(invites.companyId, id));
await tx.delete(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, id));
await tx.delete(companyMemberships).where(eq(companyMemberships.companyId, id));
await tx.delete(issues).where(eq(issues.companyId, id));
await tx.delete(goals).where(eq(goals.companyId, id));
await tx.delete(projects).where(eq(projects.companyId, id));

View File

@@ -985,7 +985,7 @@ export function heartbeatService(db: Db) {
: outcome === "cancelled"
? "cancelled"
: outcome === "failed"
? "adapter_failed"
? (adapterResult.errorCode ?? "adapter_failed")
: null,
exitCode: adapterResult.exitCode,
signal: adapterResult.signal,

View File

@@ -12,6 +12,7 @@ export { costService } from "./costs.js";
export { heartbeatService } from "./heartbeat.js";
export { dashboardService } from "./dashboard.js";
export { sidebarBadgeService } from "./sidebar-badges.js";
export { accessService } from "./access.js";
export { logActivity, type LogActivityInput } from "./activity-log.js";
export { publishLiveEvent, subscribeCompanyLiveEvents } from "./live-events.js";
export { createStorageServiceFromConfig, getStorageService } from "../storage/index.js";

View File

@@ -4,6 +4,7 @@ import {
agents,
assets,
companies,
companyMemberships,
goals,
heartbeatRuns,
issueAttachments,
@@ -77,6 +78,24 @@ export function issueService(db: Db) {
}
}
async function assertAssignableUser(companyId: string, userId: string) {
const membership = await db
.select({ id: companyMemberships.id })
.from(companyMemberships)
.where(
and(
eq(companyMemberships.companyId, companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, userId),
eq(companyMemberships.status, "active"),
),
)
.then((rows) => rows[0] ?? null);
if (!membership) {
throw notFound("Assignee user not found");
}
}
async function isTerminalOrMissingHeartbeatRun(runId: string) {
const run = await db
.select({ status: heartbeatRuns.status })
@@ -157,9 +176,18 @@ export function issueService(db: Db) {
.then((rows) => rows[0] ?? null),
create: async (companyId: string, data: Omit<typeof issues.$inferInsert, "companyId">) => {
if (data.assigneeAgentId && data.assigneeUserId) {
throw unprocessable("Issue can only have one assignee");
}
if (data.assigneeAgentId) {
await assertAssignableAgent(companyId, data.assigneeAgentId);
}
if (data.assigneeUserId) {
await assertAssignableUser(companyId, data.assigneeUserId);
}
if (data.status === "in_progress" && !data.assigneeAgentId && !data.assigneeUserId) {
throw unprocessable("in_progress issues require an assignee");
}
return db.transaction(async (tx) => {
const [company] = await tx
.update(companies)
@@ -203,12 +231,23 @@ export function issueService(db: Db) {
updatedAt: new Date(),
};
if (patch.status === "in_progress" && !patch.assigneeAgentId && !existing.assigneeAgentId) {
const nextAssigneeAgentId =
data.assigneeAgentId !== undefined ? data.assigneeAgentId : existing.assigneeAgentId;
const nextAssigneeUserId =
data.assigneeUserId !== undefined ? data.assigneeUserId : existing.assigneeUserId;
if (nextAssigneeAgentId && nextAssigneeUserId) {
throw unprocessable("Issue can only have one assignee");
}
if (patch.status === "in_progress" && !nextAssigneeAgentId && !nextAssigneeUserId) {
throw unprocessable("in_progress issues require an assignee");
}
if (data.assigneeAgentId) {
await assertAssignableAgent(existing.companyId, data.assigneeAgentId);
}
if (data.assigneeUserId) {
await assertAssignableUser(existing.companyId, data.assigneeUserId);
}
applyStatusSideEffects(data.status, patch);
if (data.status && data.status !== "done") {
@@ -220,7 +259,10 @@ export function issueService(db: Db) {
if (data.status && data.status !== "in_progress") {
patch.checkoutRunId = null;
}
if (data.assigneeAgentId !== undefined && data.assigneeAgentId !== existing.assigneeAgentId) {
if (
(data.assigneeAgentId !== undefined && data.assigneeAgentId !== existing.assigneeAgentId) ||
(data.assigneeUserId !== undefined && data.assigneeUserId !== existing.assigneeUserId)
) {
patch.checkoutRunId = null;
}
@@ -277,6 +319,7 @@ export function issueService(db: Db) {
.update(issues)
.set({
assigneeAgentId: agentId,
assigneeUserId: null,
checkoutRunId,
executionRunId: checkoutRunId,
status: "in_progress",

View File

@@ -8,7 +8,7 @@ const FAILED_HEARTBEAT_STATUSES = ["failed", "timed_out"];
export function sidebarBadgeService(db: Db) {
return {
get: async (companyId: string): Promise<SidebarBadges> => {
get: async (companyId: string, extra?: { joinRequests?: number }): Promise<SidebarBadges> => {
const actionableApprovals = await db
.select({ count: sql<number>`count(*)` })
.from(approvals)
@@ -39,10 +39,12 @@ export function sidebarBadgeService(db: Db) {
FAILED_HEARTBEAT_STATUSES.includes(row.runStatus),
).length;
const joinRequests = extra?.joinRequests ?? 0;
return {
inbox: actionableApprovals + failedRuns,
inbox: actionableApprovals + failedRuns + joinRequests,
approvals: actionableApprovals,
failedRuns,
joinRequests,
};
},
};