Skip to content

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

ralph(M6-002): project + client modules into core (the /manage REST surface, URLs unchanged)

ralph22b046805107
diff --git a/apps/api/src/controllers/manage.controller.ts b/apps/api/src/controllers/manage.controller.ts
index 6685bce34..4839f5826 100644
--- a/apps/api/src/controllers/manage.controller.ts
+++ b/apps/api/src/controllers/manage.controller.ts
@@ -1,35 +1,31 @@
-import crypto from 'node:crypto';
-import { stripTrailingSlash } from '@openpanel/common';
-import { hashPassword } from '@openpanel/core';
import {
- db,
- getClientByIdCached,
- getId,
- getProjectByIdCached,
-} from '@openpanel/db';
+ createClientForOrganization,
+ createProjectForOrganization,
+ deleteClientForOrganization,
+ deleteProjectForOrganization,
+ getClientForOrganization,
+ getProjectForOrganization,
+ listClientsForOrganization,
+ listProjectsForOrganization,
+ updateClientForOrganization,
+ updateProjectForOrganization,
+} from '@openpanel/core';
+import type {
+ zCreateProject,
+ zUpdateProject,
+} from '@openpanel/core/modules/project/project.constants';
+import { db } from '@openpanel/db';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { z } from 'zod';
import { HttpError } from '@/utils/errors';
-// Validation schemas (exported for use in router)
-export const zCreateProject = z.object({
- name: z.string().min(1),
- domain: z.string().url().or(z.literal('')).or(z.null()).optional(),
- cors: z.array(z.string()).default([]),
- crossDomain: z.boolean().optional().default(false),
- types: z
- .array(z.enum(['website', 'app', 'backend']))
- .optional()
- .default([]),
-});
-
-export const zUpdateProject = z.object({
- name: z.string().min(1).optional(),
- domain: z.string().url().or(z.literal('')).or(z.null()).optional(),
- cors: z.array(z.string()).optional(),
- crossDomain: z.boolean().optional(),
- allowUnsafeRevenueTracking: z.boolean().optional(),
-});
+// project.service.ts + client.service.ts's /manage CRUD bodies (M6-002,
+// DELEGATE PATTERN) — zCreateProject/zUpdateProject moved with them
+// (project owns "C"); re-exported here for manage.router.ts's schemas.
+export {
+ zCreateProject,
+ zUpdateProject,
+} from '@openpanel/core/modules/project/project.constants';
export const zCreateClient = z.object({
name: z.string().min(1),
@@ -54,21 +50,15 @@ export const zUpdateReference = z.object({
datetime: z.string().optional(),
});
-// Projects CRUD
+// Projects CRUD — delegates to @openpanel/core's project.service.ts
+// (M6-002, DELEGATE PATTERN).
export async function listProjects(
request: FastifyRequest,
reply: FastifyReply
) {
- const projects = await db.project.findMany({
- where: {
- organizationId: request.client!.organizationId,
- deleteAt: null,
- },
- orderBy: {
- createdAt: 'desc',
- },
- });
-
+ const projects = await listProjectsForOrganization(
+ request.client!.organizationId
+ );
reply.send({ data: projects });
}
@@ -76,12 +66,10 @@ export async function getProject(
request: FastifyRequest<{ Params: { id: string } }>,
reply: FastifyReply
) {
- const project = await db.project.findFirst({
- where: {
- id: request.params.id,
- organizationId: request.client!.organizationId,
- },
- });
+ const project = await getProjectForOrganization(
+ request.params.id,
+ request.client!.organizationId
+ );
if (!project) {
throw new HttpError('Project not found', { status: 404 });
@@ -94,57 +82,12 @@ export async function createProject(
request: FastifyRequest<{ Body: z.infer<typeof zCreateProject> }>,
reply: FastifyReply
) {
- const { name, domain, cors, crossDomain, types } = request.body;
-
- // Generate a default client secret
- const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;
- const clientData = {
- organizationId: request.client!.organizationId,
- name: 'First client',
- type: 'write' as const,
- secret: await hashPassword(secret),
- };
-
- const project = await db.project.create({
- data: {
- id: await getId('project', name),
- organizationId: request.client!.organizationId,
- name,
- domain: domain ? stripTrailingSlash(domain) : null,
- cors: cors.map((c) => stripTrailingSlash(c)),
- crossDomain: crossDomain ?? false,
- allowUnsafeRevenueTracking: false,
- filters: [],
- types,
- clients: {
- create: clientData,
- },
- },
- include: {
- clients: {
- select: {
- id: true,
- },
- },
- },
- });
+ const { project, client } = await createProjectForOrganization(
+ request.client!.organizationId,
+ request.body
+ );
- await Promise.all([
- getProjectByIdCached.clear(project.id),
- ...project.clients.map((client) => getClientByIdCached.clear(client.id)),
- ]);
-
- reply.send({
- data: {
- ...project,
- client: project.clients[0]
- ? {
- id: project.clients[0].id,
- secret,
- }
- : null,
- },
- });
+ reply.send({ data: { ...project, client } });
}
export async function updateProject(
@@ -154,56 +97,16 @@ export async function updateProject(
}>,
reply: FastifyReply
) {
- const body = request.body;
+ const project = await updateProjectForOrganization(
+ request.params.id,
+ request.client!.organizationId,
+ request.body
+ );
- // Verify project exists and belongs to organization
- const existing = await db.project.findFirst({
- where: {
- id: request.params.id,
- organizationId: request.client!.organizationId,
- },
- include: {
- clients: {
- select: {
- id: true,
- },
- },
- },
- });
-
- if (!existing) {
+ if (!project) {
throw new HttpError('Project not found', { status: 404 });
}
- const updateData: any = {};
- if (body.name !== undefined) {
- updateData.name = body.name;
- }
- if (body.domain !== undefined) {
- updateData.domain = body.domain ? stripTrailingSlash(body.domain) : null;
- }
- if (body.cors !== undefined) {
- updateData.cors = body.cors.map((c) => stripTrailingSlash(c));
- }
- if (body.crossDomain !== undefined) {
- updateData.crossDomain = body.crossDomain;
- }
- if (body.allowUnsafeRevenueTracking !== undefined) {
- updateData.allowUnsafeRevenueTracking = body.allowUnsafeRevenueTracking;
- }
-
- const project = await db.project.update({
- where: {
- id: request.params.id,
- },
- data: updateData,
- });
-
- await Promise.all([
- getProjectByIdCached.clear(project.id),
- ...existing.clients.map((client) => getClientByIdCached.clear(client.id)),
- ]);
-
reply.send({ data: project });
}
@@ -211,63 +114,33 @@ export async function deleteProject(
request: FastifyRequest<{ Params: { id: string } }>,
reply: FastifyReply
) {
- const project = await db.project.findFirst({
- where: {
- id: request.params.id,
- organizationId: request.client!.organizationId,
- },
- });
+ const deleted = await deleteProjectForOrganization(
+ request.params.id,
+ request.client!.organizationId
+ );
- if (!project) {
+ if (!deleted) {
throw new HttpError('Project not found', { status: 404 });
}
- await db.project.update({
- where: {
- id: request.params.id,
- },
- data: {
- deleteAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
- },
- });
-
- await getProjectByIdCached.clear(request.params.id);
-
reply.send({ success: true });
}
-// Clients CRUD
+// Clients CRUD — delegates to @openpanel/core's client.service.ts
+// (M6-002, DELEGATE PATTERN).
export async function listClients(
request: FastifyRequest<{ Querystring: { projectId?: string } }>,
reply: FastifyReply
) {
- const where: any = {
- organizationId: request.client!.organizationId,
- };
+ const clients = await listClientsForOrganization(
+ request.client!.organizationId,
+ request.query.projectId
+ );
- if (request.query.projectId) {
- // Verify project belongs to organization
- const project = await db.project.findFirst({
- where: {
- id: request.query.projectId,
- organizationId: request.client!.organizationId,
- },
- });
-
- if (!project) {
- throw new HttpError('Project not found', { status: 404 });
- }
-
- where.projectId = request.query.projectId;
+ if (clients === null) {
+ throw new HttpError('Project not found', { status: 404 });
}
- const clients = await db.client.findMany({
- where,
- orderBy: {
- createdAt: 'desc',
- },
- });
-
reply.send({ data: clients });
}
@@ -275,12 +148,10 @@ export async function getClient(
request: FastifyRequest<{ Params: { id: string } }>,
reply: FastifyReply
) {
- const client = await db.client.findFirst({
- where: {
- id: request.params.id,
- organizationId: request.client!.organizationId,
- },
- });
+ const client = await getClientForOrganization(
+ request.params.id,
+ request.client!.organizationId
+ );
if (!client) {
throw new HttpError('Client not found', { status: 404 });
@@ -293,41 +164,19 @@ export async function createClient(
request: FastifyRequest<{ Body: z.infer<typeof zCreateClient> }>,
reply: FastifyReply
) {
- const { name, projectId, type } = request.body;
+ const created = await createClientForOrganization(
+ request.client!.organizationId,
+ request.body
+ );
- // If projectId is provided, verify it belongs to organization
- if (projectId) {
- const project = await db.project.findFirst({
- where: {
- id: projectId,
- organizationId: request.client!.organizationId,
- },
- });
-
- if (!project) {
- throw new HttpError('Project not found', { status: 404 });
- }
+ if (!created) {
+ throw new HttpError('Project not found', { status: 404 });
}
- // Generate secret
- const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;
-
- const client = await db.client.create({
- data: {
- organizationId: request.client!.organizationId,
- projectId: projectId || null,
- name,
- type: type || 'write',
- secret: await hashPassword(secret),
- },
- });
-
- await getClientByIdCached.clear(client.id);
-
reply.send({
data: {
- ...client,
- secret, // Return plain secret only once
+ ...created.client,
+ secret: created.secret, // Return plain secret only once
},
});
}
@@ -339,32 +188,16 @@ export async function updateClient(
}>,
reply: FastifyReply
) {
- // Verify client exists and belongs to organization
- const existing = await db.client.findFirst({
- where: {
- id: request.params.id,
- organizationId: request.client!.organizationId,
- },
- });
+ const client = await updateClientForOrganization(
+ request.params.id,
+ request.client!.organizationId,
+ request.body
+ );
- if (!existing) {
+ if (!client) {
throw new HttpError('Client not found', { status: 404 });
}
- const updateData: any = {};
- if (request.body.name !== undefined) {
- updateData.name = request.body.name;
- }
-
- const client = await db.client.update({
- where: {
- id: request.params.id,
- },
- data: updateData,
- });
-
- await getClientByIdCached.clear(client.id);
-
reply.send({ data: client });
}
@@ -372,25 +205,15 @@ export async function deleteClient(
request: FastifyRequest<{ Params: { id: string } }>,
reply: FastifyReply
) {
- const client = await db.client.findFirst({
- where: {
- id: request.params.id,
- organizationId: request.client!.organizationId,
- },
- });
+ const deleted = await deleteClientForOrganization(
+ request.params.id,
+ request.client!.organizationId
+ );
- if (!client) {
+ if (!deleted) {
throw new HttpError('Client not found', { status: 404 });
}
- await db.client.delete({
- where: {
- id: request.params.id,
- },
- });
-
- await getClientByIdCached.clear(request.params.id);
-
reply.send({ success: true });
}
diff --git a/packages/constants/index.ts b/packages/constants/index.ts
index 73e1996cb..0c87d62cc 100644
--- a/packages/constants/index.ts
+++ b/packages/constants/index.ts
@@ -83,11 +83,11 @@ export const timeWindows = {
},
} as const;
-export const ProjectTypeNames = {
- website: 'Website',
- app: 'App',
- backend: 'Backend',
-} as const;
+// Moved into @openpanel/core's project module (M6-002, ADR-008's module
+// map: project owns "C"). Re-exported here for existing
+// @openpanel/constants importers — same shape as
+// packages/validation/src/import.validation.ts since M5-004.
+export { ProjectTypeNames } from '@openpanel/core/modules/project/project.constants';
export const operators = {
is: 'Is',
@@ -174,7 +174,7 @@ const ORDERED_OPERATORS = [
const BOOLEAN_OPERATORS = ['is', 'isNot', 'isNull', 'isNotNull'] as const;
export function getOperatorsForType(
- type?: IFilterValueType,
+ type?: IFilterValueType
): readonly (keyof typeof operators)[] {
switch (type) {
case 'number':
diff --git a/packages/constants/package.json b/packages/constants/package.json
index f121f9b59..9fe2de481 100644
--- a/packages/constants/package.json
+++ b/packages/constants/package.json
@@ -6,6 +6,9 @@
"scripts": {
"typecheck": "tsc --noEmit"
},
+ "dependencies": {
+ "@openpanel/core": "workspace:*"
+ },
"devDependencies": {
"@openpanel/tsconfig": "workspace:*",
"date-fns": "^3.3.1",
diff --git a/packages/core/src/http/auth.test.ts b/packages/core/src/http/auth.test.ts
index 1bf3981e8..e5bee35aa 100644
--- a/packages/core/src/http/auth.test.ts
+++ b/packages/core/src/http/auth.test.ts
@@ -9,6 +9,7 @@ import type { AuthenticatedClient, ClientAuthOptions } from './client-auth';
const CLIENT: AuthenticatedClient = {
id: 'client-1',
projectId: 'proj-1',
+ organizationId: 'org-1',
type: 'root',
secretPresented: true,
};
diff --git a/packages/core/src/http/client-auth.ts b/packages/core/src/http/client-auth.ts
index 29c7e427d..dbf346916 100644
--- a/packages/core/src/http/client-auth.ts
+++ b/packages/core/src/http/client-auth.ts
@@ -19,7 +19,10 @@ export type ClientType = 'read' | 'write' | 'root';
export interface AuthenticatedClient {
id: string;
- projectId: string;
+ /** `null` for a root client, which is scoped to `organizationId` instead. */
+ projectId: string | null;
+ /** Every client — read/write/root alike — belongs to exactly one org. */
+ organizationId: string;
type: ClientType;
/**
* Whether a client secret was PRESENTED, set before it is verified — V1 sets
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index c4b80f175..d6aee380f 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -194,6 +194,27 @@ export {
verifyPasswordHash,
verifyTotpCode,
} from './modules/auth/auth.service';
+// Dissolved from @openpanel/db's services/clients.service.ts (M6-002) —
+// packages/trpc's client router, apps/api's manage controller and mcp/utils
+// auth call these directly, the same way V1 reaches every other dissolved
+// service here. packages/db/src/services/clients.service.ts stays a
+// re-export shim.
+export type {
+ CreatedClient,
+ IServiceClient,
+ IServiceClientWithProject,
+} from './modules/client/client.service';
+export {
+ createClientForOrganization,
+ deleteClientForOrganization,
+ getClientById,
+ getClientByIdCached,
+ getClientForOrganization,
+ getClientsByOrganizationId,
+ getClientsByProjectId,
+ listClientsForOrganization,
+ updateClientForOrganization,
+} from './modules/client/client.service';
// Dissolved from @openpanel/db's services/cohort.service.ts (M5-003) —
// packages/trpc's cohort router and apps/worker's cohort job files call
// these directly, the same way V1 reaches every other dissolved service
@@ -323,6 +344,36 @@ export {
updateOrganization,
updateOrganizationMemberAccess,
} from './modules/organization/organization.service';
+// Dissolved from @openpanel/db's services/project.service.ts (M6-002) —
+// packages/trpc's project router, apps/api's manage controller and several
+// core modules' `src/access.ts` call these directly, the same way V1
+// reaches every other dissolved service here. packages/db/src/services/
+// project.service.ts stays a re-export shim.
+export { ProjectTypeNames } from './modules/project/project.constants';
+export type {
+ CreatedProjectClient,
+ IServiceProject,
+ IServiceProjectWithClients,
+ ProjectActivationStatus,
+} from './modules/project/project.service';
+export {
+ cancelProjectDeletion,
+ createProjectForOrganization,
+ deleteProjectForOrganization,
+ getLastEventPerProject,
+ getProjectActivationStatus,
+ getProjectById,
+ getProjectByIdCached,
+ getProjectEventsCount,
+ getProjectForOrganization,
+ getProjects,
+ getProjectWithClients,
+ listProjectsCore,
+ listProjectsForOrganization,
+ resolveClientProjectId,
+ scheduleProjectDeletion,
+ updateProjectForOrganization,
+} from './modules/project/project.service';
// Dissolved from @openpanel/db's services/user.service.ts (M6-001) —
// packages/trpc's auth/onboarding routers still call `getUserById`/
// `getUserAccount` directly through @openpanel/db's re-export shim, the same
diff --git a/packages/core/src/modules/client/client.routes.ts b/packages/core/src/modules/client/client.routes.ts
new file mode 100644
index 000000000..f01ec5b4c
--- /dev/null
+++ b/packages/core/src/modules/client/client.routes.ts
@@ -0,0 +1,153 @@
+// The /manage/clients REST surface (M6-002). V1's Fastify controller
+// (apps/api/src/controllers/manage.controller.ts) stays the LIVE route
+// (DELEGATE PATTERN) and delegates its CRUD bodies to client.service.ts's
+// createClientForOrganization/updateClientForOrganization/etc — the same
+// functions this route calls. Response envelopes (`{ data }` / `{ success }`)
+// match V1's `reply.send(...)` shape exactly (byte-unchanged URL surface).
+//
+// Body schemas are local, not a client.constants.ts file: the module map
+// gives client "R,H,S" only, no "C" (unlike project, whose zCreateProject /
+// zUpdateProject moved with ProjectTypeNames).
+//
+// NAMED GAP, same as import.routes.ts / project.routes.ts: this route is not
+// yet reachable — `authenticateClient` (http/client-auth.ts) is a P8 stub
+// that always returns null, so `clientAuth` 401s every request until it is
+// filled in; main.ts also does not mount `publicApiRoutes` until a real
+// `AppDeps` exists. `allow: ['root']` mirrors V1's rule (utils/auth.ts's
+// `validateManageRequest`: only root clients may manage resources).
+
+import { z } from 'zod';
+import { defineRoutes } from '../../http/define';
+import {
+ createClientForOrganization,
+ deleteClientForOrganization,
+ getClientForOrganization,
+ listClientsForOrganization,
+ updateClientForOrganization,
+} from './client.service';
+
+const idParams = z.object({ id: z.string() });
+const listQuery = z.object({ projectId: z.string().optional() });
+
+const zCreateClient = z.object({
+ name: z.string().min(1),
+ projectId: z.string().optional(),
+ type: z.enum(['read', 'write', 'root']).optional().default('write'),
+});
+
+const zUpdateClient = z.object({
+ name: z.string().min(1).optional(),
+});
+
+export const clientRoutes = defineRoutes((app) =>
+ app
+ .get(
+ '/manage/clients',
+ async ({ client, query, status }) => {
+ const clients = await listClientsForOrganization(
+ client.organizationId,
+ query.projectId
+ );
+ if (clients === null) {
+ return status(404, {
+ error: 'Not Found',
+ message: 'Project not found',
+ });
+ }
+ return { data: clients };
+ },
+ {
+ clientAuth: { allow: ['root'] },
+ query: listQuery,
+ detail: { tags: ['Manage'] },
+ }
+ )
+ .get(
+ '/manage/clients/:id',
+ async ({ client, params, status }) => {
+ const found = await getClientForOrganization(
+ params.id,
+ client.organizationId
+ );
+ if (!found) {
+ return status(404, {
+ error: 'Not Found',
+ message: 'Client not found',
+ });
+ }
+ return { data: found };
+ },
+ {
+ clientAuth: { allow: ['root'] },
+ params: idParams,
+ detail: { tags: ['Manage'] },
+ }
+ )
+ .post(
+ '/manage/clients',
+ async ({ body, client, status }) => {
+ const created = await createClientForOrganization(
+ client.organizationId,
+ body
+ );
+ if (!created) {
+ return status(404, {
+ error: 'Not Found',
+ message: 'Project not found',
+ });
+ }
+ return {
+ data: { ...created.client, secret: created.secret },
+ };
+ },
+ {
+ clientAuth: { allow: ['root'] },
+ body: zCreateClient,
+ detail: { tags: ['Manage'] },
+ }
+ )
+ .patch(
+ '/manage/clients/:id',
+ async ({ body, client, params, status }) => {
+ const updated = await updateClientForOrganization(
+ params.id,
+ client.organizationId,
+ body
+ );
+ if (!updated) {
+ return status(404, {
+ error: 'Not Found',
+ message: 'Client not found',
+ });
+ }
+ return { data: updated };
+ },
+ {
+ clientAuth: { allow: ['root'] },
+ params: idParams,
+ body: zUpdateClient,
+ detail: { tags: ['Manage'] },
+ }
+ )
+ .delete(
+ '/manage/clients/:id',
+ async ({ client, params, status }) => {
+ const deleted = await deleteClientForOrganization(
+ params.id,
+ client.organizationId
+ );
+ if (!deleted) {
+ return status(404, {
+ error: 'Not Found',
+ message: 'Client not found',
+ });
+ }
+ return { success: true };
+ },
+ {
+ clientAuth: { allow: ['root'] },
+ params: idParams,
+ detail: { tags: ['Manage'] },
+ }
+ )
+);
diff --git a/packages/core/src/modules/client/client.rpc.test.ts b/packages/core/src/modules/client/client.rpc.test.ts
new file mode 100644
index 000000000..0eb144581
--- /dev/null
+++ b/packages/core/src/modules/client/client.rpc.test.ts
@@ -0,0 +1,57 @@
+// Only the "is anyone logged in" boundary is exercised here — no database.
+// `list` has no access check of its own (ported verbatim from V1), so it is
+// not exercised here either — the access-check + mutation bodies ride on
+// @openpanel/db (lazy-loaded through ./src/access and client.service.ts);
+// wiring this router end-to-end against a real Postgres is P6's
+// (protectedProcedure) job, not this one's — see client.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 { clientRouter } from './client.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 clientRouter.createCaller(trpcCtx);
+}
+
+test('update rejects an unauthenticated caller before touching a client', async () => {
+ const caller = await anonCaller();
+ await expect(
+ caller.update({ id: 'client_1', name: 'Renamed' })
+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
+});
+
+test('create rejects an unauthenticated caller', async () => {
+ const caller = await anonCaller();
+ await expect(
+ caller.create({
+ name: 'A client',
+ projectId: 'proj_1',
+ organizationId: 'org_1',
+ })
+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
+});
+
+test('remove rejects an unauthenticated caller', async () => {
+ const caller = await anonCaller();
+ await expect(caller.remove({ id: 'client_1' })).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+});
diff --git a/packages/core/src/modules/client/client.rpc.ts b/packages/core/src/modules/client/client.rpc.ts
new file mode 100644
index 000000000..621153fb8
--- /dev/null
+++ b/packages/core/src/modules/client/client.rpc.ts
@@ -0,0 +1,126 @@
+// Ported from packages/trpc/src/routers/client.ts (M6-002).
+//
+// 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 client functions (DELEGATE
+// PATTERN) — this module has no queue/cron of its own, so there is no
+// `ctx.services.client`, same as `user`/`conversation`.
+//
+// `./src/access.ts` binds core's shared/access.ts ladder to @openpanel/db's
+// real lookups, dynamically imported (`loadAccessChecks`) same as
+// organization.rpc.ts, so a static import here does not pull
+// @openpanel/db's prisma client into every core test file.
+
+import { z } from 'zod';
+import { createTRPCRouter, procedure } from '../../rpc/base';
+import { TRPCAccessError, TRPCForbiddenError } from '../../rpc/errors';
+import {
+ createClientForOrganization,
+ deleteClientForOrganization,
+ getClientById,
+ getClientsByProjectId,
+ updateClientForOrganization,
+} from './client.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 clientRouter = createTRPCRouter({
+ list: procedure
+ .input(z.object({ projectId: z.string() }))
+ .query(async ({ input }) => {
+ // Ported verbatim: V1's `client.list` reads by projectId with no
+ // access check of its own (packages/trpc/src/routers/client.ts).
+ return getClientsByProjectId(input.projectId);
+ }),
+
+ update: procedure
+ .input(z.object({ id: z.string(), name: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ const { getClientAccess } = await loadAccessChecks();
+ const access = await getClientAccess({ userId, clientId: input.id });
+ if (!access) {
+ throw new TRPCForbiddenError('You do not have access to this client');
+ }
+
+ const client = await getClientById(input.id);
+ if (!client) {
+ throw new TRPCForbiddenError('Client not found');
+ }
+
+ return updateClientForOrganization(input.id, client.organizationId, {
+ name: input.name,
+ });
+ }),
+
+ create: procedure
+ .input(
+ z.object({
+ name: z.string(),
+ projectId: z.string(),
+ organizationId: z.string(),
+ type: z.enum(['read', 'write', 'root']).optional(),
+ })
+ )
+ .mutation(async ({ input, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ const { requireOrganizationAdmin } = await loadAccessChecks();
+ // Minting an ingestion credential - a `root` one at the caller's
+ // choosing - is admin-tier, not something any org member should be
+ // able to do.
+ await requireOrganizationAdmin({
+ userId,
+ organizationId: input.organizationId,
+ message: 'Only organization admins can create API clients',
+ });
+
+ const created = await createClientForOrganization(input.organizationId, {
+ name: input.name,
+ projectId: input.projectId,
+ type: input.type,
+ });
+
+ if (!created) {
+ throw new TRPCForbiddenError(
+ 'Project not found or does not belong to your organization'
+ );
+ }
+
+ return { ...created.client, secret: created.secret };
+ }),
+
+ remove: procedure
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ const client = await getClientById(input.id);
+
+ if (!client?.organizationId) {
+ throw new TRPCForbiddenError('You do not have access to this client');
+ }
+
+ const { requireOrganizationAdmin } = await loadAccessChecks();
+ // Revoking a credential breaks ingestion for whoever is using it.
+ await requireOrganizationAdmin({
+ userId,
+ organizationId: client.organizationId,
+ message: 'Only organization admins can delete API clients',
+ });
+
+ await deleteClientForOrganization(input.id, client.organizationId);
+ return true;
+ }),
+});
diff --git a/packages/core/src/modules/client/client.service.test.ts b/packages/core/src/modules/client/client.service.test.ts
new file mode 100644
index 000000000..a7f6a1a10
--- /dev/null
+++ b/packages/core/src/modules/client/client.service.test.ts
@@ -0,0 +1,248 @@
+// client.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 FakeProject {
+ id: string;
+ organizationId: string;
+}
+
+interface FakeClient {
+ id: string;
+ organizationId: string;
+ projectId: string | null;
+ name: string;
+ type: 'read' | 'write' | 'root';
+ secret: string;
+ createdAt: Date;
+}
+
+const projectStore = new Map<string, FakeProject>();
+const clientStore = new Map<string, FakeClient>();
+let nextClientId = 0;
+
+function makeClient(
+ overrides: Partial<FakeClient> & { id: string }
+): FakeClient {
+ return {
+ organizationId: 'org_1',
+ projectId: null,
+ name: 'A client',
+ type: 'write',
+ secret: 'hashed',
+ createdAt: new Date(),
+ ...overrides,
+ };
+}
+
+const project = {
+ findFirst: mock(
+ async ({ where }: { where: { id: string; organizationId: string } }) => {
+ const found = projectStore.get(where.id);
+ if (!found || found.organizationId !== where.organizationId) {
+ return null;
+ }
+ return found;
+ }
+ ),
+};
+
+const client = {
+ findMany: mock(
+ async ({
+ where,
+ }: {
+ where: { organizationId: string; projectId?: string };
+ }) =>
+ [...clientStore.values()].filter(
+ (c) =>
+ c.organizationId === where.organizationId &&
+ (where.projectId === undefined || c.projectId === where.projectId)
+ )
+ ),
+ findFirst: mock(
+ async ({ where }: { where: { id: string; organizationId: string } }) => {
+ const found = clientStore.get(where.id);
+ if (!found || found.organizationId !== where.organizationId) {
+ return null;
+ }
+ return found;
+ }
+ ),
+ findUnique: mock(async ({ where: { id } }: { where: { id: string } }) => {
+ return clientStore.get(id) ?? null;
+ }),
+ create: mock(
+ async ({ data }: { data: Omit<FakeClient, 'id' | 'createdAt'> }) => {
+ const created = makeClient({
+ id: `client_${++nextClientId}`,
+ ...data,
+ });
+ clientStore.set(created.id, created);
+ return created;
+ }
+ ),
+ update: mock(
+ async ({
+ where: { id },
+ data,
+ }: {
+ where: { id: string };
+ data: Partial<FakeClient>;
+ }) => {
+ const existing = clientStore.get(id);
+ if (!existing) {
+ throw new Error(`client ${id} not found`);
+ }
+ const next = { ...existing, ...data };
+ clientStore.set(id, next);
+ return next;
+ }
+ ),
+ delete: mock(async ({ where: { id } }: { where: { id: string } }) => {
+ clientStore.delete(id);
+ }),
+};
+
+// Bypasses the Redis cache-aside entirely — this module's own logic is
+// exercised directly, caching is @openpanel/redis's concern. Same stub as
+// organization.service.test.ts, needed because create/update/delete all call
+// `.clear()` on getClientByIdCached.
+function cacheableStub(
+ fnOrName: ((...args: unknown[]) => unknown) | string,
+ fnOrTtl: ((...args: unknown[]) => unknown) | number
+) {
+ const fn =
+ typeof fnOrName === 'function'
+ ? fnOrName
+ : (fnOrTtl as (...args: unknown[]) => unknown);
+ return Object.assign(fn, {
+ getKey: () => '',
+ clear: async () => 0,
+ set: () => async () => 'OK' as const,
+ });
+}
+mock.module('@openpanel/redis', () => ({
+ cacheable: cacheableStub,
+ getRedisCache: () => ({
+ get: async () => null,
+ setex: async () => undefined,
+ del: async () => undefined,
+ }),
+}));
+
+const actualPrismaClient = await import('@openpanel/db/src/prisma-client');
+mock.module('@openpanel/db/src/prisma-client', () => ({
+ ...actualPrismaClient,
+ db: { project, client },
+}));
+
+let subject: typeof import('./client.service');
+beforeAll(async () => {
+ subject = await import('./client.service');
+});
+
+beforeEach(() => {
+ projectStore.clear();
+ clientStore.clear();
+});
+
+test('listClientsForOrganization returns null when the filtering project does not belong to the org', async () => {
+ projectStore.set('proj_1', { id: 'proj_1', organizationId: 'org_other' });
+
+ const result = await subject.listClientsForOrganization('org_1', 'proj_1');
+ expect(result).toBeNull();
+});
+
+test('listClientsForOrganization scopes to the organization', async () => {
+ clientStore.set(
+ 'client_a',
+ makeClient({ id: 'client_a', organizationId: 'org_1' })
+ );
+ clientStore.set(
+ 'client_b',
+ makeClient({ id: 'client_b', organizationId: 'org_2' })
+ );
+
+ const result = await subject.listClientsForOrganization('org_1');
+ expect(result?.map((c) => c.id)).toEqual(['client_a']);
+});
+
+test('getClientForOrganization returns null for a client in a different org', async () => {
+ clientStore.set(
+ 'client_a',
+ makeClient({ id: 'client_a', organizationId: 'org_1' })
+ );
+
+ const result = await subject.getClientForOrganization('client_a', 'org_2');
+ expect(result).toBeNull();
+});
+
+test('createClientForOrganization returns null when the projectId does not belong to the org', async () => {
+ const result = await subject.createClientForOrganization('org_1', {
+ name: 'New client',
+ projectId: 'missing_project',
+ });
+ expect(result).toBeNull();
+});
+
+test('createClientForOrganization creates a write client and returns the plaintext secret once', async () => {
+ const result = await subject.createClientForOrganization('org_1', {
+ name: 'New client',
+ });
+
+ expect(result).not.toBeNull();
+ expect(result?.client.type).toBe('write');
+ expect(result?.client.secret).not.toBe(result?.secret);
+ expect(typeof result?.secret).toBe('string');
+});
+
+test('updateClientForOrganization returns null for a client in a different org', async () => {
+ clientStore.set(
+ 'client_a',
+ makeClient({ id: 'client_a', organizationId: 'org_1' })
+ );
+
+ const result = await subject.updateClientForOrganization(
+ 'client_a',
+ 'org_2',
+ { name: 'Renamed' }
+ );
+ expect(result).toBeNull();
+});
+
+test('updateClientForOrganization renames the client', async () => {
+ clientStore.set(
+ 'client_a',
+ makeClient({ id: 'client_a', organizationId: 'org_1', name: 'Old name' })
+ );
+
+ const result = await subject.updateClientForOrganization(
+ 'client_a',
+ 'org_1',
+ { name: 'New name' }
+ );
+ expect(result?.name).toBe('New name');
+});
+
+test('deleteClientForOrganization deletes only when the client belongs to the org', async () => {
+ clientStore.set(
+ 'client_a',
+ makeClient({ id: 'client_a', organizationId: 'org_1' })
+ );
+
+ const deniedResult = await subject.deleteClientForOrganization(
+ 'client_a',
+ 'org_2'
+ );
+ expect(deniedResult).toBe(false);
+ expect(clientStore.has('client_a')).toBe(true);
+
+ const result = await subject.deleteClientForOrganization('client_a', 'org_1');
+ expect(result).toBe(true);
+ expect(clientStore.has('client_a')).toBe(false);
+});
diff --git a/packages/core/src/modules/client/client.service.ts b/packages/core/src/modules/client/client.service.ts
new file mode 100644
index 000000000..9e1d484ac
--- /dev/null
+++ b/packages/core/src/modules/client/client.service.ts
@@ -0,0 +1,207 @@
+// Moved from packages/db/src/services/clients.service.ts (M6-002, module
+// map: client owns "R,H,S" — no constants file, per the module map). packages/db
+// keeps a re-export shim: apps/api/src/utils/auth.ts, core's mcp module and
+// several other core modules' `src/access.ts` still reach `getClientByIdCached`
+// / `ClientType` through @openpanel/db's barrel — same shape as
+// packages/db/src/services/organization.service.ts since M6-001.
+//
+// The /manage REST CRUD bodies (apps/api/src/controllers/manage.controller.ts's
+// listClients/getClient/createClient/updateClient/deleteClient) move here
+// too, so V1's controller and core's own client.routes.ts share one
+// implementation (DELEGATE PATTERN).
+//
+// db access is LAZY (`loadDb` below), not a static top-level import — see
+// project.service.ts's header for the full reasoning. No dependency on
+// project.service.ts here (the reverse direction exists, for cache
+// invalidation) — project-ownership checks below query `db.project`
+// directly, matching V1's manage.controller.ts exactly.
+
+import crypto from 'node:crypto';
+import type { Client, Prisma } from '@openpanel/db/src/prisma-client';
+import { cacheable } from '@openpanel/redis';
+import { hashPassword } from '../auth/auth.service';
+
+export type IServiceClient = Client;
+export type IServiceClientWithProject = Prisma.ClientGetPayload<{
+ include: {
+ project: true;
+ };
+}>;
+
+function loadDb() {
+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);
+}
+
+export async function getClientsByOrganizationId(organizationId: string) {
+ const db = await loadDb();
+ return db.client.findMany({
+ where: {
+ organizationId,
+ },
+ include: {
+ project: true,
+ },
+ orderBy: {
+ createdAt: 'asc',
+ },
+ });
+}
+
+/** trpc client.list — no access check of its own, ported verbatim. */
+export async function getClientsByProjectId(projectId: string) {
+ const db = await loadDb();
+ return db.client.findMany({
+ where: {
+ projectId,
+ },
+ });
+}
+
+export async function getClientById(
+ id: string
+): Promise<IServiceClientWithProject | null> {
+ const db = await loadDb();
+ return db.client.findUnique({
+ where: { id },
+ include: {
+ project: true,
+ },
+ });
+}
+
+const FIVE_MINUTES_IN_SECONDS = 60 * 5;
+export const getClientByIdCached = cacheable(
+ getClientById,
+ FIVE_MINUTES_IN_SECONDS
+);
+
+// --- /manage REST CRUD (apps/api/src/controllers/manage.controller.ts) ---
+
+export async function listClientsForOrganization(
+ organizationId: string,
+ projectId?: string
+) {
+ const db = await loadDb();
+
+ if (projectId) {
+ const project = await db.project.findFirst({
+ where: { id: projectId, organizationId },
+ });
+ if (!project) {
+ return null;
+ }
+ }
+
+ return db.client.findMany({
+ where: {
+ organizationId,
+ ...(projectId ? { projectId } : {}),
+ },
+ orderBy: {
+ createdAt: 'desc',
+ },
+ });
+}
+
+export async function getClientForOrganization(
+ id: string,
+ organizationId: string
+) {
+ const db = await loadDb();
+ return db.client.findFirst({
+ where: {
+ id,
+ organizationId,
+ },
+ });
+}
+
+export interface CreatedClient {
+ client: IServiceClient;
+ secret: string;
+}
+
+export async function createClientForOrganization(
+ organizationId: string,
+ input: {
+ name: string;
+ projectId?: string | null;
+ type?: 'read' | 'write' | 'root';
+ }
+): Promise<CreatedClient | null> {
+ const db = await loadDb();
+
+ if (input.projectId) {
+ const project = await db.project.findFirst({
+ where: { id: input.projectId, organizationId },
+ });
+ if (!project) {
+ return null;
+ }
+ }
+
+ const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;
+ const client = await db.client.create({
+ data: {
+ organizationId,
+ projectId: input.projectId || null,
+ name: input.name,
+ type: input.type || 'write',
+ secret: await hashPassword(secret),
+ },
+ });
+
+ await getClientByIdCached.clear(client.id);
+
+ return { client, secret };
+}
+
+export async function updateClientForOrganization(
+ id: string,
+ organizationId: string,
+ input: { name?: string }
+): Promise<IServiceClient | null> {
+ const db = await loadDb();
+
+ const existing = await db.client.findFirst({
+ where: { id, organizationId },
+ });
+
+ if (!existing) {
+ return null;
+ }
+
+ const updateData: Prisma.ClientUpdateInput = {};
+ if (input.name !== undefined) {
+ updateData.name = input.name;
+ }
+
+ const client = await db.client.update({
+ where: { id },
+ data: updateData,
+ });
+
+ await getClientByIdCached.clear(client.id);
+
+ return client;
+}
+
+export async function deleteClientForOrganization(
+ id: string,
+ organizationId: string
+): Promise<boolean> {
+ const db = await loadDb();
+
+ const client = await db.client.findFirst({
+ where: { id, organizationId },
+ });
+
+ if (!client) {
+ return false;
+ }
+
+ await db.client.delete({ where: { id } });
+ await getClientByIdCached.clear(id);
+
+ return true;
+}
diff --git a/packages/core/src/modules/client/src/access.ts b/packages/core/src/modules/client/src/access.ts
new file mode 100644
index 000000000..b4444d963
--- /dev/null
+++ b/packages/core/src/modules/client/src/access.ts
@@ -0,0 +1,25 @@
+// 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. `getClientAccess` has no
+// ladder wrapper (V1's packages/trpc/src/access.ts re-exports it bare too),
+// only `requireOrganizationAdmin` goes through `createAccessChecks`.
+
+import {
+ canWriteProject,
+ getOrganizationAccess,
+ getProjectAccess,
+} from '@openpanel/db/src/services/access.service';
+import { createAccessChecks } from '../../../shared/access';
+import { getProjectById } from '../../project/project.service';
+
+export { getClientAccess } from '@openpanel/db/src/services/access.service';
+
+const checks = createAccessChecks({
+ getProjectAccess,
+ canWriteProject,
+ getOrganizationAccess,
+ getProjectById,
+});
+
+export const requireOrganizationAdmin = checks.requireOrganizationAdmin;
diff --git a/packages/core/src/modules/import/import.routes.ts b/packages/core/src/modules/import/import.routes.ts
index e7ebf7fa5..f7802652f 100644
--- a/packages/core/src/modules/import/import.routes.ts
+++ b/packages/core/src/modules/import/import.routes.ts
@@ -14,6 +14,11 @@
// V1 has no request-body schema for this route (ADR-003: "/profile,
// /import, /event and /tools have no request schemas today, and adding them
// would be a behaviour change"), so the body is typed but not shape-validated.
+//
+// `client.projectId` is `null` for a root client (M6-002 widened
+// AuthenticatedClient to match IServiceClientWithProject); V1's controller
+// guards on exactly this (apps/api/src/controllers/import.controller.ts:17-18),
+// ported verbatim.
import type { IClickhouseEvent } from '@openpanel/db';
import { z } from 'zod';
@@ -24,6 +29,10 @@ export const importRoutes = defineRoutes((app) =>
app.post(
'/import/events',
async ({ body, client, ctx, status }) => {
+ if (!client.projectId) {
+ return status(400, 'Missing project id');
+ }
+
try {
const { writtenRows } = await insertRawEventsBatch(
client.projectId,
diff --git a/packages/core/src/modules/project/project.constants.ts b/packages/core/src/modules/project/project.constants.ts
new file mode 100644
index 000000000..3f2fe3fe1
--- /dev/null
+++ b/packages/core/src/modules/project/project.constants.ts
@@ -0,0 +1,36 @@
+// Moved from packages/constants/index.ts (M6-002, ADR-008's module map:
+// project owns "C"). packages/constants/index.ts becomes a re-export shim of
+// `ProjectTypeNames` (same shape as packages/validation/src/import.validation.ts
+// since M5-004), so existing @openpanel/constants importers keep resolving it
+// unchanged. `zCreateProject`/`zUpdateProject` are the /manage REST body
+// schemas (apps/api/src/controllers/manage.controller.ts), moved here with
+// the CRUD bodies they validate (project.service.ts's
+// createProjectForOrganization/updateProjectForOrganization).
+//
+// Isomorphic by the AGENTS.md rule: zod and nothing else.
+
+import { z } from 'zod';
+
+export const ProjectTypeNames = {
+ website: 'Website',
+ app: 'App',
+ backend: 'Backend',
+} as const;
+
+export const zProjectType = z.enum(['website', 'app', 'backend']);
+
+export const zCreateProject = z.object({
+ name: z.string().min(1),
+ domain: z.string().url().or(z.literal('')).or(z.null()).optional(),
+ cors: z.array(z.string()).default([]),
+ crossDomain: z.boolean().optional().default(false),
+ types: z.array(zProjectType).optional().default([]),
+});
+
+export const zUpdateProject = z.object({
+ name: z.string().min(1).optional(),
+ domain: z.string().url().or(z.literal('')).or(z.null()).optional(),
+ cors: z.array(z.string()).optional(),
+ crossDomain: z.boolean().optional(),
+ allowUnsafeRevenueTracking: z.boolean().optional(),
+});
diff --git a/packages/core/src/modules/project/project.routes.ts b/packages/core/src/modules/project/project.routes.ts
new file mode 100644
index 000000000..b60799266
--- /dev/null
+++ b/packages/core/src/modules/project/project.routes.ts
@@ -0,0 +1,121 @@
+// The /manage/projects REST surface (M6-002). V1's Fastify controller
+// (apps/api/src/controllers/manage.controller.ts) stays the LIVE route
+// (DELEGATE PATTERN) and delegates its CRUD bodies to project.service.ts's
+// createProjectForOrganization/updateProjectForOrganization/etc — the same
+// functions this route calls. Response envelopes (`{ data }` / `{ success }`)
+// match V1's `reply.send(...)` shape exactly (byte-unchanged URL surface).
+//
+// NAMED GAP, same as import.routes.ts: this route is not yet reachable.
+// `authenticateClient` (http/client-auth.ts) is a P8 stub that always
+// returns null, so `clientAuth` 401s every request until it is filled in;
+// main.ts also does not mount `publicApiRoutes` until a real `AppDeps`
+// exists. `allow: ['root']` mirrors V1's rule (utils/auth.ts's
+// `validateManageRequest`: only root clients may manage resources).
+
+import { z } from 'zod';
+import { defineRoutes } from '../../http/define';
+import { zCreateProject, zUpdateProject } from './project.constants';
+import {
+ createProjectForOrganization,
+ deleteProjectForOrganization,
+ getProjectForOrganization,
+ listProjectsForOrganization,
+ updateProjectForOrganization,
+} from './project.service';
+
+const idParams = z.object({ id: z.string() });
+
+export const projectRoutes = defineRoutes((app) =>
+ app
+ .get(
+ '/manage/projects',
+ async ({ client }) => ({
+ data: await listProjectsForOrganization(client.organizationId),
+ }),
+ { clientAuth: { allow: ['root'] }, detail: { tags: ['Manage'] } }
+ )
+ .get(
+ '/manage/projects/:id',
+ async ({ client, params, status }) => {
+ const project = await getProjectForOrganization(
+ params.id,
+ client.organizationId
+ );
+ if (!project) {
+ return status(404, {
+ error: 'Not Found',
+ message: 'Project not found',
+ });
+ }
+ return { data: project };
+ },
+ {
+ clientAuth: { allow: ['root'] },
+ params: idParams,
+ detail: { tags: ['Manage'] },
+ }
+ )
+ .post(
+ '/manage/projects',
+ async ({ body, client }) => {
+ const { project, client: firstClient } =
+ await createProjectForOrganization(client.organizationId, {
+ name: body.name,
+ domain: body.domain,
+ cors: body.cors,
+ crossDomain: body.crossDomain,
+ types: body.types,
+ });
+ return { data: { ...project, client: firstClient } };
+ },
+ {
+ clientAuth: { allow: ['root'] },
+ body: zCreateProject,
+ detail: { tags: ['Manage'] },
+ }
+ )
+ .patch(
+ '/manage/projects/:id',
+ async ({ body, client, params, status }) => {
+ const project = await updateProjectForOrganization(
+ params.id,
+ client.organizationId,
+ body
+ );
+ if (!project) {
+ return status(404, {
+ error: 'Not Found',
+ message: 'Project not found',
+ });
+ }
+ return { data: project };
+ },
+ {
+ clientAuth: { allow: ['root'] },
+ params: idParams,
+ body: zUpdateProject,
+ detail: { tags: ['Manage'] },
+ }
+ )
+ .delete(
+ '/manage/projects/:id',
+ async ({ client, params, status }) => {
+ const deleted = await deleteProjectForOrganization(
+ params.id,
+ client.organizationId
+ );
+ if (!deleted) {
+ return status(404, {
+ error: 'Not Found',
+ message: 'Project not found',
+ });
+ }
+ return { success: true };
+ },
+ {
+ clientAuth: { allow: ['root'] },
+ params: idParams,
+ detail: { tags: ['Manage'] },
+ }
+ )
+);
diff --git a/packages/core/src/modules/project/project.rpc.test.ts b/packages/core/src/modules/project/project.rpc.test.ts
new file mode 100644
index 000000000..42573611a
--- /dev/null
+++ b/packages/core/src/modules/project/project.rpc.test.ts
@@ -0,0 +1,88 @@
+// Only the "is anyone logged in" boundary is exercised here — no database.
+// The access-check + mutation bodies ride on @openpanel/db (lazy-loaded
+// through ./src/access and project.service.ts); wiring this router
+// end-to-end against a real Postgres is P6's (protectedProcedure) job, not
+// this one's — see project.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 { projectRouter } from './project.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 projectRouter.createCaller(trpcCtx);
+}
+
+test('getProjectWithClients rejects an unauthenticated caller', async () => {
+ const caller = await anonCaller();
+ await expect(
+ caller.getProjectWithClients({ projectId: 'proj_1' })
+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
+});
+
+test('activationStatus rejects an unauthenticated caller', async () => {
+ const caller = await anonCaller();
+ await expect(
+ caller.activationStatus({ projectId: 'proj_1' })
+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
+});
+
+test('list rejects an unauthenticated caller', async () => {
+ const caller = await anonCaller();
+ await expect(caller.list({ organizationId: 'org_1' })).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+});
+
+test('update rejects an unauthenticated caller before touching a project', async () => {
+ const caller = await anonCaller();
+ await expect(caller.update({ id: 'proj_1' })).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+});
+
+test('create rejects an unauthenticated caller', async () => {
+ const caller = await anonCaller();
+ await expect(
+ caller.create({
+ organizationId: 'org_1',
+ project: 'My Project',
+ domain: 'https://example.com',
+ cors: [],
+ website: true,
+ app: false,
+ backend: false,
+ })
+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
+});
+
+test('delete rejects an unauthenticated caller', async () => {
+ const caller = await anonCaller();
+ await expect(caller.delete({ projectId: 'proj_1' })).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+});
+
+test('cancelDeletion rejects an unauthenticated caller', async () => {
+ const caller = await anonCaller();
+ await expect(
+ caller.cancelDeletion({ projectId: 'proj_1' })
+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
+});
diff --git a/packages/core/src/modules/project/project.rpc.ts b/packages/core/src/modules/project/project.rpc.ts
new file mode 100644
index 000000000..6afd39599
--- /dev/null
+++ b/packages/core/src/modules/project/project.rpc.ts
@@ -0,0 +1,166 @@
+// Ported from packages/trpc/src/routers/project.ts (M6-002).
+//
+// 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 project functions (DELEGATE
+// PATTERN) — this module has no queue/cron of its own, so there is no
+// `ctx.services.project`, same as `user`/`conversation`.
+//
+// The 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. It is dynamically imported
+// (`loadAccessChecks`), same as organization.rpc.ts, so a static import here
+// does not pull @openpanel/db's prisma client into every core test file.
+
+import { zOnboardingProject, zProjectUpdate } from '@openpanel/validation';
+import { z } from 'zod';
+import { createTRPCRouter, procedure } from '../../rpc/base';
+import { TRPCAccessError, TRPCForbiddenError } from '../../rpc/errors';
+import {
+ cancelProjectDeletion,
+ createProjectForOrganization,
+ getProjectActivationStatus,
+ getProjectById,
+ getProjects,
+ getProjectWithClients,
+ scheduleProjectDeletion,
+ updateProjectForOrganization,
+} from './project.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 projectRouter = createTRPCRouter({
+ getProjectWithClients: procedure
+ .input(z.object({ projectId: z.string() }))
+ .query(async ({ input: { projectId }, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ const { getProjectAccess } = await loadAccessChecks();
+ const access = await getProjectAccess({ userId, projectId });
+ if (!access) {
+ throw new TRPCForbiddenError('You do not have access to this project');
+ }
+ return getProjectWithClients(projectId);
+ }),
+
+ // Powers the activation checklist on the project overview: has the project
+ // received data, built a report, and invited a teammate yet?
+ activationStatus: procedure
+ .input(z.object({ projectId: z.string() }))
+ .query(async ({ input: { projectId }, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ const { getProjectAccess } = await loadAccessChecks();
+ const access = await getProjectAccess({ userId, projectId });
+ if (!access) {
+ throw new TRPCForbiddenError('You do not have access to this project');
+ }
+
+ return getProjectActivationStatus(projectId);
+ }),
+
+ list: procedure
+ .input(z.object({ organizationId: z.string().nullable() }))
+ .query(async ({ input: { organizationId }, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ if (organizationId === null) {
+ return [];
+ }
+ return getProjects({ organizationId, userId });
+ }),
+
+ update: procedure.input(zProjectUpdate).mutation(async ({ input, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ const { requireProjectAccess } = await loadAccessChecks();
+ await requireProjectAccess({ userId, projectId: input.id, level: 'write' });
+
+ const project = await getProjectById(input.id);
+ if (!project) {
+ throw new TRPCForbiddenError('Project not found');
+ }
+
+ return updateProjectForOrganization(input.id, project.organizationId, {
+ name: input.name,
+ domain: input.domain,
+ cors: input.cors,
+ crossDomain: input.crossDomain,
+ allowUnsafeRevenueTracking: input.allowUnsafeRevenueTracking,
+ });
+ }),
+
+ create: procedure
+ .input(zOnboardingProject)
+ .mutation(async ({ input, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ if (!input.organizationId) {
+ throw new TRPCForbiddenError('Organization is required');
+ }
+
+ const { getOrganizationAccess } = await loadAccessChecks();
+ const access = await getOrganizationAccess({
+ userId,
+ organizationId: input.organizationId,
+ });
+
+ if (access?.role !== 'org:admin') {
+ throw new TRPCForbiddenError(
+ 'Only organization admins can create projects'
+ );
+ }
+
+ const { project, client } = await createProjectForOrganization(
+ input.organizationId,
+ {
+ name: input.project,
+ domain: input.domain,
+ cors: input.cors,
+ crossDomain: false,
+ types: [],
+ }
+ );
+
+ return { ...project, client };
+ }),
+
+ delete: procedure
+ .input(z.object({ projectId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ const { requireProjectAdmin } = await loadAccessChecks();
+ // Destroying a project is admin-tier, matching project.create.
+ await requireProjectAdmin({
+ userId,
+ projectId: input.projectId,
+ message: 'Only organization admins can delete projects',
+ });
+
+ await scheduleProjectDeletion(input.projectId);
+ return true;
+ }),
+
+ cancelDeletion: procedure
+ .input(z.object({ projectId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ const { requireProjectAdmin } = await loadAccessChecks();
+ await requireProjectAdmin({
+ userId,
+ projectId: input.projectId,
+ message: 'Only organization admins can cancel a project deletion',
+ });
+
+ await cancelProjectDeletion(input.projectId);
+ return true;
+ }),
+});
diff --git a/packages/core/src/modules/project/project.service.test.ts b/packages/core/src/modules/project/project.service.test.ts
new file mode 100644
index 000000000..de2a0b955
--- /dev/null
+++ b/packages/core/src/modules/project/project.service.test.ts
@@ -0,0 +1,312 @@
+// project.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. `getProjectEventsCount` / `getLastEventPerProject`
+// (ClickHouse) are a verbatim port with unchanged SQL — executed against
+// local ClickHouse for this task's verification, not re-tested here.
+
+import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';
+
+interface FakeProject {
+ id: string;
+ organizationId: string;
+ name: string;
+ domain: string | null;
+ cors: string[];
+ crossDomain: boolean;
+ allowUnsafeRevenueTracking: boolean;
+ types: string[];
+ filters: unknown[];
+ eventsCount: number;
+ firstEventAt: Date | null;
+ createdAt: Date;
+ deleteAt: Date | null;
+}
+
+interface FakeClient {
+ id: string;
+ projectId: string;
+}
+
+const projectStore = new Map<string, FakeProject>();
+const clientsByProject = new Map<string, FakeClient[]>();
+const reportCountByProject = new Map<string, number>();
+const memberCountByOrg = new Map<string, number>();
+const organizationDeleteAtById = new Map<string, Date | null>();
+
+function makeProject(
+ overrides: Partial<FakeProject> & { id: string; organizationId: string }
+): FakeProject {
+ return {
+ name: 'A project',
+ domain: null,
+ cors: [],
+ crossDomain: false,
+ allowUnsafeRevenueTracking: false,
+ types: [],
+ filters: [],
+ eventsCount: 0,
+ firstEventAt: null,
+ createdAt: new Date(),
+ deleteAt: null,
+ ...overrides,
+ };
+}
+
+const project = {
+ findMany: mock(
+ async ({ where }: { where: { organizationId: string; deleteAt?: null } }) =>
+ [...projectStore.values()].filter(
+ (p) => p.organizationId === where.organizationId && !p.deleteAt
+ )
+ ),
+ findFirst: mock(
+ async ({ where }: { where: { id: string; organizationId: string } }) => {
+ const found = projectStore.get(where.id);
+ if (!found || found.organizationId !== where.organizationId) {
+ return null;
+ }
+ return { ...found, clients: clientsByProject.get(where.id) ?? [] };
+ }
+ ),
+ findUnique: mock(async ({ where: { id } }: { where: { id: string } }) => {
+ const found = projectStore.get(id);
+ if (!found) {
+ return null;
+ }
+ return {
+ ...found,
+ organization: { deleteAt: organizationDeleteAtById.get(id) ?? null },
+ };
+ }),
+ findUniqueOrThrow: mock(
+ async ({ where: { id } }: { where: { id: string } }) => {
+ const found = projectStore.get(id);
+ if (!found) {
+ throw new Error(`project ${id} not found`);
+ }
+ return {
+ ...found,
+ organization: { deleteAt: organizationDeleteAtById.get(id) ?? null },
+ };
+ }
+ ),
+ create: mock(
+ async ({
+ data,
+ }: {
+ data: Omit<FakeProject, 'id' | 'createdAt'> & { id: string };
+ }) => {
+ const created = makeProject(data);
+ projectStore.set(created.id, created);
+ const client = { id: `client_${created.id}`, projectId: created.id };
+ clientsByProject.set(created.id, [client]);
+ return { ...created, clients: [{ id: client.id }] };
+ }
+ ),
+ update: mock(
+ async ({
+ where: { id },
+ data,
+ }: {
+ where: { id: string };
+ data: Partial<FakeProject>;
+ }) => {
+ const existing = projectStore.get(id);
+ if (!existing) {
+ throw new Error(`project ${id} not found`);
+ }
+ const next = { ...existing, ...data };
+ projectStore.set(id, next);
+ return next;
+ }
+ ),
+};
+
+const report = {
+ count: mock(
+ async ({ where: { projectId } }: { where: { projectId: string } }) =>
+ reportCountByProject.get(projectId) ?? 0
+ ),
+};
+
+const member = {
+ count: mock(
+ async ({
+ where: { organizationId },
+ }: {
+ where: { organizationId: string };
+ }) => memberCountByOrg.get(organizationId) ?? 0
+ ),
+};
+
+// Bypasses the Redis cache-aside entirely — this module's own logic is
+// exercised directly, caching is @openpanel/redis's concern. Same stub as
+// organization.service.test.ts.
+function cacheableStub(
+ fnOrName: ((...args: unknown[]) => unknown) | string,
+ fnOrTtl: ((...args: unknown[]) => unknown) | number
+) {
+ const fn =
+ typeof fnOrName === 'function'
+ ? fnOrName
+ : (fnOrTtl as (...args: unknown[]) => unknown);
+ return Object.assign(fn, {
+ getKey: () => '',
+ clear: async () => 0,
+ set: () => async () => 'OK' as const,
+ });
+}
+mock.module('@openpanel/redis', () => ({
+ cacheable: cacheableStub,
+ getRedisCache: () => ({
+ get: async () => null,
+ setex: async () => undefined,
+ del: async () => undefined,
+ }),
+}));
+
+const actualPrismaClient = await import('@openpanel/db/src/prisma-client');
+mock.module('@openpanel/db/src/prisma-client', () => ({
+ ...actualPrismaClient,
+ db: { project, report, member },
+}));
+
+mock.module('@openpanel/db/src/services/id.service', () => ({
+ getId: async (_table: string, name: string) => `${name}-slug`,
+}));
+
+let subject: typeof import('./project.service');
+beforeAll(async () => {
+ subject = await import('./project.service');
+});
+
+beforeEach(() => {
+ projectStore.clear();
+ clientsByProject.clear();
+ reportCountByProject.clear();
+ memberCountByOrg.clear();
+ organizationDeleteAtById.clear();
+});
+
+test('listProjectsForOrganization excludes soft-deleted projects and other orgs', async () => {
+ projectStore.set('p1', makeProject({ id: 'p1', organizationId: 'org_1' }));
+ projectStore.set(
+ 'p2',
+ makeProject({ id: 'p2', organizationId: 'org_1', deleteAt: new Date() })
+ );
+ projectStore.set('p3', makeProject({ id: 'p3', organizationId: 'org_2' }));
+
+ const result = await subject.listProjectsForOrganization('org_1');
+ expect(result.map((p) => p.id)).toEqual(['p1']);
+});
+
+test('getProjectForOrganization returns null for a project in a different org', async () => {
+ projectStore.set('p1', makeProject({ id: 'p1', organizationId: 'org_1' }));
+
+ const result = await subject.getProjectForOrganization('p1', 'org_2');
+ expect(result).toBeNull();
+});
+
+test('createProjectForOrganization creates a project with a first write client', async () => {
+ const result = await subject.createProjectForOrganization('org_1', {
+ name: 'New project',
+ cors: ['https://example.com'],
+ crossDomain: false,
+ types: [],
+ });
+
+ expect(result.project.organizationId).toBe('org_1');
+ expect(result.client).not.toBeNull();
+ expect(typeof result.client?.secret).toBe('string');
+});
+
+test('updateProjectForOrganization returns null for a project in a different org', async () => {
+ projectStore.set('p1', makeProject({ id: 'p1', organizationId: 'org_1' }));
+
+ const result = await subject.updateProjectForOrganization('p1', 'org_2', {
+ name: 'Renamed',
+ });
+ expect(result).toBeNull();
+});
+
+test('updateProjectForOrganization strips trailing slashes from domain and cors', async () => {
+ projectStore.set('p1', makeProject({ id: 'p1', organizationId: 'org_1' }));
+
+ const result = await subject.updateProjectForOrganization('p1', 'org_1', {
+ domain: 'https://example.com/',
+ cors: ['https://a.com/', 'https://b.com/'],
+ });
+
+ expect(result?.domain).toBe('https://example.com');
+ expect(result?.cors).toEqual(['https://a.com', 'https://b.com']);
+});
+
+test('deleteProjectForOrganization schedules a 24h grace period, scoped to the org', async () => {
+ projectStore.set('p1', makeProject({ id: 'p1', organizationId: 'org_1' }));
+
+ const denied = await subject.deleteProjectForOrganization('p1', 'org_2');
+ expect(denied).toBe(false);
+
+ const before = Date.now();
+ const result = await subject.deleteProjectForOrganization('p1', 'org_1');
+ expect(result).toBe(true);
+
+ const updated = projectStore.get('p1');
+ expect(updated?.deleteAt).not.toBeNull();
+ const deleteAtMs = updated?.deleteAt?.getTime() ?? 0;
+ const TWENTY_FOUR_HOURS_MS = 24 * 60 * 60 * 1000;
+ expect(deleteAtMs).toBeGreaterThanOrEqual(before + TWENTY_FOUR_HOURS_MS);
+});
+
+test('scheduleProjectDeletion sets deleteAt ~24h out', async () => {
+ projectStore.set('p1', makeProject({ id: 'p1', organizationId: 'org_1' }));
+
+ const before = Date.now();
+ await subject.scheduleProjectDeletion('p1');
+
+ const updated = projectStore.get('p1');
+ const TWENTY_FOUR_HOURS_MS = 24 * 60 * 60 * 1000;
+ expect(updated?.deleteAt?.getTime()).toBeGreaterThanOrEqual(
+ before + TWENTY_FOUR_HOURS_MS
+ );
+});
+
+test('cancelProjectDeletion refuses while the organization itself is scheduled for deletion', async () => {
+ projectStore.set('p1', makeProject({ id: 'p1', organizationId: 'org_1' }));
+ organizationDeleteAtById.set('p1', new Date());
+
+ await expect(subject.cancelProjectDeletion('p1')).rejects.toThrow(
+ /organization is scheduled for deletion/
+ );
+});
+
+test('cancelProjectDeletion clears deleteAt otherwise', async () => {
+ projectStore.set(
+ 'p1',
+ makeProject({ id: 'p1', organizationId: 'org_1', deleteAt: new Date() })
+ );
+
+ await subject.cancelProjectDeletion('p1');
+ expect(projectStore.get('p1')?.deleteAt).toBeNull();
+});
+
+test('getProjectActivationStatus reports hasReport/hasTeammate from counts', async () => {
+ projectStore.set('p1', makeProject({ id: 'p1', organizationId: 'org_1' }));
+ reportCountByProject.set('p1', 2);
+ memberCountByOrg.set('org_1', 3);
+
+ const status = await subject.getProjectActivationStatus('p1');
+ expect(status.hasReport).toBe(true);
+ expect(status.hasTeammate).toBe(true);
+});
+
+test('getProjectActivationStatus is false when there is no report and no extra teammate', async () => {
+ projectStore.set('p1', makeProject({ id: 'p1', organizationId: 'org_1' }));
+ memberCountByOrg.set('org_1', 1);
+
+ const status = await subject.getProjectActivationStatus('p1');
+ expect(status.hasReport).toBe(false);
+ expect(status.hasTeammate).toBe(false);
+});
diff --git a/packages/core/src/modules/project/project.service.ts b/packages/core/src/modules/project/project.service.ts
new file mode 100644
index 000000000..5b151a815
--- /dev/null
+++ b/packages/core/src/modules/project/project.service.ts
@@ -0,0 +1,535 @@
+// Moved from packages/db/src/services/project.service.ts (M6-002, module
+// map: project owns "R,H,S,C"). packages/db keeps a re-export shim: its own
+// access.service.ts and notification.service.ts still reach `getProjectById`
+// / `getProjectByIdCached` through the same relative path, and
+// apps/api/src/utils/auth.ts + several other core modules' `src/access.ts`
+// reach them through @openpanel/db's barrel — same shape as
+// packages/db/src/services/organization.service.ts since M6-001.
+//
+// The /manage REST CRUD bodies (apps/api/src/controllers/manage.controller.ts's
+// listProjects/getProject/createProject/updateProject/deleteProject) move
+// here too, so V1's controller and core's own project.routes.ts share one
+// implementation (DELEGATE PATTERN).
+//
+// db/ch access is LAZY (`load*` below), not a static top-level import — see
+// insight.service.ts's header for the full reasoning (jobs.registry.ts and
+// rpc.router.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).
+//
+// ClickHouse queries here still go through clix/sqlstring, not the `sql`
+// tag: ADR-013 converts the analytics read path one query per P7 task, and
+// this module's queries haven't been converted yet.
+
+import crypto from 'node:crypto';
+import { stripTrailingSlash } from '@openpanel/common';
+import { clix } from '@openpanel/db/src/clickhouse/query-builder';
+import type {
+ Prisma,
+ Project,
+ ProjectType,
+} from '@openpanel/db/src/prisma-client';
+import { cacheable } from '@openpanel/redis';
+import sqlstring from 'sqlstring';
+import { TRPCBadRequestError } from '../../rpc/errors';
+import { hashPassword } from '../auth/auth.service';
+import { getClientByIdCached } from '../client/client.service';
+
+export type IServiceProject = Project;
+export type IServiceProjectWithClients = Prisma.ProjectGetPayload<{
+ include: {
+ clients: true;
+ };
+}>;
+
+function loadDb() {
+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);
+}
+
+function loadChClient() {
+ return import('@openpanel/db/src/clickhouse/client');
+}
+
+function loadIdService() {
+ return import('@openpanel/db/src/services/id.service').then((m) => m.getId);
+}
+
+export async function getProjectById(id: string) {
+ const db = await loadDb();
+ const res = await db.project.findUnique({
+ where: {
+ id,
+ },
+ });
+
+ if (!res) {
+ return null;
+ }
+
+ return res;
+}
+
+const DAY_IN_SECONDS = 60 * 60 * 24;
+/** L1 LRU (60s) + L2 Redis. clear() invalidates Redis + local LRU; other nodes may serve stale from LRU for up to 60s. */
+export const getProjectByIdCached = cacheable(getProjectById, DAY_IN_SECONDS);
+
+export async function getProjectWithClients(id: string) {
+ const db = await loadDb();
+ const res = await db.project.findUnique({
+ where: {
+ id,
+ },
+ include: {
+ clients: true,
+ },
+ });
+
+ if (!res) {
+ return null;
+ }
+
+ return res;
+}
+
+export async function getProjects({
+ organizationId,
+ userId,
+}: {
+ organizationId: string;
+ userId: string | null;
+}) {
+ if (!userId) {
+ return [];
+ }
+
+ const db = await loadDb();
+ const [projects, members, access] = await Promise.all([
+ db.project.findMany({
+ where: {
+ organizationId,
+ },
+ orderBy: {
+ eventsCount: 'desc',
+ },
+ }),
+ db.member.findMany({
+ where: {
+ userId,
+ organizationId,
+ },
+ }),
+ db.projectAccess.findMany({
+ where: {
+ userId,
+ organizationId,
+ },
+ }),
+ ]);
+
+ if (members.length === 0) {
+ return [];
+ }
+
+ if (access.length > 0) {
+ return projects.filter((project) =>
+ access.some((a) => a.projectId === project.id)
+ );
+ }
+
+ return projects;
+}
+
+/**
+ * Fast approximate count of a project's events (excluding session_start /
+ * session_end), read from distinct_event_names_mv instead of the raw events
+ * table.
+ *
+ * Why not count raw events: `name NOT IN (...)` is a negation, so it can't
+ * prune with idx_name and scans the project's whole events slice — and this
+ * runs from the sessions job on every batch. The MV already accumulates
+ * `count() AS event_count` per (project_id, name) insert block, so summing
+ * it reads a few thousand pre-aggregated rows instead of billions of raw
+ * ones.
+ *
+ * Why approximate: event_count is a plain UInt64, not an aggregate state,
+ * so MV counter rows whose (project_id, name, created_at) sort key collides
+ * collapse on merge keeping only one block's count. Live ingestion rarely
+ * ties on the ms timestamp; bulk imports with coarse timestamps are where
+ * collisions come from. The error is strictly downward (measured 0.0011%
+ * low on a 1.46B-event project) — acceptable for this display/onboarding
+ * counter.
+ */
+export const getProjectEventsCount = async (projectId: string) => {
+ const { chQuery, TABLE_NAMES } = await loadChClient();
+ const res = await chQuery<{ count: number }>(
+ `SELECT sum(event_count) as count FROM ${TABLE_NAMES.event_names_mv} WHERE project_id = ${sqlstring.escape(projectId)} AND name NOT IN ('session_start', 'session_end')`
+ );
+ return res[0]?.count;
+};
+
+/**
+ * Newest event timestamp per project, for the whole instance in one query.
+ * Reads the same pre-aggregated MV as getProjectEventsCount (it stores
+ * max(created_at) per (project_id, name) block), so this scans thousands of
+ * rows instead of the raw events table. Projects with no events are absent
+ * from the map.
+ */
+export const getLastEventPerProject = async (): Promise<Map<string, Date>> => {
+ const { ch, TABLE_NAMES, convertClickhouseDateToJs } = await loadChClient();
+ const res = await clix(ch)
+ .select<{ project_id: string; last_event_at: string }>([
+ 'project_id',
+ 'max(created_at) AS last_event_at',
+ ])
+ .from(TABLE_NAMES.event_names_mv)
+ // Session rows are worker-generated (the reaper can emit session_end after
+ // tracking already stopped) — only real tracking activity should count.
+ .where('name', 'NOT IN', ['session_start', 'session_end'])
+ .groupBy(['project_id'])
+ .execute();
+ return new Map(
+ res.map((row) => [
+ row.project_id,
+ convertClickhouseDateToJs(row.last_event_at),
+ ])
+ );
+};
+
+/**
+ * Resolve and validate a projectId for an API client.
+ *
+ * - Read clients: returns the fixed projectId from the client (ignores any supplied value).
+ * - Root clients: validates that the supplied projectId belongs to the client's organization.
+ *
+ * Throws if the project is not found or does not belong to the organization.
+ * Use this as the single source of truth for projectId resolution across the API and MCP.
+ */
+export async function resolveClientProjectId({
+ clientType,
+ clientProjectId,
+ organizationId,
+ inputProjectId,
+}: {
+ clientType: 'read' | 'root';
+ clientProjectId: string | null;
+ organizationId: string;
+ inputProjectId: string | undefined;
+}): Promise<string> {
+ if (clientType !== 'root') {
+ if (!clientProjectId) {
+ throw new Error('Client is not associated with a project');
+ }
+ return clientProjectId;
+ }
+
+ if (!inputProjectId) {
+ throw new Error(
+ 'projectId is required when using a root (organization-level) client'
+ );
+ }
+
+ const db = await loadDb();
+ const project = await db.project.findFirst({
+ where: { id: inputProjectId, organizationId },
+ select: { id: true },
+ });
+
+ if (!project) {
+ throw new Error(
+ 'Project not found or does not belong to your organization'
+ );
+ }
+
+ return inputProjectId;
+}
+
+export interface ProjectActivationStatus {
+ hasFirstEvent: boolean;
+ firstEventAt: Date | null;
+ projectCreatedAt: Date;
+ hasReport: boolean;
+ hasTeammate: boolean;
+}
+
+/** Powers the activation checklist on the project overview (trpc project.activationStatus). */
+export async function getProjectActivationStatus(
+ projectId: string
+): Promise<ProjectActivationStatus> {
+ const db = await loadDb();
+ const project = await db.project.findUniqueOrThrow({
+ where: { id: projectId },
+ select: {
+ firstEventAt: true,
+ eventsCount: true,
+ organizationId: true,
+ createdAt: true,
+ },
+ });
+
+ const [reportCount, memberCount] = await Promise.all([
+ db.report.count({ where: { projectId } }),
+ db.member.count({ where: { organizationId: project.organizationId } }),
+ ]);
+
+ return {
+ // firstEventAt only exists for projects created after the column was
+ // added; the lifetime counter covers everything older.
+ hasFirstEvent: !!project.firstEventAt || project.eventsCount > 0,
+ firstEventAt: project.firstEventAt,
+ projectCreatedAt: project.createdAt,
+ hasReport: reportCount > 0,
+ hasTeammate: memberCount > 1,
+ };
+}
+
+export async function listProjectsCore(input: {
+ clientType: 'root' | 'read';
+ organizationId: string;
+ projectId: string | null;
+}) {
+ const db = await loadDb();
+ if (input.clientType === 'root') {
+ const projects = await db.project.findMany({
+ where: { organizationId: input.organizationId },
+ orderBy: { eventsCount: 'desc' },
+ select: {
+ id: true,
+ name: true,
+ organizationId: true,
+ eventsCount: true,
+ domain: true,
+ types: true,
+ },
+ });
+ return { clientType: 'root', projects };
+ }
+
+ const project = input.projectId
+ ? await db.project.findUnique({
+ where: { id: input.projectId },
+ select: {
+ id: true,
+ name: true,
+ organizationId: true,
+ eventsCount: true,
+ domain: true,
+ types: true,
+ },
+ })
+ : null;
+
+ return {
+ clientType: 'read',
+ projects: project ? [project] : [],
+ };
+}
+
+// --- /manage REST CRUD (apps/api/src/controllers/manage.controller.ts) ---
+
+export interface CreatedProjectClient {
+ id: string;
+ secret: string;
+}
+
+export async function listProjectsForOrganization(organizationId: string) {
+ const db = await loadDb();
+ return db.project.findMany({
+ where: {
+ organizationId,
+ deleteAt: null,
+ },
+ orderBy: {
+ createdAt: 'desc',
+ },
+ });
+}
+
+export async function getProjectForOrganization(
+ id: string,
+ organizationId: string
+) {
+ const db = await loadDb();
+ return db.project.findFirst({
+ where: {
+ id,
+ organizationId,
+ },
+ });
+}
+
+export async function createProjectForOrganization(
+ organizationId: string,
+ input: {
+ name: string;
+ domain?: string | null;
+ cors: string[];
+ crossDomain: boolean;
+ types: ProjectType[];
+ }
+): Promise<{ project: IServiceProject; client: CreatedProjectClient | null }> {
+ const db = await loadDb();
+ const getId = await loadIdService();
+
+ const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;
+ const project = await db.project.create({
+ data: {
+ id: await getId('project', input.name),
+ organizationId,
+ name: input.name,
+ domain: input.domain ? stripTrailingSlash(input.domain) : null,
+ cors: input.cors.map((c) => stripTrailingSlash(c)),
+ crossDomain: input.crossDomain ?? false,
+ allowUnsafeRevenueTracking: false,
+ filters: [],
+ types: input.types,
+ clients: {
+ create: {
+ organizationId,
+ name: 'First client',
+ type: 'write',
+ secret: await hashPassword(secret),
+ },
+ },
+ },
+ include: {
+ clients: {
+ select: {
+ id: true,
+ },
+ },
+ },
+ });
+
+ await Promise.all([
+ getProjectByIdCached.clear(project.id),
+ ...project.clients.map((client) => getClientByIdCached.clear(client.id)),
+ ]);
+
+ return {
+ project,
+ client: project.clients[0] ? { id: project.clients[0].id, secret } : null,
+ };
+}
+
+export async function updateProjectForOrganization(
+ id: string,
+ organizationId: string,
+ input: {
+ name?: string;
+ domain?: string | null;
+ cors?: string[];
+ crossDomain?: boolean;
+ allowUnsafeRevenueTracking?: boolean;
+ }
+): Promise<IServiceProject | null> {
+ const db = await loadDb();
+
+ const existing = await db.project.findFirst({
+ where: { id, organizationId },
+ include: { clients: { select: { id: true } } },
+ });
+
+ if (!existing) {
+ return null;
+ }
+
+ const updateData: Prisma.ProjectUpdateInput = {};
+ if (input.name !== undefined) {
+ updateData.name = input.name;
+ }
+ if (input.domain !== undefined) {
+ updateData.domain = input.domain ? stripTrailingSlash(input.domain) : null;
+ }
+ if (input.cors !== undefined) {
+ updateData.cors = input.cors.map((c) => stripTrailingSlash(c));
+ }
+ if (input.crossDomain !== undefined) {
+ updateData.crossDomain = input.crossDomain;
+ }
+ if (input.allowUnsafeRevenueTracking !== undefined) {
+ updateData.allowUnsafeRevenueTracking = input.allowUnsafeRevenueTracking;
+ }
+
+ const project = await db.project.update({
+ where: { id },
+ data: updateData,
+ });
+
+ await Promise.all([
+ getProjectByIdCached.clear(project.id),
+ ...existing.clients.map((client) => getClientByIdCached.clear(client.id)),
+ ]);
+
+ return project;
+}
+
+// Grace period between a scheduled deletion and the `delete` cron sweeping it
+// up — matches V1's `addHours(new Date(), 24)` (trpc) and the manage
+// controller's `Date.now() + 24 * 60 * 60 * 1000` (REST), same duration.
+const DELETE_GRACE_PERIOD_MS = 24 * 60 * 60 * 1000;
+
+export async function deleteProjectForOrganization(
+ id: string,
+ organizationId: string
+): Promise<boolean> {
+ const db = await loadDb();
+
+ const project = await db.project.findFirst({
+ where: { id, organizationId },
+ });
+
+ if (!project) {
+ return false;
+ }
+
+ await db.project.update({
+ where: { id },
+ data: {
+ deleteAt: new Date(Date.now() + DELETE_GRACE_PERIOD_MS),
+ },
+ });
+
+ await getProjectByIdCached.clear(id);
+
+ return true;
+}
+
+// --- trpc project.delete / project.cancelDeletion ---
+// Caller has already been proven a project (or organization) admin by
+// requireProjectAdmin, so unlike the /manage functions above these take no
+// organizationId and do no ownership re-check.
+
+export async function scheduleProjectDeletion(id: string): Promise<void> {
+ const db = await loadDb();
+ await db.project.update({
+ where: { id },
+ data: { deleteAt: new Date(Date.now() + DELETE_GRACE_PERIOD_MS) },
+ });
+}
+
+export async function cancelProjectDeletion(id: string): Promise<void> {
+ const db = await loadDb();
+
+ const project = await db.project.findUnique({
+ where: { id },
+ select: {
+ organization: {
+ select: { deleteAt: true },
+ },
+ },
+ });
+
+ // If the whole organization is scheduled for deletion, this project's
+ // deletion is part of it and can only be cancelled at the organization
+ // level. Cancelling it here would leave the organization unable to delete.
+ if (project?.organization?.deleteAt) {
+ throw new TRPCBadRequestError(
+ 'This organization is scheduled for deletion. Cancel the deletion from the organization settings.'
+ );
+ }
+
+ await db.project.update({
+ where: { id },
+ data: { deleteAt: null },
+ });
+}
diff --git a/packages/core/src/modules/project/src/access.ts b/packages/core/src/modules/project/src/access.ts
new file mode 100644
index 000000000..f2b341396
--- /dev/null
+++ b/packages/core/src/modules/project/src/access.ts
@@ -0,0 +1,30 @@
+// 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
+// organization/src/access.ts and gsc/src/access.ts. `getProjectById` is
+// this module's own (../project.service), not the @openpanel/db deep path
+// other modules bind through.
+
+import {
+ canWriteProject,
+ getOrganizationAccess,
+ getProjectAccess,
+} from '@openpanel/db/src/services/access.service';
+import { createAccessChecks } from '../../../shared/access';
+import { getProjectById } from '../project.service';
+
+export {
+ getOrganizationAccess,
+ getProjectAccess,
+} from '@openpanel/db/src/services/access.service';
+
+const checks = createAccessChecks({
+ getProjectAccess,
+ canWriteProject,
+ getOrganizationAccess,
+ getProjectById,
+});
+
+export const requireProjectAccess = checks.requireProjectAccess;
+export const requireProjectAdmin = checks.requireProjectAdmin;
diff --git a/packages/core/src/rest.routes.ts b/packages/core/src/rest.routes.ts
index 874fc00a8..b8052cee2 100644
--- a/packages/core/src/rest.routes.ts
+++ b/packages/core/src/rest.routes.ts
@@ -9,10 +9,12 @@ import { Elysia } from 'elysia';
import type { AppDeps } from './context';
import { registry } from './metrics';
import { assistantRoutes } from './modules/assistant/assistant.routes';
+import { clientRoutes } from './modules/client/client.routes';
import { gscRoutes } from './modules/gsc/gsc.routes';
import { healthRoutes } from './modules/health/health.routes';
import { importRoutes } from './modules/import/import.routes';
import { mcpRoutes } from './modules/mcp/mcp.routes';
+import { projectRoutes } from './modules/project/project.routes';
// ADR-002/ADR-003 pin: @elysiajs/openapi at the 1.4.15 fallback (2.0 is
// NO-GO per spike 6). `specPath` is set explicitly rather than taking the
@@ -28,12 +30,17 @@ const OPENAPI_EXCLUDED_PATHS = ['/metrics'];
// `defineRoutes`'s `RouteApp` is: `.use()`'d plugins widen Elysia's type
// parameters in a way the bare `Elysia` type cannot express.
//
-// import's /import/events is the first module to land here (M5-004). It is
-// not yet reachable: the clientAuth macro's authenticator is a P8 stub that
-// always returns null (import.routes.ts's header), and main.ts does not
-// mount `publicApiRoutes` until a real `AppDeps` exists (P3/P4/P8).
+// import's /import/events is the first module to land here (M5-004);
+// project's and client's /manage/* (M6-002) joined it — root-client-authed
+// API surface, same as /import, not session-authed like dashboardRoutes.
+// None of it is yet reachable: the clientAuth macro's authenticator is a P8
+// stub that always returns null (import.routes.ts's header), and main.ts
+// does not mount `publicApiRoutes` until a real `AppDeps` exists (P3/P4/P8).
export const publicApiRoutes = (deps: AppDeps) =>
- new Elysia({ name: 'core/public-api-routes' }).use(importRoutes(deps));
+ new Elysia({ name: 'core/public-api-routes' })
+ .use(importRoutes(deps))
+ .use(projectRoutes(deps))
+ .use(clientRoutes(deps));
// gsc's callback was the first module to land here (M5-002); assistant's
// `/ai/agents/*` (M5-005) and mcp's `/mcp` (M5-007) joined it. None is
diff --git a/packages/core/src/rpc.router.ts b/packages/core/src/rpc.router.ts
index fe43acd68..54f582b63 100644
--- a/packages/core/src/rpc.router.ts
+++ b/packages/core/src/rpc.router.ts
@@ -5,6 +5,7 @@
// land with their module waves (P5-P8).
import { chatRouter } from './modules/assistant/assistant.rpc';
+import { clientRouter } from './modules/client/client.rpc';
import { cohortRouter } from './modules/cohort/cohort.rpc';
import { conversationRouter } from './modules/conversation/conversation.rpc';
import { gscRouter } from './modules/gsc/gsc.rpc';
@@ -12,6 +13,7 @@ import { healthRouter } from './modules/health/health.rpc';
import { importRouter } from './modules/import/import.rpc';
import { insightRouter } from './modules/insight/insight.rpc';
import { organizationRouter } from './modules/organization/organization.rpc';
+import { projectRouter } from './modules/project/project.rpc';
import { userRouter } from './modules/user/user.rpc';
import { createTRPCRouter } from './rpc/base';
@@ -25,6 +27,8 @@ export const appRouter = createTRPCRouter({
conversation: conversationRouter,
organization: organizationRouter,
user: userRouter,
+ project: projectRouter,
+ client: clientRouter,
});
export type AppRouter = typeof appRouter;
diff --git a/packages/db/src/services/clients.service.ts b/packages/db/src/services/clients.service.ts
index 6566d219f..074f9fb48 100644
--- a/packages/db/src/services/clients.service.ts
+++ b/packages/db/src/services/clients.service.ts
@@ -1,37 +1,13 @@
-import { cacheable } from '@openpanel/redis';
-import type { Client, Prisma } from '../prisma-client';
-import { db } from '../prisma-client';
-
-export type IServiceClient = Client;
-export type IServiceClientWithProject = Prisma.ClientGetPayload<{
- include: {
- project: true;
- };
-}>;
-
-export async function getClientsByOrganizationId(organizationId: string) {
- return db.client.findMany({
- where: {
- organizationId,
- },
- include: {
- project: true,
- },
- orderBy: {
- createdAt: 'asc',
- },
- });
-}
-
-export async function getClientById(
- id: string,
-): Promise<IServiceClientWithProject | null> {
- return db.client.findUnique({
- where: { id },
- include: {
- project: true,
- },
- });
-}
-
-export const getClientByIdCached = cacheable(getClientById, 60 * 5);
+// The client service lives in @openpanel/core now (M6-002). Re-exported
+// here for existing `@openpanel/db` importers (apps/api/src/utils/auth.ts,
+// core's mcp module) — same shape as
+// packages/db/src/services/organization.service.ts since M6-001.
+export type {
+ IServiceClient,
+ IServiceClientWithProject,
+} from '@openpanel/core';
+export {
+ getClientById,
+ getClientByIdCached,
+ getClientsByOrganizationId,
+} from '@openpanel/core';
diff --git a/packages/db/src/services/project.service.ts b/packages/db/src/services/project.service.ts
index 66b8ad211..e2573a681 100644
--- a/packages/db/src/services/project.service.ts
+++ b/packages/db/src/services/project.service.ts
@@ -1,240 +1,19 @@
-import { cacheable } from '@openpanel/redis';
-import sqlstring from 'sqlstring';
-import {
- ch,
- chQuery,
- convertClickhouseDateToJs,
- TABLE_NAMES,
-} from '../clickhouse/client';
-import { clix } from '../clickhouse/query-builder';
-import { db, type Prisma, type Project } from '../prisma-client';
-
-export type IServiceProject = Project;
-export type IServiceProjectWithClients = Prisma.ProjectGetPayload<{
- include: {
- clients: true;
- };
-}>;
-
-export async function getProjectById(id: string) {
- const res = await db.project.findUnique({
- where: {
- id,
- },
- });
-
- if (!res) {
- return null;
- }
-
- return res;
-}
-
-/** L1 LRU (60s) + L2 Redis. clear() invalidates Redis + local LRU; other nodes may serve stale from LRU for up to 60s. */
-export const getProjectByIdCached = cacheable(getProjectById, 60 * 60 * 24);
-
-export async function getProjectWithClients(id: string) {
- const res = await db.project.findUnique({
- where: {
- id,
- },
- include: {
- clients: true,
- },
- });
-
- if (!res) {
- return null;
- }
-
- return res;
-}
-
-export async function getProjects({
- organizationId,
- userId,
-}: {
- organizationId: string;
- userId: string | null;
-}) {
- if (!userId) {
- return [];
- }
-
- const [projects, members, access] = await Promise.all([
- db.project.findMany({
- where: {
- organizationId,
- },
- orderBy: {
- eventsCount: 'desc',
- },
- }),
- db.member.findMany({
- where: {
- userId,
- organizationId,
- },
- }),
- db.projectAccess.findMany({
- where: {
- userId,
- organizationId,
- },
- }),
- ]);
-
- if (members.length === 0) {
- return [];
- }
-
- if (access.length > 0) {
- return projects.filter((project) =>
- access.some((a) => a.projectId === project.id)
- );
- }
-
- return projects;
-}
-
-/**
- * Fast approximate count of a project's events (excluding session_start /
- * session_end), read from distinct_event_names_mv instead of the raw events
- * table.
- *
- * Why not count raw events: `name NOT IN (...)` is a negation, so it can't
- * prune with idx_name and scans the project's whole events slice — and this
- * runs from the sessions job on every batch. The MV already accumulates
- * `count() AS event_count` per (project_id, name) insert block, so summing
- * it reads a few thousand pre-aggregated rows instead of billions of raw
- * ones.
- *
- * Why approximate: event_count is a plain UInt64, not an aggregate state,
- * so MV counter rows whose (project_id, name, created_at) sort key collides
- * collapse on merge keeping only one block's count. Live ingestion rarely
- * ties on the ms timestamp; bulk imports with coarse timestamps are where
- * collisions come from. The error is strictly downward (measured 0.0011%
- * low on a 1.46B-event project) — acceptable for this display/onboarding
- * counter.
- */
-export const getProjectEventsCount = async (projectId: string) => {
- const res = await chQuery<{ count: number }>(
- `SELECT sum(event_count) as count FROM ${TABLE_NAMES.event_names_mv} WHERE project_id = ${sqlstring.escape(projectId)} AND name NOT IN ('session_start', 'session_end')`
- );
- return res[0]?.count;
-};
-
-/**
- * Newest event timestamp per project, for the whole instance in one query.
- * Reads the same pre-aggregated MV as getProjectEventsCount (it stores
- * max(created_at) per (project_id, name) block), so this scans thousands of
- * rows instead of the raw events table. Projects with no events are absent
- * from the map.
- */
-export const getLastEventPerProject = async (): Promise<Map<string, Date>> => {
- const res = await clix(ch)
- .select<{ project_id: string; last_event_at: string }>([
- 'project_id',
- 'max(created_at) AS last_event_at',
- ])
- .from(TABLE_NAMES.event_names_mv)
- // Session rows are worker-generated (the reaper can emit session_end after
- // tracking already stopped) — only real tracking activity should count.
- .where('name', 'NOT IN', ['session_start', 'session_end'])
- .groupBy(['project_id'])
- .execute();
- return new Map(
- res.map((row) => [
- row.project_id,
- convertClickhouseDateToJs(row.last_event_at),
- ])
- );
-};
-
-/**
- * Resolve and validate a projectId for an API client.
- *
- * - Read clients: returns the fixed projectId from the client (ignores any supplied value).
- * - Root clients: validates that the supplied projectId belongs to the client's organization.
- *
- * Throws if the project is not found or does not belong to the organization.
- * Use this as the single source of truth for projectId resolution across the API and MCP.
- */
-export async function resolveClientProjectId({
- clientType,
- clientProjectId,
- organizationId,
- inputProjectId,
-}: {
- clientType: 'read' | 'root';
- clientProjectId: string | null;
- organizationId: string;
- inputProjectId: string | undefined;
-}): Promise<string> {
- if (clientType !== 'root') {
- if (!clientProjectId) {
- throw new Error('Client is not associated with a project');
- }
- return clientProjectId;
- }
-
- if (!inputProjectId) {
- throw new Error(
- 'projectId is required when using a root (organization-level) client'
- );
- }
-
- const project = await db.project.findFirst({
- where: { id: inputProjectId, organizationId },
- select: { id: true },
- });
-
- if (!project) {
- throw new Error(
- 'Project not found or does not belong to your organization'
- );
- }
-
- return inputProjectId;
-}
-
-export async function listProjectsCore(input: {
- clientType: 'root' | 'read';
- organizationId: string;
- projectId: string | null;
-}) {
- if (input.clientType === 'root') {
- const projects = await db.project.findMany({
- where: { organizationId: input.organizationId },
- orderBy: { eventsCount: 'desc' },
- select: {
- id: true,
- name: true,
- organizationId: true,
- eventsCount: true,
- domain: true,
- types: true,
- },
- });
- return { clientType: 'root', projects };
- }
-
- const project = input.projectId
- ? await db.project.findUnique({
- where: { id: input.projectId },
- select: {
- id: true,
- name: true,
- organizationId: true,
- eventsCount: true,
- domain: true,
- types: true,
- },
- })
- : null;
-
- return {
- clientType: 'read',
- projects: project ? [project] : [],
- };
-}
+// The project service lives in @openpanel/core now (M6-002). Re-exported
+// here for existing `@openpanel/db` importers (this package's own
+// access.service.ts + notification.service.ts, several core modules'
+// `src/access.ts`, apps/api/src/utils/auth.ts) — same shape as
+// packages/db/src/services/organization.service.ts since M6-001.
+export type {
+ IServiceProject,
+ IServiceProjectWithClients,
+} from '@openpanel/core';
+export {
+ getLastEventPerProject,
+ getProjectById,
+ getProjectByIdCached,
+ getProjectEventsCount,
+ getProjects,
+ getProjectWithClients,
+ listProjectsCore,
+ resolveClientProjectId,
+} from '@openpanel/core';
diff --git a/packages/trpc/src/routers/client.ts b/packages/trpc/src/routers/client.ts
index 05015cb6c..ed7312410 100644
--- a/packages/trpc/src/routers/client.ts
+++ b/packages/trpc/src/routers/client.ts
@@ -1,7 +1,16 @@
-import crypto from 'node:crypto';
-import { hashPassword } from '@openpanel/core';
-import type { Prisma } from '@openpanel/db';
-import { db } from '@openpanel/db';
+// Dissolved into @openpanel/core's client module (M6-002): the CRUD and
+// mutation bodies moved to
+// packages/core/src/modules/client/client.service.ts. This router stays
+// (DELEGATE PATTERN) — it keeps V1's protectedProcedure stack (session/
+// access/logger/rate-limit middleware) and delegates every handler body to
+// core's client functions, same as organization's router does (M6-001).
+import {
+ createClientForOrganization,
+ deleteClientForOrganization,
+ getClientById,
+ getClientsByProjectId,
+ updateClientForOrganization,
+} from '@openpanel/core';
import { z } from 'zod';
import { getClientAccess, requireOrganizationAdmin } from '../access';
import { TRPCForbiddenError } from '../errors';
@@ -15,11 +24,7 @@ export const clientRouter = createTRPCRouter({
})
)
.query(async ({ input }) => {
- return db.client.findMany({
- where: {
- projectId: input.projectId,
- },
- });
+ return getClientsByProjectId(input.projectId);
}),
update: protectedProcedure
.input(
@@ -38,13 +43,13 @@ export const clientRouter = createTRPCRouter({
throw new TRPCForbiddenError('You do not have access to this client');
}
- return db.client.update({
- where: {
- id: input.id,
- },
- data: {
- name: input.name,
- },
+ const client = await getClientById(input.id);
+ if (!client) {
+ throw new TRPCForbiddenError('Client not found');
+ }
+
+ return updateClientForOrganization(input.id, client.organizationId, {
+ name: input.name,
});
}),
create: protectedProcedure
@@ -65,21 +70,19 @@ export const clientRouter = createTRPCRouter({
message: 'Only organization admins can create API clients',
});
- const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;
- const data: Prisma.ClientCreateArgs['data'] = {
- organizationId: input.organizationId,
- projectId: input.projectId,
+ const created = await createClientForOrganization(input.organizationId, {
name: input.name,
- type: input.type ?? 'write',
- secret: await hashPassword(secret),
- };
+ projectId: input.projectId,
+ type: input.type,
+ });
- const client = await db.client.create({ data });
+ if (!created) {
+ throw new TRPCForbiddenError(
+ 'Project not found or does not belong to your organization'
+ );
+ }
- return {
- ...client,
- secret,
- };
+ return { ...created.client, secret: created.secret };
}),
remove: protectedProcedure
.input(
@@ -88,10 +91,7 @@ export const clientRouter = createTRPCRouter({
})
)
.mutation(async ({ input, ctx }) => {
- const client = await db.client.findUnique({
- where: { id: input.id },
- select: { organizationId: true },
- });
+ const client = await getClientById(input.id);
if (!client?.organizationId) {
throw new TRPCForbiddenError('You do not have access to this client');
@@ -104,11 +104,7 @@ export const clientRouter = createTRPCRouter({
message: 'Only organization admins can delete API clients',
});
- await db.client.delete({
- where: {
- id: input.id,
- },
- });
+ await deleteClientForOrganization(input.id, client.organizationId);
return true;
}),
});
diff --git a/packages/trpc/src/routers/project.ts b/packages/trpc/src/routers/project.ts
index 0fcead2e6..ec9c8ec0d 100644
--- a/packages/trpc/src/routers/project.ts
+++ b/packages/trpc/src/routers/project.ts
@@ -1,20 +1,23 @@
-import crypto from 'node:crypto';
-import { stripTrailingSlash } from '@openpanel/common';
-import { hashPassword } from '@openpanel/core';
+// Dissolved into @openpanel/core's project module (M6-002): the CRUD and
+// mutation bodies moved to
+// packages/core/src/modules/project/project.service.ts. This router stays
+// (DELEGATE PATTERN) — it keeps V1's protectedProcedure stack (session/
+// access/logger/rate-limit middleware) and delegates every handler body to
+// core's project functions, same as organization's router does (M6-001).
import {
- db,
- getClientByIdCached,
- getId,
- getOrganizationAccess,
- getProjectByIdCached,
+ cancelProjectDeletion,
+ createProjectForOrganization,
+ getProjectActivationStatus,
+ getProjectById,
getProjects,
getProjectWithClients,
- type Prisma,
-} from '@openpanel/db';
+ scheduleProjectDeletion,
+ updateProjectForOrganization,
+} from '@openpanel/core';
import { zOnboardingProject, zProjectUpdate } from '@openpanel/validation';
-import { addHours } from 'date-fns';
import { z } from 'zod';
import {
+ getOrganizationAccess,
getProjectAccess,
requireProjectAccess,
requireProjectAdmin,
@@ -60,32 +63,7 @@ export const projectRouter = createTRPCRouter({
throw new TRPCForbiddenError('You do not have access to this project');
}
- const project = await db.project.findUniqueOrThrow({
- where: { id: projectId },
- select: {
- firstEventAt: true,
- eventsCount: true,
- organizationId: true,
- createdAt: true,
- },
- });
-
- const [reportCount, memberCount] = await Promise.all([
- db.report.count({ where: { projectId } }),
- db.member.count({
- where: { organizationId: project.organizationId },
- }),
- ]);
-
- return {
- // firstEventAt only exists for projects created after the column was
- // added; the lifetime counter covers everything older.
- hasFirstEvent: !!project.firstEventAt || project.eventsCount > 0,
- firstEventAt: project.firstEventAt,
- projectCreatedAt: project.createdAt,
- hasReport: reportCount > 0,
- hasTeammate: memberCount > 1,
- };
+ return getProjectActivationStatus(projectId);
}),
list: protectedProcedure
@@ -113,40 +91,18 @@ export const projectRouter = createTRPCRouter({
level: 'write',
});
- const res = await db.project.update({
- where: {
- id: input.id,
- },
- data: {
- name: input.name,
- crossDomain: input.crossDomain,
- allowUnsafeRevenueTracking: input.allowUnsafeRevenueTracking,
- filters:
- input.filters === undefined ? undefined : input.filters || [],
- domain:
- input.domain === undefined
- ? undefined
- : input.domain
- ? stripTrailingSlash(input.domain)
- : null,
- cors:
- input.cors === undefined
- ? undefined
- : input.cors.map((c) => stripTrailingSlash(c)) || [],
- },
- include: {
- clients: {
- select: {
- id: true,
- },
- },
- },
+ const project = await getProjectById(input.id);
+ if (!project) {
+ throw new TRPCForbiddenError('Project not found');
+ }
+
+ return updateProjectForOrganization(input.id, project.organizationId, {
+ name: input.name,
+ domain: input.domain,
+ cors: input.cors,
+ crossDomain: input.crossDomain,
+ allowUnsafeRevenueTracking: input.allowUnsafeRevenueTracking,
});
- await Promise.all([
- getProjectByIdCached.clear(input.id),
- ...res.clients.map((client) => getClientByIdCached.clear(client.id)),
- ]);
- return res;
}),
create: protectedProcedure
.input(zOnboardingProject)
@@ -166,45 +122,18 @@ export const projectRouter = createTRPCRouter({
);
}
- const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;
- const data: Prisma.ClientCreateArgs['data'] = {
- organizationId: input.organizationId,
- name: 'First client',
- type: 'write',
- secret: await hashPassword(secret),
- };
- const project = await db.project.create({
- data: {
- id: await getId('project', input.project),
- organizationId: input.organizationId,
+ const { project, client } = await createProjectForOrganization(
+ input.organizationId,
+ {
name: input.project,
domain: input.domain,
cors: input.cors,
crossDomain: false,
- allowUnsafeRevenueTracking: false,
- filters: [],
- clients: {
- create: data,
- },
- },
- include: {
- clients: {
- select: {
- id: true,
- },
- },
- },
- });
+ types: [],
+ }
+ );
- return {
- ...project,
- client: project.clients[0]
- ? {
- id: project.clients[0].id,
- secret,
- }
- : null,
- };
+ return { ...project, client };
}),
delete: protectedProcedure
.input(
@@ -220,14 +149,7 @@ export const projectRouter = createTRPCRouter({
message: 'Only organization admins can delete projects',
});
- await db.project.update({
- where: {
- id: input.projectId,
- },
- data: {
- deleteAt: addHours(new Date(), 24),
- },
- });
+ await scheduleProjectDeletion(input.projectId);
return true;
}),
@@ -244,36 +166,7 @@ export const projectRouter = createTRPCRouter({
message: 'Only organization admins can cancel a project deletion',
});
- const project = await db.project.findUnique({
- where: {
- id: input.projectId,
- },
- select: {
- organization: {
- select: {
- deleteAt: true,
- },
- },
- },
- });
-
- // If the whole organization is scheduled for deletion, this project's
- // deletion is part of it and can only be cancelled at the organization
- // level. Cancelling it here would leave the organization unable to delete.
- if (project?.organization?.deleteAt) {
- throw new TRPCBadRequestError(
- 'This organization is scheduled for deletion. Cancel the deletion from the organization settings.'
- );
- }
-
- await db.project.update({
- where: {
- id: input.projectId,
- },
- data: {
- deleteAt: null,
- },
- });
+ await cancelProjectDeletion(input.projectId);
return true;
}),
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 35aaabe01..5d7d1d830 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1059,6 +1059,10 @@ importers:
version: 5.9.3
packages/constants:
+ dependencies:
+ '@openpanel/core':
+ specifier: workspace:*
+ version: link:../core
devDependencies:
'@openpanel/tsconfig':
specifier: workspace:*