OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M6-004): share + reference + email(trpc-only) modules into core
ralph2d8e4d82bc59
diff --git a/packages/constants/index.ts b/packages/constants/index.tsindex 0c87d62cc..d5d2263f9 100644--- a/packages/constants/index.ts+++ b/packages/constants/index.ts@@ -595,33 +595,13 @@ export function getCountry(code?: string) {return countries[code as keyof typeof countries];}-// Keys must match the template `category` in @openpanel/email. Each entry's-// label + description drive the account email-preferences toggles.-export const emailCategories = {- onboarding: {- label: 'Onboarding',- description: 'Get started tips and guidance emails',- },- weekly_digest: {- label: 'Weekly digest',- description: 'A weekly summary of your analytics with AI-surfaced insights',- },- product_alerts: {- label: 'Product alerts',- description:- 'Important notices about your projects: tracking stopped sending data, event limits, and alerts from your notification rules',- },- // Kept separate from `onboarding` on purpose: opting out of getting-started- // tips must not also opt you out of being told your account is winding down.- // The final deletion warning has no category at all, so it always sends.- account_lifecycle: {- label: 'Account status',- description:- 'Notices about your trial ending, event ingestion being paused, and data scheduled for removal',- },-} as const;--export type EmailCategory = keyof typeof emailCategories;+// Moved into @openpanel/core's email module (M6-004, ADR-008's module map:+// email owns "C"). Re-exported here for existing @openpanel/constants+// importers (packages/trpc's email router, apps/start's unsubscribe ++// email-preferences pages) — same shape as `ProjectTypeNames`'s re-export+// since M6-002. Keys must match the template `category` in @openpanel/email.+export { emailCategories } from '@openpanel/core/modules/email/email.constants';+export type { EmailCategory } from '@openpanel/core/modules/email/email.constants';export const chartColors = [{ main: '#2563EB', translucent: 'rgba(37, 99, 235, 0.1)' },diff --git a/packages/core/package.json b/packages/core/package.jsonindex f10c5436b..9c037a5e4 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -54,6 +54,7 @@"prom-client": "^15.1.3","qrcode": "^1.5.4","ramda": "^0.29.1",+ "short-unique-id": "^5.0.3","sqlstring": "^2.3.3","superjson": "^1.13.3","ua-parser-js": "^2.0.6",diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 9b79b21e3..f91fbe4f2 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -289,6 +289,13 @@ export {listConversations,upsertConversationTitle,} from './modules/conversation/conversation.service';+// R + C only (M6-004): the router's three bodies are three small+// `db.emailUnsubscribe` calls, small enough to live inline in+// `email.rpc.ts` rather than a dedicated `email.service.ts` — see that+// file's header. `emailCategories` moved from @openpanel/constants (ADR-008's+// module map: email owns "C"); @openpanel/constants keeps a re-export shim.+export type { EmailCategory } from './modules/email/email.constants';+export { emailCategories } from './modules/email/email.constants';// Dissolved from @openpanel/db's src/gsc.ts + services/gsc.service.ts// (M5-002) — apps/worker's gsc job file, apps/api's gsc OAuth callback// controller and packages/trpc's gsc router call these directly, the same@@ -427,6 +434,54 @@ export {scheduleProjectDeletion,updateProjectForOrganization,} from './modules/project/project.service';+// Moved from packages/db/src/services/reference.service.ts, plus the+// query/mutation bodies packages/trpc/src/routers/reference.ts held inline+// (M6-004) — packages/trpc's reference router calls these directly, the same+// way V1 reaches every other dissolved service here. packages/db keeps a+// re-export shim.+export type { IServiceReference } from './modules/reference/reference.service';+export {+ createReference,+ deleteReference,+ getChartReferences,+ getReferenceById,+ getReferenceByIdOrThrow,+ listReferences,+ updateReference,+} from './modules/reference/reference.service';+// Moved from packages/db/src/services/share.service.ts, plus the+// query/mutation bodies packages/trpc/src/routers/share.ts held inline+// (M6-004, ADR-008's module map: share owns "C") — packages/trpc's share+// router calls these directly, the same way V1 reaches every other dissolved+// service here. packages/db keeps a re-export shim: auth.service.ts's+// signInToShare and packages/trpc's chart/overview routers still reach+// validateShareAccess/validateOverviewShareAccess through it.+export {+ zShareDashboard,+ zShareOverview,+ zShareReport,+} from './modules/share/share.constants';+export {+ createShareDashboard,+ createShareOverview,+ createShareReport,+ getShareByProjectId,+ getShareDashboard,+ getShareDashboardById,+ getShareDashboardByDashboardId,+ getShareDashboardReports,+ getShareDashboardSettings,+ getShareOverview,+ getShareOverviewById,+ getShareOverviewSettings,+ getShareReport,+ getShareReportById,+ getShareReportByReportId,+ getShareReportSettings,+ validateOverviewShareAccess,+ validateReportAccess,+ validateShareAccess,+} from './modules/share/share.service';// Dissolved from @openpanel/db's services/user.service.ts (M6-001) —// packages/trpc's auth/onboarding routers call `getUserById`/// `getUserAccount` directly through @openpanel/db's re-export shim, the samediff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.tsindex aea1977bc..73b588a46 100644--- a/packages/core/src/modules/auth/auth.service.ts+++ b/packages/core/src/modules/auth/auth.service.ts@@ -135,7 +135,10 @@ export function createAuthService(_deps: ServiceDeps): AuthService {// import — see user.service.ts's header for the full reasoning, and because// a static import of @openpanel/db here specifically WOULD be a cycle// (this file's own header, above: db already depends on core for-// `hashSessionToken`).+// `hashSessionToken`). `loadShare` points at `../share/share.service`+// directly since M6-004 — share.service.ts statically imports this file's+// own `hashPassword`, so the two are mutually lazy/eager by design, not a+// live cycle.//// None of these functions take a `TrpcContext`/`Ctx`: they take exactly the// primitives they touch (`setCookie`, `cookies.get`, `logger`), so this file@@ -176,7 +179,7 @@ function loadRegistration() {}function loadShare() {- return import('@openpanel/db/src/services/share.service');+ return import('../share/share.service');}function dashboardUrl(): string {diff --git a/packages/core/src/modules/email/email.constants.ts b/packages/core/src/modules/email/email.constants.tsnew file mode 100644index 000000000..467ac8671--- /dev/null+++ b/packages/core/src/modules/email/email.constants.ts@@ -0,0 +1,32 @@+// Moved from packages/constants/index.ts (M6-004, ADR-008's module map:+// email owns "C"). packages/constants re-exports these for existing+// @openpanel/constants importers — same shape as packages/constants/index.ts's+// `ProjectTypeNames` re-export since M6-002.+//+// Keys must match the template `category` in @openpanel/email. Each entry's+// label + description drive the account email-preferences toggles.+export const emailCategories = {+ onboarding: {+ label: 'Onboarding',+ description: 'Get started tips and guidance emails',+ },+ weekly_digest: {+ label: 'Weekly digest',+ description: 'A weekly summary of your analytics with AI-surfaced insights',+ },+ product_alerts: {+ label: 'Product alerts',+ description:+ 'Important notices about your projects: tracking stopped sending data, event limits, and alerts from your notification rules',+ },+ // Kept separate from `onboarding` on purpose: opting out of getting-started+ // tips must not also opt you out of being told your account is winding down.+ // The final deletion warning has no category at all, so it always sends.+ account_lifecycle: {+ label: 'Account status',+ description:+ 'Notices about your trial ending, event ingestion being paused, and data scheduled for removal',+ },+} as const;++export type EmailCategory = keyof typeof emailCategories;diff --git a/packages/core/src/modules/email/email.rpc.test.ts b/packages/core/src/modules/email/email.rpc.test.tsnew file mode 100644index 000000000..c04e0aa24--- /dev/null+++ b/packages/core/src/modules/email/email.rpc.test.ts@@ -0,0 +1,56 @@+// Only the "is anyone logged in" boundary (+ the token check, which never+// touches a database) is exercised here. `unsubscribe`'s upsert and+// `getPreferences`/`updatePreferences`'s reads ride on @openpanel/db+// (lazy-loaded, see email.rpc.ts's header); wiring this router end-to-end+// against a real Postgres is P6's (protectedProcedure) job, not this one's.++import { expect, test } from 'bun:test';+import { stubHttpCtx } from '../../../test/rpc-fixtures';+import { makeTrpcContext } from '../../rpc/base';+import type { CookieOptions } from '../../shared/cookie';+import { emailRouter } from './email.rpc';++const COOKIE_OPTIONS: CookieOptions = {+ domain: '.openpanel.dev',+ secure: true,+ sameSite: 'lax',+ httpOnly: true,+ path: '/',+};++// EMPTY_SESSION's shape (packages/db/src/services/auth-session.service.ts) —+// `TrpcContext.session` is never literally `null`, only its `userId` is.+const EMPTY_SESSION = { session: null, user: null, userId: null };++async function anonCaller() {+ const { ctx } = stubHttpCtx({}, EMPTY_SESSION);+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {+ cookieOptions: COOKIE_OPTIONS,+ });+ return emailRouter.createCaller(trpcCtx);+}++test('getPreferences rejects an unauthenticated caller', async () => {+ const caller = await anonCaller();+ await expect(caller.getPreferences()).rejects.toMatchObject({+ code: 'UNAUTHORIZED',+ });+});++test('updatePreferences rejects an unauthenticated caller', async () => {+ const caller = await anonCaller();+ await expect(+ caller.updatePreferences({ categories: { onboarding: false } })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('unsubscribe rejects an invalid token before touching the database', async () => {+ const caller = await anonCaller();+ await expect(+ caller.unsubscribe({+ email: '[email protected]',+ category: 'onboarding',+ token: 'not-a-real-token',+ })+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+});diff --git a/packages/core/src/modules/email/email.rpc.ts b/packages/core/src/modules/email/email.rpc.tsnew file mode 100644index 000000000..799339d5b--- /dev/null+++ b/packages/core/src/modules/email/email.rpc.ts@@ -0,0 +1,117 @@+// Ported from packages/trpc/src/routers/email.ts (M6-004).+//+// Deliberately R + C only (no `email.service.ts`): the three procedures'+// bodies are three small `db.emailUnsubscribe` calls, inlined here the same+// way conversation.rpc.ts inlines its organization lookup. Sending/templates+// stay in @openpanel/email (TARGET_ARCHITECTURE §7); core's+// `clients/email.ts` already wraps that package for the one thing this+// module doesn't need — sending.+//+// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware+// stack — lands in core with auth (rpc/base.ts: "those need the resolved+// Session shape and the access rules, so they land with auth (P6)"). Until+// then this router does its own minimal "is anyone logged in" check inline,+// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route+// through packages/trpc's own `protectedProcedure` (full stack included) and+// delegates its handler bodies to core's `verifyUnsubscribeToken` ++// `emailCategories` (DELEGATE PATTERN) — this module has no queue/cron of+// its own, so there is no `ctx.services.email`, same as `user`/`reference`.+//+// `verifyUnsubscribeToken` is imported from @openpanel/email's own+// `unsubscribe.ts` file, not its barrel: the barrel (`@openpanel/email` ->+// `./src`) pulls in @openpanel/db, which is exactly the cycle+// `clients/email.ts`'s header describes for `sendEmail`. `unsubscribe.ts`+// itself only touches `node:crypto`, so importing it directly sidesteps the+// cycle instead of deferring it.++import { verifyUnsubscribeToken } from '@openpanel/email/src/unsubscribe';+import { z } from 'zod';+import { createTRPCRouter, procedure } from '../../rpc/base';+import { TRPCAccessError, TRPCBadRequestError } from '../../rpc/errors';+import { emailCategories } from './email.constants';++function loadDb() {+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);+}++function requireLogin(userId: string | null | undefined): string {+ if (!userId) {+ throw new TRPCAccessError('Not authenticated');+ }+ return userId;+}++export const emailRouter = createTRPCRouter({+ unsubscribe: procedure+ .input(+ z.object({+ email: z.string().email(),+ category: z.string(),+ token: z.string(),+ })+ )+ .mutation(async ({ input }) => {+ const { email, category, token } = input;++ if (!verifyUnsubscribeToken(email, category, token)) {+ throw new TRPCBadRequestError('Invalid unsubscribe link');+ }++ const db = await loadDb();+ await db.emailUnsubscribe.upsert({+ where: { email_category: { email, category } },+ create: { email, category },+ update: {},+ });++ return { success: true };+ }),++ getPreferences: procedure.query(async ({ ctx }) => {+ requireLogin(ctx.session.userId);+ if (!ctx.session.user?.email) {+ throw new Error('User not authenticated');+ }+ const email = ctx.session.user.email;++ const db = await loadDb();+ const unsubscribes = await db.emailUnsubscribe.findMany({+ where: { email },+ select: { category: true },+ });+ const unsubscribedCategories = new Set(+ unsubscribes.map((u) => u.category)+ );++ const preferences: Record<string, boolean> = {};+ for (const category of Object.keys(emailCategories)) {+ preferences[category] = !unsubscribedCategories.has(category);+ }+ return preferences;+ }),++ updatePreferences: procedure+ .input(z.object({ categories: z.record(z.string(), z.boolean()) }))+ .mutation(async ({ input, ctx }) => {+ requireLogin(ctx.session.userId);+ const email = ctx.session.user?.email;+ if (!email) {+ throw new Error('User not authenticated');+ }++ const db = await loadDb();+ for (const [category, subscribed] of Object.entries(input.categories)) {+ if (subscribed) {+ await db.emailUnsubscribe.deleteMany({ where: { email, category } });+ } else {+ await db.emailUnsubscribe.upsert({+ where: { email_category: { email, category } },+ create: { email, category },+ update: {},+ });+ }+ }++ return { success: true };+ }),+});diff --git a/packages/core/src/modules/reference/reference.rpc.test.ts b/packages/core/src/modules/reference/reference.rpc.test.tsnew file mode 100644index 000000000..859880092--- /dev/null+++ b/packages/core/src/modules/reference/reference.rpc.test.ts@@ -0,0 +1,69 @@+// Only the "is anyone logged in" boundary is exercised here — no database.+// The access-check + CRUD logic ride on @openpanel/db (lazy-loaded, see+// reference.service.ts's header); wiring this router end-to-end against a+// real Postgres is P6's (protectedProcedure) job, not this one's — see+// reference.rpc.ts's header.++import { expect, test } from 'bun:test';+import { stubHttpCtx } from '../../../test/rpc-fixtures';+import { makeTrpcContext } from '../../rpc/base';+import type { CookieOptions } from '../../shared/cookie';+import { referenceRouter } from './reference.rpc';++const COOKIE_OPTIONS: CookieOptions = {+ domain: '.openpanel.dev',+ secure: true,+ sameSite: 'lax',+ httpOnly: true,+ path: '/',+};++// EMPTY_SESSION's shape (packages/db/src/services/auth-session.service.ts) —+// `TrpcContext.session` is never literally `null`, only its `userId` is.+const EMPTY_SESSION = { session: null, user: null, userId: null };++async function anonCaller() {+ const { ctx } = stubHttpCtx({}, EMPTY_SESSION);+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {+ cookieOptions: COOKIE_OPTIONS,+ });+ return referenceRouter.createCaller(trpcCtx);+}++test('getReferences rejects an unauthenticated caller', async () => {+ const caller = await anonCaller();+ await expect(+ caller.getReferences({ projectId: 'proj_1' })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('create rejects an unauthenticated caller', async () => {+ const caller = await anonCaller();+ await expect(+ caller.create({+ title: 'Launch',+ description: null,+ datetime: '2026-09-03T00:00:00.000Z',+ projectId: 'proj_1',+ })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('update rejects an unauthenticated caller before looking up the reference', async () => {+ const caller = await anonCaller();+ await expect(+ caller.update({+ id: 'ref_1',+ title: 'Launch',+ description: null,+ datetime: '2026-09-03T00:00:00.000Z',+ })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('delete rejects an unauthenticated caller before looking up the reference', async () => {+ const caller = await anonCaller();+ await expect(caller.delete({ id: 'ref_1' })).rejects.toMatchObject({+ code: 'UNAUTHORIZED',+ });+});diff --git a/packages/core/src/modules/reference/reference.rpc.ts b/packages/core/src/modules/reference/reference.rpc.tsnew file mode 100644index 000000000..0114293f1--- /dev/null+++ b/packages/core/src/modules/reference/reference.rpc.ts@@ -0,0 +1,108 @@+// Ported from packages/trpc/src/routers/reference.ts (M6-004).+//+// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware+// stack — lands in core with auth (rpc/base.ts: "those need the resolved+// Session shape and the access rules, so they land with auth (P6)"). Until+// then this router does its own minimal "is anyone logged in" check inline,+// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route+// through packages/trpc's own `protectedProcedure` (full stack included) and+// delegates its handler bodies to core's reference functions (DELEGATE+// PATTERN) — this module has no queue/cron of its own, so there is no+// `ctx.services.reference`, same as `user`/`conversation`.+//+// The per-project access ladder itself IS shared: `./src/access.ts` binds+// core's shared/access.ts ladder to @openpanel/db's real lookups, the same+// way packages/trpc/src/access.ts does for V1. `create` has no access check+// here either — same gap V1's router has (ported verbatim, not fixed).++import { zCreateReference, zRange } from '@openpanel/validation';+import { z } from 'zod';+import { createTRPCRouter, procedure } from '../../rpc/base';+import { TRPCAccessError, TRPCForbiddenError } from '../../rpc/errors';+import {+ createReference,+ deleteReference,+ getChartReferences,+ getReferenceByIdOrThrow,+ listReferences,+ updateReference,+} from './reference.service';++function loadAccessChecks() {+ return import('./src/access');+}++function requireLogin(userId: string | null | undefined): string {+ if (!userId) {+ throw new TRPCAccessError('Not authenticated');+ }+ return userId;+}++export const referenceRouter = createTRPCRouter({+ getReferences: procedure+ .input(z.object({ projectId: z.string(), cursor: z.number().optional() }))+ .query(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ const { getProjectAccess } = await loadAccessChecks();+ const access = await getProjectAccess({+ userId,+ projectId: input.projectId,+ });+ if (!access) {+ throw new TRPCForbiddenError('You do not have access to this project');+ }+ return listReferences(input);+ }),++ create: procedure.input(zCreateReference).mutation(({ input, ctx }) => {+ requireLogin(ctx.session.userId);+ return createReference(input);+ }),++ update: procedure+ .input(+ z.object({+ id: z.string(),+ title: z.string(),+ description: z.string().nullish(),+ datetime: z.string(),+ })+ )+ .mutation(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ const existing = await getReferenceByIdOrThrow(input.id);+ const { requireProjectAccess } = await loadAccessChecks();+ await requireProjectAccess({+ userId,+ projectId: existing.projectId,+ level: 'write',+ });+ return updateReference(input);+ }),++ delete: procedure+ .input(z.object({ id: z.string() }))+ .mutation(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ const existing = await getReferenceByIdOrThrow(input.id);+ const { requireProjectAccess } = await loadAccessChecks();+ await requireProjectAccess({+ userId,+ projectId: existing.projectId,+ level: 'write',+ });+ return deleteReference(input.id);+ }),++ getChartReferences: procedure+ .input(+ z.object({+ projectId: z.string(),+ startDate: z.string().nullish(),+ endDate: z.string().nullish(),+ range: zRange,+ })+ )+ .query(({ input }) => getChartReferences(input)),+});diff --git a/packages/core/src/modules/reference/reference.service.test.ts b/packages/core/src/modules/reference/reference.service.test.tsnew file mode 100644index 000000000..43e4eb130--- /dev/null+++ b/packages/core/src/modules/reference/reference.service.test.ts@@ -0,0 +1,201 @@+// reference.service.ts's db access is lazy (`await import(...)` inside each+// function — see the file's header), which is exactly what makes+// `mock.module` work here with no import-time side effects to race: every+// mock below is registered before the subject's first call, not before its+// (side-effect-free) import.++import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';++interface FakeReference {+ id: string;+ title: string;+ description: string | null;+ projectId: string;+ date: Date;+}++const referenceStore = new Map<string, FakeReference>();++function makeReference(+ overrides: Partial<FakeReference> & { id: string }+): FakeReference {+ return {+ title: 'Launch',+ description: null,+ projectId: 'proj_1',+ date: new Date('2026-09-01T00:00:00.000Z'),+ ...overrides,+ };+}++const reference = {+ findUnique: mock(async ({ where: { id } }: { where: { id: string } }) => {+ return referenceStore.get(id) ?? null;+ }),+ findUniqueOrThrow: mock(+ async ({ where: { id } }: { where: { id: string } }) => {+ const found = referenceStore.get(id);+ if (!found) {+ throw new Error(`reference ${id} not found`);+ }+ return found;+ }+ ),+ findMany: mock(+ async ({+ where,+ take,+ skip,+ }: {+ where: { projectId?: string; date?: { gte: Date; lte: Date } };+ take?: number;+ skip?: number;+ }) => {+ let rows = [...referenceStore.values()];+ if (where.projectId) {+ rows = rows.filter((r) => r.projectId === where.projectId);+ }+ if (where.date) {+ rows = rows.filter(+ (r) => r.date >= where.date!.gte && r.date <= where.date!.lte+ );+ }+ if (skip) {+ rows = rows.slice(skip);+ }+ return take ? rows.slice(0, take) : rows;+ }+ ),+ create: mock(async ({ data }: { data: Omit<FakeReference, 'id'> }) => {+ const row = makeReference({ id: `ref_${referenceStore.size + 1}`, ...data });+ referenceStore.set(row.id, row);+ return row;+ }),+ update: mock(+ async ({+ where: { id },+ data,+ }: {+ where: { id: string };+ data: Partial<FakeReference>;+ }) => {+ const existing = referenceStore.get(id);+ if (!existing) {+ throw new Error(`reference ${id} not found`);+ }+ const next = { ...existing, ...data };+ referenceStore.set(id, next);+ return next;+ }+ ),+ delete: mock(async ({ where: { id } }: { where: { id: string } }) => {+ const existing = referenceStore.get(id);+ referenceStore.delete(id);+ return existing;+ }),+};++const actualPrismaClient = await import('@openpanel/db/src/prisma-client');+mock.module('@openpanel/db/src/prisma-client', () => ({+ ...actualPrismaClient,+ db: { reference },+}));++const getSettingsForProject = mock(async () => ({ timezone: 'UTC' }));+mock.module('@openpanel/db/src/services/organization.service', () => ({+ getSettingsForProject,+}));++const getChartStartEndDate = mock(() => ({+ startDate: '2026-08-25 00:00:00',+ endDate: '2026-09-01 23:59:59',+}));+mock.module('@openpanel/db/src/services/date.service', () => ({+ getChartStartEndDate,+}));++let subject: typeof import('./reference.service');+beforeAll(async () => {+ subject = await import('./reference.service');+});++beforeEach(() => {+ referenceStore.clear();+ getSettingsForProject.mockClear();+ getChartStartEndDate.mockClear();+});++test('getReferenceById returns null for a missing reference', async () => {+ expect(await subject.getReferenceById('missing')).toBeNull();+});++test('getReferenceByIdOrThrow throws for a missing reference', async () => {+ await expect(subject.getReferenceByIdOrThrow('missing')).rejects.toThrow();+});++test('listReferences paginates by cursor, 50 per page', async () => {+ const REFERENCE_COUNT = 55;+ for (const i of Array.from({ length: REFERENCE_COUNT }, (_, idx) => idx)) {+ referenceStore.set(`ref_${i}`, makeReference({ id: `ref_${i}` }));+ }+ const firstPage = await subject.listReferences({ projectId: 'proj_1' });+ expect(firstPage).toHaveLength(50);++ const secondPage = await subject.listReferences({+ projectId: 'proj_1',+ cursor: 1,+ });+ expect(secondPage).toHaveLength(5);+});++test('createReference stores the date as a Date, not a string', async () => {+ const result = await subject.createReference({+ title: 'Launch',+ description: 'v2 ships',+ projectId: 'proj_1',+ datetime: '2026-09-03T12:00:00.000Z',+ });+ expect(result.date).toBeInstanceOf(Date);+ expect(result.title).toBe('Launch');+});++test('updateReference normalizes a nullish description to null', async () => {+ referenceStore.set('ref_1', makeReference({ id: 'ref_1', description: 'old' }));+ const result = await subject.updateReference({+ id: 'ref_1',+ title: 'Renamed',+ description: undefined,+ datetime: '2026-09-03T00:00:00.000Z',+ });+ expect(result).toMatchObject({ title: 'Renamed', description: null });+});++test('deleteReference removes the row', async () => {+ referenceStore.set('ref_1', makeReference({ id: 'ref_1' }));+ await subject.deleteReference('ref_1');+ expect(referenceStore.has('ref_1')).toBe(false);+});++test('getChartReferences filters by the resolved date window', async () => {+ referenceStore.set(+ 'ref_in_range',+ makeReference({+ id: 'ref_in_range',+ date: new Date('2026-08-28T00:00:00.000Z'),+ })+ );+ referenceStore.set(+ 'ref_out_of_range',+ makeReference({+ id: 'ref_out_of_range',+ date: new Date('2026-01-01T00:00:00.000Z'),+ })+ );++ const result = await subject.getChartReferences({+ projectId: 'proj_1',+ range: 'last30Days' as never,+ });+ expect(result.map((r) => r.id)).toEqual(['ref_in_range']);+ expect(getSettingsForProject).toHaveBeenCalledWith('proj_1');+});diff --git a/packages/core/src/modules/reference/reference.service.ts b/packages/core/src/modules/reference/reference.service.tsnew file mode 100644index 000000000..15178605a--- /dev/null+++ b/packages/core/src/modules/reference/reference.service.ts@@ -0,0 +1,128 @@+// Moved from packages/db/src/services/reference.service.ts, plus the+// query/mutation bodies packages/trpc/src/routers/reference.ts held inline+// (M6-004, DELEGATE PATTERN: V1's router and this package's own+// reference.rpc.ts share one implementation, same as+// conversation.service.ts since M5-006). packages/db keeps a re-export shim:+// nothing outside this module's own routers reached it directly, but the+// shape stays for any future @openpanel/db importer, same as+// packages/db/src/services/organization.service.ts since M6-001.+//+// db access is LAZY, not a static top-level import — see insight.service.ts's+// header for the full reasoning (jobs.registry.ts and services.ts pull this+// module into the eager barrel chain nearly every core test file reaches, and+// constructing @openpanel/db's clients at import time would spawn a+// pino-pretty transport worker thread per test file).++import type { Reference } from '@openpanel/db/src/prisma-client';+import type { IChartRange } from '@openpanel/validation';++export type IServiceReference = Reference;++const REFERENCES_PAGE_SIZE = 50;++function loadDb() {+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);+}++function loadDateService() {+ return import('@openpanel/db/src/services/date.service');+}++function loadOrganizationService() {+ return import('@openpanel/db/src/services/organization.service');+}++export async function getReferenceById(id: string): Promise<Reference | null> {+ const db = await loadDb();+ return db.reference.findUnique({ where: { id } });+}++/** Throws Prisma's own not-found error, same as V1's inline+ * `findUniqueOrThrow` call sites — used by both routers' ownership lookup+ * ahead of their own access check. */+export async function getReferenceByIdOrThrow(id: string): Promise<Reference> {+ const db = await loadDb();+ return db.reference.findUniqueOrThrow({ where: { id } });+}++export async function listReferences(input: {+ projectId: string;+ cursor?: number;+}): Promise<Reference[]> {+ const db = await loadDb();+ return db.reference.findMany({+ where: { projectId: input.projectId },+ take: REFERENCES_PAGE_SIZE,+ skip: input.cursor ? input.cursor * REFERENCES_PAGE_SIZE : 0,+ });+}++export async function createReference(input: {+ title: string;+ description?: string | null;+ datetime: string;+ projectId: string;+}): Promise<Reference> {+ const db = await loadDb();+ return db.reference.create({+ data: {+ title: input.title,+ description: input.description,+ projectId: input.projectId,+ date: new Date(input.datetime),+ },+ });+}++export async function updateReference(input: {+ id: string;+ title: string;+ description?: string | null;+ datetime: string;+}): Promise<Reference> {+ const db = await loadDb();+ return db.reference.update({+ where: { id: input.id },+ data: {+ title: input.title,+ description: input.description ?? null,+ date: new Date(input.datetime),+ },+ });+}++export async function deleteReference(id: string): Promise<Reference> {+ const db = await loadDb();+ return db.reference.delete({ where: { id } });+}++export async function getChartReferences(input: {+ projectId: string;+ startDate?: string | null;+ endDate?: string | null;+ range: IChartRange;+}): Promise<Reference[]> {+ const { getSettingsForProject } = await loadOrganizationService();+ const { timezone } = await getSettingsForProject(input.projectId);++ const { getChartStartEndDate } = await loadDateService();+ const { startDate, endDate } = getChartStartEndDate(+ {+ startDate: input.startDate,+ endDate: input.endDate,+ range: input.range,+ },+ timezone+ );++ const db = await loadDb();+ return db.reference.findMany({+ where: {+ projectId: input.projectId,+ date: {+ gte: new Date(startDate),+ lte: new Date(endDate),+ },+ },+ });+}diff --git a/packages/core/src/modules/reference/src/access.ts b/packages/core/src/modules/reference/src/access.tsnew file mode 100644index 000000000..6b3a1661f--- /dev/null+++ b/packages/core/src/modules/reference/src/access.ts@@ -0,0 +1,24 @@+// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for+// this module's own router — the same binding packages/trpc/src/access.ts+// does for V1, self-contained here because the general core -> db binding+// itself moves with auth (P6), not this wave. Same shape as+// conversation/src/access.ts.++import {+ canWriteProject,+ getOrganizationAccess,+ getProjectAccess,+} from '@openpanel/db/src/services/access.service';+import { getProjectById } from '@openpanel/db/src/services/project.service';+import { createAccessChecks } from '../../../shared/access';++export { getProjectAccess } from '@openpanel/db/src/services/access.service';++const checks = createAccessChecks({+ getProjectAccess,+ canWriteProject,+ getOrganizationAccess,+ getProjectById,+});++export const requireProjectAccess = checks.requireProjectAccess;diff --git a/packages/core/src/modules/share/share.constants.ts b/packages/core/src/modules/share/share.constants.tsnew file mode 100644index 000000000..dc5f6e8a8--- /dev/null+++ b/packages/core/src/modules/share/share.constants.ts@@ -0,0 +1,29 @@+// Moved from packages/validation/src/index.ts (M6-004, ADR-008's module map:+// share owns "C"). packages/validation re-exports these for existing+// @openpanel/validation importers — same shape as+// packages/validation/src/index.ts's onboarding/auth re-exports since M6-003.++import { z } from 'zod';++export const zShareOverview = z.object({+ organizationId: z.string(),+ projectId: z.string(),+ password: z.string().nullable(),+ public: z.boolean(),+});++export const zShareDashboard = z.object({+ organizationId: z.string(),+ projectId: z.string(),+ dashboardId: z.string(),+ password: z.string().nullable(),+ public: z.boolean(),+});++export const zShareReport = z.object({+ organizationId: z.string(),+ projectId: z.string(),+ reportId: z.string(),+ password: z.string().nullable(),+ public: z.boolean(),+});diff --git a/packages/core/src/modules/share/share.rpc.test.ts b/packages/core/src/modules/share/share.rpc.test.tsnew file mode 100644index 000000000..f08623c57--- /dev/null+++ b/packages/core/src/modules/share/share.rpc.test.ts@@ -0,0 +1,90 @@+// Only the "is anyone logged in" boundary is exercised here — no database.+// The query/mutation bodies ride on @openpanel/db (lazy-loaded, see+// share.service.ts's header); wiring this router end-to-end against a real+// Postgres is P6's (protectedProcedure) job, not this one's — see+// share.rpc.ts's header.++import { expect, test } from 'bun:test';+import { stubHttpCtx } from '../../../test/rpc-fixtures';+import { makeTrpcContext } from '../../rpc/base';+import type { CookieOptions } from '../../shared/cookie';+import { shareRouter } from './share.rpc';++const COOKIE_OPTIONS: CookieOptions = {+ domain: '.openpanel.dev',+ secure: true,+ sameSite: 'lax',+ httpOnly: true,+ path: '/',+};++// EMPTY_SESSION's shape (packages/db/src/services/auth-session.service.ts) —+// `TrpcContext.session` is never literally `null`, only its `userId` is.+const EMPTY_SESSION = { session: null, user: null, userId: null };++async function anonCaller() {+ const { ctx } = stubHttpCtx({}, EMPTY_SESSION);+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {+ cookieOptions: COOKIE_OPTIONS,+ });+ return shareRouter.createCaller(trpcCtx);+}++test('overviewSettings rejects an unauthenticated caller', async () => {+ const caller = await anonCaller();+ await expect(+ caller.overviewSettings({ projectId: 'proj_1' })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('createOverview rejects an unauthenticated caller', async () => {+ const caller = await anonCaller();+ await expect(+ caller.createOverview({+ organizationId: 'org_1',+ projectId: 'proj_1',+ public: true,+ password: null,+ })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('dashboardSettings rejects an unauthenticated caller', async () => {+ const caller = await anonCaller();+ await expect(+ caller.dashboardSettings({ projectId: 'proj_1', dashboardId: 'dash_1' })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('createDashboard rejects an unauthenticated caller before touching a project', async () => {+ const caller = await anonCaller();+ await expect(+ caller.createDashboard({+ organizationId: 'org_1',+ projectId: 'proj_1',+ dashboardId: 'dash_1',+ public: true,+ password: null,+ })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('reportSettings rejects an unauthenticated caller', async () => {+ const caller = await anonCaller();+ await expect(+ caller.reportSettings({ projectId: 'proj_1', reportId: 'report_1' })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('createReport rejects an unauthenticated caller before touching a project', async () => {+ const caller = await anonCaller();+ await expect(+ caller.createReport({+ organizationId: 'org_1',+ projectId: 'proj_1',+ reportId: 'report_1',+ public: true,+ password: null,+ })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});diff --git a/packages/core/src/modules/share/share.rpc.ts b/packages/core/src/modules/share/share.rpc.tsnew file mode 100644index 000000000..24c48aa44--- /dev/null+++ b/packages/core/src/modules/share/share.rpc.ts@@ -0,0 +1,118 @@+// Ported from packages/trpc/src/routers/share.ts (M6-004).+//+// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware+// stack — lands in core with auth (rpc/base.ts: "those need the resolved+// Session shape and the access rules, so they land with auth (P6)"). Until+// then this router does its own minimal "is anyone logged in" check inline,+// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route+// through packages/trpc's own `protectedProcedure` (full stack included) and+// delegates its handler bodies to core's share functions (DELEGATE+// PATTERN) — this module has no queue/cron of its own, so there is no+// `ctx.services.share`, same as `user`/`project`.+//+// The per-project access ladder itself IS shared: `./src/access.ts` binds+// core's shared/access.ts ladder to @openpanel/db's real lookups, the same+// way packages/trpc/src/access.ts does for V1. `createOverview` has no access+// check here either — same gap V1's router has (ported verbatim, not fixed).++import { z } from 'zod';+import { createTRPCRouter, procedure } from '../../rpc/base';+import { TRPCAccessError } from '../../rpc/errors';+import { zShareDashboard, zShareOverview, zShareReport } from './share.constants';+import {+ createShareDashboard,+ createShareOverview,+ createShareReport,+ getShareDashboard,+ getShareDashboardReports,+ getShareDashboardSettings,+ getShareOverview,+ getShareOverviewSettings,+ getShareReport,+ getShareReportSettings,+} from './share.service';++function loadAccessChecks() {+ return import('./src/access');+}++function requireLogin(userId: string | null | undefined): string {+ if (!userId) {+ throw new TRPCAccessError('Not authenticated');+ }+ return userId;+}++export const shareRouter = createTRPCRouter({+ overview: procedure+ .input(z.object({ shareId: z.string() }))+ .query(({ input, ctx }) => getShareOverview(input.shareId, ctx.cookies)),++ overviewSettings: procedure+ .input(z.object({ projectId: z.string() }))+ .query(({ input, ctx }) => {+ requireLogin(ctx.session.userId);+ return getShareOverviewSettings(input.projectId);+ }),++ createOverview: procedure+ .input(zShareOverview)+ .mutation(({ input, ctx }) => {+ requireLogin(ctx.session.userId);+ return createShareOverview(input);+ }),++ dashboard: procedure+ .input(z.object({ shareId: z.string() }))+ .query(({ input, ctx }) => getShareDashboard(input.shareId, ctx.cookies)),++ dashboardSettings: procedure+ .input(z.object({ projectId: z.string(), dashboardId: z.string() }))+ .query(({ input, ctx }) => {+ requireLogin(ctx.session.userId);+ return getShareDashboardSettings(input.projectId, input.dashboardId);+ }),++ createDashboard: procedure+ .input(zShareDashboard)+ .mutation(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ const { requireProjectAccess } = await loadAccessChecks();+ await requireProjectAccess({+ userId,+ projectId: input.projectId,+ level: 'write',+ });+ return createShareDashboard(input);+ }),++ dashboardReports: procedure+ .input(z.object({ shareId: z.string() }))+ .query(({ input, ctx }) =>+ getShareDashboardReports(input.shareId, ctx.cookies)+ ),++ report: procedure+ .input(z.object({ shareId: z.string() }))+ .query(({ input, ctx }) => getShareReport(input.shareId, ctx.cookies)),++ reportSettings: procedure+ .input(z.object({ projectId: z.string(), reportId: z.string() }))+ .query(({ input, ctx }) => {+ requireLogin(ctx.session.userId);+ return getShareReportSettings(input.projectId, input.reportId);+ }),++ createReport: procedure+ .input(zShareReport)+ .mutation(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ const { requireProjectAccess } = await loadAccessChecks();+ await requireProjectAccess({+ userId,+ projectId: input.projectId,+ level: 'write',+ });+ return createShareReport(input);+ }),+});diff --git a/packages/core/src/modules/share/share.service.test.ts b/packages/core/src/modules/share/share.service.test.tsnew file mode 100644index 000000000..9d17e8807--- /dev/null+++ b/packages/core/src/modules/share/share.service.test.ts@@ -0,0 +1,399 @@+// share.service.ts's db access is lazy (`await import(...)` inside each+// function — see the file's header), which is exactly what makes+// `mock.module` work here with no import-time side effects to race: every+// mock below is registered before the subject's first call, not before its+// (side-effect-free) import.++import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';++interface FakeShare {+ id: string;+ organizationId: string;+ projectId: string;+ public: boolean;+ password: string | null;+}++interface FakeDashboardShare extends FakeShare {+ dashboardId: string;+}++interface FakeReportShare extends FakeShare {+ reportId: string;+}++const overviewStore = new Map<string, FakeShare>();+const dashboardShareStore = new Map<string, FakeDashboardShare>();+const reportShareStore = new Map<string, FakeReportShare>();++const ORG = { name: 'Acme Inc' };+const PROJECT = { name: 'Landing page' };++function findOverviewByProjectId(projectId: string) {+ return [...overviewStore.values()].find((s) => s.projectId === projectId);+}++function findDashboardShareByDashboardId(dashboardId: string) {+ return [...dashboardShareStore.values()].find(+ (s) => s.dashboardId === dashboardId+ );+}++function findReportShareByReportId(reportId: string) {+ return [...reportShareStore.values()].find((s) => s.reportId === reportId);+}++const shareOverview = {+ findUnique: mock(+ async ({ where }: { where: { id?: string; projectId?: string } }) => {+ const share = where.id+ ? overviewStore.get(where.id)+ : where.projectId+ ? findOverviewByProjectId(where.projectId)+ : undefined;+ if (!share) {+ return null;+ }+ return { ...share, organization: ORG, project: PROJECT };+ }+ ),+ findFirst: mock(async ({ where: { id } }: { where: { id: string } }) => {+ const share = overviewStore.get(id);+ return share ? { ...share, project: PROJECT } : null;+ }),+ upsert: mock(+ async ({+ where: { projectId },+ create,+ update,+ }: {+ where: { projectId: string };+ create: FakeShare;+ update: { public: boolean; password: string | null };+ }) => {+ const existing = findOverviewByProjectId(projectId);+ const next = existing+ ? { ...existing, ...update }+ : { ...create };+ overviewStore.set(next.id, next);+ return next;+ }+ ),+};++const shareDashboard = {+ findUnique: mock(+ async ({ where }: { where: { id?: string; dashboardId?: string } }) => {+ const share = where.id+ ? dashboardShareStore.get(where.id)+ : where.dashboardId+ ? findDashboardShareByDashboardId(where.dashboardId)+ : undefined;+ if (!share) {+ return null;+ }+ return { ...share, organization: ORG, project: PROJECT, dashboard: { name: 'Main' } };+ }+ ),+ findFirst: mock(async ({ where: { id } }: { where: { id: string } }) => {+ const share = dashboardShareStore.get(id);+ if (!share) {+ return null;+ }+ return {+ ...share,+ dashboard: { name: 'Main', project: PROJECT, reports: [] },+ };+ }),+ upsert: mock(+ async ({+ where: { dashboardId },+ create,+ update,+ }: {+ where: { dashboardId: string };+ create: FakeDashboardShare;+ update: { public: boolean; password: string | null };+ }) => {+ const existing = findDashboardShareByDashboardId(dashboardId);+ const next = existing ? { ...existing, ...update } : { ...create };+ dashboardShareStore.set(next.id, next);+ return next;+ }+ ),+};++const shareReport = {+ findUnique: mock(+ async ({ where }: { where: { id?: string; reportId?: string } }) => {+ const share = where.id+ ? reportShareStore.get(where.id)+ : where.reportId+ ? findReportShareByReportId(where.reportId)+ : undefined;+ if (!share) {+ return null;+ }+ return {+ ...share,+ organization: ORG,+ project: PROJECT,+ report: { id: 'report_raw' },+ };+ }+ ),+ findFirst: mock(async ({ where: { id } }: { where: { id: string } }) => {+ const share = reportShareStore.get(id);+ return share ? { ...share, report: { project: PROJECT } } : null;+ }),+ upsert: mock(+ async ({+ where: { reportId },+ create,+ update,+ }: {+ where: { reportId: string };+ create: FakeReportShare;+ update: { public: boolean; password: string | null };+ }) => {+ const existing = findReportShareByReportId(reportId);+ const next = existing ? { ...existing, ...update } : { ...create };+ reportShareStore.set(next.id, next);+ return next;+ }+ ),+};++const actualPrismaClient = await import('@openpanel/db/src/prisma-client');+mock.module('@openpanel/db/src/prisma-client', () => ({+ ...actualPrismaClient,+ db: { shareOverview, shareDashboard, shareReport },+}));++const getDashboardById = mock(async (id: string, projectId: string) =>+ id === 'dash_missing' ? null : { id, projectId, name: 'Main' }+);+mock.module('@openpanel/db/src/services/dashboard.service', () => ({+ getDashboardById,+}));++const getReportById = mock(async (id: string) =>+ id === 'report_missing'+ ? null+ : { id, projectId: 'proj_1', name: 'Weekly report' }+);+const transformReport = mock((report: unknown) => ({+ ...(report as Record<string, unknown>),+ transformed: true,+}));+const getReportsByDashboardId = mock(async () => [{ id: 'report_1' }]);+mock.module('@openpanel/db/src/services/reports.service', () => ({+ getReportById,+ transformReport,+ getReportsByDashboardId,+}));++const getProjectAccess = mock(+ async ({ userId }: { userId: string; projectId: string }) =>+ userId === 'member' ? { level: 'read' } : null+);+mock.module('@openpanel/db/src/services/access.service', () => ({+ getProjectAccess,+}));++let subject: typeof import('./share.service');+beforeAll(async () => {+ subject = await import('./share.service');+});++beforeEach(() => {+ overviewStore.clear();+ dashboardShareStore.clear();+ reportShareStore.clear();+ getDashboardById.mockClear();+ getReportById.mockClear();+ transformReport.mockClear();+ getReportsByDashboardId.mockClear();+ getProjectAccess.mockClear();+});++function cookies(values: Record<string, string> = {}) {+ return { get: (name: string) => values[name] };+}++test('getShareOverview throws NOT_FOUND when the share is missing or not public', async () => {+ await expect(subject.getShareOverview('missing', cookies())).rejects.toMatchObject(+ { code: 'NOT_FOUND' }+ );++ overviewStore.set('share_1', {+ id: 'share_1',+ organizationId: 'org_1',+ projectId: 'proj_1',+ public: false,+ password: null,+ });+ await expect(subject.getShareOverview('share_1', cookies())).rejects.toMatchObject(+ { code: 'NOT_FOUND' }+ );+});++test('getShareOverview returns a locked shape when password-protected without the unlock cookie', async () => {+ overviewStore.set('share_1', {+ id: 'share_1',+ organizationId: 'org_1',+ projectId: 'proj_1',+ public: true,+ password: 'hashed',+ });++ const result = await subject.getShareOverview('share_1', cookies());+ expect(result).toEqual({+ id: 'share_1',+ requiresPassword: true,+ organization: ORG,+ project: PROJECT,+ });+ // Never leaks the hash on the locked shape.+ expect(result).not.toHaveProperty('password');+});++test('getShareOverview unlocks with the shared-overview cookie', async () => {+ overviewStore.set('share_1', {+ id: 'share_1',+ organizationId: 'org_1',+ projectId: 'proj_1',+ public: true,+ password: 'hashed',+ });++ const result = await subject.getShareOverview(+ 'share_1',+ cookies({ 'shared-overview-share_1': '1' })+ );+ expect(result).toMatchObject({ id: 'share_1', requiresPassword: false });+});++test('getShareOverviewSettings returns null when no share exists for the project', async () => {+ expect(await subject.getShareOverviewSettings('proj_missing')).toBeNull();+});++test('createShareOverview hashes the password and reports hasPassword', async () => {+ const result = await subject.createShareOverview({+ organizationId: 'org_1',+ projectId: 'proj_1',+ public: true,+ password: 'sekret123',+ });+ expect(result).toMatchObject({ public: true, hasPassword: true });++ const noPassword = await subject.createShareOverview({+ organizationId: 'org_1',+ projectId: 'proj_2',+ public: false,+ password: null,+ });+ expect(noPassword).toMatchObject({ public: false, hasPassword: false });+});++test('createShareDashboard throws NOT_FOUND when the dashboard does not exist', async () => {+ await expect(+ subject.createShareDashboard({+ organizationId: 'org_1',+ projectId: 'proj_1',+ dashboardId: 'dash_missing',+ public: true,+ password: null,+ })+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+});++test('createShareDashboard upserts once the dashboard exists', async () => {+ const result = await subject.createShareDashboard({+ organizationId: 'org_1',+ projectId: 'proj_1',+ dashboardId: 'dash_1',+ public: true,+ password: null,+ });+ expect(result).toMatchObject({ public: true, hasPassword: false });+});++test('getShareDashboardReports rejects without the unlock cookie when password-protected', async () => {+ dashboardShareStore.set('share_1', {+ id: 'share_1',+ organizationId: 'org_1',+ projectId: 'proj_1',+ dashboardId: 'dash_1',+ public: true,+ password: 'hashed',+ });++ await expect(+ subject.getShareDashboardReports('share_1', cookies())+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('getShareDashboardReports returns the dashboard reports once unlocked', async () => {+ dashboardShareStore.set('share_1', {+ id: 'share_1',+ organizationId: 'org_1',+ projectId: 'proj_1',+ dashboardId: 'dash_1',+ public: true,+ password: null,+ });++ const result = await subject.getShareDashboardReports('share_1', cookies());+ expect(result).toMatchObject([{ id: 'report_1' }]);+ expect(getReportsByDashboardId).toHaveBeenCalledWith('dash_1');+});++test('createShareReport throws NOT_FOUND when the report belongs to a different project', async () => {+ await expect(+ subject.createShareReport({+ organizationId: 'org_1',+ projectId: 'proj_other',+ reportId: 'report_1',+ public: true,+ password: null,+ })+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+});++test('getShareReport transforms the report once unlocked', async () => {+ reportShareStore.set('share_1', {+ id: 'share_1',+ organizationId: 'org_1',+ projectId: 'proj_1',+ reportId: 'report_1',+ public: true,+ password: null,+ });++ const result = await subject.getShareReport('share_1', cookies());+ expect(result).toMatchObject({ id: 'share_1', requiresPassword: false });+ expect(transformReport).toHaveBeenCalledWith({ id: 'report_raw' });+});++test('validateOverviewShareAccess requires membership when no shareId is given', async () => {+ await expect(+ subject.validateOverviewShareAccess(undefined, 'proj_1', {+ cookies: cookies(),+ session: undefined,+ })+ ).rejects.toThrow('Authentication required');++ await expect(+ subject.validateOverviewShareAccess(undefined, 'proj_1', {+ cookies: cookies(),+ session: { userId: 'stranger' },+ })+ ).rejects.toThrow('You do not have access to this project');++ const result = await subject.validateOverviewShareAccess(undefined, 'proj_1', {+ cookies: cookies(),+ session: { userId: 'member' },+ });+ expect(result).toEqual({ isValid: true });+});diff --git a/packages/core/src/modules/share/share.service.ts b/packages/core/src/modules/share/share.service.tsnew file mode 100644index 000000000..9f47a92d2--- /dev/null+++ b/packages/core/src/modules/share/share.service.ts@@ -0,0 +1,545 @@+// Moved from packages/db/src/services/share.service.ts, plus the+// query/mutation bodies packages/trpc/src/routers/share.ts held inline+// (M6-004, DELEGATE PATTERN: V1's router and this package's own share.rpc.ts+// share one implementation, same as organization.service.ts since M6-001).+// packages/db keeps a re-export shim: auth.service.ts's signInToShare+// (M6-003) and packages/trpc's chart/overview routers still reach+// validateShareAccess/validateOverviewShareAccess through it.+//+// db access is LAZY, not a static top-level import — see insight.service.ts's+// header for the full reasoning (jobs.registry.ts and services.ts pull this+// module into the eager barrel chain nearly every core test file reaches, and+// constructing @openpanel/db's clients at import time would spawn a+// pino-pretty transport worker thread per test file).++import ShortUniqueId from 'short-unique-id';+import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';+import { hashPassword } from '../auth/auth.service';++const SHARE_ID_LENGTH = 6;+const uid = new ShortUniqueId({ length: SHARE_ID_LENGTH });++/** `HttpCtx.cookies`'s shape, named locally so this file has no import from+ * the rpc/http layer that calls it — same as auth.service.ts's CookieReader. */+interface CookieReader {+ get(name: string): string | undefined;+}++function loadDb() {+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);+}++function loadAccessService() {+ return import('@openpanel/db/src/services/access.service');+}++function loadDashboardService() {+ return import('@openpanel/db/src/services/dashboard.service');+}++function loadReportsService() {+ return import('@openpanel/db/src/services/reports.service');+}++// -----------------------------------------------------------------------+// Raw lookups (ported verbatim from packages/db/src/services/share.service.ts).++export async function getShareOverviewById(id: string) {+ const db = await loadDb();+ return db.shareOverview.findFirst({+ where: { id },+ include: { project: true },+ });+}++export async function getShareByProjectId(projectId: string) {+ const db = await loadDb();+ return db.shareOverview.findUnique({ where: { projectId } });+}++export async function getShareDashboardById(id: string) {+ const db = await loadDb();+ return db.shareDashboard.findFirst({+ where: { id },+ include: { dashboard: { include: { project: true } } },+ });+}++export async function getShareDashboardByDashboardId(dashboardId: string) {+ const db = await loadDb();+ return db.shareDashboard.findUnique({ where: { dashboardId } });+}++export async function getShareReportById(id: string) {+ const db = await loadDb();+ return db.shareReport.findFirst({+ where: { id },+ include: { report: { include: { project: true } } },+ });+}++export async function getShareReportByReportId(reportId: string) {+ const db = await loadDb();+ return db.shareReport.findUnique({ where: { reportId } });+}++/**+ * @deprecated Zero call sites (ADR-015 register entry #14, graded DEAD).+ * Ported as-is — removal is a separate P6/P7 task, not this one's.+ */+export async function validateReportAccess(+ reportId: string,+ shareId: string,+ shareType: 'dashboard' | 'report'+) {+ const db = await loadDb();++ if (shareType === 'dashboard') {+ const share = await db.shareDashboard.findUnique({+ where: { id: shareId },+ include: {+ dashboard: {+ include: {+ reports: { where: { id: reportId } },+ },+ },+ },+ });++ if (!share || !share.public) {+ throw new Error('Share not found or not public');+ }++ if (!share.dashboard.reports.some((r) => r.id === reportId)) {+ throw new Error('Report does not belong to this dashboard');+ }++ return share;+ }++ const share = await db.shareReport.findUnique({+ where: { id: shareId },+ include: { report: true },+ });++ if (!share || !share.public) {+ throw new Error('Share not found or not public');+ }++ if (share.reportId !== reportId) {+ throw new Error('Report ID mismatch');+ }++ return share;+}++export async function validateShareAccess(+ shareId: string,+ reportId: string,+ ctx: {+ cookies: CookieReader;+ session?: { userId?: string | null };+ }+): Promise<{ projectId: string; isValid: boolean }> {+ const db = await loadDb();+ const { getProjectAccess } = await loadAccessService();++ const dashboardShare = await db.shareDashboard.findUnique({+ where: { id: shareId },+ include: {+ dashboard: {+ include: {+ reports: { where: { id: reportId } },+ },+ },+ },+ });++ if (+ dashboardShare?.dashboard?.reports &&+ dashboardShare.dashboard.reports.length > 0+ ) {+ if (!dashboardShare.public) {+ throw new Error('Share not found or not public');+ }++ const projectId = dashboardShare.projectId;++ if (!dashboardShare.password) {+ return { projectId, isValid: true };+ }++ const hasCookie = !!ctx.cookies.get(`shared-dashboard-${shareId}`);+ const hasMemberAccess =+ ctx.session?.userId &&+ (await getProjectAccess({ userId: ctx.session.userId, projectId }));++ return { projectId, isValid: hasCookie || !!hasMemberAccess };+ }++ const reportShare = await db.shareReport.findUnique({+ where: { id: shareId, reportId },+ include: { report: true },+ });++ if (reportShare) {+ if (!reportShare.public) {+ throw new Error('Share not found or not public');+ }++ const projectId = reportShare.projectId;++ if (!reportShare.password) {+ return { projectId, isValid: true };+ }++ const hasCookie = !!ctx.cookies.get(`shared-report-${shareId}`);+ const hasMemberAccess =+ ctx.session?.userId &&+ (await getProjectAccess({ userId: ctx.session.userId, projectId }));++ return { projectId, isValid: hasCookie || !!hasMemberAccess };+ }++ throw new Error('Share not found');+}++export async function validateOverviewShareAccess(+ shareId: string | undefined,+ projectId: string,+ ctx: {+ cookies: CookieReader;+ session?: { userId?: string | null };+ }+): Promise<{ isValid: boolean }> {+ const db = await loadDb();+ const { getProjectAccess } = await loadAccessService();++ if (shareId) {+ const share = await db.shareOverview.findUnique({+ where: { id: shareId },+ });++ if (!share || !share.public) {+ throw new Error('Share not found or not public');+ }++ if (share.projectId !== projectId) {+ throw new Error('Project ID mismatch');+ }++ if (!share.password) {+ return { isValid: true };+ }++ const hasCookie = !!ctx.cookies.get(`shared-overview-${shareId}`);+ const hasMemberAccess =+ ctx.session?.userId &&+ (await getProjectAccess({ userId: ctx.session.userId, projectId }));++ return { isValid: hasCookie || !!hasMemberAccess };+ }++ if (!ctx.session?.userId) {+ throw new Error('Authentication required');+ }++ const access = await getProjectAccess({+ userId: ctx.session.userId,+ projectId,+ });++ if (!access) {+ throw new Error('You do not have access to this project');+ }++ return { isValid: true };+}++// -----------------------------------------------------------------------+// Router bodies (ported from packages/trpc/src/routers/share.ts).+//+// The `overview`/`dashboard`/`report` functions below are unauthenticated and+// serve the public viewer, addressed only by `shareId`. They project an+// explicit allow-list of columns and refuse to hand back any shared content+// until the `public` flag and the password cookie have both been checked.+// Returning the row and letting the client decide is what leaked the argon2+// password hash and private report definitions (GHSA-7gv7-c464-9wh8).+//+// The `*Settings`/`create*` functions are for the owner's share modal and+// never return the password hash either — only whether one is set.++/** Shape returned to a viewer who has not unlocked a password-protected share. */+function lockedShare(+ id: string,+ organization: { name: string },+ project: { name: string }+) {+ return {+ id,+ requiresPassword: true as const,+ organization,+ project,+ };+}++export async function getShareOverview(shareId: string, cookies: CookieReader) {+ const db = await loadDb();+ const share = await db.shareOverview.findUnique({+ where: { id: shareId },+ select: {+ id: true,+ public: true,+ password: true,+ projectId: true,+ organization: { select: { name: true } },+ project: { select: { name: true } },+ },+ });++ if (!(share && share.public)) {+ throw new TRPCNotFoundError('Share not found');+ }++ const hasAccess = !!cookies.get(`shared-overview-${share.id}`);+ if (share.password && !hasAccess) {+ return lockedShare(share.id, share.organization, share.project);+ }++ return {+ id: share.id,+ requiresPassword: false as const,+ organization: share.organization,+ project: share.project,+ projectId: share.projectId,+ };+}++export async function getShareOverviewSettings(projectId: string) {+ const db = await loadDb();+ const share = await db.shareOverview.findUnique({+ where: { projectId },+ select: { id: true, public: true, password: true },+ });++ if (!share) {+ return null;+ }++ return { id: share.id, public: share.public, hasPassword: !!share.password };+}++export async function createShareOverview(input: {+ organizationId: string;+ projectId: string;+ public: boolean;+ password: string | null;+}) {+ const db = await loadDb();+ const passwordHash = input.password ? await hashPassword(input.password) : null;++ const share = await db.shareOverview.upsert({+ where: { projectId: input.projectId },+ create: {+ id: uid.rnd(),+ organizationId: input.organizationId,+ projectId: input.projectId,+ public: input.public,+ password: passwordHash,+ },+ update: { public: input.public, password: passwordHash },+ select: { id: true, public: true, password: true },+ });++ return { id: share.id, public: share.public, hasPassword: !!share.password };+}++export async function getShareDashboard(shareId: string, cookies: CookieReader) {+ const db = await loadDb();+ const share = await db.shareDashboard.findUnique({+ where: { id: shareId },+ select: {+ id: true,+ public: true,+ password: true,+ organization: { select: { name: true } },+ project: { select: { name: true } },+ dashboard: { select: { name: true } },+ },+ });++ if (!(share && share.public)) {+ throw new TRPCNotFoundError('Dashboard share not found');+ }++ const hasAccess = !!cookies.get(`shared-dashboard-${share.id}`);+ if (share.password && !hasAccess) {+ return lockedShare(share.id, share.organization, share.project);+ }++ return {+ id: share.id,+ requiresPassword: false as const,+ organization: share.organization,+ project: share.project,+ dashboard: share.dashboard,+ };+}++export async function getShareDashboardSettings(+ projectId: string,+ dashboardId: string+) {+ const db = await loadDb();+ const share = await db.shareDashboard.findUnique({+ where: { dashboardId },+ select: { id: true, public: true, password: true, projectId: true },+ });++ if (!share || share.projectId !== projectId) {+ return null;+ }++ return { id: share.id, public: share.public, hasPassword: !!share.password };+}++/** The caller must already have write access to `input.projectId` — the RPC+ * layer's job (each transport still owns its own access-check plumbing). */+export async function createShareDashboard(input: {+ organizationId: string;+ projectId: string;+ dashboardId: string;+ public: boolean;+ password: string | null;+}) {+ const { getDashboardById } = await loadDashboardService();+ const dashboard = await getDashboardById(input.dashboardId, input.projectId);+ if (!dashboard) {+ throw new TRPCNotFoundError('Dashboard not found');+ }++ const passwordHash = input.password ? await hashPassword(input.password) : null;++ const db = await loadDb();+ const share = await db.shareDashboard.upsert({+ where: { dashboardId: input.dashboardId },+ create: {+ id: uid.rnd(),+ organizationId: input.organizationId,+ projectId: input.projectId,+ dashboardId: input.dashboardId,+ public: input.public,+ password: passwordHash,+ },+ update: { public: input.public, password: passwordHash },+ select: { id: true, public: true, password: true },+ });++ return { id: share.id, public: share.public, hasPassword: !!share.password };+}++export async function getShareDashboardReports(+ shareId: string,+ cookies: CookieReader+) {+ const share = await getShareDashboardById(shareId);++ if (!(share && share.public)) {+ throw new TRPCNotFoundError('Dashboard share not found');+ }++ const hasAccess = !!cookies.get(`shared-dashboard-${share.id}`);+ if (share.password && !hasAccess) {+ throw new TRPCAccessError('Password required');+ }++ const { getReportsByDashboardId } = await loadReportsService();+ return getReportsByDashboardId(share.dashboardId);+}++export async function getShareReport(shareId: string, cookies: CookieReader) {+ const db = await loadDb();+ const share = await db.shareReport.findUnique({+ where: { id: shareId },+ select: {+ id: true,+ public: true,+ password: true,+ projectId: true,+ organization: { select: { name: true } },+ project: { select: { name: true } },+ report: true,+ },+ });++ if (!(share && share.public)) {+ throw new TRPCNotFoundError('Report share not found');+ }++ const hasAccess = !!cookies.get(`shared-report-${share.id}`);+ if (share.password && !hasAccess) {+ return lockedShare(share.id, share.organization, share.project);+ }++ const { transformReport } = await loadReportsService();+ return {+ id: share.id,+ requiresPassword: false as const,+ organization: share.organization,+ project: share.project,+ projectId: share.projectId,+ report: transformReport(share.report),+ };+}++export async function getShareReportSettings(+ projectId: string,+ reportId: string+) {+ const db = await loadDb();+ const share = await db.shareReport.findUnique({+ where: { reportId },+ select: { id: true, public: true, password: true, projectId: true },+ });++ if (!share || share.projectId !== projectId) {+ return null;+ }++ return { id: share.id, public: share.public, hasPassword: !!share.password };+}++/** The caller must already have write access to `input.projectId` — the RPC+ * layer's job (each transport still owns its own access-check plumbing). */+export async function createShareReport(input: {+ organizationId: string;+ projectId: string;+ reportId: string;+ public: boolean;+ password: string | null;+}) {+ const { getReportById } = await loadReportsService();+ const report = await getReportById(input.reportId);+ if (!report || report.projectId !== input.projectId) {+ throw new TRPCNotFoundError('Report not found');+ }++ const passwordHash = input.password ? await hashPassword(input.password) : null;++ const db = await loadDb();+ const share = await db.shareReport.upsert({+ where: { reportId: input.reportId },+ create: {+ id: uid.rnd(),+ organizationId: input.organizationId,+ projectId: input.projectId,+ reportId: input.reportId,+ public: input.public,+ password: passwordHash,+ },+ update: { public: input.public, password: passwordHash },+ select: { id: true, public: true, password: true },+ });++ return { id: share.id, public: share.public, hasPassword: !!share.password };+}diff --git a/packages/core/src/modules/share/src/access.ts b/packages/core/src/modules/share/src/access.tsnew file mode 100644index 000000000..18ce81d56--- /dev/null+++ b/packages/core/src/modules/share/src/access.ts@@ -0,0 +1,22 @@+// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for+// this module's own router — the same binding packages/trpc/src/access.ts+// does for V1, self-contained here because the general core -> db binding+// itself moves with auth (P6), not this wave. Same shape as+// conversation/src/access.ts.++import {+ canWriteProject,+ getOrganizationAccess,+ getProjectAccess,+} from '@openpanel/db/src/services/access.service';+import { getProjectById } from '@openpanel/db/src/services/project.service';+import { createAccessChecks } from '../../../shared/access';++const checks = createAccessChecks({+ getProjectAccess,+ canWriteProject,+ getOrganizationAccess,+ getProjectById,+});++export const requireProjectAccess = checks.requireProjectAccess;diff --git a/packages/core/src/rpc.router.ts b/packages/core/src/rpc.router.tsindex edfc90f42..52a93a7bf 100644--- a/packages/core/src/rpc.router.ts+++ b/packages/core/src/rpc.router.ts@@ -9,6 +9,7 @@ import { authRouter } from './modules/auth/auth.rpc';import { clientRouter } from './modules/client/client.rpc';import { cohortRouter } from './modules/cohort/cohort.rpc';import { conversationRouter } from './modules/conversation/conversation.rpc';+import { emailRouter } from './modules/email/email.rpc';import { gscRouter } from './modules/gsc/gsc.rpc';import { healthRouter } from './modules/health/health.rpc';import { importRouter } from './modules/import/import.rpc';@@ -16,6 +17,8 @@ import { insightRouter } from './modules/insight/insight.rpc';import { onboardingRouter } from './modules/onboarding/onboarding.rpc';import { organizationRouter } from './modules/organization/organization.rpc';import { projectRouter } from './modules/project/project.rpc';+import { referenceRouter } from './modules/reference/reference.rpc';+import { shareRouter } from './modules/share/share.rpc';import { userRouter } from './modules/user/user.rpc';import { createTRPCRouter } from './rpc/base';@@ -33,6 +36,9 @@ export const appRouter = createTRPCRouter({client: clientRouter,auth: authRouter,onboarding: onboardingRouter,+ reference: referenceRouter,+ share: shareRouter,+ email: emailRouter,});export type AppRouter = typeof appRouter;diff --git a/packages/db/src/services/reference.service.ts b/packages/db/src/services/reference.service.tsindex c589b05b8..d4f098dcd 100644--- a/packages/db/src/services/reference.service.ts+++ b/packages/db/src/services/reference.service.ts@@ -1,18 +1,15 @@-import type { Prisma, Reference } from '../prisma-client';-import { db } from '../prisma-client';--export type IServiceReference = Reference;--export async function getReferenceById(id: string) {- const reference = await db.reference.findUnique({- where: {- id,- },- });-- if (!reference) {- return null;- }-- return reference;-}+// The reference service — plus the query/mutation bodies+// packages/trpc/src/routers/reference.ts held inline — lives in+// @openpanel/core now (M6-004). Re-exported here for existing+// `@openpanel/db` importers — same shape as+// packages/db/src/services/organization.service.ts since M6-001.+export type { IServiceReference } from '@openpanel/core';+export {+ createReference,+ deleteReference,+ getChartReferences,+ getReferenceById,+ getReferenceByIdOrThrow,+ listReferences,+ updateReference,+} from '@openpanel/core';diff --git a/packages/db/src/services/share.service.ts b/packages/db/src/services/share.service.tsindex 2764aaa32..fb3f39e67 100644--- a/packages/db/src/services/share.service.ts+++ b/packages/db/src/services/share.service.ts@@ -1,283 +1,27 @@-import { db } from '../prisma-client';-import { getProjectAccess } from './access.service';--export function getShareOverviewById(id: string) {- return db.shareOverview.findFirst({- where: {- id,- },- include: {- project: true,- },- });-}--export function getShareByProjectId(projectId: string) {- return db.shareOverview.findUnique({- where: {- projectId,- },- });-}--// Dashboard sharing functions-export function getShareDashboardById(id: string) {- return db.shareDashboard.findFirst({- where: {- id,- },- include: {- dashboard: {- include: {- project: true,- },- },- },- });-}--export function getShareDashboardByDashboardId(dashboardId: string) {- return db.shareDashboard.findUnique({- where: {- dashboardId,- },- });-}--// Report sharing functions-export function getShareReportById(id: string) {- return db.shareReport.findFirst({- where: {- id,- },- include: {- report: {- include: {- project: true,- },- },- },- });-}--export function getShareReportByReportId(reportId: string) {- return db.shareReport.findUnique({- where: {- reportId,- },- });-}--// Validation for secure endpoints-export async function validateReportAccess(- reportId: string,- shareId: string,- shareType: 'dashboard' | 'report',-) {- if (shareType === 'dashboard') {- const share = await db.shareDashboard.findUnique({- where: { id: shareId },- include: {- dashboard: {- include: {- reports: {- where: { id: reportId },- },- },- },- },- });-- if (!share || !share.public) {- throw new Error('Share not found or not public');- }-- if (!share.dashboard.reports.some((r) => r.id === reportId)) {- throw new Error('Report does not belong to this dashboard');- }-- return share;- }-- const share = await db.shareReport.findUnique({- where: { id: shareId },- include: {- report: true,- },- });-- if (!share || !share.public) {- throw new Error('Share not found or not public');- }-- if (share.reportId !== reportId) {- throw new Error('Report ID mismatch');- }-- return share;-}--// Unified validation for share access-export async function validateShareAccess(- shareId: string,- reportId: string,- ctx: {- // Read by name only, so a transport that has no cookie record (Elysia's- // proxy, core's CookieJar) can satisfy this without materialising one.- cookies: { get(name: string): string | undefined };- session?: { userId?: string | null };- },-): Promise<{ projectId: string; isValid: boolean }> {- // Check ShareDashboard first- const dashboardShare = await db.shareDashboard.findUnique({- where: { id: shareId },- include: {- dashboard: {- include: {- reports: {- where: { id: reportId },- },- },- },- },- });-- if (- dashboardShare?.dashboard?.reports &&- dashboardShare.dashboard.reports.length > 0- ) {- if (!dashboardShare.public) {- throw new Error('Share not found or not public');- }-- const projectId = dashboardShare.projectId;-- // If no password is set, share is public and accessible- if (!dashboardShare.password) {- return {- projectId,- isValid: true,- };- }-- // If password is set, require cookie OR member access- const hasCookie = !!ctx.cookies.get(`shared-dashboard-${shareId}`);- const hasMemberAccess =- ctx.session?.userId &&- (await getProjectAccess({- userId: ctx.session.userId,- projectId,- }));-- return {- projectId,- isValid: hasCookie || !!hasMemberAccess,- };- }-- // Check ShareReport- const reportShare = await db.shareReport.findUnique({- where: { id: shareId, reportId },- include: {- report: true,- },- });-- if (reportShare) {- if (!reportShare.public) {- throw new Error('Share not found or not public');- }-- const projectId = reportShare.projectId;-- // If no password is set, share is public and accessible- if (!reportShare.password) {- return {- projectId,- isValid: true,- };- }-- // If password is set, require cookie OR member access- const hasCookie = !!ctx.cookies.get(`shared-report-${shareId}`);- const hasMemberAccess =- ctx.session?.userId &&- (await getProjectAccess({- userId: ctx.session.userId,- projectId,- }));-- return {- projectId,- isValid: hasCookie || !!hasMemberAccess,- };- }-- throw new Error('Share not found');-}--// Validation for overview share access-export async function validateOverviewShareAccess(- shareId: string | undefined,- projectId: string,- ctx: {- // Read by name only, so a transport that has no cookie record (Elysia's- // proxy, core's CookieJar) can satisfy this without materialising one.- cookies: { get(name: string): string | undefined };- session?: { userId?: string | null };- },-): Promise<{ isValid: boolean }> {- // If shareId is provided, validate share access- if (shareId) {- const share = await db.shareOverview.findUnique({- where: { id: shareId },- });-- if (!share || !share.public) {- throw new Error('Share not found or not public');- }-- // Verify the share is for the correct project- if (share.projectId !== projectId) {- throw new Error('Project ID mismatch');- }-- // If no password is set, share is public and accessible- if (!share.password) {- return {- isValid: true,- };- }-- // If password is set, require cookie OR member access- const hasCookie = !!ctx.cookies.get(`shared-overview-${shareId}`);- const hasMemberAccess =- ctx.session?.userId &&- (await getProjectAccess({- userId: ctx.session.userId,- projectId,- }));-- return {- isValid: hasCookie || !!hasMemberAccess,- };- }-- // If no shareId, require authenticated user with project access- if (!ctx.session?.userId) {- throw new Error('Authentication required');- }-- const access = await getProjectAccess({- userId: ctx.session.userId,- projectId,- });-- if (!access) {- throw new Error('You do not have access to this project');- }-- return {- isValid: true,- };-}+// The share service — plus the query/mutation bodies+// packages/trpc/src/routers/share.ts held inline — lives in @openpanel/core+// now (M6-004). Re-exported here for existing `@openpanel/db` importers+// (packages/trpc's chart/overview routers, which still reach+// validateShareAccess/validateOverviewShareAccess through it) — same shape+// as packages/db/src/services/organization.service.ts since M6-001.+export {+ createShareDashboard,+ createShareOverview,+ createShareReport,+ getShareByProjectId,+ getShareDashboard,+ getShareDashboardById,+ getShareDashboardByDashboardId,+ getShareDashboardReports,+ getShareDashboardSettings,+ getShareOverview,+ getShareOverviewById,+ getShareOverviewSettings,+ getShareReport,+ getShareReportById,+ getShareReportByReportId,+ getShareReportSettings,+ validateOverviewShareAccess,+ validateReportAccess,+ validateShareAccess,+} from '@openpanel/core';diff --git a/packages/trpc/src/routers/email.ts b/packages/trpc/src/routers/email.tsindex 0c37d3e48..aeef07d6a 100644--- a/packages/trpc/src/routers/email.ts+++ b/packages/trpc/src/routers/email.ts@@ -1,4 +1,11 @@-import { emailCategories } from '@openpanel/constants';+// Dissolved into @openpanel/core's email module (M6-004): `emailCategories`+// moved to packages/core/src/modules/email/email.constants.ts. This router+// stays (DELEGATE PATTERN) — it keeps V1's protectedProcedure stack and its+// own db calls (core's email module is R + C only, no service — see+// core's email.rpc.ts header), reading the same `emailCategories` core now+// owns instead of @openpanel/constants' copy.++import { emailCategories } from '@openpanel/core';import { db } from '@openpanel/db';import { verifyUnsubscribeToken } from '@openpanel/email';import { z } from 'zod';diff --git a/packages/trpc/src/routers/reference.ts b/packages/trpc/src/routers/reference.tsindex 8f208a3cf..58fe87d3e 100644--- a/packages/trpc/src/routers/reference.ts+++ b/packages/trpc/src/routers/reference.ts@@ -1,53 +1,46 @@-import { z } from 'zod';+// Dissolved into @openpanel/core's reference module (M6-004): the+// query/mutation bodies moved to+// packages/core/src/modules/reference/reference.service.ts. This router+// stays (DELEGATE PATTERN) — it keeps V1's protectedProcedure stack+// (session/access/logger middleware) and delegates every handler body to+// core's reference functions, same as organization's router does (M6-001).+// `create` has no access check here either — same gap core's own router has+// (ported verbatim, not fixed).-import { db, getChartStartEndDate, getSettingsForProject } from '@openpanel/db';+import {+ createReference,+ deleteReference,+ getChartReferences,+ getReferenceByIdOrThrow,+ listReferences,+ updateReference,+} from '@openpanel/core';import { zCreateReference, zRange } from '@openpanel/validation';-+import { z } from 'zod';import { getProjectAccess, requireProjectAccess } from '../access';import { TRPCForbiddenError } from '../errors';import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc';export const referenceRouter = createTRPCRouter({getReferences: protectedProcedure- .input(- z.object({- projectId: z.string(),- cursor: z.number().optional(),- }),- )- .query(async ({ input: { projectId, cursor }, ctx }) => {+ .input(z.object({ projectId: z.string(), cursor: z.number().optional() }))+ .query(async ({ input, ctx }) => {const access = await getProjectAccess({userId: ctx.session.userId,- projectId,+ projectId: input.projectId,});if (!access) {throw new TRPCForbiddenError('You do not have access to this project');}- return db.reference.findMany({- where: {- projectId,- },- take: 50,- skip: cursor ? cursor * 50 : 0,- });+ return listReferences(input);}),create: protectedProcedure.input(zCreateReference)- .mutation(- async ({ input: { title, description, datetime, projectId } }) => {- return db.reference.create({- data: {- title,- description,- projectId,- date: new Date(datetime),- },- });- },- ),+ .mutation(({ input }) => createReference(input)),+update: protectedProcedure.input(z.object({@@ -55,12 +48,10 @@ export const referenceRouter = createTRPCRouter({title: z.string(),description: z.string().nullish(),datetime: z.string(),- }),+ })).mutation(async ({ input, ctx }) => {- const existing = await db.reference.findUniqueOrThrow({- where: { id: input.id },- });+ const existing = await getReferenceByIdOrThrow(input.id);await requireProjectAccess({userId: ctx.session.userId,@@ -68,23 +59,13 @@ export const referenceRouter = createTRPCRouter({level: 'write',});- return db.reference.update({- where: { id: input.id },- data: {- title: input.title,- description: input.description ?? null,- date: new Date(input.datetime),- },- });+ return updateReference(input);}),+delete: protectedProcedure.input(z.object({ id: z.string() })).mutation(async ({ input: { id }, ctx }) => {- const reference = await db.reference.findUniqueOrThrow({- where: {- id,- },- });+ const reference = await getReferenceByIdOrThrow(id);await requireProjectAccess({userId: ctx.session.userId,@@ -92,12 +73,9 @@ export const referenceRouter = createTRPCRouter({level: 'write',});- return db.reference.delete({- where: {- id,- },- });+ return deleteReference(id);}),+getChartReferences: publicProcedure.input(z.object({@@ -105,19 +83,7 @@ export const referenceRouter = createTRPCRouter({startDate: z.string().nullish(),endDate: z.string().nullish(),range: zRange,- }),+ }))- .query(async ({ input: { projectId, ...input } }) => {- const { timezone } = await getSettingsForProject(projectId);- const { startDate, endDate } = getChartStartEndDate(input, timezone);- return db.reference.findMany({- where: {- projectId,- date: {- gte: new Date(startDate),- lte: new Date(endDate),- },- },- });- }),+ .query(({ input }) => getChartReferences(input)),});diff --git a/packages/trpc/src/routers/share.test.ts b/packages/trpc/src/routers/share.test.tsindex 26ddade8d..83f647f6a 100644--- a/packages/trpc/src/routers/share.test.ts+++ b/packages/trpc/src/routers/share.test.ts@@ -11,23 +11,41 @@ const {shareOverviewFindUnique: vi.fn(),}));+// The share business logic itself moved to @openpanel/core (M6-004); share.ts+// now only delegates to it. `@openpanel/db` is still mocked for `../access`'s+// and `trpc.ts`'s own imports (unrelated to this file's assertions) — the+// deep `@openpanel/db/src/*` paths below are what core's share functions+// actually read through (lazy `await import(...)`, so vi.mock still applies+// to the dynamic form).vi.mock('@openpanel/db', () => ({+ getProjectById: vi.fn(),+ getProjectAccess: vi.fn(),+ getOrganizationAccess: vi.fn(),+ getClientAccess: vi.fn(),+ canWriteProject: vi.fn(),+ runWithAlsSession: (_id: unknown, fn: () => unknown) => fn(),+}));++vi.mock('@openpanel/db/src/prisma-client', () => ({db: {shareReport: { findUnique: shareReportFindUnique },shareDashboard: { findUnique: shareDashboardFindUnique },shareOverview: { findUnique: shareOverviewFindUnique },},+}));++vi.mock('@openpanel/db/src/services/reports.service', () => ({transformReport: (report: unknown) => report,- getDashboardById: vi.fn(),getReportById: vi.fn(),getReportsByDashboardId: vi.fn(),- getShareDashboardById: vi.fn(),- getProjectById: vi.fn(),+}));++vi.mock('@openpanel/db/src/services/dashboard.service', () => ({+ getDashboardById: vi.fn(),+}));++vi.mock('@openpanel/db/src/services/access.service', () => ({getProjectAccess: vi.fn(),- getOrganizationAccess: vi.fn(),- getClientAccess: vi.fn(),- canWriteProject: vi.fn(),- runWithAlsSession: (_id: unknown, fn: () => unknown) => fn(),}));import { shareRouter } from './share';diff --git a/packages/trpc/src/routers/share.ts b/packages/trpc/src/routers/share.tsindex ba725fb3f..3abcd8d47 100644--- a/packages/trpc/src/routers/share.ts+++ b/packages/trpc/src/routers/share.ts@@ -1,191 +1,51 @@-import { hashUserPassword as hashPassword } from '@openpanel/core';-import {- db,- getDashboardById,- getReportById,- getReportsByDashboardId,- getShareDashboardById,- transformReport,-} from '@openpanel/db';+// Dissolved into @openpanel/core's share module (M6-004): the query/mutation+// bodies moved to packages/core/src/modules/share/share.service.ts. This+// router stays (DELEGATE PATTERN) — it keeps V1's protectedProcedure stack+// (session/access/logger middleware) and delegates every handler body to+// core's share functions, same as reference's router does.+import {+ createShareDashboard,+ createShareOverview,+ createShareReport,+ getShareDashboard,+ getShareDashboardReports,+ getShareDashboardSettings,+ getShareOverview,+ getShareOverviewSettings,+ getShareReport,+ getShareReportSettings,zShareDashboard,zShareOverview,zShareReport,-} from '@openpanel/validation';-import ShortUniqueId from 'short-unique-id';+} from '@openpanel/core';import { z } from 'zod';import { requireProjectAccess } from '../access';-import { TRPCAccessError, TRPCNotFoundError } from '../errors';import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc';-const uid = new ShortUniqueId({ length: 6 });--/**- * Share lookups are split in two on purpose.- *- * The `overview`/`dashboard`/`report` procedures are unauthenticated and serve- * the public viewer, addressed only by `shareId` (the value in the share link).- * They project an explicit allow-list of columns and refuse to hand back any- * shared content until the `public` flag and the password cookie have both been- * checked. Returning the row and letting the client decide is what leaked the- * argon2 password hash and private report definitions (GHSA-7gv7-c464-9wh8).- *- * The `*Settings` procedures are authenticated and serve the owner's share- * modal, addressed by the underlying object id. They never return the hash- * either - only whether one is set.- */--/** Shape returned to a viewer who has not unlocked a password-protected share. */-function lockedShare(- id: string,- organization: { name: string },- project: { name: string }-) {- return {- id,- requiresPassword: true as const,- organization,- project,- };-}-export const shareRouter = createTRPCRouter({overview: publicProcedure.input(z.object({ shareId: z.string() }))- .query(async ({ input, ctx }) => {- const share = await db.shareOverview.findUnique({- where: { id: input.shareId },- select: {- id: true,- public: true,- password: true,- projectId: true,- organization: { select: { name: true } },- project: { select: { name: true } },- },- });-- if (!(share && share.public)) {- throw new TRPCNotFoundError('Share not found');- }-- const hasAccess = !!ctx.cookies.get(`shared-overview-${share.id}`);- if (share.password && !hasAccess) {- return lockedShare(share.id, share.organization, share.project);- }-- return {- id: share.id,- requiresPassword: false as const,- organization: share.organization,- project: share.project,- projectId: share.projectId,- };- }),+ .query(({ input, ctx }) => getShareOverview(input.shareId, ctx.cookies)),overviewSettings: protectedProcedure.input(z.object({ projectId: z.string() }))- .query(async ({ input }) => {- const share = await db.shareOverview.findUnique({- where: { projectId: input.projectId },- select: { id: true, public: true, password: true },- });-- if (!share) {- return null;- }-- return {- id: share.id,- public: share.public,- hasPassword: !!share.password,- };- }),+ .query(({ input }) => getShareOverviewSettings(input.projectId)),createOverview: protectedProcedure.input(zShareOverview)- .mutation(async ({ input }) => {- const passwordHash = input.password- ? await hashPassword(input.password)- : null;-- const share = await db.shareOverview.upsert({- where: {- projectId: input.projectId,- },- create: {- id: uid.rnd(),- organizationId: input.organizationId,- projectId: input.projectId,- public: input.public,- password: passwordHash,- },- update: {- public: input.public,- password: passwordHash,- },- select: { id: true, public: true, password: true },- });-- return {- id: share.id,- public: share.public,- hasPassword: !!share.password,- };- }),+ .mutation(({ input }) => createShareOverview(input)),// Dashboard sharingdashboard: publicProcedure.input(z.object({ shareId: z.string() }))- .query(async ({ input, ctx }) => {- const share = await db.shareDashboard.findUnique({- where: { id: input.shareId },- select: {- id: true,- public: true,- password: true,- organization: { select: { name: true } },- project: { select: { name: true } },- dashboard: { select: { name: true } },- },- });-- if (!(share && share.public)) {- throw new TRPCNotFoundError('Dashboard share not found');- }-- const hasAccess = !!ctx.cookies.get(`shared-dashboard-${share.id}`);- if (share.password && !hasAccess) {- return lockedShare(share.id, share.organization, share.project);- }-- return {- id: share.id,- requiresPassword: false as const,- organization: share.organization,- project: share.project,- dashboard: share.dashboard,- };- }),+ .query(({ input, ctx }) => getShareDashboard(input.shareId, ctx.cookies)),dashboardSettings: protectedProcedure.input(z.object({ projectId: z.string(), dashboardId: z.string() }))- .query(async ({ input }) => {- const share = await db.shareDashboard.findUnique({- where: { dashboardId: input.dashboardId },- select: { id: true, public: true, password: true, projectId: true },- });-- if (!share || share.projectId !== input.projectId) {- return null;- }-- return {- id: share.id,- public: share.public,- hasPassword: !!share.password,- };- }),+ .query(({ input }) =>+ getShareDashboardSettings(input.projectId, input.dashboardId)+ ),createDashboard: protectedProcedure.input(zShareDashboard)@@ -195,121 +55,25 @@ export const shareRouter = createTRPCRouter({projectId: input.projectId,level: 'write',});-- const dashboard = await getDashboardById(- input.dashboardId,- input.projectId- );- if (!dashboard) {- throw new TRPCNotFoundError('Dashboard not found');- }-- const passwordHash = input.password- ? await hashPassword(input.password)- : null;-- const share = await db.shareDashboard.upsert({- where: {- dashboardId: input.dashboardId,- },- create: {- id: uid.rnd(),- organizationId: input.organizationId,- projectId: input.projectId,- dashboardId: input.dashboardId,- public: input.public,- password: passwordHash,- },- update: {- public: input.public,- password: passwordHash,- },- select: { id: true, public: true, password: true },- });-- return {- id: share.id,- public: share.public,- hasPassword: !!share.password,- };+ return createShareDashboard(input);}),dashboardReports: publicProcedure- .input(- z.object({- shareId: z.string(),- })- )- .query(async ({ input, ctx }) => {- const share = await getShareDashboardById(input.shareId);-- if (!(share && share.public)) {- throw new TRPCNotFoundError('Dashboard share not found');- }-- // Check password access- const hasAccess = !!ctx.cookies.get(`shared-dashboard-${share.id}`);- if (share.password && !hasAccess) {- throw new TRPCAccessError('Password required');- }-- return getReportsByDashboardId(share.dashboardId);- }),+ .input(z.object({ shareId: z.string() }))+ .query(({ input, ctx }) =>+ getShareDashboardReports(input.shareId, ctx.cookies)+ ),// Report sharingreport: publicProcedure.input(z.object({ shareId: z.string() }))- .query(async ({ input, ctx }) => {- const share = await db.shareReport.findUnique({- where: { id: input.shareId },- select: {- id: true,- public: true,- password: true,- projectId: true,- organization: { select: { name: true } },- project: { select: { name: true } },- report: true,- },- });-- if (!(share && share.public)) {- throw new TRPCNotFoundError('Report share not found');- }-- const hasAccess = !!ctx.cookies.get(`shared-report-${share.id}`);- if (share.password && !hasAccess) {- return lockedShare(share.id, share.organization, share.project);- }-- return {- id: share.id,- requiresPassword: false as const,- organization: share.organization,- project: share.project,- projectId: share.projectId,- report: transformReport(share.report),- };- }),+ .query(({ input, ctx }) => getShareReport(input.shareId, ctx.cookies)),reportSettings: protectedProcedure.input(z.object({ projectId: z.string(), reportId: z.string() }))- .query(async ({ input }) => {- const share = await db.shareReport.findUnique({- where: { reportId: input.reportId },- select: { id: true, public: true, password: true, projectId: true },- });-- if (!share || share.projectId !== input.projectId) {- return null;- }-- return {- id: share.id,- public: share.public,- hasPassword: !!share.password,- };- }),+ .query(({ input }) =>+ getShareReportSettings(input.projectId, input.reportId)+ ),createReport: protectedProcedure.input(zShareReport)@@ -319,39 +83,6 @@ export const shareRouter = createTRPCRouter({projectId: input.projectId,level: 'write',});-- const report = await getReportById(input.reportId);- if (!report || report.projectId !== input.projectId) {- throw new TRPCNotFoundError('Report not found');- }-- const passwordHash = input.password- ? await hashPassword(input.password)- : null;-- const share = await db.shareReport.upsert({- where: {- reportId: input.reportId,- },- create: {- id: uid.rnd(),- organizationId: input.organizationId,- projectId: input.projectId,- reportId: input.reportId,- public: input.public,- password: passwordHash,- },- update: {- public: input.public,- password: passwordHash,- },- select: { id: true, public: true, password: true },- });-- return {- id: share.id,- public: share.public,- hasPassword: !!share.password,- };+ return createShareReport(input);}),});diff --git a/packages/validation/src/index.ts b/packages/validation/src/index.tsindex a2eb7d450..42e21e8cd 100644--- a/packages/validation/src/index.ts+++ b/packages/validation/src/index.ts@@ -346,28 +346,11 @@ export const zUpdateMemberAccess = z.object({access: z.array(zProjectAccessGrant),});-export const zShareOverview = z.object({- organizationId: z.string(),- projectId: z.string(),- password: z.string().nullable(),- public: z.boolean(),-});--export const zShareDashboard = z.object({- organizationId: z.string(),- projectId: z.string(),- dashboardId: z.string(),- password: z.string().nullable(),- public: z.boolean(),-});--export const zShareReport = z.object({- organizationId: z.string(),- projectId: z.string(),- reportId: z.string(),- password: z.string().nullable(),- public: z.boolean(),-});+// Moved into @openpanel/core's share module (M6-004, ADR-008's module map:+// share owns "C"). Re-exported here for existing @openpanel/validation+// importers (packages/trpc's share router, apps/start's share modals) — same+// shape as ./onboarding.constants.ts re-export since M6-003.+export * from '@openpanel/core/modules/share/share.constants';export const zCreateReference = z.object({title: z.string(),diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex ffa380583..f137d33b5 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1190,6 +1190,9 @@ importers:ramda:specifier: ^0.29.1version: 0.29.1+ short-unique-id:+ specifier: ^5.0.3+ version: 5.0.3sqlstring:specifier: ^2.3.3version: 2.3.3