fix: enforce active organization boundary

This commit is contained in:
2026-07-10 18:42:12 +08:00
parent f07f280b8f
commit d730e51c3d
24 changed files with 1686 additions and 460 deletions
+12 -5
View File
@@ -11,6 +11,7 @@ import {
createProjectFromOrgAdmin,
moveProjectToFolder,
} from "../projectOnboarding.js";
import { lockActiveOrganization } from "./status.js";
export interface ExplorerFolderNode {
readonly id: string;
@@ -120,6 +121,7 @@ export async function renameFolder(
},
) {
return prisma.$transaction(async (tx) => {
await lockActiveOrganization(tx, input.organizationId);
const folder = await requireActiveFolder(tx, input.folderId, input.organizationId);
if (input.parentId !== undefined && input.parentId !== null) {
if (input.parentId === folder.id) {
@@ -148,6 +150,7 @@ export async function archiveFolder(
input: { readonly organizationId: string; readonly folderId: string },
): Promise<{ readonly archived: true; readonly folderId: string }> {
return prisma.$transaction(async (tx) => {
await lockActiveOrganization(tx, input.organizationId);
const folder = await requireActiveFolder(tx, input.folderId, input.organizationId);
const childFolders = await tx.folder.count({
where: { parentId: folder.id, archivedAt: null },
@@ -195,11 +198,14 @@ export async function renameProject(
},
) {
const name = requireNonEmpty(input.name, "project name");
const project = await requireActiveProject(prisma, input.projectId, input.organizationId);
return prisma.project.update({
where: { id: project.id },
data: { name },
select: { id: true, name: true, folderId: true },
return prisma.$transaction(async (tx) => {
await lockActiveOrganization(tx, input.organizationId);
const project = await requireActiveProject(tx, input.projectId, input.organizationId);
return tx.project.update({
where: { id: project.id },
data: { name },
select: { id: true, name: true, folderId: true },
});
});
}
@@ -223,6 +229,7 @@ export async function archiveProject(
input: { readonly organizationId: string; readonly projectId: string },
): Promise<{ readonly archived: true; readonly projectId: string }> {
return prisma.$transaction(async (tx) => {
await lockActiveOrganization(tx, input.organizationId);
const project = await requireActiveProject(tx, input.projectId, input.organizationId);
const activeBinding = await tx.projectGroupBinding.findFirst({
where: { projectId: project.id, archivedAt: null },
+89 -87
View File
@@ -7,7 +7,8 @@
* 3. Cannot revoke or demote the last remaining OWNER.
* 4. ADMIN cannot modify OWNER memberships.
*/
import type { OrganizationMemberRole, PrismaClient } from "@prisma/client";
import type { OrganizationMemberRole, Prisma, PrismaClient } from "@prisma/client";
import { lockActiveOrganization } from "./status.js";
export interface OrgMemberRow {
readonly userId: string;
@@ -56,32 +57,32 @@ export async function addOrgMember(
const openId = requireNonEmpty(input.feishuOpenId, "feishuOpenId");
assertCanAssignRole(input.actorRole, input.role, /* targetIsOwner */ false);
const user = await prisma.user.upsert({
where: { feishuOpenId: openId },
create: {
feishuOpenId: openId,
displayName: input.displayName?.trim() || openId,
},
update: {
...(input.displayName !== undefined && input.displayName.trim() !== ""
? { displayName: input.displayName.trim() }
: {}),
},
});
const existing = await prisma.organizationMembership.findFirst({
where: { organizationId: input.organizationId, userId: user.id, revokedAt: null },
});
if (existing !== null) {
throw new Error(`user ${user.id} is already an active member`);
}
const membership = await prisma.organizationMembership.create({
data: {
organizationId: input.organizationId,
userId: user.id,
role: input.role,
},
const { user, membership } = await prisma.$transaction(async (tx) => {
await lockActiveOrganization(tx, input.organizationId);
const user = await tx.user.upsert({
where: { feishuOpenId: openId },
create: {
feishuOpenId: openId,
displayName: input.displayName?.trim() || openId,
},
update: {
...(input.displayName !== undefined && input.displayName.trim() !== ""
? { displayName: input.displayName.trim() }
: {}),
},
});
const existing = await tx.organizationMembership.findFirst({
where: { organizationId: input.organizationId, userId: user.id, revokedAt: null },
});
if (existing !== null) throw new Error(`user ${user.id} is already an active member`);
const membership = await tx.organizationMembership.create({
data: {
organizationId: input.organizationId,
userId: user.id,
role: input.role,
},
});
return { user, membership };
});
return {
@@ -104,46 +105,47 @@ export async function setOrgMemberRole(
readonly role: OrganizationMemberRole;
},
): Promise<OrgMemberRow> {
const membership = await prisma.organizationMembership.findFirst({
where: {
organizationId: input.organizationId,
userId: input.targetUserId,
revokedAt: null,
},
select: {
id: true,
role: true,
createdAt: true,
user: {
select: { id: true, feishuOpenId: true, displayName: true, avatarUrl: true },
return prisma.$transaction(async (tx) => {
await lockActiveOrganization(tx, input.organizationId);
const membership = await tx.organizationMembership.findFirst({
where: {
organizationId: input.organizationId,
userId: input.targetUserId,
revokedAt: null,
},
},
select: {
id: true,
role: true,
createdAt: true,
user: {
select: { id: true, feishuOpenId: true, displayName: true, avatarUrl: true },
},
},
});
if (membership === null) throw new Error(`member not found: ${input.targetUserId}`);
assertCanAssignRole(input.actorRole, input.role, membership.role === "OWNER");
if (membership.role === "OWNER" && input.actorRole !== "OWNER") {
throw new Error("cannot modify OWNER membership as ADMIN");
}
if (membership.role === "OWNER" && input.role !== "OWNER") {
await assertNotLastOwner(tx, input.organizationId, input.targetUserId);
}
const updated = await tx.organizationMembership.update({
where: { id: membership.id },
data: { role: input.role },
});
return {
userId: membership.user.id,
feishuOpenId: membership.user.feishuOpenId,
displayName: membership.user.displayName,
avatarUrl: membership.user.avatarUrl,
role: updated.role,
createdAt: membership.createdAt.toISOString(),
};
});
if (membership === null) {
throw new Error(`member not found: ${input.targetUserId}`);
}
assertCanAssignRole(input.actorRole, input.role, membership.role === "OWNER");
if (membership.role === "OWNER" && input.actorRole !== "OWNER") {
throw new Error("cannot modify OWNER membership as ADMIN");
}
if (membership.role === "OWNER" && input.role !== "OWNER") {
await assertNotLastOwner(prisma, input.organizationId, input.targetUserId);
}
const updated = await prisma.organizationMembership.update({
where: { id: membership.id },
data: { role: input.role },
});
return {
userId: membership.user.id,
feishuOpenId: membership.user.feishuOpenId,
displayName: membership.user.displayName,
avatarUrl: membership.user.avatarUrl,
role: updated.role,
createdAt: membership.createdAt.toISOString(),
};
}
export async function revokeOrgMember(
@@ -155,27 +157,27 @@ export async function revokeOrgMember(
readonly targetUserId: string;
},
): Promise<{ readonly revoked: true; readonly userId: string }> {
const membership = await prisma.organizationMembership.findFirst({
where: {
organizationId: input.organizationId,
userId: input.targetUserId,
revokedAt: null,
},
select: { id: true, role: true },
});
if (membership === null) {
throw new Error(`member not found: ${input.targetUserId}`);
}
if (membership.role === "OWNER" && input.actorRole !== "OWNER") {
throw new Error("cannot revoke OWNER membership as ADMIN");
}
if (membership.role === "OWNER") {
await assertNotLastOwner(prisma, input.organizationId, input.targetUserId);
}
await prisma.organizationMembership.update({
where: { id: membership.id },
data: { revokedAt: new Date() },
await prisma.$transaction(async (tx) => {
await lockActiveOrganization(tx, input.organizationId);
const membership = await tx.organizationMembership.findFirst({
where: {
organizationId: input.organizationId,
userId: input.targetUserId,
revokedAt: null,
},
select: { id: true, role: true },
});
if (membership === null) throw new Error(`member not found: ${input.targetUserId}`);
if (membership.role === "OWNER" && input.actorRole !== "OWNER") {
throw new Error("cannot revoke OWNER membership as ADMIN");
}
if (membership.role === "OWNER") {
await assertNotLastOwner(tx, input.organizationId, input.targetUserId);
}
await tx.organizationMembership.update({
where: { id: membership.id },
data: { revokedAt: new Date() },
});
});
return { revoked: true as const, userId: input.targetUserId };
}
@@ -194,7 +196,7 @@ function assertCanAssignRole(
}
async function assertNotLastOwner(
prisma: PrismaClient,
prisma: PrismaClient | Prisma.TransactionClient,
organizationId: string,
targetUserId: string,
): Promise<void> {
+62
View File
@@ -0,0 +1,62 @@
import type { OrganizationStatus, Prisma } from "@prisma/client";
export class InactiveOrganizationError extends Error {
readonly organizationId: string;
readonly status: Exclude<OrganizationStatus, "ACTIVE">;
constructor(organizationId: string, status: Exclude<OrganizationStatus, "ACTIVE">) {
super(`organization ${organizationId} is ${status}; customer operations require ACTIVE`);
this.name = "InactiveOrganizationError";
this.organizationId = organizationId;
this.status = status;
}
}
export function inactiveOrganizationReason(
organizationId: string,
status: OrganizationStatus,
): string | undefined {
if (status === "ACTIVE") return undefined;
return `organization ${organizationId} is ${status}; customer operations require ACTIVE`;
}
export function requireActiveOrganizationStatus(
organizationId: string,
status: OrganizationStatus,
): void {
if (status !== "ACTIVE") throw new InactiveOrganizationError(organizationId, status);
}
/**
* Lock the Organization row for a customer operation and verify ACTIVE.
* PostgreSQL UPDATE takes a conflicting row lock, so lifecycle transitions
* serialize with the entire transaction that called this function.
*/
export async function lockActiveOrganization(
prisma: Prisma.TransactionClient,
organizationId: string,
): Promise<void> {
const rows = await prisma.$queryRaw<Array<{ readonly id: string; readonly status: OrganizationStatus }>>`
SELECT "id", "status"::text AS "status"
FROM "Organization"
WHERE "id" = ${organizationId}
FOR SHARE
`;
const organization = rows[0];
if (organization === undefined) throw new Error(`organization not found: ${organizationId}`);
requireActiveOrganizationStatus(organization.id, organization.status);
}
/** Resolve a Project's tenant inside the transaction, then take the lifecycle lock. */
export async function lockActiveProjectOrganization(
prisma: Prisma.TransactionClient,
projectId: string,
): Promise<string> {
const project = await prisma.project.findUnique({
where: { id: projectId },
select: { organizationId: true },
});
if (project === null) throw new Error(`project not found: ${projectId}`);
await lockActiveOrganization(prisma, project.organizationId);
return project.organizationId;
}
+72 -67
View File
@@ -5,6 +5,7 @@
* grants that use this team as principal (product pin).
*/
import type { Prisma, PrismaClient } from "@prisma/client";
import { lockActiveOrganization } from "./status.js";
export interface TeamRow {
readonly id: string;
@@ -59,20 +60,21 @@ export async function createTeam(
): Promise<TeamRow> {
const slug = sanitizeSlug(input.slug);
const name = requireNonEmpty(input.name, "name");
const existing = await prisma.team.findFirst({
where: { organizationId: input.organizationId, slug, archivedAt: null },
select: { id: true },
});
if (existing !== null) {
throw new Error(`team slug already exists: ${slug}`);
}
const team = await prisma.team.create({
data: {
organizationId: input.organizationId,
slug,
name,
...(input.description !== undefined ? { description: input.description } : {}),
},
const team = await prisma.$transaction(async (tx) => {
await lockActiveOrganization(tx, input.organizationId);
const existing = await tx.team.findFirst({
where: { organizationId: input.organizationId, slug, archivedAt: null },
select: { id: true },
});
if (existing !== null) throw new Error(`team slug already exists: ${slug}`);
return tx.team.create({
data: {
organizationId: input.organizationId,
slug,
name,
...(input.description !== undefined ? { description: input.description } : {}),
},
});
});
return {
id: team.id,
@@ -93,21 +95,24 @@ export async function updateTeam(
readonly description?: string | null | undefined;
},
): Promise<TeamRow> {
const team = await requireActiveTeam(prisma, input.teamId, input.organizationId);
const updated = await prisma.team.update({
where: { id: team.id },
data: {
...(input.name !== undefined ? { name: requireNonEmpty(input.name, "name") } : {}),
...(input.description !== undefined ? { description: input.description } : {}),
},
select: {
id: true,
slug: true,
name: true,
description: true,
createdAt: true,
_count: { select: { memberships: { where: { revokedAt: null } } } },
},
const updated = await prisma.$transaction(async (tx) => {
await lockActiveOrganization(tx, input.organizationId);
const team = await requireActiveTeam(tx, input.teamId, input.organizationId);
return tx.team.update({
where: { id: team.id },
data: {
...(input.name !== undefined ? { name: requireNonEmpty(input.name, "name") } : {}),
...(input.description !== undefined ? { description: input.description } : {}),
},
select: {
id: true,
slug: true,
name: true,
description: true,
createdAt: true,
_count: { select: { memberships: { where: { revokedAt: null } } } },
},
});
});
return {
id: updated.id,
@@ -127,6 +132,7 @@ export async function archiveTeam(
input: { readonly organizationId: string; readonly teamId: string },
): Promise<{ readonly archived: true; readonly teamId: string; readonly revokedGrants: number }> {
return prisma.$transaction(async (tx) => {
await lockActiveOrganization(tx, input.organizationId);
const team = await requireActiveTeam(tx, input.teamId, input.organizationId);
const now = new Date();
await tx.team.update({
@@ -183,34 +189,32 @@ export async function addTeamMember(
readonly feishuOpenId?: string | undefined;
},
): Promise<TeamMemberRow> {
const team = await requireActiveTeam(prisma, input.teamId, input.organizationId);
const user = await resolveUser(prisma, input);
// User should be an org member to join a team (product pin for pilot).
const membership = await prisma.organizationMembership.findFirst({
where: {
organizationId: input.organizationId,
userId: user.id,
revokedAt: null,
},
select: { id: true },
});
if (membership === null) {
throw new Error(`user ${user.id} is not an active member of the organization`);
}
const existing = await prisma.teamMembership.findFirst({
where: { teamId: team.id, userId: user.id, revokedAt: null },
});
if (existing !== null) {
throw new Error(`user ${user.id} is already on team ${team.id}`);
}
const row = await prisma.teamMembership.create({
data: { teamId: team.id, userId: user.id },
const result = await prisma.$transaction(async (tx) => {
await lockActiveOrganization(tx, input.organizationId);
const team = await requireActiveTeam(tx, input.teamId, input.organizationId);
const user = await resolveUser(tx, input);
// User should be an org member to join a team (product pin for pilot).
const membership = await tx.organizationMembership.findFirst({
where: {
organizationId: input.organizationId,
userId: user.id,
revokedAt: null,
},
select: { id: true },
});
if (membership === null) throw new Error(`user ${user.id} is not an active member of the organization`);
const existing = await tx.teamMembership.findFirst({
where: { teamId: team.id, userId: user.id, revokedAt: null },
});
if (existing !== null) throw new Error(`user ${user.id} is already on team ${team.id}`);
const row = await tx.teamMembership.create({ data: { teamId: team.id, userId: user.id } });
return { user, row };
});
return {
userId: user.id,
feishuOpenId: user.feishuOpenId,
displayName: user.displayName,
createdAt: row.createdAt.toISOString(),
userId: result.user.id,
feishuOpenId: result.user.feishuOpenId,
displayName: result.user.displayName,
createdAt: result.row.createdAt.toISOString(),
};
}
@@ -222,23 +226,24 @@ export async function revokeTeamMember(
readonly userId: string;
},
): Promise<{ readonly revoked: true; readonly userId: string }> {
await requireActiveTeam(prisma, input.teamId, input.organizationId);
const membership = await prisma.teamMembership.findFirst({
where: { teamId: input.teamId, userId: input.userId, revokedAt: null },
select: { id: true },
});
if (membership === null) {
throw new Error(`team member not found: ${input.userId}`);
}
await prisma.teamMembership.update({
where: { id: membership.id },
data: { revokedAt: new Date() },
await prisma.$transaction(async (tx) => {
await lockActiveOrganization(tx, input.organizationId);
await requireActiveTeam(tx, input.teamId, input.organizationId);
const membership = await tx.teamMembership.findFirst({
where: { teamId: input.teamId, userId: input.userId, revokedAt: null },
select: { id: true },
});
if (membership === null) throw new Error(`team member not found: ${input.userId}`);
await tx.teamMembership.update({
where: { id: membership.id },
data: { revokedAt: new Date() },
});
});
return { revoked: true as const, userId: input.userId };
}
async function resolveUser(
prisma: PrismaClient,
prisma: PrismaClient | Prisma.TransactionClient,
input: { readonly userId?: string | undefined; readonly feishuOpenId?: string | undefined },
): Promise<{ readonly id: string; readonly feishuOpenId: string; readonly displayName: string }> {
if (input.userId !== undefined && input.userId !== "") {