Skip to content

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

fix(api): project-restricted members only get digest and notification emails for their projects (#559)

Carl-Gerhard Lindesvärd0385d320b690
diff --git a/packages/core/src/modules/insight/insight.service.test.ts b/packages/core/src/modules/insight/insight.service.test.ts
index cd49d2112..4e8109d61 100644
--- a/packages/core/src/modules/insight/insight.service.test.ts
+++ b/packages/core/src/modules/insight/insight.service.test.ts
@@ -36,12 +36,72 @@ const redis = {
};
// insight.service.ts never touches ClickHouse directly (it's PG-only, via
// $executeRaw above), so `deps.ch` stays unbuilt.
+// One active project in an organization with an all-scope member, a member
+// granted this project and a member granted another one.
+const digestProject = { id: 'p1', name: 'Project', organizationId: 'org_1' };
+const project = {
+ findMany: mock(async () => [
+ { ...digestProject, organization: { subscriptionState: 'active' } },
+ ]),
+};
+const projectInsight = { findMany: mock(async () => []) };
+const member = {
+ findMany: mock(async () => [
+ {
+ userId: 'u_all',
+ role: 'org:member',
+ projectScope: 'all',
+ projects: [],
+ user: { email: '[email protected]' },
+ },
+ {
+ userId: 'u_this',
+ role: 'org:member',
+ projectScope: 'selected',
+ projects: [{ projectId: 'p1', level: null }],
+ user: { email: '[email protected]' },
+ },
+ {
+ userId: 'u_other',
+ role: 'org:member',
+ projectScope: 'selected',
+ projects: [{ projectId: 'p_other', level: null }],
+ user: { email: '[email protected]' },
+ },
+ ]),
+};
+const projectAccess = { findMany: mock(async () => []) };
+
const deps = {
- db: { $executeRaw },
+ db: { $executeRaw, project, projectInsight, member, projectAccess },
redis,
config: testCoreConfig(),
} as unknown as import('../../services').ServiceDeps;
+const overviewSummary = {
+ unique_visitors: 10,
+ total_sessions: 12,
+ total_screen_views: 30,
+ bounce_rate: 40,
+};
+const getAnalyticsOverviewCore = mock(async () => ({
+ summary: overviewSummary,
+}));
+mock.module('../overview/overview.service', () => ({
+ getAnalyticsOverviewCore,
+}));
+
+const generateWeeklyNarrative = mock(async () => 'A good week.');
+mock.module('./src/narrative', () => ({ generateWeeklyNarrative }));
+
+const sentEmails: { to: string; template: string }[] = [];
+mock.module('../../clients/email', () => ({
+ sendEmail: (template: string, options: { to: string }) => {
+ sentEmails.push({ to: options.to, template });
+ return Promise.resolve();
+ },
+}));
+
const spikesQuery = mock(async () => [
{ anchorDate: '2026-09-01', spikes: [] },
]);
@@ -182,3 +242,30 @@ test('createInsightService binds every InsightService method', () => {
expect(typeof service[method]).toBe('function');
}
});
+
+test('sendWeeklyDigests mails only the members who can open the project', async () => {
+ const noop = () => undefined;
+ const logger: import('../../logger').Logger = {
+ fatal: noop,
+ error: noop,
+ warn: noop,
+ info: noop,
+ debug: noop,
+ trace: noop,
+ child: () => logger,
+ };
+
+ const result = await subject.sendWeeklyDigests(deps, logger);
+
+ expect(getAnalyticsOverviewCore).toHaveBeenCalledTimes(2);
+ expect(member.findMany).toHaveBeenCalledWith(
+ expect.objectContaining({
+ where: { organizationId: 'org_1', user: { deletedAt: null } },
+ })
+ );
+ expect(result).toEqual({ projects: 1, sent: 1 });
+ expect(sentEmails).toEqual([
+ { to: '[email protected]', template: 'weekly-digest' },
+ { to: '[email protected]', template: 'weekly-digest' },
+ ]);
+});
diff --git a/packages/core/src/modules/insight/insight.service.ts b/packages/core/src/modules/insight/insight.service.ts
index 84d07f2a4..10e88cede 100644
--- a/packages/core/src/modules/insight/insight.service.ts
+++ b/packages/core/src/modules/insight/insight.service.ts
@@ -6,6 +6,7 @@
import { sendEmail } from '../../clients/email';
import type { Logger } from '../../logger';
import type { ServiceDeps, Services } from '../../services';
+import { listProjectMemberEmails } from '../../shared/access-lookups';
import { createEngine, type EngineConfig } from './src/engine';
import {
ENRICH_VERSION,
@@ -473,22 +474,10 @@ async function buildDigestData(
};
}
-async function recipientsForOrg(
- deps: ServiceDeps,
- organizationId: string
-): Promise<string[]> {
- const db = deps.db;
- const members = await db.member.findMany({
- where: { organizationId },
- select: { email: true },
- });
- return [...new Set(members.map((m) => m.email).filter(Boolean))];
-}
-
/**
* Per active project: week-over-week stats + the AI's email-worthy insights +
- * a generated narrative, mailed to org members. The `weeklyDigest` cron job
- * body.
+ * a generated narrative, mailed to the members who can open the project.
+ * The `weeklyDigest` cron job body.
*/
export async function sendWeeklyDigests(
deps: ServiceDeps,
@@ -524,7 +513,10 @@ export async function sendWeeklyDigests(
if (skipped || !data) {
continue;
}
- const emails = await recipientsForOrg(deps, project.organizationId);
+ const emails = await listProjectMemberEmails(db, {
+ organizationId: project.organizationId,
+ projectId: project.id,
+ });
if (emails.length === 0) {
continue;
}
diff --git a/packages/core/src/modules/notification/notification.service.test.ts b/packages/core/src/modules/notification/notification.service.test.ts
index bea30da01..f1fcebecc 100644
--- a/packages/core/src/modules/notification/notification.service.test.ts
+++ b/packages/core/src/modules/notification/notification.service.test.ts
@@ -114,20 +114,59 @@ const integration = {
};
const project = {
- findUniqueOrThrow: mock(async () => ({ organizationId: 'org_1' })),
+ findUniqueOrThrow: mock(async () => ({
+ name: 'Project',
+ organizationId: 'org_1',
+ })),
};
+const member = {
+ findMany: mock(async () => [
+ {
+ userId: 'u_all',
+ role: 'org:member',
+ projectScope: 'all',
+ projects: [],
+ user: { email: '[email protected]' },
+ },
+ {
+ userId: 'u_other',
+ role: 'org:member',
+ projectScope: 'selected',
+ projects: [{ projectId: 'proj_other', level: null }],
+ user: { email: '[email protected]' },
+ },
+ {
+ userId: 'u_this',
+ role: 'org:member',
+ projectScope: 'selected',
+ projects: [{ projectId: 'proj_1', level: null }],
+ user: { email: '[email protected]' },
+ },
+ ]),
+};
+const projectAccess = { findMany: mock(async () => []) };
+
+const sentEmails: { to: string; template: string }[] = [];
+mock.module('../../clients/email', () => ({
+ sendEmail: (template: string, options: { to: string }) => {
+ sentEmails.push({ to: options.to, template });
+ return Promise.resolve();
+ },
+}));
+
// Every function under test takes `ServiceDeps`, so `deps.db` IS the fake
// below. The `@openpanel/db/src/prisma-client` mock stays for `Prisma.JsonNull`
// / `Prisma.DbNull`, which `prismaSentinels` reads from that module.
const actualPrismaClient = await import('@openpanel/db/src/prisma-client');
mock.module('@openpanel/db/src/prisma-client', () => ({
...actualPrismaClient,
- db: { notificationRule, integration, project },
+ db: { notificationRule, integration, project, member, projectAccess },
}));
const deps = {
- db: { notificationRule, integration, project },
+ db: { notificationRule, integration, project, member, projectAccess },
+ config: {},
} as unknown as import('../../services').ServiceDeps;
let subject: typeof import('./notification.service');
@@ -138,6 +177,7 @@ beforeAll(async () => {
beforeEach(() => {
ruleStore.clear();
integrationStore.clear();
+ sentEmails.length = 0;
publishedEvents.length = 0;
notificationRule.create.mockClear();
notificationRule.update.mockClear();
@@ -386,3 +426,19 @@ test('deliverNotification publishes the app pseudo-integration instead of enqueu
},
]);
});
+
+test('deliverNotification emails only the members who can open the project', async () => {
+ await subject.deliverNotification(deps, {
+ projectId: 'proj_1',
+ title: 'Hello',
+ message: 'World',
+ sendToApp: false,
+ sendToEmail: true,
+ } as never);
+
+ expect(member.findMany).toHaveBeenCalled();
+ expect(sentEmails).toEqual([
+ { to: '[email protected]', template: 'notification-rule' },
+ { to: '[email protected]', template: 'notification-rule' },
+ ]);
+});
diff --git a/packages/core/src/modules/notification/notification.service.ts b/packages/core/src/modules/notification/notification.service.ts
index b53fb22a2..62a9fcc3c 100644
--- a/packages/core/src/modules/notification/notification.service.ts
+++ b/packages/core/src/modules/notification/notification.service.ts
@@ -8,6 +8,7 @@ import { cacheablePerDb, type DbScope } from '../../cacheable-per-deps';
import { sendEmail } from '../../clients/email';
import { TRPCBadRequestError, TRPCForbiddenError } from '../../rpc/errors';
import type { ServiceDeps, Services } from '../../services';
+import { listProjectMemberEmails } from '../../shared/access-lookups';
import type {
IServiceCreateEventPayload,
IServiceEvent,
@@ -260,18 +261,10 @@ export async function deliverNotification(
where: { id: notification.projectId },
select: { name: true, organizationId: true },
});
- const members = await db.member.findMany({
- where: {
- organizationId: project.organizationId,
- user: { deletedAt: null },
- },
- include: { user: { select: { email: true } } },
+ const emails = await listProjectMemberEmails(db, {
+ organizationId: project.organizationId,
+ projectId: notification.projectId,
});
- const emails = new Set(
- members.flatMap((member) =>
- member.user?.email ? [member.user.email] : []
- )
- );
for (const to of emails) {
await sendEmail('notification-rule', {
to,
diff --git a/packages/core/src/shared/access-lookups.test.ts b/packages/core/src/shared/access-lookups.test.ts
index ef08be7e1..9dd594f33 100644
--- a/packages/core/src/shared/access-lookups.test.ts
+++ b/packages/core/src/shared/access-lookups.test.ts
@@ -3,7 +3,12 @@
// 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';
+import type { Db } from '../context';
+import {
+ effectiveProjectGrants,
+ listProjectMemberEmails,
+ 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']) {
@@ -155,3 +160,67 @@ test('duplicate legacy rows for one project keep the read restriction', () => {
});
}
});
+
+test('listProjectMemberEmails mails all-scope members and selected members with a row, nobody else', async () => {
+ const members = [
+ {
+ userId: 'u_all',
+ role: 'org:member',
+ projectScope: 'all',
+ projects: [],
+ user: { email: '[email protected]' },
+ },
+ {
+ userId: 'u_this',
+ role: 'viewer',
+ projectScope: 'selected',
+ projects: [{ projectId: 'p1', level: 'read' }],
+ user: { email: '[email protected]' },
+ },
+ {
+ userId: 'u_other',
+ role: 'org:admin',
+ projectScope: 'selected',
+ projects: [{ projectId: 'p2', level: null }],
+ user: { email: '[email protected]' },
+ },
+ {
+ userId: 'u_legacy',
+ role: 'org:member',
+ projectScope: 'all',
+ projects: [],
+ user: { email: '[email protected]' },
+ },
+ {
+ userId: 'u_dup',
+ role: 'org:member',
+ projectScope: 'all',
+ projects: [],
+ user: { email: '[email protected]' },
+ },
+ ];
+ // A project_access row written by the previous image restricts u_legacy to p2.
+ const legacyGrants = [
+ { userId: 'u_legacy', projectId: 'p2', level: 'write' },
+ ];
+ const memberWhere: unknown[] = [];
+ const db = {
+ member: {
+ findMany: async ({ where }: { where: unknown }) => {
+ memberWhere.push(where);
+ return members;
+ },
+ },
+ projectAccess: { findMany: async () => legacyGrants },
+ } as unknown as Db;
+
+ const emails = await listProjectMemberEmails(db, {
+ organizationId: 'org_1',
+ projectId: 'p1',
+ });
+
+ expect(emails.sort()).toEqual(['[email protected]', '[email protected]']);
+ expect(memberWhere).toEqual([
+ { organizationId: 'org_1', user: { deletedAt: null } },
+ ]);
+});
diff --git a/packages/core/src/shared/access-lookups.ts b/packages/core/src/shared/access-lookups.ts
index 5c6a2e1a0..77268e546 100644
--- a/packages/core/src/shared/access-lookups.ts
+++ b/packages/core/src/shared/access-lookups.ts
@@ -134,6 +134,67 @@ export async function getMemberProjectGrants(
};
}
+/**
+ * Emails of the members who can open one project, by the same rule as
+ * `getProjectAccess`. Per-project mail (weekly digests, notification rules)
+ * goes through this: mailing every member of the organization sends a
+ * `selected`-scope member reports for projects they cannot see.
+ */
+export async function listProjectMemberEmails(
+ db: Db,
+ { organizationId, projectId }: { organizationId: string; projectId: string }
+): Promise<string[]> {
+ const [members, legacyGrants] = await Promise.all([
+ db.member.findMany({
+ where: { organizationId, user: { deletedAt: null } },
+ select: {
+ userId: true,
+ role: true,
+ projectScope: true,
+ projects: { select: { projectId: true, level: true } },
+ user: { select: { email: true } },
+ },
+ }),
+ db.projectAccess.findMany({
+ where: { organizationId },
+ select: { userId: true, projectId: true, level: true },
+ }),
+ ]);
+
+ const legacyByUser = new Map<
+ string,
+ { projectId: string; level: AccessLevel }[]
+ >();
+ for (const grant of legacyGrants) {
+ const grants = legacyByUser.get(grant.userId) ?? [];
+ grants.push(grant);
+ legacyByUser.set(grant.userId, grants);
+ }
+
+ const emails = new Set<string>();
+ for (const member of members) {
+ const email = member.user?.email;
+ if (!email) {
+ continue;
+ }
+ const grants = effectiveProjectGrants({
+ ...member,
+ legacyGrants: member.userId
+ ? (legacyByUser.get(member.userId) ?? [])
+ : [],
+ });
+ const access = resolveProjectAccess({
+ role: member.role,
+ projectScope: grants.projectScope,
+ grant: grants.projects.find((row) => row.projectId === projectId) ?? null,
+ });
+ if (access) {
+ emails.add(email);
+ }
+ }
+ return [...emails];
+}
+
/**
* Resolve a user's access to one project.
*