Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

feat(dashboard): members get an explicit project scope, all or selected projects (#545)

Carl-Gerhard Lindesvärd1e5bfa6a53e0
diff --git a/apps/start/e2e/org-members.spec.ts b/apps/start/e2e/org-members.spec.ts
index fde750be4..e77074622 100644
--- a/apps/start/e2e/org-members.spec.ts
+++ b/apps/start/e2e/org-members.spec.ts
@@ -27,6 +27,7 @@ interface Invite {
id: string;
email: string;
role: string;
+ projectScope: 'all' | 'selected';
projectAccess: { projectId: string; level: string }[];
}
@@ -35,7 +36,8 @@ interface Member {
userId: string;
email: string;
role: string;
- access: { projectId: string; level: string }[];
+ projectScope: 'all' | 'selected';
+ projects: { projectId: string; level: string | null }[];
}
const THROWAWAY_EMAIL = /^e2e-org-\d+@example\.com$/;
@@ -61,9 +63,8 @@ const sendInvite = (sheet: Locator) =>
sheet.getByRole('button', { name: 'Invite user' }).click();
const pickProjects = async (page: Page, scope: Locator, names: string[]) => {
- await scope
- .getByRole('button', { name: /Restrict access to projects/ })
- .click();
+ await scope.getByRole('radio', { name: 'Selected projects' }).click();
+ await scope.getByRole('button', { name: /Choose projects/ }).click();
for (const name of names) {
await page.getByRole('option', { name }).click();
}
@@ -162,7 +163,7 @@ test('the members tab lists the admin and filters by email', async ({
await expect(page).toHaveURL(/\/members\/members$/);
const adminRow = page.getByRole('row', { name: new RegExp(seed.user.email) });
await expect(adminRow).toContainText('Seed Admin');
- await expect(adminRow).toContainText('org:admin');
+ await expect(adminRow).toContainText('owner');
await expect(adminRow).toContainText('All projects');
const search = page.getByRole('textbox', { name: 'Search email' });
@@ -247,14 +248,15 @@ test('an admin invite with project access shows in the list and can be copied an
await sheet.getByRole('button', { name: 'Close' }).first().click();
const row = page.getByRole('row', { name: new RegExp(email) });
- await expect(row).toContainText('org:admin');
+ await expect(row).toContainText('admin');
await expect(row).toContainText('Acme Web (read-only)');
await expect(row).toContainText('Acme Shop');
await shot(page, 'invitations');
const invites = await listInvites(page, seed.organizationId);
const invite = invites.find((candidate) => candidate.email === email);
- expect(invite?.role).toBe('org:admin');
+ expect(invite?.role).toBe('admin');
+ expect(invite?.projectScope).toBe('selected');
expect(invite?.projectAccess).toEqual([
{ projectId: 'acme-web', level: 'read' },
{ projectId: 'acme-shop', level: 'write' },
@@ -295,9 +297,8 @@ test('the project access picker only offers projects', async ({
}) => {
await gotoHydrated(page, `/${seed.organizationId}/members/invitations`);
const sheet = await openInviteSheet(page);
- await sheet
- .getByRole('button', { name: /Restrict access to projects/ })
- .click();
+ await sheet.getByRole('radio', { name: 'Selected projects' }).click();
+ await sheet.getByRole('button', { name: /Choose projects/ }).click();
await expect(page.getByRole('option', { name: 'Acme Web' })).toBeVisible();
await page.keyboard.type('no-such-project');
await expect(page.getByRole('option', { name: /Pick/ })).toHaveCount(0);
@@ -342,12 +343,13 @@ test.describe('an invited member', () => {
const member = (await listMembers(page, seed.organizationId)).find(
(candidate) => candidate.email === email
);
- expect(member?.role).toBe('org:member');
+ expect(member?.role).toBe('member');
+ expect(member?.projectScope).toBe('selected');
expect(
- member?.access.map((grant) => [grant.projectId, grant.level])
+ member?.projects.map((grant) => [grant.projectId, grant.level])
).toEqual([
['acme-web', 'read'],
- ['acme-shop', 'write'],
+ ['acme-shop', null],
]);
// Restricted UI for a non-admin.
diff --git a/apps/start/src/components/organization/yearly-switch-prompt.tsx b/apps/start/src/components/organization/yearly-switch-prompt.tsx
index 114fb8f07..093c11706 100644
--- a/apps/start/src/components/organization/yearly-switch-prompt.tsx
+++ b/apps/start/src/components/organization/yearly-switch-prompt.tsx
@@ -1,4 +1,5 @@
import type { IServiceOrganization } from '@openpanel/core';
+import { isOrganizationAdminRole } from '@openpanel/core/modules/organization/organization.constants';
import { useQuery } from '@tanstack/react-query';
import { differenceInMonths } from 'date-fns';
import { useEffect, useState } from 'react';
@@ -48,7 +49,8 @@ export default function YearlySwitchPrompt({
{ enabled: eligible && !dismissed }
)
);
- const isAdmin = accessQuery.data?.role === 'org:admin';
+ const isAdmin =
+ !!accessQuery.data && isOrganizationAdminRole(accessQuery.data.role);
const currentProductQuery = useQuery(
trpc.subscription.getCurrent.queryOptions(
diff --git a/apps/start/src/components/settings/delete-organization.tsx b/apps/start/src/components/settings/delete-organization.tsx
index 5a4a18e61..dda5167e4 100644
--- a/apps/start/src/components/settings/delete-organization.tsx
+++ b/apps/start/src/components/settings/delete-organization.tsx
@@ -1,4 +1,5 @@
import type { IServiceOrganization } from '@openpanel/core';
+import { isOrganizationAdminRole } from '@openpanel/core/modules/organization/organization.constants';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { addHours, format, startOfHour } from 'date-fns';
import { TrashIcon } from 'lucide-react';
@@ -9,7 +10,9 @@ import { Widget, WidgetBody, WidgetHead } from '@/components/widget';
import { handleError, useTRPC } from '@/integrations/trpc/react';
import { pushModal } from '@/modals';
-type Props = { organization: IServiceOrganization };
+interface Props {
+ organization: IServiceOrganization;
+}
export default function DeleteOrganization({ organization }: Props) {
const trpc = useTRPC();
@@ -35,7 +38,7 @@ export default function DeleteOrganization({ organization }: Props) {
);
// Only admins can delete the organization. The server enforces this too.
- if (myAccess?.role !== 'org:admin') {
+ if (!(myAccess && isOrganizationAdminRole(myAccess.role))) {
return null;
}
diff --git a/apps/start/src/components/settings/invites/columns.tsx b/apps/start/src/components/settings/invites/columns.tsx
index a93001a37..ebe8c6e59 100644
--- a/apps/start/src/components/settings/invites/columns.tsx
+++ b/apps/start/src/components/settings/invites/columns.tsx
@@ -115,6 +115,13 @@ function AccessCell({
const projects = projectsQuery.data ?? [];
const access = row.original.projectAccess ?? [];
+ if (row.original.projectScope === 'all') {
+ return <Badge variant={'secondary'}>All projects</Badge>;
+ }
+ if (access.length === 0) {
+ return <Badge variant={'secondary'}>No projects</Badge>;
+ }
+
return (
<>
{access.map((grant) => {
@@ -133,7 +140,6 @@ function AccessCell({
</Badge>
);
})}
- {access.length === 0 && <Badge variant={'secondary'}>All projects</Badge>}
</>
);
}
diff --git a/apps/start/src/components/settings/members/columns.tsx b/apps/start/src/components/settings/members/columns.tsx
index 315cedc50..2d865365f 100644
--- a/apps/start/src/components/settings/members/columns.tsx
+++ b/apps/start/src/components/settings/members/columns.tsx
@@ -65,18 +65,23 @@ export function useColumns() {
},
},
{
- accessorKey: 'access',
+ accessorKey: 'projects',
header: 'Access',
cell: ({ row }) => {
- const access = row.original.access ?? [];
- if (access.length === 0) {
+ if (row.original.projectScope === 'all') {
return <div className="text-muted-foreground">All projects</div>;
}
+ if (row.original.projects.length === 0) {
+ return <div className="text-muted-foreground">No projects</div>;
+ }
return (
<div className="row flex-wrap gap-2">
- {row.original.access?.map((item) => (
+ {row.original.projects.map((item) => (
<Badge key={item.projectId} variant={'outline'}>
{item.projectId}
+ {item.level === 'read' || row.original.role === 'viewer'
+ ? ' (read-only)'
+ : ''}
</Badge>
))}
</div>
diff --git a/apps/start/src/components/settings/project-access-grants.tsx b/apps/start/src/components/settings/project-access-grants.tsx
index f48c3dd9f..3e7ab8bc9 100644
--- a/apps/start/src/components/settings/project-access-grants.tsx
+++ b/apps/start/src/components/settings/project-access-grants.tsx
@@ -54,7 +54,7 @@ export function ProjectAccessGrants({
value: project.id,
}))}
onChange={(ids) => handleSelectionChange(ids as string[])}
- placeholder="Restrict access to projects"
+ placeholder="Choose projects"
value={selectedIds}
/>
diff --git a/apps/start/src/components/settings/project-scope-picker.tsx b/apps/start/src/components/settings/project-scope-picker.tsx
new file mode 100644
index 000000000..30c75a5d8
--- /dev/null
+++ b/apps/start/src/components/settings/project-scope-picker.tsx
@@ -0,0 +1,69 @@
+import {
+ type IProjectAccessGrant,
+ type ProjectScope,
+ SELECT_A_PROJECT_MESSAGE,
+} from '@openpanel/core/modules/organization/organization.constants';
+import { useId } from 'react';
+import { ProjectAccessGrants } from '@/components/settings/project-access-grants';
+import { Label } from '@/components/ui/label';
+import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
+
+interface ProjectScopePickerProps {
+ projectScope: ProjectScope;
+ access: IProjectAccessGrant[];
+ onScopeChange: (projectScope: ProjectScope) => void;
+ onAccessChange: (access: IProjectAccessGrant[]) => void;
+ projects: { id: string; name: string }[];
+}
+
+/**
+ * "All projects" follows projects created later; "Selected projects" is
+ * exactly the list below it, and an empty list means no project at all.
+ */
+export function ProjectScopePicker({
+ projectScope,
+ access,
+ onScopeChange,
+ onAccessChange,
+ projects,
+}: ProjectScopePickerProps) {
+ const allId = useId();
+ const selectedId = useId();
+
+ return (
+ <div className="col gap-3">
+ <RadioGroup
+ className="flex gap-4"
+ onValueChange={(value) => onScopeChange(value as ProjectScope)}
+ value={projectScope}
+ >
+ <div className="flex items-center gap-2">
+ <RadioGroupItem id={allId} value="all" />
+ <Label className="mb-0" htmlFor={allId}>
+ All projects
+ </Label>
+ </div>
+ <div className="flex items-center gap-2">
+ <RadioGroupItem id={selectedId} value="selected" />
+ <Label className="mb-0" htmlFor={selectedId}>
+ Selected projects
+ </Label>
+ </div>
+ </RadioGroup>
+ {projectScope === 'selected' && (
+ <>
+ <ProjectAccessGrants
+ onChange={onAccessChange}
+ projects={projects}
+ value={access}
+ />
+ {access.length === 0 && (
+ <p className="text-muted-foreground text-sm">
+ {SELECT_A_PROJECT_MESSAGE}
+ </p>
+ )}
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/apps/start/src/hooks/use-organization-access.ts b/apps/start/src/hooks/use-organization-access.ts
index 514448741..fe8ce3aa9 100644
--- a/apps/start/src/hooks/use-organization-access.ts
+++ b/apps/start/src/hooks/use-organization-access.ts
@@ -1,3 +1,4 @@
+import { isOrganizationAdminRole } from '@openpanel/core/modules/organization/organization.constants';
import { useQuery } from '@tanstack/react-query';
import { useTRPC } from '@/integrations/trpc/react';
@@ -12,6 +13,6 @@ export function useOrganizationAccess(organizationId: string | undefined) {
return {
role: data?.role ?? null,
- isAdmin: data?.role === 'org:admin',
+ isAdmin: !!data && isOrganizationAdminRole(data.role),
};
}
diff --git a/apps/start/src/modals/create-invite.tsx b/apps/start/src/modals/create-invite.tsx
index 2411d1375..44553f244 100644
--- a/apps/start/src/modals/create-invite.tsx
+++ b/apps/start/src/modals/create-invite.tsx
@@ -6,7 +6,7 @@ import { Controller, useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
import { InputWithLabel } from '@/components/forms/input-with-label';
-import { ProjectAccessGrants } from '@/components/settings/project-access-grants';
+import { ProjectScopePicker } from '@/components/settings/project-scope-picker';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
@@ -35,14 +35,17 @@ export default function CreateInvite() {
const queryClient = useQueryClient();
- const { register, handleSubmit, formState, reset, control } = useForm<IForm>({
- resolver: zodResolver(zInviteUser),
- defaultValues: {
- organizationId,
- access: [],
- role: 'org:member',
- },
- });
+ const { register, handleSubmit, formState, reset, control, watch } =
+ useForm<IForm>({
+ resolver: zodResolver(zInviteUser),
+ defaultValues: {
+ organizationId,
+ projectScope: 'all',
+ access: [],
+ role: 'member',
+ },
+ });
+ const projectScope = watch('projectScope');
const mutation = useMutation(
trpc.organization.inviteUser.mutationOptions({
@@ -130,13 +133,13 @@ export default function CreateInvite() {
ref={field.ref}
>
<div className="flex items-center gap-2">
- <RadioGroupItem id="member" value="org:member" />
+ <RadioGroupItem id="member" value="member" />
<Label className="mb-0" htmlFor="member">
Member
</Label>
</div>
<div className="flex items-center gap-2">
- <RadioGroupItem id="admin" value="org:admin" />
+ <RadioGroupItem id="admin" value="admin" />
<Label className="mb-0" htmlFor="admin">
Admin
</Label>
@@ -144,21 +147,30 @@ export default function CreateInvite() {
</RadioGroup>
)}
/>
+ <p className="mt-1 text-muted-foreground text-sm">
+ Admins manage members and projects. Members can edit the
+ projects they have access to.
+ </p>
</div>
<Controller
control={control}
name="access"
render={({ field }) => (
<div>
- <Label>Restrict access</Label>
- <ProjectAccessGrants
- onChange={field.onChange}
- projects={projects}
- value={field.value}
+ <Label>Project access</Label>
+ <Controller
+ control={control}
+ name="projectScope"
+ render={({ field: scopeField }) => (
+ <ProjectScopePicker
+ access={field.value}
+ onAccessChange={field.onChange}
+ onScopeChange={scopeField.onChange}
+ projectScope={projectScope}
+ projects={projects}
+ />
+ )}
/>
- <p className="mt-1 text-muted-foreground text-sm">
- Leave empty to give access to all projects
- </p>
</div>
)}
/>
diff --git a/apps/start/src/modals/edit-member.tsx b/apps/start/src/modals/edit-member.tsx
index 8792d4f53..86edee567 100644
--- a/apps/start/src/modals/edit-member.tsx
+++ b/apps/start/src/modals/edit-member.tsx
@@ -1,12 +1,15 @@
import type { IServiceMember } from '@openpanel/core';
-import type { IProjectAccessGrant } from '@openpanel/core/modules/organization/organization.constants';
+import type {
+ IProjectAccessGrant,
+ ProjectScope,
+} from '@openpanel/core/modules/organization/organization.constants';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import { toast } from 'sonner';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
import { ButtonContainer } from '@/components/button-container';
-import { ProjectAccessGrants } from '@/components/settings/project-access-grants';
+import { ProjectScopePicker } from '@/components/settings/project-scope-picker';
import { Button } from '@/components/ui/button';
import { handleError, useTRPC } from '@/integrations/trpc/react';
@@ -17,12 +20,15 @@ export default function EditMember(member: EditMemberProps) {
const trpc = useTRPC();
const toGrants = (): IProjectAccessGrant[] =>
- member.access?.map((a) => ({
- projectId: a.projectId,
- // `admin` is not offered per project - it collapses to write here.
- level: a.level === 'read' ? ('read' as const) : ('write' as const),
- })) ?? [];
+ member.projects.map((row) => ({
+ projectId: row.projectId,
+ // A null level derives from the role, which is write for everyone but viewers.
+ level: row.level === 'read' ? ('read' as const) : ('write' as const),
+ }));
+ const [projectScope, setProjectScope] = useState<ProjectScope>(
+ member.projectScope
+ );
const [access, setAccess] = useState<IProjectAccessGrant[]>(toGrants);
const projectsQuery = useQuery(
@@ -33,6 +39,7 @@ export default function EditMember(member: EditMemberProps) {
trpc.organization.updateMemberAccess.mutationOptions({
onError(error) {
handleError(error);
+ setProjectScope(member.projectScope);
setAccess(toGrants());
},
onSuccess() {
@@ -59,10 +66,12 @@ export default function EditMember(member: EditMemberProps) {
/>
<div className="col gap-4">
- <ProjectAccessGrants
- onChange={setAccess}
+ <ProjectScopePicker
+ access={access}
+ onAccessChange={setAccess}
+ onScopeChange={setProjectScope}
+ projectScope={projectScope}
projects={projects}
- value={access}
/>
<ButtonContainer>
@@ -70,11 +79,15 @@ export default function EditMember(member: EditMemberProps) {
Cancel
</Button>
<Button
- disabled={mutation.isPending}
+ disabled={
+ mutation.isPending ||
+ (projectScope === 'selected' && access.length === 0)
+ }
onClick={() =>
mutation.mutate({
userId: member.user!.id,
organizationId: member.organizationId,
+ projectScope,
access,
})
}
diff --git a/apps/start/src/routes/_app.$organizationId.billing.tsx b/apps/start/src/routes/_app.$organizationId.billing.tsx
index fe5ec2fb1..9325da536 100644
--- a/apps/start/src/routes/_app.$organizationId.billing.tsx
+++ b/apps/start/src/routes/_app.$organizationId.billing.tsx
@@ -1,3 +1,4 @@
+import { isOrganizationAdminRole } from '@openpanel/core/modules/organization/organization.constants';
import { useQuery } from '@tanstack/react-query';
import { createFileRoute, redirect } from '@tanstack/react-router';
import { BoxSelectIcon } from 'lucide-react';
@@ -25,7 +26,7 @@ export const Route = createFileRoute('/_app/$organizationId/billing')({
organizationId: params.organizationId,
})
);
- if (access?.role !== 'org:admin') {
+ if (!(access && isOrganizationAdminRole(access.role))) {
throw redirect({
to: '/$organizationId',
params: { organizationId: params.organizationId },
diff --git a/apps/start/src/routes/_app.$organizationId.members._tabs.tsx b/apps/start/src/routes/_app.$organizationId.members._tabs.tsx
index 203904308..e192cdaef 100644
--- a/apps/start/src/routes/_app.$organizationId.members._tabs.tsx
+++ b/apps/start/src/routes/_app.$organizationId.members._tabs.tsx
@@ -1,3 +1,4 @@
+import { isOrganizationAdminRole } from '@openpanel/core/modules/organization/organization.constants';
import {
createFileRoute,
Outlet,
@@ -26,7 +27,7 @@ export const Route = createFileRoute('/_app/$organizationId/members/_tabs')({
organizationId: params.organizationId,
})
);
- if (access?.role !== 'org:admin') {
+ if (!(access && isOrganizationAdminRole(access.role))) {
throw redirect({
to: '/$organizationId',
params: { organizationId: params.organizationId },
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 986959d44..85d796fe3 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -235,6 +235,7 @@ export {
export { checkNotificationRulesForEvent } from './modules/notification/src/notification-dispatch';
export { createOnboardingService } from './modules/onboarding/onboarding.service';
export type {
+ IServiceInvite,
IServiceMember,
IServiceOrganization,
} from './modules/organization/organization.service';
@@ -363,12 +364,16 @@ export {
} from './rpc/handler';
export type { AppRouter } from './rpc.router';
export { appRouter } from './rpc.router';
-export type { IProjectAccess } from './shared/access-lookups';
+export type {
+ IOrganizationAccess,
+ IProjectAccess,
+} from './shared/access-lookups';
export {
canWriteProject,
getClientAccess,
getOrganizationAccess,
getProjectAccess,
+ resolveProjectAccess,
} from './shared/access-lookups';
export {
DEFAULT_IP_HEADER_ORDER,
diff --git a/packages/core/src/modules/auth/auth.service.access.test.ts b/packages/core/src/modules/auth/auth.service.access.test.ts
index f782e403c..42a70f136 100644
--- a/packages/core/src/modules/auth/auth.service.access.test.ts
+++ b/packages/core/src/modules/auth/auth.service.access.test.ts
@@ -9,7 +9,19 @@ interface FakeProjectAccess {
}
let projectAccess: FakeProjectAccess | null = null;
-let organizationAccess: { role: string } | null = null;
+interface FakeOrganizationAccess {
+ role: string;
+ userId: string;
+ organization: { createdByUserId: string | null };
+}
+
+let organizationAccess: FakeOrganizationAccess | null = null;
+
+const memberAccess = (role: string): FakeOrganizationAccess => ({
+ role,
+ userId: 'user_1',
+ organization: { createdByUserId: null },
+});
let projectById: { organizationId: string | null } | null = null;
const getProjectAccess = mock(async () => projectAccess);
@@ -98,7 +110,7 @@ test('requireProjectAccess allows write and admin levels to write', async () =>
});
test('requireOrganizationAdmin rejects a non-admin with the default message', async () => {
- organizationAccess = { role: 'member' };
+ organizationAccess = memberAccess('org:member');
await expect(
authService().requireOrganizationAdmin({
userId: 'user_1',
@@ -129,15 +141,56 @@ test('requireProjectAdmin fails closed when the project has no organization', as
test('requireProjectAdmin defers to the organization-admin gate once resolved', async () => {
projectById = { organizationId: 'org_1' };
- organizationAccess = { role: 'org:admin' };
+ organizationAccess = memberAccess('org:admin');
await expect(
authService().requireProjectAdmin({ userId: 'user_1', projectId: 'proj_1' })
- ).resolves.toEqual({ role: 'org:admin' });
+ ).resolves.toMatchObject({ role: 'org:admin' });
+});
+
+test('requireOrganizationAdmin accepts the stored and the new admin spellings, and refuses a viewer', async () => {
+ for (const role of ['org:admin', 'admin', 'owner']) {
+ organizationAccess = memberAccess(role);
+ await expect(
+ authService().requireOrganizationAdmin({
+ userId: 'user_1',
+ organizationId: 'org_1',
+ })
+ ).resolves.toBeDefined();
+ }
+ organizationAccess = memberAccess('viewer');
+ await expect(
+ authService().requireOrganizationAdmin({
+ userId: 'user_1',
+ organizationId: 'org_1',
+ })
+ ).rejects.toThrow('Only organization admins can do this');
+});
+
+test('getOrganizationAccess reports the creator as owner and maps the stored spellings', async () => {
+ organizationAccess = {
+ role: 'org:admin',
+ userId: 'user_1',
+ organization: { createdByUserId: 'user_1' },
+ };
+ await expect(
+ authService().getOrganizationAccess({
+ userId: 'user_1',
+ organizationId: 'org_1',
+ })
+ ).resolves.toMatchObject({ role: 'owner' });
+
+ organizationAccess = memberAccess('org:member');
+ await expect(
+ authService().getOrganizationAccess({
+ userId: 'user_1',
+ organizationId: 'org_1',
+ })
+ ).resolves.toMatchObject({ role: 'member' });
});
test('getProjectAccess / getOrganizationAccess reach the same fake lookups', async () => {
projectAccess = { level: 'admin' };
- organizationAccess = { role: 'org:admin' };
+ organizationAccess = memberAccess('org:admin');
await expect(
authService().getProjectAccess({ userId: 'user_1', projectId: 'proj_1' })
).resolves.toEqual({ level: 'admin' });
@@ -146,5 +199,5 @@ test('getProjectAccess / getOrganizationAccess reach the same fake lookups', asy
userId: 'user_1',
organizationId: 'org_1',
})
- ).resolves.toMatchObject({ role: 'org:admin' });
+ ).resolves.toMatchObject({ role: 'admin' });
});
diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.ts
index f80bb350d..25b9a1d16 100644
--- a/packages/core/src/modules/auth/auth.service.ts
+++ b/packages/core/src/modules/auth/auth.service.ts
@@ -7,9 +7,15 @@ import {
getOrganizationAccess as getOrganizationAccessLookup,
getProjectAccess as getProjectAccessLookup,
getProjectById,
+ type IOrganizationAccess,
type IProjectAccess,
} from '../../shared/access-lookups';
import type { ISetCookie } from '../../shared/cookie';
+import {
+ isOrganizationAdminRole,
+ type OrganizationRole,
+ resolveOrganizationRole,
+} from '../organization/organization.constants';
import { type AccessChecks, createAccessChecks } from './src/access';
import {
deleteSessionTokenCookie,
@@ -87,6 +93,8 @@ export function getAccessChecks(): Promise<ProjectAccessChecks> {
getProjectAccess: getProjectAccessLookup,
canWriteProject,
getOrganizationAccess: getOrganizationAccessLookup,
+ isOrganizationAdmin: (access) =>
+ !!access && isOrganizationAdminRole(resolveOrganizationRole(access)),
getProjectById,
})
);
@@ -147,10 +155,16 @@ export function createAuthService(
return getProjectAccessLookup(args);
}
- function getOrganizationAccess(
+ async function getOrganizationAccess(
...args: Parameters<typeof getOrganizationAccessLookup>
- ): ReturnType<typeof getOrganizationAccessLookup> {
- return getOrganizationAccessLookup(...args);
+ ): Promise<
+ (Omit<IOrganizationAccess, 'role'> & { role: OrganizationRole }) | null
+ > {
+ const access = await getOrganizationAccessLookup(...args);
+ if (!access) {
+ return null;
+ }
+ return { ...access, role: resolveOrganizationRole(access) };
}
function getClientAccess(
diff --git a/packages/core/src/modules/auth/src/access.ts b/packages/core/src/modules/auth/src/access.ts
index 647a52c11..2255c872e 100644
--- a/packages/core/src/modules/auth/src/access.ts
+++ b/packages/core/src/modules/auth/src/access.ts
@@ -36,6 +36,8 @@ export interface AccessLookups<
userId: string;
organizationId: string;
}): Promise<TOrganizationAccess | null>;
+ /** role in {owner, admin}. */
+ isOrganizationAdmin(access: TOrganizationAccess | null): boolean;
getProjectById(
projectId: string
): Promise<{ organizationId: string | null } | null>;
@@ -62,13 +64,11 @@ export interface AccessChecks<
}): Promise<TOrganizationAccess>;
}
-const ORGANIZATION_ADMIN_ROLE = 'org:admin';
-
/**
* The permission ladder. Two independent controls:
*
- * - ADMIN is the organization role (`member.role === 'org:admin'`). It gates
- * destruction and billing.
+ * - ADMIN is the organization role (owner or admin). It gates destruction
+ * and billing.
* - WRITE is the per-project access level. It gates every mutation; `admin`
* level counts as a superset of `write`.
* - READ is the floor: membership of the project.
@@ -127,7 +127,7 @@ export function createAccessChecks<
organizationId,
});
- if (access?.role !== ORGANIZATION_ADMIN_ROLE) {
+ if (!(access && lookups.isOrganizationAdmin(access))) {
throw new TRPCForbiddenError(message);
}
diff --git a/packages/core/src/modules/onboarding/onboarding.service.ts b/packages/core/src/modules/onboarding/onboarding.service.ts
index f3d38df64..801800882 100644
--- a/packages/core/src/modules/onboarding/onboarding.service.ts
+++ b/packages/core/src/modules/onboarding/onboarding.service.ts
@@ -12,6 +12,7 @@ import {
type SequenceSubject,
step,
} from '../email/src/sequence';
+import { toStoredOrganizationRole } from '../organization/organization.constants';
import {
getOrganizationById,
getOrganizationEventsCount,
@@ -35,15 +36,15 @@ export async function canSkipOnboarding(
// Sequential, not Promise.all: the early return below skips the projectAccess query
// for any user with a membership, which a parallel fetch would give up.
const db = deps.db;
- const members = await db.member.findMany({ where: { userId } });
- if (members.length > 0) {
+ const members = await db.member.count({ where: { userId } });
+ if (members > 0) {
return { canSkip: true };
}
- const projectAccess = await db.projectAccess.findMany({
- where: { userId },
- });
- return { canSkip: projectAccess.length > 0 };
+ // Rows without a membership never granted access, but they did let the user
+ // past onboarding; kept until `project_access` is dropped.
+ const projectAccess = await db.projectAccess.count({ where: { userId } });
+ return { canSkip: projectAccess > 0 };
}
async function createOrGetOnboardingOrganization(
@@ -62,9 +63,9 @@ async function createOrGetOnboardingOrganization(
const db = deps.db;
const organizationId = await getId(deps, 'organization', input.organization);
- // Create the organization and its owner (org:admin member) atomically. The
- // `delete` cron treats an organization with no org:admin member as ownerless
- // and removes it, so an organization must never exist without one.
+ // Create the organization and its owner atomically. The `delete` cron
+ // treats an organization with no admin member as ownerless and removes it,
+ // so an organization must never exist without one.
const [organization] = await db.$transaction([
db.organization.create({
data: {
@@ -78,13 +79,15 @@ async function createOrGetOnboardingOrganization(
subscriptionPeriodEventsLimit: TRIAL_EVENTS_LIMIT,
timezone: input.timezone,
onboarding: '',
+ // Equal to the id so it is unique; see code migration 26.
+ slug: organizationId,
},
}),
db.member.create({
data: {
email: (await getUserById(deps, userId)).email,
organizationId,
- role: 'org:admin',
+ role: toStoredOrganizationRole('owner'),
userId,
},
}),
diff --git a/packages/core/src/modules/organization/organization.constants.test.ts b/packages/core/src/modules/organization/organization.constants.test.ts
index 7e77cad1f..8d18fe3d0 100644
--- a/packages/core/src/modules/organization/organization.constants.test.ts
+++ b/packages/core/src/modules/organization/organization.constants.test.ts
@@ -1,5 +1,10 @@
import { describe, expect, it } from 'bun:test';
-import { zEditOrganization, zTimezone } from './organization.constants';
+import {
+ zEditOrganization,
+ zInviteUser,
+ zTimezone,
+ zUpdateMemberAccess,
+} from './organization.constants';
describe('zTimezone', () => {
it('accepts IANA zones, trims, and canonicalises case', () => {
@@ -21,3 +26,41 @@ describe('zTimezone', () => {
).toBe(false);
});
});
+
+// The previous image reads no project_access rows as every project.
+describe('an empty selected scope', () => {
+ const invite = {
+ email: '[email protected]',
+ organizationId: 'org_1',
+ role: 'member' as const,
+ };
+
+ it('is rejected for invites and access updates', () => {
+ expect(
+ zInviteUser.safeParse({ ...invite, projectScope: 'selected', access: [] })
+ .success
+ ).toBe(false);
+ expect(
+ zUpdateMemberAccess.safeParse({
+ userId: 'user_1',
+ organizationId: 'org_1',
+ projectScope: 'selected',
+ access: [],
+ }).success
+ ).toBe(false);
+ });
+
+ it('allows all projects, or a selection with at least one project', () => {
+ expect(
+ zInviteUser.safeParse({ ...invite, projectScope: 'all', access: [] })
+ .success
+ ).toBe(true);
+ expect(
+ zInviteUser.safeParse({
+ ...invite,
+ projectScope: 'selected',
+ access: [{ projectId: 'proj_1', level: 'read' }],
+ }).success
+ ).toBe(true);
+ });
+});
diff --git a/packages/core/src/modules/organization/organization.constants.ts b/packages/core/src/modules/organization/organization.constants.ts
index 1abbc7fb6..eff949275 100644
--- a/packages/core/src/modules/organization/organization.constants.ts
+++ b/packages/core/src/modules/organization/organization.constants.ts
@@ -13,18 +13,127 @@ export const zProjectAccessGrant = z.object({
});
export type IProjectAccessGrant = z.infer<typeof zProjectAccessGrant>;
-export const zInviteUser = z.object({
- email: z.string().max(MAX_EMAIL).email(),
- organizationId: z.string().max(MAX_ID),
- role: z.enum(['org:admin', 'org:member']),
- access: z.array(zProjectAccessGrant),
-});
+/**
+ * Organization roles. `owner` and `admin` manage the organization; `member`
+ * edits the projects in scope; `viewer` only reads them.
+ */
+export const ORGANIZATION_ROLES = [
+ 'owner',
+ 'admin',
+ 'member',
+ 'viewer',
+] as const;
+export const zOrganizationRole = z.enum(ORGANIZATION_ROLES);
+export type OrganizationRole = z.infer<typeof zOrganizationRole>;
-export const zUpdateMemberAccess = z.object({
- userId: z.string(),
- organizationId: z.string(),
- access: z.array(zProjectAccessGrant),
-});
+/**
+ * Owner is derived from who created the organization, never assigned. Viewer
+ * is not offered until the stored roles are renamed: the previous image does
+ * not know it and would give a viewer write access after a rollback.
+ */
+export const zInvitableRole = z.enum(['admin', 'member']);
+export type InvitableRole = z.infer<typeof zInvitableRole>;
+
+const ORGANIZATION_ADMIN_ROLES: ReadonlySet<OrganizationRole> = new Set([
+ 'owner',
+ 'admin',
+]);
+
+// The spellings the previous build wrote and still compares against. They are
+// read and written as-is for one more build so a rolling deploy or rollback
+// never turns an admin into a member; the stored rename is the next build's
+// migration.
+const STORED_ROLE_BY_ROLE: Record<OrganizationRole, string> = {
+ owner: 'org:admin',
+ admin: 'org:admin',
+ member: 'org:member',
+ viewer: 'viewer',
+};
+const ROLE_BY_STORED_ROLE: Record<string, OrganizationRole> = {
+ 'org:admin': 'admin',
+ 'org:member': 'member',
+};
+
+/** Every stored spelling that counts as an organization admin, for database filters. */
+export const STORED_ADMIN_ROLES = ['org:admin', 'admin', 'owner'] as const;
+
+export function normalizeOrganizationRole(stored: string): OrganizationRole {
+ const mapped = ROLE_BY_STORED_ROLE[stored];
+ if (mapped) {
+ return mapped;
+ }
+ const parsed = zOrganizationRole.safeParse(stored);
+ return parsed.success ? parsed.data : 'member';
+}
+
+export function toStoredOrganizationRole(role: OrganizationRole): string {
+ return STORED_ROLE_BY_ROLE[role];
+}
+
+/**
+ * The role a membership row resolves to. The organization's creator is its
+ * owner; the stored row still says admin until the next build's migration.
+ */
+export function resolveOrganizationRole(member: {
+ role: string;
+ userId: string | null;
+ organization: { createdByUserId: string | null };
+}): OrganizationRole {
+ const role = normalizeOrganizationRole(member.role);
+ const isCreator =
+ member.userId !== null &&
+ member.userId === member.organization.createdByUserId;
+ return role === 'admin' && isCreator ? 'owner' : role;
+}
+
+export function isOrganizationAdminRole(role: OrganizationRole): boolean {
+ return ORGANIZATION_ADMIN_ROLES.has(role);
+}
+
+/**
+ * `all` follows projects created later. `selected` means exactly the listed
+ * projects, and an empty list is no project at all.
+ */
+export const zProjectScope = z.enum(['all', 'selected']);
+export type ProjectScope = z.infer<typeof zProjectScope>;
+
+export const SELECT_A_PROJECT_MESSAGE = 'Select at least one project';
+
+/**
+ * The previous image reads "no project_access rows" as every project, so an
+ * empty selection would widen access on an old pod or after a rollback.
+ * Allowed again once `project_access` is dropped.
+ */
+function hasGrantsWhenSelected(value: {
+ projectScope: ProjectScope;
+ access: unknown[];
+}): boolean {
+ return value.projectScope === 'all' || value.access.length > 0;
+}
+
+const SELECTED_NEEDS_GRANTS = {
+ message: SELECT_A_PROJECT_MESSAGE,
+ path: ['access'],
+};
+
+export const zInviteUser = z
+ .object({
+ email: z.string().max(MAX_EMAIL).email(),
+ organizationId: z.string().max(MAX_ID),
+ role: zInvitableRole,
+ projectScope: zProjectScope,
+ access: z.array(zProjectAccessGrant),
+ })
+ .refine(hasGrantsWhenSelected, SELECTED_NEEDS_GRANTS);
+
+export const zUpdateMemberAccess = z
+ .object({
+ userId: z.string(),
+ organizationId: z.string(),
+ projectScope: zProjectScope,
+ access: z.array(zProjectAccessGrant),
+ })
+ .refine(hasGrantsWhenSelected, SELECTED_NEEDS_GRANTS);
export const DEFAULT_TIMEZONE = 'UTC';
diff --git a/packages/core/src/modules/organization/organization.rpc.test.ts b/packages/core/src/modules/organization/organization.rpc.test.ts
index ff7e42da1..4d0e3d33b 100644
--- a/packages/core/src/modules/organization/organization.rpc.test.ts
+++ b/packages/core/src/modules/organization/organization.rpc.test.ts
@@ -64,7 +64,8 @@ test('inviteUser rejects an unauthenticated caller', async () => {
caller.inviteUser({
organizationId: 'org_1',
- role: 'org:member',
+ role: 'member',
+ projectScope: 'all',
access: [],
})
).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
diff --git a/packages/core/src/modules/organization/organization.rpc.ts b/packages/core/src/modules/organization/organization.rpc.ts
index 08d5ea4aa..436c55c20 100644
--- a/packages/core/src/modules/organization/organization.rpc.ts
+++ b/packages/core/src/modules/organization/organization.rpc.ts
@@ -90,6 +90,7 @@ export const organizationRouter = createTRPCRouter({
organizationId: input.organizationId,
email: input.email,
role: input.role,
+ projectScope: input.projectScope,
access: input.access,
invitedById: userId,
});
@@ -144,6 +145,7 @@ export const organizationRouter = createTRPCRouter({
return ctx.services.organization.updateMemberAccess({
organizationId: input.organizationId,
targetUserId: input.userId,
+ projectScope: input.projectScope,
access: input.access,
});
}),
diff --git a/packages/core/src/modules/organization/organization.service.test.ts b/packages/core/src/modules/organization/organization.service.test.ts
index a814ec834..b0513144f 100644
--- a/packages/core/src/modules/organization/organization.service.test.ts
+++ b/packages/core/src/modules/organization/organization.service.test.ts
@@ -31,6 +31,13 @@ interface FakeMember {
userId: string | null;
role: string;
email: string;
+ projectScope?: 'all' | 'selected';
+}
+
+interface FakeMemberProject {
+ memberId: string;
+ projectId: string;
+ level: 'read' | null;
}
interface FakeInvite {
@@ -39,6 +46,7 @@ interface FakeInvite {
organizationId: string;
role: string;
createdById: string;
+ projectScope?: 'all' | 'selected';
projectAccess: { projectId: string; level: 'read' | 'write' }[];
expiresAt: Date;
createdAt: Date;
@@ -86,6 +94,7 @@ const projectAccessStore = new Map<
level: string;
}
>();
+const memberProjectStore: FakeMemberProject[] = [];
function resetStores() {
organizationStore.clear();
@@ -94,6 +103,7 @@ function resetStores() {
inviteStore.clear();
userStore.clear();
projectAccessStore.clear();
+ memberProjectStore.length = 0;
}
const organization = {
@@ -221,6 +231,20 @@ const project = {
};
const member = {
+ findUnique: mock(
+ async ({
+ where,
+ }: {
+ where: {
+ organizationId_userId: { organizationId: string; userId: string };
+ };
+ }) =>
+ [...memberStore.values()].find(
+ (m) =>
+ m.organizationId === where.organizationId_userId.organizationId &&
+ m.userId === where.organizationId_userId.userId
+ ) ?? null
+ ),
count: mock(
async ({ where }: { where: { userId: string; organizationId: string } }) =>
[...memberStore.values()].filter(
@@ -244,7 +268,31 @@ const member = {
}) =>
[...memberStore.values()]
.filter((m) => m.organizationId === where.organizationId && m.userId)
- .map((m) => ({ ...m, user: userStore.get(m.userId as string) }))
+ .map((m) => ({
+ ...m,
+ user: userStore.get(m.userId as string),
+ projects: memberProjectStore.filter((row) => row.memberId === m.id),
+ organization: {
+ createdByUserId:
+ organizationStore.get(m.organizationId)?.createdByUserId ?? null,
+ },
+ }))
+ ),
+ update: mock(
+ async ({
+ where: { id },
+ data,
+ }: {
+ where: { id: string };
+ data: Partial<FakeMember>;
+ }) => {
+ const existing = memberStore.get(id);
+ if (!existing) {
+ throw new Error('member not found');
+ }
+ Object.assign(existing, data);
+ return existing;
+ }
),
delete: mock(
async ({
@@ -402,6 +450,22 @@ const projectAccess = {
),
};
+const memberProject = {
+ deleteMany: mock(async ({ where }: { where: { memberId: string } }) => {
+ const remaining = memberProjectStore.filter(
+ (row) => row.memberId !== where.memberId
+ );
+ const count = memberProjectStore.length - remaining.length;
+ memberProjectStore.length = 0;
+ memberProjectStore.push(...remaining);
+ return { count };
+ }),
+ createMany: mock(async ({ data }: { data: FakeMemberProject[] }) => {
+ memberProjectStore.push(...data);
+ return { count: data.length };
+ }),
+};
+
const $transaction = mock(async (ops: Promise<unknown>[]) => Promise.all(ops));
// `connectUserToOrganization` reaches `shared/access-lookups.ts` (cacheable, on
@@ -416,6 +480,7 @@ const deps = {
invite,
user,
projectAccess,
+ memberProject,
$transaction,
},
ch: { command: chCommand },
@@ -459,9 +524,9 @@ function seedMemberWithTwoProjects() {
}
const EXPECTED_CLEARED_ACCESS_KEYS = [
- 'getOrganizationAccess:{"userId":"user_1","organizationId":"org_1"}',
- 'getProjectAccessV2:{"userId":"user_1","projectId":"proj_1"}',
- 'getProjectAccessV2:{"userId":"user_1","projectId":"proj_2"}',
+ 'getOrganizationAccessV2:{"userId":"user_1","organizationId":"org_1"}',
+ 'getProjectAccessV3:{"userId":"user_1","projectId":"proj_1"}',
+ 'getProjectAccessV3:{"userId":"user_1","projectId":"proj_2"}',
];
// Spread the real module: `mock.module` replaces this specifier process-wide,
// and `event-buffer.ts` value-imports `publishEvent` from here, so a partial
@@ -645,6 +710,7 @@ test('updateOrganizationMemberAccess drops the cached access for every project o
await subject.updateOrganizationMemberAccess(deps, {
organizationId: 'org_1',
targetUserId: 'user_1',
+ projectScope: 'selected',
access: [{ projectId: 'proj_1', level: 'read' }],
});
@@ -660,6 +726,7 @@ test('connectUserToOrganization drops the cached access for every project of the
organizationId: 'org_1',
role: 'org:member',
createdById: 'user_admin',
+ projectScope: 'selected',
projectAccess: [{ projectId: 'proj_1', level: 'read' }],
expiresAt: new Date(Date.now() + 60_000),
createdAt: EPOCH,
@@ -697,12 +764,182 @@ test('updateOrganizationMemberAccess replaces project access with the given gran
await subject.updateOrganizationMemberAccess(deps, {
organizationId: 'org_1',
targetUserId: 'user_1',
+ projectScope: 'selected',
access: [{ projectId: 'proj_new', level: 'write' }],
});
const remaining = [...projectAccessStore.values()];
expect(remaining).toHaveLength(1);
expect(remaining[0]).toMatchObject({ projectId: 'proj_new', level: 'write' });
+ expect(memberProjectStore).toEqual([
+ { memberId: 'member_1', projectId: 'proj_new', level: null },
+ ]);
+ expect(memberStore.get('member_1')?.projectScope).toBe('selected');
+});
+
+test('updateOrganizationMemberAccess with scope all clears both tables', async () => {
+ memberStore.set('member_1', {
+ id: 'member_1',
+ organizationId: 'org_1',
+ userId: 'user_1',
+ role: 'org:member',
+ email: '[email protected]',
+ projectScope: 'selected',
+ });
+ memberProjectStore.push({
+ memberId: 'member_1',
+ projectId: 'proj_old',
+ level: 'read',
+ });
+ projectAccessStore.set('access_old', {
+ id: 'access_old',
+ userId: 'user_1',
+ organizationId: 'org_1',
+ projectId: 'proj_old',
+ level: 'read',
+ });
+
+ await subject.updateOrganizationMemberAccess(deps, {
+ organizationId: 'org_1',
+ targetUserId: 'user_1',
+ projectScope: 'all',
+ access: [{ projectId: 'proj_old', level: 'read' }],
+ });
+
+ expect(memberProjectStore).toHaveLength(0);
+ expect(projectAccessStore.size).toBe(0);
+ expect(memberStore.get('member_1')?.projectScope).toBe('all');
+});
+
+// An old pod accepting a restricted invite mid-deploy leaves the member on the
+// default `all` with only legacy rows; the list must not show "All projects".
+test("getMembers reports legacy grants as the member's selection", async () => {
+ memberStore.set('member_1', {
+ id: 'member_1',
+ organizationId: 'org_1',
+ userId: 'user_1',
+ role: 'org:member',
+ email: '[email protected]',
+ projectScope: 'all',
+ });
+ projectAccessStore.set('access_1', {
+ id: 'access_1',
+ userId: 'user_1',
+ organizationId: 'org_1',
+ projectId: 'proj_1',
+ level: 'read',
+ });
+
+ const [member] = await subject.getMembers(deps, 'org_1');
+
+ expect(member?.projectScope).toBe('selected');
+ expect(member?.projects).toEqual([{ projectId: 'proj_1', level: 'read' }]);
+});
+
+test("connectUserToOrganization keeps an existing member's scope and grants", async () => {
+ memberStore.set('member_1', {
+ id: 'member_1',
+ organizationId: 'org_1',
+ userId: 'user_1',
+ role: 'org:member',
+ email: '[email protected]',
+ projectScope: 'all',
+ });
+ inviteStore.set('invite_1', {
+ id: 'invite_1',
+ email: '[email protected]',
+ organizationId: 'org_1',
+ role: 'org:member',
+ createdById: 'user_admin',
+ projectScope: 'selected',
+ projectAccess: [],
+ expiresAt: new Date(Date.now() + 60_000),
+ createdAt: EPOCH,
+ });
+
+ await subject.connectUserToOrganization(deps, {
+ user: { id: 'user_1', email: '[email protected]' } as never,
+ inviteId: 'invite_1',
+ });
+
+ expect(memberStore.get('member_1')?.projectScope).toBe('all');
+ expect(memberProjectStore).toHaveLength(0);
+ expect(inviteStore.has('invite_1')).toBe(false);
+});
+
+// Invites from before the scope column, or from the previous image during a
+// rolling deploy, default to `all` and carry the restriction only in grants.
+test('connectUserToOrganization treats an invite with grants as selected whatever its stored scope', async () => {
+ projectStore.set('proj_1', {
+ id: 'proj_1',
+ organizationId: 'org_1',
+ deleteAt: null,
+ });
+ inviteStore.set('invite_1', {
+ id: 'invite_1',
+ email: '[email protected]',
+ organizationId: 'org_1',
+ role: 'org:member',
+ createdById: 'user_admin',
+ projectScope: 'all',
+ projectAccess: [{ projectId: 'proj_1', level: 'write' }],
+ expiresAt: new Date(Date.now() + 60_000),
+ createdAt: EPOCH,
+ });
+
+ const created = await subject.connectUserToOrganization(deps, {
+ user: { id: 'user_1', email: '[email protected]' } as never,
+ inviteId: 'invite_1',
+ });
+
+ expect(memberStore.get(created.id)?.projectScope).toBe('selected');
+ expect(memberProjectStore).toEqual([
+ { memberId: created.id, projectId: 'proj_1', level: null },
+ ]);
+});
+
+test('connectUserToOrganization writes the invite grants to both tables, keeping only read as a level', async () => {
+ projectStore.set('proj_1', {
+ id: 'proj_1',
+ organizationId: 'org_1',
+ deleteAt: null,
+ });
+ projectStore.set('proj_2', {
+ id: 'proj_2',
+ organizationId: 'org_1',
+ deleteAt: null,
+ });
+ inviteStore.set('invite_1', {
+ id: 'invite_1',
+ email: '[email protected]',
+ organizationId: 'org_1',
+ role: 'org:member',
+ createdById: 'user_admin',
+ projectScope: 'selected',
+ projectAccess: [
+ { projectId: 'proj_1', level: 'read' },
+ { projectId: 'proj_2', level: 'write' },
+ ],
+ expiresAt: new Date(Date.now() + 60_000),
+ createdAt: EPOCH,
+ });
+
+ const member = await subject.connectUserToOrganization(deps, {
+ user: { id: 'user_1', email: '[email protected]' } as never,
+ inviteId: 'invite_1',
+ });
+
+ expect(member.projectScope).toBe('selected');
+ expect(memberProjectStore).toEqual([
+ { memberId: member.id, projectId: 'proj_1', level: 'read' },
+ { memberId: member.id, projectId: 'proj_2', level: null },
+ ]);
+ expect(
+ [...projectAccessStore.values()].map((row) => [row.projectId, row.level])
+ ).toEqual([
+ ['proj_1', 'read'],
+ ['proj_2', 'write'],
+ ]);
});
// Guards: access rows must not be written for a user never confirmed as a
@@ -718,6 +955,7 @@ test('updateOrganizationMemberAccess refuses a user who is not a member', async
subject.updateOrganizationMemberAccess(deps, {
organizationId: 'org_1',
targetUserId: 'not_a_member',
+ projectScope: 'selected',
access: [{ projectId: 'proj_new', level: 'write' }],
})
).rejects.toThrow(/not a member/i);
@@ -743,6 +981,7 @@ test('updateOrganizationMemberAccess refuses a project from another organization
subject.updateOrganizationMemberAccess(deps, {
organizationId: 'org_1',
targetUserId: 'user_1',
+ projectScope: 'selected',
access: [{ projectId: 'proj_elsewhere', level: 'write' }],
})
).rejects.toThrow(/not in this organization/i);
@@ -764,7 +1003,8 @@ test('inviteUserToOrganization refuses when the email is already a member', asyn
subject.inviteUserToOrganization(deps, {
organizationId: 'org_1',
- role: 'org:member',
+ role: 'member',
+ projectScope: 'all',
access: [],
invitedById: 'user_admin',
})
@@ -787,7 +1027,8 @@ test('inviteUserToOrganization refuses a duplicate pending invite', async () =>
subject.inviteUserToOrganization(deps, {
organizationId: 'org_1',
- role: 'org:member',
+ role: 'member',
+ projectScope: 'all',
access: [],
invitedById: 'user_admin',
})
@@ -800,7 +1041,8 @@ test('inviteUserToOrganization connects an existing user immediately, with no em
const result = await subject.inviteUserToOrganization(deps, {
organizationId: 'org_1',
- role: 'org:member',
+ role: 'member',
+ projectScope: 'all',
access: [],
invitedById: 'user_admin',
});
@@ -813,7 +1055,8 @@ test('inviteUserToOrganization emails a new user and leaves the invite pending',
const result = await subject.inviteUserToOrganization(deps, {
organizationId: 'org_1',
- role: 'org:member',
+ role: 'member',
+ projectScope: 'all',
access: [],
invitedById: 'user_admin',
});
diff --git a/packages/core/src/modules/organization/organization.service.ts b/packages/core/src/modules/organization/organization.service.ts
index 98cbe4b64..9ec13cc26 100644
--- a/packages/core/src/modules/organization/organization.service.ts
+++ b/packages/core/src/modules/organization/organization.service.ts
@@ -3,9 +3,9 @@
import { sql } from '@openpanel/db/src/clickhouse/sql';
import type {
+ AccessLevel,
Invite,
Prisma,
- ProjectAccess,
User,
} from '@openpanel/db/src/prisma-client';
import { DateTime, generateSecureId } from '@openpanel/shared';
@@ -19,21 +19,37 @@ import { sendEmail } from '../../clients/email';
import { TRPCBadRequestError, TRPCNotFoundError } from '../../rpc/errors';
import type { ServiceDeps, Services } from '../../services';
import {
+ effectiveProjectGrants,
getOrganizationAccess,
getProjectAccess,
} from '../../shared/access-lookups';
import { formatClickhouseDate } from '../../shared/ch-dates';
import { replicatedTarget, TABLE_NAMES } from '../../shared/ch-tables';
-import { DEFAULT_TIMEZONE, isValidTimezone } from './organization.constants';
+import {
+ DEFAULT_TIMEZONE,
+ type InvitableRole,
+ type IProjectAccessGrant,
+ isValidTimezone,
+ normalizeOrganizationRole,
+ type OrganizationRole,
+ type ProjectScope,
+ resolveOrganizationRole,
+ STORED_ADMIN_ROLES,
+ toStoredOrganizationRole,
+} from './organization.constants';
export type IServiceOrganization = Awaited<
ReturnType<typeof getOrganizationById>
>;
-export type IServiceInvite = Invite;
-export type IServiceMember = Prisma.MemberGetPayload<{
- include: { user: true };
-}> & { access: ProjectAccess[] };
-export type IServiceProjectAccess = ProjectAccess;
+export type IServiceInvite = Omit<Invite, 'role'> & { role: OrganizationRole };
+export type IServiceMember = Omit<
+ Prisma.MemberGetPayload<{ include: { user: true } }>,
+ 'role' | 'projectScope'
+> & {
+ role: OrganizationRole;
+ projectScope: ProjectScope;
+ projects: { projectId: string; level: AccessLevel | null }[];
+};
// Session bookkeeping rows are worker-generated (the reaper can emit
// session_end long after tracking stopped), so they are not billable activity.
@@ -114,9 +130,9 @@ export const getOrganizationByProjectIdCached = cacheablePerDb(
export async function getInvites(
deps: ServiceDeps,
organizationId: string
-): Promise<Invite[]> {
+): Promise<IServiceInvite[]> {
const db = deps.db;
- return db.invite.findMany({
+ const invites = await db.invite.findMany({
where: {
organizationId,
},
@@ -124,6 +140,10 @@ export async function getInvites(
createdAt: 'desc',
},
});
+ return invites.map((invite) => ({
+ ...invite,
+ role: normalizeOrganizationRole(invite.role),
+ }));
}
export async function getInviteById(deps: ServiceDeps, inviteId: string) {
@@ -159,7 +179,7 @@ export async function getMembers(
organizationId: string
): Promise<IServiceMember[]> {
const db = deps.db;
- const [members, access] = await Promise.all([
+ const [members, legacyGrants] = await Promise.all([
db.member.findMany({
where: {
organizationId,
@@ -169,19 +189,70 @@ export async function getMembers(
},
include: {
user: true,
+ projects: { select: { projectId: true, level: true } },
+ organization: { select: { createdByUserId: true } },
},
}),
db.projectAccess.findMany({
- where: {
- organizationId,
- },
+ where: { organizationId },
+ select: { userId: true, projectId: true, level: true },
}),
]);
- return members.map((member) => ({
+ // The same projection the access lookup applies, so the edit modal never
+ // starts from "all projects" for a member an old pod restricted.
+ return members.map(({ organization, ...member }) => ({
...member,
- access: access.filter((a) => a.userId === member.userId),
- })) as IServiceMember[];
+ ...effectiveProjectGrants({
+ projectScope: member.projectScope,
+ projects: member.projects,
+ legacyGrants: legacyGrants.filter(
+ (grant) => grant.userId === member.userId
+ ),
+ }),
+ role: resolveOrganizationRole({ ...member, organization }),
+ }));
+}
+
+/**
+ * Write a member's project grants to both tables. `project_access` is the
+ * previous build's source of truth and is kept in step for one more build so
+ * a rollback changes nobody's access; the next build drops it.
+ */
+function writeMemberProjects(
+ deps: ServiceDeps,
+ member: { id: string; userId: string; organizationId: string },
+ projectScope: ProjectScope,
+ grants: IProjectAccessGrant[]
+) {
+ const db = deps.db;
+ const selected = projectScope === 'all' ? [] : grants;
+ return [
+ db.member.update({
+ where: { id: member.id },
+ data: { projectScope },
+ }),
+ db.memberProject.deleteMany({ where: { memberId: member.id } }),
+ db.memberProject.createMany({
+ data: selected.map((grant) => ({
+ memberId: member.id,
+ projectId: grant.projectId,
+ // Write is what the role gives; only a restriction is worth storing.
+ level: grant.level === 'read' ? 'read' : null,
+ })),
+ }),
+ db.projectAccess.deleteMany({
+ where: { userId: member.userId, organizationId: member.organizationId },
+ }),
+ db.projectAccess.createMany({
+ data: selected.map((grant) => ({
+ userId: member.userId,
+ organizationId: member.organizationId,
+ projectId: grant.projectId,
+ level: grant.level,
+ })),
+ }),
+ ];
}
/**
@@ -239,11 +310,25 @@ export async function connectUserToOrganization(
throw new Error('Invite expired');
}
+ // Invites written before the scope column, or by the previous image during
+ // a rolling deploy, carry their restriction only in `projectAccess`.
+ const projectScope: ProjectScope =
+ invite.projectAccess.length > 0 ? 'selected' : invite.projectScope;
+
+ const existing = await db.member.findUnique({
+ where: {
+ organizationId_userId: {
+ organizationId: invite.organizationId,
+ userId: user.id,
+ },
+ },
+ });
+
// The invite might be consumed by a user who is already a member of the
// organization (e.g. accepting it a second time). Upsert atomically against
// the (organizationId, userId) unique constraint so concurrent consumption
// cannot create duplicate membership rows; an existing membership is reused
- // unchanged and the invite is still consumed below.
+ // unchanged, grants included, and the invite is still consumed below.
const member = await db.member.upsert({
where: {
organizationId_userId: {
@@ -258,19 +343,23 @@ export async function connectUserToOrganization(
role: invite.role,
email: user.email,
invitedById: invite.createdById,
+ projectScope,
},
});
- for (const grant of invite.projectAccess) {
- await db.projectAccess.create({
- data: {
- projectId: grant.projectId,
- userId: user.id,
- organizationId: invite.organizationId,
- // The level the inviting admin chose, not a hardcoded default.
- level: grant.level,
- },
- });
+ if (!existing) {
+ await db.$transaction(
+ writeMemberProjects(
+ deps,
+ {
+ id: member.id,
+ userId: user.id,
+ organizationId: invite.organizationId,
+ },
+ projectScope,
+ invite.projectAccess
+ )
+ );
}
await clearMemberAccessCache(deps, {
@@ -583,7 +672,7 @@ export async function runDeleteCron(
where: {
OR: [
{ deleteAt: { lte: now } },
- { members: { none: { role: 'org:admin' } } },
+ { members: { none: { role: { in: [...STORED_ADMIN_ROLES] } } } },
],
},
include: { projects: { select: { id: true } } },
@@ -727,8 +816,9 @@ export async function inviteUserToOrganization(
input: {
organizationId: string;
email: string;
- role: 'org:admin' | 'org:member';
- access: { projectId: string; level: 'read' | 'write' }[];
+ role: InvitableRole;
+ projectScope: ProjectScope;
+ access: IProjectAccessGrant[];
invitedById: string;
}
): Promise<InviteUserResult> {
@@ -769,20 +859,18 @@ export async function inviteUserToOrganization(
);
}
- await assertProjectsInOrganization(
- deps,
- input.organizationId,
- input.access ?? []
- );
+ const access = input.projectScope === 'all' ? [] : input.access;
+ await assertProjectsInOrganization(deps, input.organizationId, access);
const invite = await db.invite.create({
data: {
id: generateSecureId('invite'),
email,
organizationId: input.organizationId,
- role: input.role,
+ role: toStoredOrganizationRole(input.role),
createdById: input.invitedById,
- projectAccess: input.access ?? [],
+ projectScope: input.projectScope,
+ projectAccess: access,
expiresAt: new Date(Date.now() + INVITE_EXPIRY_MS),
},
include: {
@@ -918,9 +1006,10 @@ export async function updateOrganizationMemberAccess(
input: {
organizationId: string;
targetUserId: string;
- access: { projectId: string; level: 'read' | 'write' }[];
+ projectScope: ProjectScope;
+ access: IProjectAccessGrant[];
}
-) {
+): Promise<void> {
const db = deps.db;
// The rows below are keyed on a user this never confirmed was a member, so
@@ -935,31 +1024,25 @@ export async function updateOrganizationMemberAccess(
if (!member) {
throw new TRPCNotFoundError('User is not a member of this organization');
}
- await assertProjectsInOrganization(deps, input.organizationId, input.access);
+ const access = input.projectScope === 'all' ? [] : input.access;
+ await assertProjectsInOrganization(deps, input.organizationId, access);
- const result = await db.$transaction([
- db.projectAccess.deleteMany({
- where: {
+ await db.$transaction(
+ writeMemberProjects(
+ deps,
+ {
+ id: member.id,
userId: input.targetUserId,
organizationId: input.organizationId,
},
- }),
- db.projectAccess.createMany({
- // The level the admin chose; a hardcoded 'read' hid that nothing enforced
- // levels (GHSA-f9rx-pxgw-c6rg).
- data: input.access.map((grant) => ({
- userId: input.targetUserId,
- organizationId: input.organizationId,
- projectId: grant.projectId,
- level: grant.level,
- })),
- }),
- ]);
+ input.projectScope,
+ access
+ )
+ );
await clearMemberAccessCache(deps, {
userId: input.targetUserId,
organizationId: input.organizationId,
});
- return result;
}
export function createOrganizationService(
@@ -993,11 +1076,10 @@ export function createOrganizationService(
): Promise<void> => removeOrganizationMember(deps, input),
updateMemberAccess: (
input: Parameters<typeof updateOrganizationMemberAccess>[1]
- ): ReturnType<typeof updateOrganizationMemberAccess> =>
- updateOrganizationMemberAccess(deps, input),
+ ): Promise<void> => updateOrganizationMemberAccess(deps, input),
members: (organizationId: string): Promise<IServiceMember[]> =>
getMembers(deps, organizationId),
- invitations: (organizationId: string): Promise<Invite[]> =>
+ invitations: (organizationId: string): Promise<IServiceInvite[]> =>
getInvites(deps, organizationId),
getInvite: (inviteId: string): ReturnType<typeof getInviteById> =>
getInviteById(deps, inviteId),
diff --git a/packages/core/src/modules/project/project.rpc.ts b/packages/core/src/modules/project/project.rpc.ts
index 30fbf5485..27b558df5 100644
--- a/packages/core/src/modules/project/project.rpc.ts
+++ b/packages/core/src/modules/project/project.rpc.ts
@@ -88,17 +88,12 @@ export const projectRouter = createTRPCRouter({
throw new TRPCForbiddenError('Organization is required');
}
- const access = await ctx.services.auth.getOrganizationAccess({
+ await ctx.services.auth.requireOrganizationAdmin({
userId,
organizationId: input.organizationId,
+ message: 'Only organization admins can create projects',
});
- if (access?.role !== 'org:admin') {
- throw new TRPCForbiddenError(
- 'Only organization admins can create projects'
- );
- }
-
const { project, client } =
await ctx.services.project.createProjectForOrganization(
input.organizationId,
diff --git a/packages/core/src/modules/project/project.service.ts b/packages/core/src/modules/project/project.service.ts
index 153ae7e2f..9e864ede9 100644
--- a/packages/core/src/modules/project/project.service.ts
+++ b/packages/core/src/modules/project/project.service.ts
@@ -10,6 +10,7 @@ import { cacheablePerDb, type DbScope } from '../../cacheable-per-deps';
import { chQuery } from '../../ch-query';
import { TRPCBadRequestError } from '../../rpc/errors';
import type { ServiceDeps, Services } from '../../services';
+import { getMemberProjectGrants } from '../../shared/access-lookups';
import { convertClickhouseDateToJs } from '../../shared/ch-dates';
import { TABLE_NAMES } from '../../shared/ch-tables';
import { hashClientSecret } from '../../shared/client-secret';
@@ -86,7 +87,7 @@ export async function getProjects(
return [];
}
- const [projects, members, access] = await Promise.all([
+ const [projects, member] = await Promise.all([
deps.db.project.findMany({
where: {
organizationId,
@@ -95,31 +96,19 @@ export async function getProjects(
eventsCount: 'desc',
},
}),
- deps.db.member.findMany({
- where: {
- userId,
- organizationId,
- },
- }),
- deps.db.projectAccess.findMany({
- where: {
- userId,
- organizationId,
- },
- }),
+ getMemberProjectGrants(deps.db, { userId, organizationId }),
]);
- if (members.length === 0) {
+ if (!member) {
return [];
}
- if (access.length > 0) {
- return projects.filter((project) =>
- access.some((a) => a.projectId === project.id)
- );
+ if (member.projectScope === 'all') {
+ return projects;
}
- return projects;
+ const selected = new Set(member.projects.map((row) => row.projectId));
+ return projects.filter((project) => selected.has(project.id));
}
/**
diff --git a/packages/core/src/modules/realtime/realtime.routes.test.ts b/packages/core/src/modules/realtime/realtime.routes.test.ts
index 5c780fde3..35d55f496 100644
--- a/packages/core/src/modules/realtime/realtime.routes.test.ts
+++ b/packages/core/src/modules/realtime/realtime.routes.test.ts
@@ -63,7 +63,11 @@ afterAll(() => {
// `ctx.services.auth` binds these lookups, so mocking them makes
// `getProjectAccess`/`getOrganizationAccess` observable from the test.
let projectAccess: { level: string } | null = null;
-let organizationAccess: { role: string } | null = null;
+let organizationAccess: {
+ role: string;
+ userId: string;
+ organization: { createdByUserId: string | null };
+} | null = null;
const getProjectAccess = mock(async () => projectAccess);
const getOrganizationAccess = mock(async () => organizationAccess);
mock.module('../../shared/access-lookups', () => ({
@@ -289,7 +293,11 @@ test('wsOrganizationEvents: session but no org access -> "No access" then close'
// receive other organizations' ids (the filter itself is asserted in realtime.service.test.ts).
test('wsOrganizationEvents: subscribes scoped to the organization the caller is a member of', async () => {
session = { userId: 'user_1' };
- organizationAccess = { role: 'org:member' };
+ organizationAccess = {
+ role: 'org:member',
+ userId: 'user_1',
+ organization: { createdByUserId: null },
+ };
const { ws } = await connect('/live/organization/org_1');
diff --git a/packages/core/src/modules/session/src/usage.ts b/packages/core/src/modules/session/src/usage.ts
index 7299e7d20..0cc98a5c2 100644
--- a/packages/core/src/modules/session/src/usage.ts
+++ b/packages/core/src/modules/session/src/usage.ts
@@ -6,6 +6,7 @@ import type { Organization } from '@openpanel/db/src/prisma-client';
import { cacheablePerDeps } from '../../../cacheable-per-deps';
import { sendEmail } from '../../../clients/email';
import type { ServiceDeps } from '../../../services';
+import { STORED_ADMIN_ROLES } from '../../organization/organization.constants';
import { getOrganizationBillingEventsCount } from '../../organization/organization.service';
import { getProjectEventsCount } from '../../project/project.service';
@@ -148,7 +149,7 @@ async function sendUsageAlerts(
const admins = await db.member.findMany({
where: {
organizationId: organization.id,
- role: 'org:admin',
+ role: { in: [...STORED_ADMIN_ROLES] },
user: { deletedAt: null },
},
include: { user: { select: { email: true, firstName: true } } },
diff --git a/packages/core/src/modules/user/user.service.ts b/packages/core/src/modules/user/user.service.ts
index 17b1953fe..e7e7c9b03 100644
--- a/packages/core/src/modules/user/user.service.ts
+++ b/packages/core/src/modules/user/user.service.ts
@@ -86,7 +86,7 @@ export async function listUserDeletionBlockers(
* Hard delete the user. Cascades clean up sessions, accounts, totp,
* twoFactorChallenges, members, projectAccess, invites and conversations.
* Organizations the user created have `createdByUserId`/`subscriptionCreatedByUserId`
- * set to null (SetNull); any org left without an org:admin member is then
+ * set to null (SetNull); any org left without an admin member is then
* removed by the organization module's `delete` cron.
*/
export async function deleteUserAccount(
diff --git a/packages/core/src/shared/access-lookups.test.ts b/packages/core/src/shared/access-lookups.test.ts
new file mode 100644
index 000000000..ef08be7e1
--- /dev/null
+++ b/packages/core/src/shared/access-lookups.test.ts
@@ -0,0 +1,157 @@
+// The scope rule replaced "no rows means every project". Every verdict the
+// old rule gave is re-derived here from the shape the migration writes, so a
+// change to either side shows up as a diff rather than as a surprised member.
+
+import { expect, test } from 'bun:test';
+import { effectiveProjectGrants, resolveProjectAccess } from './access-lookups';
+
+test('scope all follows the role: write for members and admins, read for viewers', () => {
+ for (const role of ['org:admin', 'org:member', 'admin', 'member', 'owner']) {
+ expect(
+ resolveProjectAccess({ role, projectScope: 'all', grant: null })
+ ).toEqual({ level: 'write' });
+ }
+ expect(
+ resolveProjectAccess({ role: 'viewer', projectScope: 'all', grant: null })
+ ).toEqual({ level: 'read' });
+});
+
+test('scope selected without a row is no access, whatever the role', () => {
+ for (const role of ['org:admin', 'owner', 'member', 'viewer']) {
+ expect(
+ resolveProjectAccess({ role, projectScope: 'selected', grant: null })
+ ).toBeNull();
+ }
+});
+
+test('a selected row derives write from the role unless it restricts to read', () => {
+ expect(
+ resolveProjectAccess({
+ role: 'org:member',
+ projectScope: 'selected',
+ grant: { level: null },
+ })
+ ).toEqual({ level: 'write' });
+ expect(
+ resolveProjectAccess({
+ role: 'org:member',
+ projectScope: 'selected',
+ grant: { level: 'read' },
+ })
+ ).toEqual({ level: 'read' });
+});
+
+test('a viewer never gets more than read from a row', () => {
+ expect(
+ resolveProjectAccess({
+ role: 'viewer',
+ projectScope: 'selected',
+ grant: { level: 'write' },
+ })
+ ).toEqual({ level: 'read' });
+});
+
+// What the previous build answered, spelled out so the migration's mapping
+// (no rows → all; rows → selected, read kept, write/admin → null) is checked
+// against it rather than assumed.
+function legacyProjectAccess(
+ rows: { projectId: string; level: 'read' | 'write' | 'admin' }[],
+ projectId: string
+) {
+ if (rows.length === 0) {
+ return { level: 'write' as const };
+ }
+ const row = rows.find((item) => item.projectId === projectId);
+ return row ? { level: row.level } : null;
+}
+
+function migrated(
+ rows: { projectId: string; level: 'read' | 'write' | 'admin' }[],
+ projectId: string
+) {
+ const grant = rows.find((item) => item.projectId === projectId);
+ return resolveProjectAccess({
+ role: 'org:member',
+ projectScope: rows.length === 0 ? 'all' : 'selected',
+ grant: grant ? { level: grant.level === 'read' ? 'read' : null } : null,
+ });
+}
+
+test('the migrated shape gives the same verdict as the legacy rule for every row shape', () => {
+ const fixtures: { projectId: string; level: 'read' | 'write' | 'admin' }[][] =
+ [
+ [],
+ [{ projectId: 'a', level: 'write' }],
+ [{ projectId: 'a', level: 'read' }],
+ [{ projectId: 'a', level: 'admin' }],
+ [
+ { projectId: 'a', level: 'read' },
+ { projectId: 'b', level: 'write' },
+ ],
+ ];
+ for (const rows of fixtures) {
+ for (const projectId of ['a', 'b', 'c']) {
+ const legacy = legacyProjectAccess(rows, projectId);
+ const current = migrated(rows, projectId);
+ // `admin` collapses to write: the ladder already treats them alike.
+ const expected =
+ legacy?.level === 'admin' ? { level: 'write' as const } : legacy;
+ expect(current).toEqual(expected);
+ }
+ }
+});
+
+test('legacy rows written by the previous image override a stale all scope', () => {
+ expect(
+ effectiveProjectGrants({
+ projectScope: 'all',
+ projects: [],
+ legacyGrants: [
+ { projectId: 'a', level: 'read' },
+ { projectId: 'b', level: 'write' },
+ ],
+ })
+ ).toEqual({
+ projectScope: 'selected',
+ projects: [
+ { projectId: 'a', level: 'read' },
+ { projectId: 'b', level: null },
+ ],
+ });
+});
+
+test('without legacy rows the member scope and rows apply as stored', () => {
+ const member = {
+ projectScope: 'selected' as const,
+ projects: [{ projectId: 'a', level: null }],
+ legacyGrants: [],
+ };
+ expect(effectiveProjectGrants(member)).toEqual({
+ projectScope: 'selected',
+ projects: [{ projectId: 'a', level: null }],
+ });
+});
+
+test('duplicate legacy rows for one project keep the read restriction', () => {
+ for (const legacyGrants of [
+ [
+ { projectId: 'a', level: 'write' as const },
+ { projectId: 'a', level: 'read' as const },
+ ],
+ [
+ { projectId: 'a', level: 'read' as const },
+ { projectId: 'a', level: 'admin' as const },
+ ],
+ ]) {
+ expect(
+ effectiveProjectGrants({
+ projectScope: 'all',
+ projects: [],
+ legacyGrants,
+ })
+ ).toEqual({
+ projectScope: 'selected',
+ projects: [{ projectId: 'a', level: 'read' }],
+ });
+ }
+});
diff --git a/packages/core/src/shared/access-lookups.ts b/packages/core/src/shared/access-lookups.ts
index e57fee254..5c6a2e1a0 100644
--- a/packages/core/src/shared/access-lookups.ts
+++ b/packages/core/src/shared/access-lookups.ts
@@ -5,8 +5,13 @@
//
// `getProjectById` is spelled here because `shared/` sits below `modules/`.
-import type { AccessLevel } from '@openpanel/db/src/prisma-client';
+import type {
+ AccessLevel,
+ Member,
+ ProjectScope,
+} from '@openpanel/db/src/prisma-client';
import { cacheable } from '@openpanel/redis';
+import type { Db } from '../context';
// Lazy: `context.ts` value-imports `services.ts`, and a static import would
// drag the whole services graph into everything that reaches this file.
@@ -36,6 +41,99 @@ export function canWriteProject(access: IProjectAccess | null): boolean {
return !!access && WRITE_LEVELS.has(access.level);
}
+/** The one role that only reads. Spelled here so `shared/` carries no other role vocabulary. */
+const READ_ONLY_ROLE = 'viewer';
+
+/**
+ * The project access rule, pure so tests and the access snapshot can run it
+ * without a database. `all` follows every project of the organization;
+ * `selected` means the member's rows and nothing else. A row's `level` only
+ * ever restricts below what the role gives.
+ */
+export function resolveProjectAccess(member: {
+ role: string;
+ projectScope: ProjectScope;
+ grant: { level: AccessLevel | null } | null;
+}): IProjectAccess | null {
+ const roleLevel: AccessLevel =
+ member.role === READ_ONLY_ROLE ? 'read' : 'write';
+ if (member.projectScope === 'all') {
+ return { level: roleLevel };
+ }
+ if (!member.grant) {
+ return null;
+ }
+ if (roleLevel === 'read') {
+ return { level: 'read' };
+ }
+ return { level: member.grant.level ?? roleLevel };
+}
+
+interface MemberGrant {
+ projectId: string;
+ level: AccessLevel | null;
+}
+
+/**
+ * The scope and grants to apply for a member while `project_access` is still
+ * written. New code keeps that table identical to `member_projects` (empty for
+ * `all`), so legacy rows only differ when the previous image wrote them during
+ * a rolling deploy; they then win, or an old pod restricting a member would
+ * leave them on `all`. Remove with `project_access`.
+ */
+export function effectiveProjectGrants(member: {
+ projectScope: ProjectScope;
+ projects: MemberGrant[];
+ legacyGrants: { projectId: string; level: AccessLevel }[];
+}): { projectScope: ProjectScope; projects: MemberGrant[] } {
+ if (member.legacyGrants.length === 0) {
+ return { projectScope: member.projectScope, projects: member.projects };
+ }
+ // project_access has no unique key; a read row among duplicates wins.
+ const levels = new Map<string, AccessLevel | null>();
+ for (const grant of member.legacyGrants) {
+ const isRead =
+ grant.level === 'read' || levels.get(grant.projectId) === 'read';
+ levels.set(grant.projectId, isRead ? 'read' : null);
+ }
+ return {
+ projectScope: 'selected',
+ projects: [...levels].map(([projectId, level]) => ({ projectId, level })),
+ };
+}
+
+/** Loads what `effectiveProjectGrants` needs for one membership, or null when there is none. */
+export async function getMemberProjectGrants(
+ db: Db,
+ { userId, organizationId }: { userId: string; organizationId: string }
+): Promise<{
+ role: string;
+ projectScope: ProjectScope;
+ projects: MemberGrant[];
+} | null> {
+ const [member, legacyGrants] = await Promise.all([
+ db.member.findFirst({
+ where: { organizationId, userId },
+ select: {
+ role: true,
+ projectScope: true,
+ projects: { select: { projectId: true, level: true } },
+ },
+ }),
+ db.projectAccess.findMany({
+ where: { organizationId, userId },
+ select: { projectId: true, level: true },
+ }),
+ ]);
+ if (!member) {
+ return null;
+ }
+ return {
+ role: member.role,
+ ...effectiveProjectGrants({ ...member, legacyGrants }),
+ };
+}
+
/**
* Resolve a user's access to one project.
*
@@ -44,11 +142,12 @@ export function canWriteProject(access: IProjectAccess | null): boolean {
* and 26 of 29 mutating procedures skipped the level check (GHSA-f9rx-pxgw-c6rg).
* With one shape, omitting the check is a type error.
*
- * The cache key is versioned: changing the return shape without renaming it
- * would serve old-shape entries for up to 5 minutes across a rolling deploy.
+ * The cache key is versioned: changing the rule or the return shape without
+ * renaming it would serve old entries for up to 5 minutes across a rolling
+ * deploy.
*/
export const getProjectAccess = cacheable(
- 'getProjectAccessV2',
+ 'getProjectAccessV3',
async ({
userId,
projectId,
@@ -62,35 +161,21 @@ export const getProjectAccess = cacheable(
return null;
}
- const db = await unscopedDb();
- const [projectAccess, member] = await Promise.all([
- db.projectAccess.findMany({
- where: {
- userId,
- organizationId: project.organizationId,
- },
- }),
- db.member.findFirst({
- where: {
- organizationId: project.organizationId,
- userId,
- },
- }),
- ]);
+ const member = await getMemberProjectGrants(await unscopedDb(), {
+ userId,
+ organizationId: project.organizationId,
+ });
if (!member) {
return null;
}
- // No explicit per-project grants means org-wide default access, and the
- // default is write.
- if (projectAccess.length === 0) {
- return { level: 'write' };
- }
-
- const row = projectAccess.find((item) => item.projectId === projectId);
-
- return row ? { level: row.level } : null;
+ return resolveProjectAccess({
+ role: member.role,
+ projectScope: member.projectScope,
+ grant:
+ member.projects.find((row) => row.projectId === projectId) ?? null,
+ });
} catch (_err) {
return null;
}
@@ -98,21 +183,27 @@ export const getProjectAccess = cacheable(
60 * 5
);
+/** The membership row plus what the auth module needs to derive the owner role. */
+export type IOrganizationAccess = Member & {
+ organization: { createdByUserId: string | null };
+};
+
export const getOrganizationAccess = cacheable(
- 'getOrganizationAccess',
+ 'getOrganizationAccessV2',
async ({
userId,
organizationId,
}: {
userId: string;
organizationId: string;
- }) => {
+ }): Promise<IOrganizationAccess | null> => {
const db = await unscopedDb();
return db.member.findFirst({
where: {
userId,
organizationId,
},
+ include: { organization: { select: { createdByUserId: true } } },
});
},
60 * 5
diff --git a/packages/db/package.json b/packages/db/package.json
index 31badef46..70141a9bd 100644
--- a/packages/db/package.json
+++ b/packages/db/package.json
@@ -11,6 +11,7 @@
"migrate:deploy:db": "bun run with-env prisma migrate deploy",
"migrate:deploy": "bun run migrate:deploy:db && bun run migrate:deploy:code",
"duplicate-events": "bun run with-env bun ./scripts/find-duplicate-events.ts",
+ "access-snapshot": "bun run with-env bun ./scripts/access-snapshot.ts",
"test": "bun test --isolate",
"typecheck": "tsc --noEmit",
"with-env": "dotenv -e ../../.env -c --"
diff --git a/packages/db/prisma/migrations/20261017150000_member_project_scope/migration.sql b/packages/db/prisma/migrations/20261017150000_member_project_scope/migration.sql
new file mode 100644
index 000000000..78a05c240
--- /dev/null
+++ b/packages/db/prisma/migrations/20261017150000_member_project_scope/migration.sql
@@ -0,0 +1,34 @@
+-- CreateEnum
+CREATE TYPE "public"."ProjectScope" AS ENUM ('all', 'selected');
+
+-- AlterTable
+ALTER TABLE "public"."invites" ADD COLUMN "projectScope" "public"."ProjectScope" NOT NULL DEFAULT 'all';
+
+-- AlterTable
+ALTER TABLE "public"."members" ADD COLUMN "projectScope" "public"."ProjectScope" NOT NULL DEFAULT 'all';
+
+-- AlterTable
+ALTER TABLE "public"."organizations" ADD COLUMN "slug" TEXT;
+
+-- CreateTable
+CREATE TABLE "public"."member_projects" (
+ "memberId" UUID NOT NULL,
+ "projectId" TEXT NOT NULL,
+ "level" "public"."AccessLevel",
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "member_projects_pkey" PRIMARY KEY ("memberId","projectId")
+);
+
+-- CreateIndex
+CREATE INDEX "member_projects_projectId_idx" ON "public"."member_projects"("projectId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "organizations_slug_key" ON "public"."organizations"("slug");
+
+-- AddForeignKey
+ALTER TABLE "public"."member_projects" ADD CONSTRAINT "member_projects_memberId_fkey" FOREIGN KEY ("memberId") REFERENCES "public"."members"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "public"."member_projects" ADD CONSTRAINT "member_projects_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES "public"."projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma
index 5e6e69a91..a4455cbbb 100644
--- a/packages/db/prisma/schema.prisma
+++ b/packages/db/prisma/schema.prisma
@@ -68,6 +68,8 @@ model ChatMessage {
model Organization {
id String @id @default(dbgenerated("gen_random_uuid()"))
name String
+ // Nullable until every row is backfilled; the organization plugin needs it.
+ slug String? @unique
projects Project[]
members Member[]
createdByUserId String?
@@ -219,24 +221,46 @@ model Session {
}
model Member {
- id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
+ id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
role String
email String
// userId is nullable because we want to allow invites to be sent to emails that are not registered
userId String?
- user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
+ user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
invitedById String?
- invitedBy User? @relation("invitedBy", fields: [invitedById], references: [id], onDelete: SetNull)
+ invitedBy User? @relation("invitedBy", fields: [invitedById], references: [id], onDelete: SetNull)
organizationId String
- organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
+ organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
+ // `all` follows projects created later; `selected` with no rows is no access.
+ projectScope ProjectScope @default(all)
+ projects MemberProject[]
meta Json?
- createdAt DateTime @default(now())
- updatedAt DateTime @default(now()) @updatedAt
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
@@unique([organizationId, userId])
@@map("members")
}
+enum ProjectScope {
+ all
+ selected
+}
+
+model MemberProject {
+ memberId String @db.Uuid
+ member Member @relation(fields: [memberId], references: [id], onDelete: Cascade)
+ projectId String
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ // Null derives the level from the role; set only to restrict below it.
+ level AccessLevel?
+ createdAt DateTime @default(now())
+
+ @@id([memberId, projectId])
+ @@index([projectId])
+ @@map("member_projects")
+}
+
model Invite {
id String @id
email String
@@ -246,6 +270,7 @@ model Invite {
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
/// [IPrismaInviteProjectAccess]
projectAccess Json @default("[]")
+ projectScope ProjectScope @default(all)
expiresAt DateTime
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
@@ -288,6 +313,7 @@ model Project {
customEvents CustomEvent[]
references Reference[]
access ProjectAccess[]
+ memberProjects MemberProject[]
notificationRules NotificationRule[]
notifications Notification[]
imports Import[]
diff --git a/packages/db/scripts/access-snapshot.ts b/packages/db/scripts/access-snapshot.ts
new file mode 100644
index 000000000..81899670e
--- /dev/null
+++ b/packages/db/scripts/access-snapshot.ts
@@ -0,0 +1,207 @@
+// Dumps what every member may do on every project of their organization, so a
+// data migration can be proven access-neutral: snapshot before, migrate,
+// snapshot after, diff.
+//
+// bun run --filter @openpanel/db access-snapshot --evaluator legacy > before.json
+// bun run --filter @openpanel/db access-snapshot --evaluator current > after.json
+// bun run --filter @openpanel/db access-snapshot --diff before.json after.json [--expect keys.json]
+//
+// `legacy` is the rule the previous build applied, spelled out here from its
+// tables (`project_access`, `members.role`), so it keeps answering after the
+// app has moved on. `current` goes through core's public lookups, the same
+// code every procedure calls, with each cache entry cleared first.
+//
+// Both tables are kept in step for one build, so both evaluators can run on
+// the same database and must agree.
+
+import {
+ canWriteProject,
+ getOrganizationAccess,
+ getProjectAccess,
+} from '@openpanel/core';
+import {
+ isOrganizationAdminRole,
+ resolveOrganizationRole,
+} from '@openpanel/core/modules/organization/organization.constants';
+import { db } from '../src/prisma-client';
+
+interface AccessLine {
+ organizationId: string;
+ userId: string;
+ projectId: string;
+ read: boolean;
+ write: boolean;
+ orgAdmin: boolean;
+}
+
+const LEGACY_ADMIN_ROLE = 'org:admin';
+const LEGACY_WRITE_LEVELS = new Set(['write', 'admin']);
+
+function lineKey(line: AccessLine): string {
+ return `${line.organizationId}|${line.userId}|${line.projectId}`;
+}
+
+function sortLines(lines: AccessLine[]): AccessLine[] {
+ return lines.sort((a, b) => lineKey(a).localeCompare(lineKey(b)));
+}
+
+async function loadMembers() {
+ return db.member.findMany({
+ where: { userId: { not: null } },
+ select: {
+ userId: true,
+ organizationId: true,
+ role: true,
+ organization: {
+ select: { projects: { select: { id: true } } },
+ },
+ },
+ });
+}
+
+async function legacySnapshot(): Promise<AccessLine[]> {
+ const [members, grants] = await Promise.all([
+ loadMembers(),
+ db.projectAccess.findMany({
+ select: {
+ userId: true,
+ organizationId: true,
+ projectId: true,
+ level: true,
+ },
+ }),
+ ]);
+ const grantsByMember = new Map<string, typeof grants>();
+ for (const grant of grants) {
+ const key = `${grant.organizationId}|${grant.userId}`;
+ grantsByMember.set(key, [...(grantsByMember.get(key) ?? []), grant]);
+ }
+
+ const lines: AccessLine[] = [];
+ for (const member of members) {
+ const userId = member.userId as string;
+ const rows = grantsByMember.get(`${member.organizationId}|${userId}`) ?? [];
+ const orgAdmin = member.role === LEGACY_ADMIN_ROLE;
+ for (const project of member.organization.projects) {
+ const row = rows.find((grant) => grant.projectId === project.id);
+ const level = rows.length === 0 ? 'write' : row?.level;
+ lines.push({
+ organizationId: member.organizationId,
+ userId,
+ projectId: project.id,
+ read: level !== undefined,
+ write: level !== undefined && LEGACY_WRITE_LEVELS.has(level),
+ orgAdmin,
+ });
+ }
+ }
+ return sortLines(lines);
+}
+
+async function currentSnapshot(): Promise<AccessLine[]> {
+ const members = await loadMembers();
+ const lines: AccessLine[] = [];
+ for (const member of members) {
+ const userId = member.userId as string;
+ const organizationId = member.organizationId;
+ await getOrganizationAccess.clear({ userId, organizationId });
+ const organizationAccess = await getOrganizationAccess({
+ userId,
+ organizationId,
+ });
+ const orgAdmin =
+ !!organizationAccess &&
+ isOrganizationAdminRole(resolveOrganizationRole(organizationAccess));
+ for (const project of member.organization.projects) {
+ await getProjectAccess.clear({ userId, projectId: project.id });
+ const access = await getProjectAccess({ userId, projectId: project.id });
+ lines.push({
+ organizationId,
+ userId,
+ projectId: project.id,
+ read: access !== null,
+ write: canWriteProject(access),
+ orgAdmin,
+ });
+ }
+ }
+ return sortLines(lines);
+}
+
+async function readLines(path: string): Promise<Map<string, AccessLine>> {
+ const lines = (await Bun.file(path).json()) as AccessLine[];
+ return new Map(lines.map((line) => [lineKey(line), line]));
+}
+
+async function diff(
+ beforePath: string,
+ afterPath: string,
+ expectPath: string | undefined
+): Promise<number> {
+ const [before, after] = await Promise.all([
+ readLines(beforePath),
+ readLines(afterPath),
+ ]);
+ const expected = new Set<string>(
+ expectPath ? ((await Bun.file(expectPath).json()) as string[]) : []
+ );
+
+ const differences: { key: string; text: string }[] = [];
+ for (const [key, line] of before) {
+ const other = after.get(key);
+ if (!other) {
+ differences.push({ key, text: `removed ${key}` });
+ continue;
+ }
+ const changed = (['read', 'write', 'orgAdmin'] as const).filter(
+ (field) => line[field] !== other[field]
+ );
+ if (changed.length > 0) {
+ const detail = changed
+ .map((field) => `${field}: ${line[field]} -> ${other[field]}`)
+ .join(', ');
+ differences.push({ key, text: `changed ${key} ${detail}` });
+ }
+ }
+ for (const key of after.keys()) {
+ if (!before.has(key)) {
+ differences.push({ key, text: `added ${key}` });
+ }
+ }
+
+ const unexpected = differences.filter(
+ (difference) => !expected.has(difference.key)
+ );
+ console.log(
+ `${before.size} lines before, ${after.size} after, ${differences.length} differences, ${unexpected.length} unexpected`
+ );
+ for (const difference of differences) {
+ console.log(difference.text);
+ }
+ return unexpected.length === 0 ? 0 : 1;
+}
+
+const args = process.argv.slice(2);
+const option = (name: string): string | undefined => {
+ const index = args.indexOf(name);
+ return index === -1 ? undefined : args[index + 1];
+};
+
+if (args.includes('--diff')) {
+ const index = args.indexOf('--diff');
+ const beforePath = args[index + 1];
+ const afterPath = args[index + 2];
+ if (!(beforePath && afterPath)) {
+ throw new Error('--diff needs two files');
+ }
+ process.exit(await diff(beforePath, afterPath, option('--expect')));
+}
+
+const evaluator = option('--evaluator') ?? 'current';
+if (evaluator !== 'legacy' && evaluator !== 'current') {
+ throw new Error(`Unknown evaluator: ${evaluator}`);
+}
+const lines =
+ evaluator === 'legacy' ? await legacySnapshot() : await currentSnapshot();
+console.log(JSON.stringify(lines, null, 2));
+process.exit(0);
diff --git a/packages/db/src/code-migrations/26-member-project-scope.ts b/packages/db/src/code-migrations/26-member-project-scope.ts
new file mode 100644
index 000000000..10aa6cc05
--- /dev/null
+++ b/packages/db/src/code-migrations/26-member-project-scope.ts
@@ -0,0 +1,154 @@
+import { db } from '../prisma-client';
+import { getIsDry, printBoxMessage } from './helpers';
+
+/**
+ * Give every member an explicit project scope.
+ *
+ * Before: a member with no `project_access` rows could reach every project,
+ * one with rows only those. After: `members.projectScope` says which, and
+ * `member_projects` lists the selected ones. Nothing is implied by absence.
+ *
+ * `project_access` is left in place and kept in sync by the app for one more
+ * build, so the previous image keeps working during the rolling deploy and
+ * a rollback needs no data change.
+ *
+ * Idempotent: scope is only ever moved towards `selected` where rows exist,
+ * and rows are inserted with ON CONFLICT DO NOTHING, so a rerun converges on
+ * the same state. Members already set to `selected` with no rows (restricted
+ * to nothing by the new UI) are not touched.
+ *
+ * Levels: `read` was a deliberate restriction and is kept. `write` and `admin`
+ * were the unenforced defaults, so they become NULL and derive from the role.
+ *
+ * Pending invites got the column default `all`; one with grants was
+ * restricted and becomes `selected`. `project_access` rows with no membership
+ * are reported and left alone: they never granted access, so making them
+ * memberships would.
+ */
+
+interface Count {
+ count: bigint;
+}
+
+async function countMembersToScope(): Promise<number> {
+ const rows = await db.$queryRaw<Count[]>`
+ SELECT COUNT(*) AS count
+ FROM members m
+ WHERE m."projectScope" = 'all'
+ AND EXISTS (
+ SELECT 1 FROM project_access pa
+ WHERE pa."userId" = m."userId"
+ AND pa."organizationId" = m."organizationId"
+ )
+ `;
+ return Number(rows[0]?.count ?? 0);
+}
+
+// Not async: `$transaction([...])` needs the PrismaPromise itself.
+function scopeMembers() {
+ return db.$executeRaw`
+ UPDATE members m
+ SET "projectScope" = 'selected'
+ WHERE m."projectScope" = 'all'
+ AND EXISTS (
+ SELECT 1 FROM project_access pa
+ WHERE pa."userId" = m."userId"
+ AND pa."organizationId" = m."organizationId"
+ )
+ `;
+}
+
+function copyGrants() {
+ return db.$executeRaw`
+ INSERT INTO member_projects ("memberId", "projectId", "level")
+ SELECT m.id, pa."projectId",
+ CASE WHEN bool_or(pa.level = 'read') THEN 'read'::"AccessLevel" END
+ FROM project_access pa
+ JOIN members m
+ ON m."userId" = pa."userId"
+ AND m."organizationId" = pa."organizationId"
+ -- project_access has no unique key; a read row among duplicates wins.
+ GROUP BY m.id, pa."projectId"
+ ON CONFLICT DO NOTHING
+ `;
+}
+
+async function countInvitesToScope(): Promise<number> {
+ const rows = await db.$queryRaw<Count[]>`
+ SELECT COUNT(*) AS count FROM invites
+ WHERE "projectScope" = 'all' AND jsonb_array_length("projectAccess") > 0
+ `;
+ return Number(rows[0]?.count ?? 0);
+}
+
+function scopeInvites() {
+ return db.$executeRaw`
+ UPDATE invites
+ SET "projectScope" = 'selected'
+ WHERE "projectScope" = 'all'
+ AND jsonb_array_length("projectAccess") > 0
+ `;
+}
+
+async function countGrantsWithoutMembership(): Promise<number> {
+ const rows = await db.$queryRaw<Count[]>`
+ SELECT COUNT(*) AS count
+ FROM project_access pa
+ WHERE NOT EXISTS (
+ SELECT 1 FROM members m
+ WHERE m."userId" = pa."userId"
+ AND m."organizationId" = pa."organizationId"
+ )
+ `;
+ return Number(rows[0]?.count ?? 0);
+}
+
+async function countOrganizationsWithoutSlug(): Promise<number> {
+ return db.organization.count({ where: { slug: null } });
+}
+
+// A slug equal to the id can never collide with another organization's;
+// new organizations get the same.
+function backfillSlugs() {
+ return db.$executeRaw`UPDATE organizations SET slug = id WHERE slug IS NULL`;
+}
+
+export async function up() {
+ const isDry = getIsDry();
+
+ const [membersToScope, grantsToCopy, invitesToScope, orphanGrants] =
+ await Promise.all([
+ countMembersToScope(),
+ db.projectAccess.count(),
+ countInvitesToScope(),
+ countGrantsWithoutMembership(),
+ ]);
+ const orphanLine = `project_access rows without a membership, left as is: ${orphanGrants}`;
+
+ if (isDry) {
+ const slugs = await countOrganizationsWithoutSlug();
+ printBoxMessage('🧪 Dry run: member project scope', [
+ `Members to set to "selected": ${membersToScope}`,
+ `project_access rows to copy: ${grantsToCopy}`,
+ `Pending invites to set to "selected": ${invitesToScope}`,
+ orphanLine,
+ `Organizations without a slug: ${slugs}`,
+ ]);
+ return;
+ }
+
+ const [scoped, copied, invitesScoped] = await db.$transaction([
+ scopeMembers(),
+ copyGrants(),
+ scopeInvites(),
+ ]);
+ const slugs = await backfillSlugs();
+
+ printBoxMessage('✅ Member project scope', [
+ `Members set to "selected": ${scoped}`,
+ `member_projects rows inserted: ${copied} (of ${grantsToCopy} grants)`,
+ `Pending invites set to "selected": ${invitesScoped}`,
+ orphanLine,
+ `Organization slugs set: ${slugs}`,
+ ]);
+}