OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M6-003): auth trpc router + onboarding module into core
ralph041f4b73620c
diff --git a/apps/api/src/controllers/oauth-callback.controller.tsx b/apps/api/src/controllers/oauth-callback.controller.tsxindex 94e971655..5317060df 100644--- a/apps/api/src/controllers/oauth-callback.controller.tsx+++ b/apps/api/src/controllers/oauth-callback.controller.tsx@@ -1,283 +1,30 @@+// Dissolved into @openpanel/core's auth module (M6-003): the github/google+// token exchange, state validation, and account find-or-create/session-issue+// logic moved to packages/core/src/modules/auth/auth.service.ts. This+// controller stays (DELEGATE PATTERN) — it keeps Fastify's cookie reads and+// the redirect shape, and delegates everything else, same as+// gsc-oauth-callback.controller.ts (M5-002).import {- Arctic,- generateSessionToken,- github,- google,- type OAuth2Tokens,- setLastAuthProviderCookie,- setSessionTokenCookie,+ assertOAuthState,+ completeOAuthCallback,+ fetchGithubOAuthUser,+ fetchGoogleOAuthUser,+ OAuthCallbackError,} from '@openpanel/core';-import {- type Account,- connectUserToOrganization,- createSession,- db,- getIsRegistrationAllowed,-} from '@openpanel/db';import type { FastifyReply, FastifyRequest } from 'fastify';import { z } from 'zod';import { LogError } from '@/utils/errors';-async function getGithubEmail(githubAccessToken: string) {- const emailListRequest = new Request('https://api.github.com/user/emails');- emailListRequest.headers.set('Authorization', `Bearer ${githubAccessToken}`);- const emailListResponse = await fetch(emailListRequest);- const emailListResult: unknown = await emailListResponse.json();- if (!Array.isArray(emailListResult) || emailListResult.length < 1) {- return null;- }- let email: string | null = null;- for (const emailRecord of emailListResult) {- const emailParser = z.object({- primary: z.boolean(),- verified: z.boolean(),- email: z.string(),- });- const emailResult = emailParser.safeParse(emailRecord);- if (!emailResult.success) {- continue;- }- if (emailResult.data.primary && emailResult.data.verified) {- email = emailResult.data.email;- }- }- return email;-}--// New types and interfaces-type Provider = 'github' | 'google';-interface OAuthUser {- id: string;- email: string;- firstName: string;- lastName?: string;-}--// Shared utility functions-async function handleExistingUser({- account,- oauthUser,- providerName,- inviteId,- reply,-}: {- account: Account;- oauthUser: OAuthUser;- providerName: Provider;- inviteId: string | undefined | null;- reply: FastifyReply;-}) {- const sessionToken = generateSessionToken();- const session = await createSession(sessionToken, account.userId);-- await db.account.update({- where: { id: account.id },- data: {- provider: providerName,- providerId: oauthUser.id,- email: oauthUser.email,- },- });+const callbackQuery = z.object({+ code: z.string(),+ state: z.string(),+});- if (inviteId) {- try {- const user = await db.user.findUniqueOrThrow({- where: { id: account.userId },- });- await connectUserToOrganization({ user, inviteId });- } catch (error) {- reply.log.error(- {- error,- inviteId,- userId: account.userId,- },- 'error connecting existing user to organization'- );- }- }-- setSessionTokenCookie(- (...args) => reply.setCookie(...args),- sessionToken,- session.expiresAt- );- setLastAuthProviderCookie(- (...args) => reply.setCookie(...args),- providerName- );- return reply.redirect(- process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL!- );-}--async function handleNewUser({- oauthUser,- providerName,- inviteId,- reply,-}: {- oauthUser: OAuthUser;- providerName: Provider;- inviteId: string | undefined | null;- reply: FastifyReply;-}) {- const existingUser = await db.user.findFirst({- where: { email: oauthUser.email },- });-- if (existingUser) {- throw new LogError(- 'Please sign in using your original authentication method',- {- existingUser,- oauthUser,- providerName,- }- );- }-- // Enforce the self-hosting registration policy here rather than before the- // IdP redirect — this is the first point where we know the user is new, so- // returning users are never caught by it.- if (!(await getIsRegistrationAllowed(inviteId))) {- // Deliberately no `oauthUser` here — this rejects people who are not users,- // so their email and name shouldn't land in application logs. The redirect- // carries `correlationId` (the request id), which is what ties a user's- // error page back to this log line if an operator needs to investigate.- throw new LogError('Registrations are not allowed', {- providerName,- inviteId,- });- }-- const user = await db.user.create({- data: {- email: oauthUser.email,- firstName: oauthUser.firstName,- lastName: oauthUser.lastName,- accounts: {- create: {- provider: providerName,- providerId: oauthUser.id,- },- },- },- });-- if (inviteId) {- try {- await connectUserToOrganization({ user, inviteId });- } catch (error) {- reply.log.error(- {- error,- inviteId,- user,- },- 'error connecting user to organization'- );- }- }-- const sessionToken = generateSessionToken();- const session = await createSession(sessionToken, user.id);- setSessionTokenCookie(- (...args) => reply.setCookie(...args),- sessionToken,- session.expiresAt- );- setLastAuthProviderCookie(- (...args) => reply.setCookie(...args),- providerName- );- return reply.redirect(- process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL!- );-}--// Provider-specific user fetching-async function fetchGithubUser(accessToken: string): Promise<OAuthUser> {- const email = await getGithubEmail(accessToken);- if (!email) {- throw new LogError('GitHub email not found or not verified');- }-- const userRequest = new Request('https://api.github.com/user');- userRequest.headers.set('Authorization', `Bearer ${accessToken}`);- const userResponse = await fetch(userRequest);-- const userSchema = z.object({- id: z.number(),- login: z.string(),- name: z- .string()- .nullish()- .transform((val) => val || ''),- });- const userJson = await userResponse.json();-- const userResult = userSchema.safeParse(userJson);- if (!userResult.success) {- throw new LogError('Error fetching Github user', {- error: userResult.error,- githubUser: userJson,- });- }-- return {- id: String(userResult.data.id),- email,- firstName: userResult.data.name || userResult.data.login || '',- };-}--async function fetchGoogleUser(tokens: OAuth2Tokens): Promise<OAuthUser> {- const claims = Arctic.decodeIdToken(tokens.idToken());-- const claimsSchema = z.object({- sub: z.string(),- email: z.string(),- email_verified: z.boolean(),- given_name: z.string().optional(),- family_name: z.string().optional(),- });-- const claimsResult = claimsSchema.safeParse(claims);- if (!claimsResult.success) {- throw new LogError('Error fetching Google user', {- error: claimsResult.error,- claims,- });- }-- if (!claimsResult.data.email_verified) {- throw new LogError('Email not verified with Google');- }-- return {- id: claimsResult.data.sub,- email: claimsResult.data.email,- firstName: claimsResult.data.given_name || '',- lastName: claimsResult.data.family_name || '',- };-}--interface ValidatedOAuthQuery {- code: string;- state: string;-}--async function validateOAuthCallback(+function parseCallbackQuery(req: FastifyRequest,- provider: Provider-): Promise<ValidatedOAuthQuery> {- const schema = z.object({- code: z.string(),- state: z.string(),- });-- const query = schema.safeParse(req.query);+ provider: 'github' | 'google'+) {+ const query = callbackQuery.safeParse(req.query);if (!query.success) {throw new LogError('Invalid callback query params', {error: query.error,@@ -285,131 +32,79 @@ async function validateOAuthCallback(provider,});}-- const { code, state } = query.data;- const storedState = req.cookies[`${provider}_oauth_state`] ?? null;- const codeVerifier =- provider === 'google' ? (req.cookies.google_code_verifier ?? null) : null;-- if (- code === null ||- state === null ||- storedState === null ||- (provider === 'google' && codeVerifier === null)- ) {- throw new LogError('Missing oauth parameters', {- code: code === null,- state: state === null,- storedState: storedState === null,- codeVerifier: provider === 'google' ? codeVerifier === null : undefined,- provider,- });- }-- if (state !== storedState) {- throw new LogError('OAuth state mismatch', {- state,- storedState,- provider,- });- }-- return { code, state };+ return query.data;}-// Main callback handlersexport async function githubCallback(req: FastifyRequest, reply: FastifyReply) {try {- const { code } = await validateOAuthCallback(req, 'github');+ const { code, state } = parseCallbackQuery(req, 'github');+ const storedState = req.cookies.github_oauth_state ?? null;const inviteId = req.cookies.inviteId;- const tokens = await github.validateAuthorizationCode(code);- const githubUser = await fetchGithubUser(tokens.accessToken());- const account = await db.account.findFirst({- where: {- OR: [- // To keep- { provider: 'github', providerId: githubUser.id },- // During migration- { provider: 'github', providerId: null, email: githubUser.email },- { provider: 'oauth', user: { email: githubUser.email } },- ],- },- });- reply.clearCookie('github_oauth_state');+ assertOAuthState('github', state, storedState);+ const oauthUser = await fetchGithubOAuthUser(code);- if (account) {- return await handleExistingUser({- account,- oauthUser: githubUser,- providerName: 'github',- inviteId,- reply,- });- }-- return await handleNewUser({- oauthUser: githubUser,- providerName: 'github',+ await completeOAuthCallback({+ provider: 'github',+ oauthUser,inviteId,- reply,+ setCookie: (...args) => reply.setCookie(...args),+ logger: req.log,});++ reply.clearCookie('github_oauth_state');+ return reply.redirect(+ process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL!+ );} catch (error) {req.log.error(error);+ reply.clearCookie('github_oauth_state');return redirectWithError(reply, error);}}export async function googleCallback(req: FastifyRequest, reply: FastifyReply) {try {- const { code } = await validateOAuthCallback(req, 'google');+ const { code, state } = parseCallbackQuery(req, 'google');+ const storedState = req.cookies.google_oauth_state ?? null;+ const codeVerifier = req.cookies.google_code_verifier ?? null;const inviteId = req.cookies.inviteId;- const codeVerifier = req.cookies.google_code_verifier!;- const tokens = await google.validateAuthorizationCode(code, codeVerifier);- const googleUser = await fetchGoogleUser(tokens);- const existingUser = await db.account.findFirst({- where: {- OR: [- // To keep- { provider: 'google', providerId: googleUser.id },- // During migration- { provider: 'google', providerId: null, email: googleUser.email },- { provider: 'oauth', user: { email: googleUser.email } },- ],- },- });-- reply.clearCookie('google_code_verifier');- reply.clearCookie('google_oauth_state');- if (existingUser) {- return await handleExistingUser({- account: existingUser,- oauthUser: googleUser,- providerName: 'google',- inviteId,- reply,+ assertOAuthState('google', state, storedState);+ if (!codeVerifier) {+ throw new OAuthCallbackError('Missing oauth parameters', {+ codeVerifier: false,});}+ const oauthUser = await fetchGoogleOAuthUser(code, codeVerifier);- return await handleNewUser({- oauthUser: googleUser,- providerName: 'google',+ await completeOAuthCallback({+ provider: 'google',+ oauthUser,inviteId,- reply,+ setCookie: (...args) => reply.setCookie(...args),+ logger: req.log,});++ reply.clearCookie('google_code_verifier');+ reply.clearCookie('google_oauth_state');+ return reply.redirect(+ process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL!+ );} catch (error) {req.log.error(error);+ reply.clearCookie('google_code_verifier');+ reply.clearCookie('google_oauth_state');return redirectWithError(reply, error);}}-function redirectWithError(reply: FastifyReply, error: LogError | unknown) {+function redirectWithError(reply: FastifyReply, error: unknown) {const url = new URL(process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL!);url.pathname = '/login';- if (error instanceof LogError) {+ if (error instanceof LogError || error instanceof OAuthCallbackError) {url.searchParams.set('error', error.message);} else {url.searchParams.set('error', 'An error occurred');diff --git a/apps/worker/src/jobs/cron.onboarding.test.ts b/apps/worker/src/jobs/cron.onboarding.test.tsdeleted file mode 100644index 8bf20f552..000000000--- a/apps/worker/src/jobs/cron.onboarding.test.ts+++ /dev/null@@ -1,199 +0,0 @@-// Onboarding email cron: the sequential drip driven by the `org.onboarding`-// pointer. db and email are mocked; we assert template selection, day gating,-// early completion on active subs, and usage personalization.--import { subDays } from 'date-fns';-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { onboardingJob } from './cron.onboarding';--const { dbMock, getOrganizationEventsCountMock, sendEmailMock } = vi.hoisted(- () => ({- dbMock: {- organization: {- findMany: vi.fn(),- update: vi.fn().mockResolvedValue({}),- },- },- getOrganizationEventsCountMock: vi.fn(),- sendEmailMock: vi.fn().mockResolvedValue({}),- }),-);--vi.mock('@openpanel/db', () => ({- db: dbMock,- getOrganizationEventsCount: getOrganizationEventsCountMock,-}));--vi.mock('@openpanel/email', () => ({- sendEmail: sendEmailMock,-}));--const org = (overrides: Record<string, unknown> = {}) => ({- id: 'org-1',- name: 'Acme',- createdAt: new Date(),- onboarding: null,- subscriptionStatus: 'trialing',- subscriptionEndsAt: new Date('2026-06-16T12:00:00Z'),- createdBy: {- id: 'user-1',- email: '[email protected]',- firstName: 'Alex',- deletedAt: null,- },- projects: [{ id: 'proj-1' }],- ...overrides,-});--const job = {} as Parameters<typeof onboardingJob>[0];--beforeEach(() => {- vi.clearAllMocks();- vi.stubEnv('SELF_HOSTED', 'false');- dbMock.organization.update.mockResolvedValue({});- sendEmailMock.mockResolvedValue({});- getOrganizationEventsCountMock.mockResolvedValue(0);-});--describe('onboardingJob', () => {- it('sends the welcome email on day 0 with hasData from clickhouse', async () => {- getOrganizationEventsCountMock.mockResolvedValue(123);- dbMock.organization.findMany.mockResolvedValue([org()]);-- const result = await onboardingJob(job);-- expect(result).toMatchObject({ emailsSent: 1 });- expect(sendEmailMock).toHaveBeenCalledWith('onboarding-welcome', {- to: '[email protected]',- data: expect.objectContaining({- firstName: 'Alex',- hasData: true,- }),- });- expect(getOrganizationEventsCountMock).toHaveBeenCalledWith(['proj-1']);- expect(dbMock.organization.update).toHaveBeenCalledWith({- where: { id: 'org-1' },- data: { onboarding: 'onboarding-welcome' },- });- });-- it('does not fetch usage for orgs that are gated on days', async () => {- dbMock.organization.findMany.mockResolvedValue([- org({- onboarding: 'onboarding-welcome',- createdAt: subDays(new Date(), 1), // next email is day 2- }),- ]);-- const result = await onboardingJob(job);-- expect(result).toMatchObject({ emailsSent: 0, orgsSkipped: 1 });- expect(sendEmailMock).not.toHaveBeenCalled();- expect(getOrganizationEventsCountMock).not.toHaveBeenCalled();- });-- it('sends the no-data branch of what-to-track on day 2', async () => {- getOrganizationEventsCountMock.mockResolvedValue(0);- dbMock.organization.findMany.mockResolvedValue([- org({- onboarding: 'onboarding-welcome',- createdAt: subDays(new Date(), 2),- }),- ]);-- await onboardingJob(job);-- expect(sendEmailMock).toHaveBeenCalledWith('onboarding-what-to-track', {- to: '[email protected]',- data: expect.objectContaining({ hasData: false, eventsCount: 0 }),- });- });-- it('completes onboarding when the org subscribed before the trial emails', async () => {- dbMock.organization.findMany.mockResolvedValue([- org({- onboarding: 'onboarding-feature-request',- createdAt: subDays(new Date(), 27),- subscriptionStatus: 'active',- }),- ]);-- const result = await onboardingJob(job);-- expect(result).toMatchObject({ emailsSent: 0, orgsCompleted: 1 });- expect(sendEmailMock).not.toHaveBeenCalled();- expect(dbMock.organization.update).toHaveBeenCalledWith({- where: { id: 'org-1' },- data: { onboarding: 'completed' },- });- });-- it('populates recommendedPlan and trial stats in the trial-ending email', async () => {- // Regression: recommendedPlan used to read subscriptionPeriodEventsCount,- // which is always 0 for trial orgs (no Polar billing period).- getOrganizationEventsCountMock.mockResolvedValue(84_211);- dbMock.organization.findMany.mockResolvedValue([- org({- onboarding: 'onboarding-feature-request',- createdAt: subDays(new Date(), 27),- }),- ]);-- await onboardingJob(job);-- expect(sendEmailMock).toHaveBeenCalledWith('onboarding-trial-ending', {- to: '[email protected]',- data: expect.objectContaining({- hasData: true,- eventsCount: 84_211,- trialEndDate: 'June 16',- // Compact-number casing (100K vs 100k) is ICU-version dependent and- // differs between macOS and Linux/CI, so match case-insensitively.- recommendedPlan: expect.stringMatching(- /100k events per month for \$20\.00/i- ),- }),- });- // Memoized — one query even though both data and recommendedPlan use it.- expect(getOrganizationEventsCountMock).toHaveBeenCalledTimes(1);- });-- it('marks onboarding completed once every email has been sent', async () => {- dbMock.organization.findMany.mockResolvedValue([- org({- onboarding: 'onboarding-trial-ending',- createdAt: subDays(new Date(), 31),- }),- ]);-- const result = await onboardingJob(job);-- expect(result).toMatchObject({ emailsSent: 0, orgsCompleted: 1 });- expect(dbMock.organization.update).toHaveBeenCalledWith({- where: { id: 'org-1' },- data: { onboarding: 'completed' },- });- });-- it('completes orgs left on the retired trial-ended pointer', async () => {- // The day-30 'onboarding-trial-ended' step moved to the wind-down sequence.- // Orgs still holding that pointer must finish the drip, not restart it from- // the welcome email. Code migration 21 settles these, but the runner has to- // be safe on its own for any that slip through.- dbMock.organization.findMany.mockResolvedValue([- org({- onboarding: 'onboarding-trial-ended',- createdAt: subDays(new Date(), 31),- }),- ]);-- const result = await onboardingJob(job);-- expect(result).toMatchObject({ emailsSent: 0, orgsCompleted: 1 });- expect(sendEmailMock).not.toHaveBeenCalled();- expect(dbMock.organization.update).toHaveBeenCalledWith({- where: { id: 'org-1' },- data: { onboarding: 'completed' },- });- });-});diff --git a/apps/worker/src/jobs/cron.onboarding.ts b/apps/worker/src/jobs/cron.onboarding.tsindex d87298d03..ceadbd48d 100644--- a/apps/worker/src/jobs/cron.onboarding.ts+++ b/apps/worker/src/jobs/cron.onboarding.ts@@ -1,239 +1,12 @@-import type { Job } from 'bullmq';-import { format } from 'date-fns';--import { db, getOrganizationEventsCount } from '@openpanel/db';-import type { CronQueuePayload } from '@openpanel/queue';--import { getRecommendedPlan } from '@openpanel/payments';-import {- type SequenceStep,- type SequenceSubject,- runSequence,- step,-} from './lib/email-sequence';-import { logger } from '../utils/logger';--/**- * The getting-started drip, from signup to a few days before the trial ends.- *- * It stops at day 26. What happens *after* the trial expires belongs to- * cron.wind-down.ts, which is anchored on the expiry rather than on signup —- * see that file. The old day-30 'onboarding-trial-ended' step moved there as- * 'wind-down-expired'.- *- * The `onboarding` column stores the last sent step, and step names are equal- * to template names for historical reasons: in-flight orgs already hold those- * values. Renaming one strands every org sitting on it (the runner completes- * them rather than replaying the sequence, but they still stop early).- */--const orgQuery = {- include: {- createdBy: {- select: {- id: true,- email: true,- firstName: true,- deletedAt: true,- },- },- projects: {- select: {- id: true,- },- },- },-} as const;--type OrgWithCreator = Awaited<- ReturnType<typeof db.organization.findMany<typeof orgQuery>>->[number];--interface OnboardingUsage {- eventsCount: number;- hasData: boolean;-};--interface OnboardingContext {- org: OrgWithCreator;- user: NonNullable<OrgWithCreator['createdBy']>;- // Lazy + memoized: only emails past the day gate pay for the ClickHouse count.- getUsage: () => Promise<OnboardingUsage>;-};--function createUsageGetter(org: OrgWithCreator) {- let promise: Promise<OnboardingUsage> | null = null;- return () => {- promise ??= getOrganizationEventsCount(- org.projects.map((project) => project.id),- ).then((eventsCount) => ({- eventsCount,- hasData: eventsCount > 0,- }));- return promise;- };-}--const getters = {- firstName: (ctx: OnboardingContext) => ctx.user.firstName || undefined,- dashboardUrl: (ctx: OnboardingContext) => {- return `${process.env.DASHBOARD_URL}/${ctx.org.id}`;- },- billingUrl: (ctx: OnboardingContext) => {- return `${process.env.DASHBOARD_URL}/${ctx.org.id}/billing`;- },- trialEndDate: (ctx: OnboardingContext) => {- return ctx.org.subscriptionEndsAt- ? format(ctx.org.subscriptionEndsAt, 'MMMM d')- : undefined;- },- recommendedPlan: async (ctx: OnboardingContext) => {- const { eventsCount } = await ctx.getUsage();- return getRecommendedPlan(- eventsCount,- (plan) =>- `${plan.formattedEvents} events per month for ${plan.formattedPrice}`,- );- },-} as const;--export const ONBOARDING_EMAILS: SequenceStep<OnboardingContext>[] = [- step<OnboardingContext, 'onboarding-welcome'>({- day: 0,- step: 'onboarding-welcome',- template: 'onboarding-welcome',- data: async (ctx) => ({- firstName: getters.firstName(ctx),- dashboardUrl: getters.dashboardUrl(ctx),- hasData: (await ctx.getUsage()).hasData,- }),- }),- step<OnboardingContext, 'onboarding-what-to-track'>({- day: 2,- step: 'onboarding-what-to-track',- template: 'onboarding-what-to-track',- data: async (ctx) => {- const usage = await ctx.getUsage();- return {- firstName: getters.firstName(ctx),- hasData: usage.hasData,- eventsCount: usage.eventsCount,- };- },- }),- step<OnboardingContext, 'onboarding-dashboards'>({- day: 6,- step: 'onboarding-dashboards',- template: 'onboarding-dashboards',- data: async (ctx) => {- const usage = await ctx.getUsage();- return {- firstName: getters.firstName(ctx),- dashboardUrl: getters.dashboardUrl(ctx),- hasData: usage.hasData,- eventsCount: usage.eventsCount,- };- },- }),- step<OnboardingContext, 'onboarding-feature-request'>({- day: 14,- step: 'onboarding-feature-request',- template: 'onboarding-feature-request',- data: async (ctx) => ({- firstName: getters.firstName(ctx),- hasData: (await ctx.getUsage()).hasData,- }),- }),- step<OnboardingContext, 'onboarding-trial-ending'>({- day: 26,- step: 'onboarding-trial-ending',- template: 'onboarding-trial-ending',- shouldSend: async ({ org }) => {- if (org.subscriptionStatus === 'active') {- return 'complete';- }- return true;- },- data: async (ctx) => {- const usage = await ctx.getUsage();- return {- firstName: getters.firstName(ctx),- billingUrl: getters.billingUrl(ctx),- recommendedPlan: await getters.recommendedPlan(ctx),- trialEndDate: getters.trialEndDate(ctx),- hasData: usage.hasData,- eventsCount: usage.eventsCount,- };- },- }),-];--export async function onboardingJob(_job: Job<CronQueuePayload>) {- if (process.env.SELF_HOSTED === 'true') {- return null;- }-- logger.info('Starting onboarding email job');-- // Fetch organizations that are in onboarding (not completed)- const orgs = await db.organization.findMany({- where: {- OR: [{ onboarding: null }, { onboarding: { notIn: ['completed'] } }],- deleteAt: null,- createdBy: {- deletedAt: null,- },- },- ...orgQuery,- });-- logger.info(`Found ${orgs.length} organizations in onboarding`);-- const contactable = orgs.filter(- (org) => org.createdBy && !org.createdBy.deletedAt,- );- const withoutCreator = orgs.length - contactable.length;-- const subjects: SequenceSubject<OnboardingContext>[] = contactable.map(- (org) => {- const user = org.createdBy as NonNullable<OrgWithCreator['createdBy']>;- return {- id: org.id,- email: user.email,- anchor: org.createdAt,- pointer: org.onboarding,- ctx: { org, user, getUsage: createUsageGetter(org) },- };- },- );-- const result = await runSequence({- name: 'onboarding',- steps: ONBOARDING_EMAILS,- subjects,- logger,- onAdvance: async (subject, stepName) => {- await db.organization.update({- where: { id: subject.id },- data: { onboarding: stepName },- });- },- onComplete: async (subject) => {- await db.organization.update({- where: { id: subject.id },- data: { onboarding: 'completed' },- });- },- });-- const summary = {- totalOrgs: orgs.length,- emailsSent: result.emailsSent,- orgsCompleted: result.completed,- orgsSkipped: result.deferred + result.stepsSkipped + withoutCreator,- };-- logger.info(summary, 'Completed onboarding email job');-- return summary;+// Dissolved into @openpanel/core's onboarding module (M6-003): the drip+// sequence (ONBOARDING_EMAILS) and the sweep itself moved to+// packages/core/src/modules/onboarding/onboarding.service.ts#runOnboardingCron.+// This file stays (DELEGATE PATTERN) — it is the `cron.ts` dispatcher's+// `onboarding` case, a thin wrapper around the core function, same shape as+// cron.delete.ts (M6-001).+import { runOnboardingCron } from '@openpanel/core';+import { logger } from '@/utils/logger';++export async function onboardingJob() {+ return await runOnboardingCron(logger);}diff --git a/apps/worker/src/jobs/cron.ts b/apps/worker/src/jobs/cron.tsindex f02db9a1d..0ec4ac29d 100644--- a/apps/worker/src/jobs/cron.ts+++ b/apps/worker/src/jobs/cron.ts@@ -13,13 +13,13 @@ import { dataHealthCronJob } from './cron.data-health';import { jobDelete } from './cron.delete';import { flushExportsJob } from './cron.flush-exports';import { insightCleanupCronJob } from './cron.insight-cleanup';-import { weeklyDigestCronJob } from './cron.weekly-digest';-import { windDownCronJob } from './cron.wind-down';import { onboardingJob } from './cron.onboarding';import { ping } from './cron.ping';import { salt } from './cron.salt';import { sessionReaperCronJob } from './cron.session-reaper';import { sessionVacuumCronJob } from './cron.session-vacuum';+import { weeklyDigestCronJob } from './cron.weekly-digest';+import { windDownCronJob } from './cron.wind-down';import { gscSyncAllJob } from './gsc';import { insightsDailyJob } from './insights';import { logger } from '@/utils/logger';@@ -58,7 +58,7 @@ export async function cronJob(job: Job<CronQueuePayload>) {return await insightsDailyJob(job);}case 'onboarding': {- return await onboardingJob(job);+ return await onboardingJob();}case 'gscSync': {return await gscSyncAllJob();diff --git a/apps/worker/src/jobs/lib/email-sequence.test.ts b/apps/worker/src/jobs/lib/email-sequence.test.tsdeleted file mode 100644index 5ce565bae..000000000--- a/apps/worker/src/jobs/lib/email-sequence.test.ts+++ /dev/null@@ -1,233 +0,0 @@-/**- * Unit tests for the sequence runner. `sendEmail` is mocked, so these assert- * decisions — which step fires, whether the pointer moves, whether side- * effects run — rather than delivery.- */-import { subDays } from 'date-fns';-import { beforeEach, describe, expect, it, vi } from 'vitest';--const { sendEmailMock } = vi.hoisted(() => ({- sendEmailMock: vi.fn().mockResolvedValue({}),-}));--vi.mock('@openpanel/email', () => ({ sendEmail: sendEmailMock }));--import {- type SequenceStep,- type SequenceSubject,- runSequence,- step,-} from './email-sequence';--type Ctx = { id: string };--const logger = {- info: vi.fn(),- warn: vi.fn(),- error: vi.fn(),-};--function makeSteps(- overrides: Partial<SequenceStep<Ctx>>[] = [],-): SequenceStep<Ctx>[] {- const base: SequenceStep<Ctx>[] = [- step<Ctx, 'onboarding-welcome'>({- day: 0,- step: 'first',- template: 'onboarding-welcome',- data: () => ({ firstName: 'A', dashboardUrl: 'x', hasData: true }),- }),- step<Ctx, 'onboarding-dashboards'>({- day: 10,- step: 'second',- template: 'onboarding-dashboards',- data: () => ({ firstName: 'A', dashboardUrl: 'x', hasData: true }),- }),- ];- return base.map((entry, index) => ({ ...entry, ...overrides[index] }));-}--function makeSubject(- pointer: string | null,- daysAgo: number,-): SequenceSubject<Ctx> {- return {- id: 'subject-1',- email: '[email protected]',- anchor: subDays(new Date(), daysAgo),- pointer,- ctx: { id: 'subject-1' },- };-}--function run(- steps: SequenceStep<Ctx>[],- subjects: SequenceSubject<Ctx>[],- extra: Partial<Parameters<typeof runSequence<Ctx>>[0]> = {},-) {- const onAdvance = vi.fn().mockResolvedValue(undefined);- const onComplete = vi.fn().mockResolvedValue(undefined);- return {- onAdvance,- onComplete,- result: runSequence<Ctx>({- name: 'test',- steps,- subjects,- onAdvance,- onComplete,- logger,- ...extra,- }),- };-}--beforeEach(() => {- vi.clearAllMocks();- sendEmailMock.mockResolvedValue({});-});--describe('runSequence', () => {- it('sends the first step and advances the pointer', async () => {- const { onAdvance, result } = run(makeSteps(), [makeSubject(null, 0)]);-- expect(await result).toMatchObject({ emailsSent: 1 });- expect(sendEmailMock).toHaveBeenCalledWith('onboarding-welcome', {- to: '[email protected]',- data: expect.objectContaining({ firstName: 'A' }),- });- expect(onAdvance).toHaveBeenCalledWith(- expect.objectContaining({ id: 'subject-1' }),- 'first',- );- });-- it('defers a step whose day gate has not been reached', async () => {- const { onAdvance, result } = run(makeSteps(), [makeSubject('first', 3)]);-- expect(await result).toMatchObject({ emailsSent: 0, deferred: 1 });- expect(sendEmailMock).not.toHaveBeenCalled();- expect(onAdvance).not.toHaveBeenCalled();- });-- it("completes rather than replays when the pointer is unknown", async () => {- // The whole reason this branch exists: the old findIndex returned -1 for a- // removed step, which restarted the sequence from the top.- const { onAdvance, onComplete, result } = run(makeSteps(), [- makeSubject('a-step-that-was-renamed', 40),- ]);-- expect(await result).toMatchObject({ emailsSent: 0, completed: 1 });- expect(sendEmailMock).not.toHaveBeenCalled();- expect(onAdvance).not.toHaveBeenCalled();- expect(onComplete).toHaveBeenCalledTimes(1);- });-- it("advances past a step whose guard returns 'skip' and sends the next", async () => {- const steps = makeSteps([{ shouldSend: async () => 'skip' as const }]);- const { onAdvance, result } = run(steps, [makeSubject(null, 40)]);-- expect(await result).toMatchObject({ emailsSent: 1, stepsSkipped: 1 });- expect(onAdvance).toHaveBeenNthCalledWith(1, expect.anything(), 'first');- expect(onAdvance).toHaveBeenNthCalledWith(2, expect.anything(), 'second');- expect(sendEmailMock).toHaveBeenCalledTimes(1);- expect(sendEmailMock).toHaveBeenCalledWith(- 'onboarding-dashboards',- expect.anything(),- );- });-- it('holds the pointer when a guard returns false', async () => {- const steps = makeSteps([{ shouldSend: async () => false }]);- const { onAdvance, result } = run(steps, [makeSubject(null, 40)]);-- expect(await result).toMatchObject({ emailsSent: 0, deferred: 1 });- expect(onAdvance).not.toHaveBeenCalled();- });-- it("finishes the sequence when a guard returns 'complete'", async () => {- const steps = makeSteps([{ shouldSend: async () => 'complete' as const }]);- const { onComplete, result } = run(steps, [makeSubject(null, 40)]);-- expect(await result).toMatchObject({ emailsSent: 0, completed: 1 });- expect(onComplete).toHaveBeenCalledTimes(1);- expect(sendEmailMock).not.toHaveBeenCalled();- });-- it('completes once the last step has been sent', async () => {- const { onComplete, result } = run(makeSteps(), [makeSubject('second', 40)]);-- expect(await result).toMatchObject({ completed: 1 });- expect(onComplete).toHaveBeenCalledTimes(1);- });-- it('completes when the final step is skipped', async () => {- const steps = makeSteps([- undefined as never,- { shouldSend: async () => 'skip' as const },- ]);- const { onComplete, result } = run(steps, [makeSubject('first', 40)]);-- expect(await result).toMatchObject({ stepsSkipped: 1, completed: 1 });- expect(onComplete).toHaveBeenCalledTimes(1);- });-- it('runs onSent before advancing', async () => {- const calls: string[] = [];- const steps = makeSteps([- {- onSent: async () => {- calls.push('onSent');- },- },- ]);- const onAdvance = vi.fn(async () => {- calls.push('advance');- });-- await runSequence<Ctx>({- name: 'test',- steps,- subjects: [makeSubject(null, 0)],- onAdvance,- onComplete: vi.fn().mockResolvedValue(undefined),- logger,- });-- expect(calls).toEqual(['onSent', 'advance']);- });-- describe('requireDelivery', () => {- it('does not advance or run onSent when the send is suppressed', async () => {- // sendEmail resolves null (rather than throwing) for a suppressed or- // misconfigured send, which is exactly the case a destructive step must- // not act on.- sendEmailMock.mockResolvedValue(null);- const onSent = vi.fn();- const steps = makeSteps([{ requireDelivery: true, onSent }]);- const { onAdvance, result } = run(steps, [makeSubject(null, 0)]);-- expect(await result).toMatchObject({ emailsSent: 0, failed: 1 });- expect(onSent).not.toHaveBeenCalled();- expect(onAdvance).not.toHaveBeenCalled();- expect(logger.error).toHaveBeenCalled();- });-- it('advances a step without the flag even when the send is suppressed', async () => {- sendEmailMock.mockResolvedValue(null);- const { onAdvance, result } = run(makeSteps(), [makeSubject(null, 0)]);-- expect(await result).toMatchObject({ emailsSent: 1 });- expect(onAdvance).toHaveBeenCalledWith(expect.anything(), 'first');- });- });-- it('holds the pointer when the send throws', async () => {- sendEmailMock.mockRejectedValue(new Error('smtp down'));- const { onAdvance, result } = run(makeSteps(), [makeSubject(null, 0)]);-- expect(await result).toMatchObject({ emailsSent: 0, failed: 1 });- expect(onAdvance).not.toHaveBeenCalled();- });--});diff --git a/apps/worker/src/jobs/lib/email-sequence.ts b/apps/worker/src/jobs/lib/email-sequence.tsindex 69fb25d8a..e0dcf21d2 100644--- a/apps/worker/src/jobs/lib/email-sequence.ts+++ b/apps/worker/src/jobs/lib/email-sequence.ts@@ -1,260 +1,12 @@-import { type EmailData, type EmailTemplate, sendEmail } from '@openpanel/email';-import { differenceInDays } from 'date-fns';--/**- * A day-gated email sequence runner, shared by the onboarding drip and the- * wind-down track.- *- * Each subject carries a pointer (the last step whose email was sent) and an- * anchor date. On every tick the runner resolves the next step, checks the day- * gate and the step's own guard, sends, then advances the pointer.- *- * Three deliberate differences from the original inline implementation in- * cron.onboarding.ts, all of which matter once a sequence ends in deletion:- *- * 1. The pointer resolves by step name and an *unknown* name completes the- * sequence rather than restarting it. The old `findIndex` returned -1 for a- * renamed or removed step, which silently sent the subject back to step 0.- * 2. `'skip'` advances past a step; `false` only defers it. The old code had- * one value for both, so a step that should be passed over stalled the- * sequence permanently.- * 3. `requireDelivery` refuses to advance unless the email actually went out.- * `sendEmail` returns null instead of throwing when a send is suppressed or- * misconfigured, so a step with side effects could otherwise fire on an- * email nobody received.- */--/**- * - `true` send it now- * - `false` not yet — leave the pointer put and reconsider next tick- * - `'skip'` doesn't apply to this subject — advance without sending- * - `'complete'` the sequence is finished for this subject- */-export type StepResult = boolean | 'skip' | 'complete';--export interface SequenceStep<TCtx, T extends EmailTemplate = EmailTemplate> {- /** Whole days since the anchor before this step may fire. */- day: number;- /**- * Stable identifier persisted as the pointer. Renaming one is a data- * migration, not a refactor — see the unknown-pointer rule above.- */- step: string;- template: T;- /**- * Only advance the pointer if the send is confirmed. Use for any step whose- * `onSent` has consequences the subject was promised an email about.- */- requireDelivery?: boolean;- shouldSend?: (ctx: TCtx) => Promise<StepResult>;- data: (ctx: TCtx) => EmailData<T> | Promise<EmailData<T>>;- /** Applied after a confirmed send, before the pointer advances. */- onSent?: (ctx: TCtx) => Promise<void>;-};--/** Keeps `template` and `data` correlated; TS can't infer that from the array. */-export function step<TCtx, T extends EmailTemplate>(- config: SequenceStep<TCtx, T>,-): SequenceStep<TCtx, EmailTemplate> {- return config as SequenceStep<TCtx, EmailTemplate>;-}--export interface SequenceSubject<TCtx> {- /** For logging only. */- id: string;- /** Recipient address. */- email: string;- /** Day gates are measured from here. */- anchor: Date;- /** Last sent step, or null if the sequence hasn't started. */- pointer: string | null;- ctx: TCtx;-};--export interface SequenceResult {- emailsSent: number;- completed: number;- /** Subjects left where they were (day gate or a `false` guard). */- deferred: number;- /** Steps advanced past without sending. */- stepsSkipped: number;- /** Sends that threw, or that `requireDelivery` rejected. */- failed: number;-};--interface Logger {- info: (obj: unknown, msg?: string) => void;- warn: (obj: unknown, msg?: string) => void;- error: (obj: unknown, msg?: string) => void;-};--export interface RunSequenceOptions<TCtx> {- /** Sequence name, for log lines. */- name: string;- steps: SequenceStep<TCtx, EmailTemplate>[];- subjects: SequenceSubject<TCtx>[];- /** Persist the pointer after a send or a skip. */- onAdvance: (subject: SequenceSubject<TCtx>, step: string) => Promise<void>;- /**- * No steps remain, or a guard returned 'complete'. Omit it when the final- * pointer must be preserved because something else reads it — a wind-down- * org at 'final_warning' is still blocked from ingesting, so overwriting- * that pointer with a completion sentinel would quietly unblock it.- */- onComplete?: (subject: SequenceSubject<TCtx>) => Promise<void>;- logger: Logger;-};--export async function runSequence<TCtx>({- name,- steps,- subjects,- onAdvance,- onComplete,- logger,-}: RunSequenceOptions<TCtx>): Promise<SequenceResult> {- const result: SequenceResult = {- emailsSent: 0,- completed: 0,- deferred: 0,- stepsSkipped: 0,- failed: 0,- };- const now = new Date();-- for (const subject of subjects) {- const startIndex = resolveIndex(steps, subject.pointer);-- if (startIndex === 'unknown') {- // A step that no longer exists. Completing is the safe reading — the- // alternative is replaying the sequence from the top.- logger.warn(- { sequence: name, subject: subject.id, pointer: subject.pointer },- 'Unknown sequence pointer, marking complete',- );- await onComplete?.(subject);- result.completed++;- continue;- }-- // One tick can cross several steps when guards skip, but never more than- // the sequence length.- let index = startIndex + 1;-- while (index < steps.length) {- const current = steps[index];- if (!current) {- break;- }-- if (differenceInDays(now, subject.anchor) < current.day) {- result.deferred++;- break;- }-- const guard = current.shouldSend- ? await current.shouldSend(subject.ctx)- : true;-- if (guard === 'complete') {- await onComplete?.(subject);- result.completed++;- break;- }-- if (guard === false) {- result.deferred++;- break;- }-- if (guard === 'skip') {- await onAdvance(subject, current.step);- result.stepsSkipped++;- index++;- continue;- }-- const sent = await sendStep({- sequence: name,- subject,- step: current,- logger,- });-- if (!sent) {- result.failed++;- break;- }-- await current.onSent?.(subject.ctx);- await onAdvance(subject, current.step);- result.emailsSent++;- break;- }-- if (index >= steps.length) {- await onComplete?.(subject);- result.completed++;- }- }-- logger.info({ sequence: name, ...result }, `Sequence ${name} tick`);-- return result;-}--function resolveIndex<TCtx>(- steps: SequenceStep<TCtx, EmailTemplate>[],- pointer: string | null,-): number | 'unknown' {- if (!pointer) {- return -1;- }- const index = steps.findIndex((entry) => entry.step === pointer);- return index === -1 ? 'unknown' : index;-}--async function sendStep<TCtx>({- sequence,- subject,- step: current,- logger,-}: {- sequence: string;- subject: SequenceSubject<TCtx>;- step: SequenceStep<TCtx, EmailTemplate>;- logger: Logger;-}): Promise<boolean> {- try {- const data = await current.data(subject.ctx);-- const delivery = await sendEmail(current.template, {- to: subject.email,- data: data as never,- });-- // A null return means suppressed, unparseable, or no provider configured —- // note that a local environment without RESEND_API_KEY/SMTP_HOST always- // lands here, so requireDelivery steps won't advance in dev.- if (current.requireDelivery && delivery === null) {- logger.error(- {- sequence,- subject: subject.id,- step: current.step,- template: current.template,- },- 'Sequence email required delivery but was not sent, holding pointer',- );- return false;- }-- return true;- } catch (error) {- logger.error(- { err: error, sequence, subject: subject.id, step: current.step },- 'Failed to send sequence email',- );- return false;- }-}+// Moved into @openpanel/core's shared/ (M6-003): the day-gated sequence+// runner shared by the onboarding drip (now in core) and the wind-down track+// (cron.wind-down.ts, still here). Re-exported for that one remaining+// importer — same shape as packages/db/src/gsc.ts since M5-002.+export type {+ RunSequenceOptions,+ SequenceResult,+ SequenceStep,+ SequenceSubject,+ StepResult,+} from '@openpanel/core';+export { runSequence, step } from '@openpanel/core';diff --git a/packages/core/package.json b/packages/core/package.jsonindex 23ea0ac0d..f10c5436b 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -32,6 +32,7 @@"@openpanel/constants": "workspace:*","@openpanel/db": "workspace:*","@openpanel/email": "workspace:*",+ "@openpanel/payments": "workspace:*","@openpanel/redis": "workspace:*","@openpanel/validation": "workspace:*","@oslojs/crypto": "^1.0.1",@@ -43,6 +44,7 @@"arctic": "^2.3.0","bullmq": "6.3.3","csv-parse": "^6.1.0",+ "date-fns": "^3.3.1","elysia": "1.4.30","ipaddr.js": "^2.5.0","lru-cache": "^11.2.4",diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex d6aee380f..9b79b21e3 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -167,20 +167,46 @@ export async function runFilterCommand(input: {// way they reach the other dissolved leaf packages here. `hashPassword` is// renamed on the way out: `./shared/crypto` already owns that name for the// (unrelated) scrypt hash client secrets use.-export type { AuthService, OAuth2Tokens } from './modules/auth/auth.service';+//+// The sign-up/sign-in/TOTP/reset-password/share/OAuth-callback half (M6-003)+// joined it here — packages/trpc's auth router and+// apps/api/src/controllers/oauth-callback.controller.tsx call these+// directly, the same way V1 reaches every other dissolved service here.+export type {+ AuthProvider,+ AuthService,+ CompleteOAuthCallbackInput,+ OAuth2Tokens,+ OAuthUser,+ SignInEmailInput,+ SignInEmailResult,+ SignInShareInput,+ SignInTotpInput,+ SignUpEmailInput,+ StartOAuthSignInInput,+ StartOAuthSignInResult,+} from './modules/auth/auth.service';export {Arctic,+ assertOAuthState,buildOtpauthUrl,COOKIE_MAX_AGE,COOKIE_OPTIONS,+ completeOAuthCallback,consumeRecoveryCode,createAuthService,decodeSessionToken,deleteSessionTokenCookie,+ disableTotp,+ enableTotp,+ extendSessionCookie,+ fetchGithubOAuthUser,+ fetchGoogleOAuthUser,generateQrDataUrl,generateRecoveryCodes,generateSessionToken,generateTotpSecret,+ getTotpStatus,github,google,googleGsc,@@ -188,9 +214,20 @@ export {hashRecoveryCodes,hashSessionToken,normalizeRecoveryCode,+ OAuthCallbackError,parseCookieDomain,+ regenerateTotpRecoveryCodes,+ requestPasswordReset,+ resetPasswordWithToken,setLastAuthProviderCookie,setSessionTokenCookie,+ setupTotp,+ signInToShare,+ signInWithEmail,+ signInWithTotp,+ signOutUser,+ signUpWithEmail,+ startOAuthSignIn,verifyPasswordHash,verifyTotpCode,} from './modules/auth/auth.service';@@ -295,6 +332,22 @@ export {selectGscSite,syncGscData,} from './modules/gsc/gsc.service';+// New module (M6-003) — the onboarding-project mutation and the onboarding+// email drip, neither of which had a packages/db/src/services/* home to move+// from. packages/trpc's onboarding router and apps/worker's onboarding cron+// job call these directly, the same way V1 reaches every other dissolved+// service here.+export type {+ CreateOnboardingProjectResult,+ OnboardingCronSummary,+ OnboardingService,+} from './modules/onboarding/onboarding.service';+export {+ canSkipOnboarding,+ createOnboardingProject,+ createOnboardingService,+ runOnboardingCron,+} from './modules/onboarding/onboarding.service';// Dissolved from @openpanel/db's services/organization.service.ts +// services/delete.service.ts (M6-001, folded together per the module map) —// packages/trpc's organization router, apps/worker's delete cron job and@@ -375,7 +428,7 @@ export {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`/+// packages/trpc's auth/onboarding routers call `getUserById`/// `getUserAccount` directly through @openpanel/db's re-export shim, the same// way they reach every other dissolved service here.export type { IServiceUser } from './modules/user/user.service';@@ -520,6 +573,18 @@ export {hashPassword,verifyPassword,} from './shared/crypto';+// Moved from apps/worker/src/jobs/lib/email-sequence.ts (M6-003) — shared by+// the onboarding module and, until it moves too, apps/worker's own+// cron.wind-down.ts, which reaches it through this barrel (same shape as+// every other still-live V1 consumer here).+export type {+ RunSequenceOptions,+ SequenceResult,+ SequenceStep,+ SequenceSubject,+ StepResult,+} from './shared/email-sequence';+export { runSequence, step } from './shared/email-sequence';export {decrypt,decryptCredential,diff --git a/packages/core/src/jobs.registry.test.ts b/packages/core/src/jobs.registry.test.tsindex dca70afda..dba1f1b26 100644--- a/packages/core/src/jobs.registry.test.ts+++ b/packages/core/src/jobs.registry.test.ts@@ -88,6 +88,7 @@ test('the cron queue carries the insight module cron fragment', () => {'gscSync','insightCleanup','insightsDaily',+ 'onboarding','weeklyDigest',].sort());@@ -146,6 +147,14 @@ test('the cron queue carries the organization module cron fragment', () => {});});+// M6-003: the onboarding module's own cron fragment.+test('the cron queue carries the onboarding module cron fragment', () => {+ expect(queues.cron.jobs.onboarding).toMatchObject({+ queue: 'cron',+ name: 'onboarding',+ });+});+// M5-004: the import module's own job. No cron fragment — imports are always// user-triggered (import.rpc.ts's create/retry), unlike gsc/cohort/insight.// legacyCompat.import already discriminates on this exact namediff --git a/packages/core/src/jobs.registry.ts b/packages/core/src/jobs.registry.tsindex 2ffd6a909..e288f36b5 100644--- a/packages/core/src/jobs.registry.ts+++ b/packages/core/src/jobs.registry.ts@@ -21,6 +21,7 @@ import {insightCronJobs,insightQueueJobs,} from './modules/insight/insight.jobs';+import { onboardingCronJobs } from './modules/onboarding/onboarding.jobs';import { organizationCronJobs } from './modules/organization/organization.jobs';const HOUR_IN_SECONDS = 3600;@@ -60,6 +61,7 @@ const cron = defineQueue('cron', {...gscCronJobs,...cohortCronJobs,...organizationCronJobs,+ ...onboardingCronJobs,},});diff --git a/packages/core/src/jobs/schedulers.ts b/packages/core/src/jobs/schedulers.tsindex 62e5f3831..72733b703 100644--- a/packages/core/src/jobs/schedulers.ts+++ b/packages/core/src/jobs/schedulers.ts@@ -8,6 +8,7 @@ import type { Logger } from '../logger';import { cohortCronSchedules } from '../modules/cohort/cohort.jobs';import { gscCronSchedules } from '../modules/gsc/gsc.jobs';import { insightCronSchedules } from '../modules/insight/insight.jobs';+import { onboardingCronSchedules } from '../modules/onboarding/onboarding.jobs';import { organizationCronSchedules } from '../modules/organization/organization.jobs';import { wrap } from './envelope';@@ -67,7 +68,9 @@ export const CRON_SCHEDULES: readonly SchedulerDefinition[] = [{ id: 'flushProfileBackfill', schedule: { every: 30_000 } },{ id: 'flushReplay', schedule: { every: 10_000 } },{ id: 'flushGroups', schedule: { every: 10_000 } },- { id: 'onboarding', schedule: { pattern: '0 * * * *' } },+ // onboarding — owned by the onboarding module, declared next to its jobs+ // (modules/onboarding/onboarding.jobs.ts).+ ...onboardingCronSchedules,// gscSync — owned by the gsc module, declared next to its jobs// (modules/gsc/gsc.jobs.ts)....gscCronSchedules,diff --git a/packages/core/src/modules/auth/auth.constants.ts b/packages/core/src/modules/auth/auth.constants.tsnew file mode 100644index 000000000..ac7a6db38--- /dev/null+++ b/packages/core/src/modules/auth/auth.constants.ts@@ -0,0 +1,71 @@+// Moved from packages/validation/src/index.ts (M6-003, ADR-008's module map:+// auth owns "C"). packages/validation/src/index.ts becomes a re-export shim+// for these symbols (same shape as packages/validation/src/cohort.validation.ts+// since M5-003), so apps/start and packages/trpc keep resolving them through+// @openpanel/validation's existing barrel unchanged. `zProvider` is new here —+// it validated `signInOAuth`'s input inline in packages/trpc/src/routers/auth.ts+// and was never exported, but it is vocabulary the same way the rest of this+// file is.+//+// Isomorphic by the AGENTS.md rule: zod and nothing else.++import { z } from 'zod';++export const zProvider = z.enum(['email', 'google', 'github']);++export const zPassword = z.string().min(8);++export const zSignInEmail = z.object({+ email: z.string().email().min(1),+ password: zPassword,+ inviteId: z.string().nullish(),+});+export type ISignInEmail = z.infer<typeof zSignInEmail>;++export const zSignUpEmail = z+ .object({+ firstName: z.string().min(1),+ lastName: z.string().min(1),+ email: z.string().email(),+ password: zPassword,+ confirmPassword: zPassword,+ inviteId: z.string().nullish(),+ })+ .refine((data) => data.password === data.confirmPassword, {+ path: ['confirmPassword'],+ message: 'Passwords do not match',+ });+export type ISignUpEmail = z.infer<typeof zSignUpEmail>;++export const zResetPassword = z.object({+ token: z.string(),+ password: z.string().min(8),+});+export type IResetPassword = z.infer<typeof zResetPassword>;++export const zRequestResetPassword = z.object({+ email: z.string().email(),+});+export type IRequestResetPassword = z.infer<typeof zRequestResetPassword>;++export const zTotpCode = z+ .string()+ .transform((v) => v.replace(/\s+/g, ''))+ .refine((v) => /^\d{6}$/.test(v), { message: 'Enter a 6-digit code' });+export type ITotpCode = z.infer<typeof zTotpCode>;++export const zTotpOrRecoveryCode = z+ .string()+ .min(1)+ .transform((v) => v.trim());+export type ITotpOrRecoveryCode = z.infer<typeof zTotpOrRecoveryCode>;++export const zSignInShare = z.object({+ password: z.string().min(1),+ shareId: z.string().min(1),+ shareType: z+ .enum(['overview', 'dashboard', 'report'])+ .optional()+ .default('overview'),+});+export type ISignInShare = z.infer<typeof zSignInShare>;diff --git a/packages/core/src/modules/auth/auth.routes.ts b/packages/core/src/modules/auth/auth.routes.tsnew file mode 100644index 000000000..3cb250e13--- /dev/null+++ b/packages/core/src/modules/auth/auth.routes.ts@@ -0,0 +1,116 @@+// The github/google OAuth callbacks (M6-003). V1's Fastify controller+// (apps/api/src/controllers/oauth-callback.controller.tsx) stays the LIVE+// route (DELEGATE PATTERN) and delegates its token-exchange/session logic to+// auth.service.ts's `completeOAuthCallback` — the same function this route+// calls, same shape as gsc.routes.ts (M5-002). This route is not yet+// reachable: main.ts does not mount `dashboardRoutes` until a real `AppDeps`+// exists (P3/P4/P8).+//+// NAMED GAP: per-route cookie signing is not wired yet (gsc.routes.ts's+// header names the same gap), so `ctx.cookies.get()` here reads the raw,+// unsigned cookie value. V1's Fastify controller does not sign these cookies+// either (only the GSC flow does), so this is not a parity regression.++import { redirect } from 'elysia';+import { z } from 'zod';+import { defineRoutes } from '../../http/define';+import {+ assertOAuthState,+ completeOAuthCallback,+ fetchGithubOAuthUser,+ fetchGoogleOAuthUser,+ OAuthCallbackError,+} from './auth.service';++const callbackQuery = z.object({+ code: z.string(),+ state: z.string(),+});++function dashboardUrl(): string {+ return (+ process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL || ''+ );+}++function loginErrorRedirect(message: string, correlationId: string) {+ const url = new URL('/login', dashboardUrl() || 'http://localhost');+ url.searchParams.set('error', message);+ url.searchParams.set('correlationId', correlationId);+ return redirect(url.toString());+}++export const authRoutes = defineRoutes((app) =>+ app+ .get(+ '/oauth/github/callback',+ async ({ query, ctx }) => {+ const storedState = ctx.cookies.get('github_oauth_state') ?? null;+ const inviteId = ctx.cookies.get('inviteId');++ try {+ assertOAuthState('github', query.state, storedState);+ const oauthUser = await fetchGithubOAuthUser(query.code);+ await completeOAuthCallback({+ provider: 'github',+ oauthUser,+ inviteId,+ setCookie: ctx.setCookie,+ logger: ctx.logger,+ });+ ctx.setCookie('github_oauth_state', '', { maxAge: 0 });+ return redirect(dashboardUrl());+ } catch (error) {+ ctx.logger.error({ err: error }, 'GitHub OAuth callback error');+ ctx.setCookie('github_oauth_state', '', { maxAge: 0 });+ const message =+ error instanceof OAuthCallbackError+ ? error.message+ : 'An error occurred';+ return loginErrorRedirect(message, ctx.requestId);+ }+ },+ { query: callbackQuery, detail: { hide: true } }+ )+ .get(+ '/oauth/google/callback',+ async ({ query, ctx }) => {+ const storedState = ctx.cookies.get('google_oauth_state') ?? null;+ const codeVerifier = ctx.cookies.get('google_code_verifier') ?? null;+ const inviteId = ctx.cookies.get('inviteId');++ try {+ assertOAuthState('google', query.state, storedState);+ if (!codeVerifier) {+ throw new OAuthCallbackError('Missing oauth parameters', {+ codeVerifier: false,+ });+ }+ const oauthUser = await fetchGoogleOAuthUser(+ query.code,+ codeVerifier+ );+ await completeOAuthCallback({+ provider: 'google',+ oauthUser,+ inviteId,+ setCookie: ctx.setCookie,+ logger: ctx.logger,+ });+ ctx.setCookie('google_oauth_state', '', { maxAge: 0 });+ ctx.setCookie('google_code_verifier', '', { maxAge: 0 });+ return redirect(dashboardUrl());+ } catch (error) {+ ctx.logger.error({ err: error }, 'Google OAuth callback error');+ ctx.setCookie('google_oauth_state', '', { maxAge: 0 });+ ctx.setCookie('google_code_verifier', '', { maxAge: 0 });+ const message =+ error instanceof OAuthCallbackError+ ? error.message+ : 'An error occurred';+ return loginErrorRedirect(message, ctx.requestId);+ }+ },+ { query: callbackQuery, detail: { hide: true } }+ )+);diff --git a/packages/core/src/modules/auth/auth.rpc.test.ts b/packages/core/src/modules/auth/auth.rpc.test.tsnew file mode 100644index 000000000..f80ea0780--- /dev/null+++ b/packages/core/src/modules/auth/auth.rpc.test.ts@@ -0,0 +1,71 @@+// Only the "is anyone logged in" boundary is exercised here — no database.+// The sign-up/sign-in/reset-password/share bodies ride on @openpanel/db+// (lazy-loaded through ./auth.service); wiring this router end-to-end+// against a real Postgres is P6's (protectedProcedure) job, not this one's —+// see auth.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 { authRouter } from './auth.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 authRouter.createCaller(trpcCtx);+}++test('totpStatus rejects an unauthenticated caller', async () => {+ const caller = await anonCaller();+ await expect(caller.totpStatus()).rejects.toMatchObject({+ code: 'UNAUTHORIZED',+ });+});++test('totpSetup rejects an unauthenticated caller', async () => {+ const caller = await anonCaller();+ await expect(caller.totpSetup()).rejects.toMatchObject({+ code: 'UNAUTHORIZED',+ });+});++test('totpEnable rejects an unauthenticated caller before checking a code', async () => {+ const caller = await anonCaller();+ await expect(caller.totpEnable({ code: '123456' })).rejects.toMatchObject({+ code: 'UNAUTHORIZED',+ });+});++test('totpDisable rejects an unauthenticated caller before checking a code', async () => {+ const caller = await anonCaller();+ await expect(caller.totpDisable({ code: '123456' })).rejects.toMatchObject({+ code: 'UNAUTHORIZED',+ });+});++test('totpRegenerateRecoveryCodes rejects an unauthenticated caller', async () => {+ const caller = await anonCaller();+ await expect(+ caller.totpRegenerateRecoveryCodes({ code: '123456' })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('session returns the caller session unauthenticated (no login required)', async () => {+ const caller = await anonCaller();+ await expect(caller.session()).resolves.toEqual(EMPTY_SESSION);+});diff --git a/packages/core/src/modules/auth/auth.rpc.ts b/packages/core/src/modules/auth/auth.rpc.tsnew file mode 100644index 000000000..79cc3de99--- /dev/null+++ b/packages/core/src/modules/auth/auth.rpc.ts@@ -0,0 +1,129 @@+// Ported from packages/trpc/src/routers/auth.ts (M6-003).+//+// 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)"). This+// router is the first to reach that comment and deliberately does not+// resolve it: wiring a full protectedProcedure (runWithAlsSession, the+// Redis-backed rate limiter) onto core's rpc/base.ts is a bigger change than+// "the auth router moves" and is left for the task that actually mounts+// `dashboardRoutes` in production (P3/P4/P8). Until then this router does+// its own minimal "is anyone logged in" check inline, same as+// organization.rpc.ts/project.rpc.ts. V1 keeps serving the live route+// through packages/trpc's own `protectedProcedure` (full stack, including+// rate limiting) and delegates every handler body to `./auth.service`+// (DELEGATE PATTERN) — the same functions this router calls.+//+// This module has no queue/cron of its own, so there is no+// `ctx.services.auth` entry here — same shape as `user`/`project`.++import {+ zProvider,+ zRequestResetPassword,+ zResetPassword,+ zSignInEmail,+ zSignInShare,+ zSignUpEmail,+ zTotpCode,+ zTotpOrRecoveryCode,+} from '@openpanel/validation';+import { z } from 'zod';+import { createTRPCRouter, procedure } from '../../rpc/base';+import { TRPCAccessError } from '../../rpc/errors';+import {+ disableTotp,+ enableTotp,+ extendSessionCookie,+ getTotpStatus,+ regenerateTotpRecoveryCodes,+ requestPasswordReset,+ resetPasswordWithToken,+ setupTotp,+ signInToShare,+ signInWithEmail,+ signInWithTotp,+ signOutUser,+ signUpWithEmail,+ startOAuthSignIn,+} from './auth.service';++function requireLogin(userId: string | null | undefined): string {+ if (!userId) {+ throw new TRPCAccessError('Not authenticated');+ }+ return userId;+}++export const authRouter = createTRPCRouter({+ signOut: procedure.mutation(async ({ ctx }) => {+ await signOutUser(ctx.setCookie, ctx.session?.session?.id);+ }),++ signInOAuth: procedure+ .input(z.object({ provider: zProvider, inviteId: z.string().nullish() }))+ .mutation(({ input, ctx }) => startOAuthSignIn(input, ctx.setCookie)),++ signUpEmail: procedure+ .input(zSignUpEmail)+ .mutation(({ input, ctx }) => signUpWithEmail(input, ctx.setCookie)),++ signInEmail: procedure+ .input(zSignInEmail)+ .mutation(({ input, ctx }) =>+ signInWithEmail(input, ctx.setCookie, ctx.logger)+ ),++ signInTotp: procedure+ .input(z.object({ code: zTotpOrRecoveryCode }))+ .mutation(({ input, ctx }) =>+ signInWithTotp(input, ctx.cookies, ctx.setCookie, ctx.logger)+ ),++ totpStatus: procedure.query(({ ctx }) =>+ getTotpStatus(requireLogin(ctx.session.userId))+ ),++ totpSetup: procedure.mutation(({ ctx }) =>+ setupTotp(requireLogin(ctx.session.userId))+ ),++ totpEnable: procedure+ .input(z.object({ code: zTotpCode }))+ .mutation(({ input, ctx }) =>+ enableTotp(requireLogin(ctx.session.userId), input.code)+ ),++ totpDisable: procedure+ .input(z.object({ code: zTotpOrRecoveryCode }))+ .mutation(({ input, ctx }) =>+ disableTotp(requireLogin(ctx.session.userId), input.code)+ ),++ totpRegenerateRecoveryCodes: procedure+ .input(z.object({ code: zTotpCode }))+ .mutation(({ input, ctx }) =>+ regenerateTotpRecoveryCodes(requireLogin(ctx.session.userId), input.code)+ ),++ resetPassword: procedure+ .input(zResetPassword)+ .mutation(({ input }) => resetPasswordWithToken(input)),++ requestResetPassword: procedure+ .input(zRequestResetPassword)+ .mutation(({ input }) => requestPasswordReset(input)),++ session: procedure.query(({ ctx }) => ctx.session),++ extendSession: procedure.mutation(({ ctx }) =>+ extendSessionCookie(+ ctx.cookies,+ Boolean(ctx.session.session),+ ctx.setCookie+ )+ ),++ signInShare: procedure+ .input(zSignInShare)+ .mutation(({ input, ctx }) => signInToShare(input, ctx.setCookie)),+});diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.tsindex d5efb6a22..aea1977bc 100644--- a/packages/core/src/modules/auth/auth.service.ts+++ b/packages/core/src/modules/auth/auth.service.ts@@ -6,6 +6,7 @@// @openpanel/core (for exactly this module's token hash) and the reverse// edge would be a cycle. That file calls back into `hashSessionToken` below.+import { z } from 'zod';import type { ServiceDeps } from '../../services';import type { ISetCookie } from '../../shared/cookie';import {@@ -14,6 +15,7 @@ import {setSessionTokenCookie,} from './src/cookie';import { parseCookieDomain } from './src/cookie-domain';+import { Arctic, github, google } from './src/oauth';import { hashPassword, verifyPasswordHash } from './src/password';import {decodeSessionToken,@@ -118,3 +120,892 @@ export function createAuthService(_deps: ServiceDeps): AuthService {parseCookieDomain,};}++// -----------------------------------------------------------------------+// The Prisma-touching half (M6-003): sign-up/sign-in, TOTP challenges,+// password reset, share unlock and the github/google OAuth callback. This+// is the logic packages/trpc/src/routers/auth.ts and+// apps/api/src/controllers/oauth-callback.controller.tsx held inline —+// neither ever had a `packages/db/src/services/*` home to move from, unlike+// every other M5/M6 module, so it is written directly here (DELEGATE+// PATTERN: both V1's trpc router and this package's own auth.rpc.ts call+// these same functions).+//+// db/session/registration/share access is LAZY, not a static top-level+// import — see user.service.ts's header for the full reasoning, and because+// a static import of @openpanel/db here specifically WOULD be a cycle+// (this file's own header, above: db already depends on core for+// `hashSessionToken`).+//+// None of these functions take a `TrpcContext`/`Ctx`: they take exactly the+// primitives they touch (`setCookie`, `cookies.get`, `logger`), so this file+// has no dependency on the rpc layer that calls it.++import { sendEmail } from '../../clients/email';+import type { Logger } from '../../logger';+import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';+import { decrypt, encrypt } from '../../shared/encryption';+import { generateSecureId } from '../../shared/id';+import { connectUserToOrganization } from '../organization/organization.service';+import { getUserAccount } from '../user/user.service';++const TWO_FACTOR_COOKIE = '2fa_challenge';+const TWO_FACTOR_CHALLENGE_TTL_SECONDS = 5 * 60;+const INVITE_COOKIE = 'inviteId';+// V1's reset-password token: 10 minutes.+const RESET_PASSWORD_TTL_MS = 1000 * 60 * 10;++export type AuthProvider = 'email' | 'google' | 'github';++/** `HttpCtx.cookies`'s shape (`shared/cookie.ts`'s `CookieJar`), named locally+ * so this file has no import from the rpc/http layer that calls it. */+interface CookieReader {+ get(name: string): string | undefined;+}++function loadDb() {+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);+}++function loadAuthSession() {+ return import('@openpanel/db/src/services/auth-session.service');+}++function loadRegistration() {+ return import('@openpanel/db/src/services/registration.service');+}++function loadShare() {+ return import('@openpanel/db/src/services/share.service');+}++function dashboardUrl(): string {+ return (+ process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL || ''+ );+}++/**+ * Best-effort consumption of an invite for a user that just authenticated.+ * Failures (expired/invalid invite) must not block the sign-in itself, so we+ * swallow and log the error instead of rethrowing.+ */+async function consumeInviteForUser(+ userId: string,+ inviteId: string,+ logger: Pick<Logger, 'error'>+): Promise<void> {+ try {+ const db = await loadDb();+ const user = await db.user.findUniqueOrThrow({ where: { id: userId } });+ await connectUserToOrganization({ user, inviteId });+ } catch (error) {+ logger.error(+ { userId, inviteId, error },+ 'Failed to connect user to organization via invite'+ );+ }+}++export async function signOutUser(+ setCookie: ISetCookie,+ sessionId: string | null | undefined+): Promise<void> {+ deleteSessionTokenCookie(setCookie);+ if (sessionId) {+ const { invalidateSession } = await loadAuthSession();+ await invalidateSession(sessionId);+ }+}++export interface StartOAuthSignInInput {+ provider: AuthProvider;+ inviteId?: string | null;+}++export type StartOAuthSignInResult =+ | { type: 'github'; url: string }+ | { type: 'google'; url: string };++/**+ * No registration check here. At this point we have no identity for the+ * caller — the IdP hasn't been hit yet — so we cannot tell a returning user+ * from a new sign-up. Gating here locks out every existing OAuth user as soon+ * as their session expires. The check lives in `completeOAuthCallback`, the+ * only place we know the user is new.+ */+export function startOAuthSignIn(+ input: StartOAuthSignInInput,+ setCookie: ISetCookie+): StartOAuthSignInResult {+ if (input.inviteId) {+ setCookie('inviteId', input.inviteId, { maxAge: 60 * 10 });+ }++ if (input.provider === 'github') {+ const state = Arctic.generateState();+ const url = github.createAuthorizationURL(state, [+ 'user:email',+ 'user:read',+ ]);+ setCookie('github_oauth_state', state, { maxAge: 60 * 10 });+ return { type: 'github', url: url.toString() };+ }++ const state = Arctic.generateState();+ const codeVerifier = Arctic.generateCodeVerifier();+ const url = google.createAuthorizationURL(state, codeVerifier, [+ 'openid',+ 'profile',+ 'email',+ ]);+ setCookie('google_oauth_state', state, { maxAge: 60 * 10 });+ setCookie('google_code_verifier', codeVerifier, { maxAge: 60 * 10 });+ return { type: 'google', url: url.toString() };+}++export interface SignUpEmailInput {+ firstName: string;+ lastName: string;+ email: string;+ password: string;+ inviteId?: string | null;+}++export async function signUpWithEmail(+ input: SignUpEmailInput,+ setCookie: ISetCookie+) {+ const { getIsRegistrationAllowed } = await loadRegistration();+ const isRegistrationAllowed = await getIsRegistrationAllowed(input.inviteId);+ if (!isRegistrationAllowed) {+ throw new TRPCAccessError('Registrations are not allowed');+ }++ const provider = 'email';+ const db = await loadDb();+ const existing = await getUserAccount({ email: input.email, provider });+ if (existing) {+ throw new TRPCNotFoundError('User already exists');+ }++ const createdUser = await db.user.create({+ data: {+ id: generateSecureId('user'),+ email: input.email,+ firstName: input.firstName,+ lastName: input.lastName,+ accounts: {+ create: {+ provider,+ password: await hashPassword(input.password),+ },+ },+ },+ });++ if (input.inviteId) {+ await connectUserToOrganization({+ user: createdUser,+ inviteId: input.inviteId,+ });+ }++ const { createSession } = await loadAuthSession();+ const token = generateSessionToken();+ const session = await createSession(token, createdUser.id);+ setSessionTokenCookie(setCookie, token, session.expiresAt);+ return session;+}++export interface SignInEmailInput {+ email: string;+ password: string;+ inviteId?: string | null;+}++export type SignInEmailResult = { type: 'totp_required' } | { type: 'email' };++export async function signInWithEmail(+ input: SignInEmailInput,+ setCookie: ISetCookie,+ logger: Pick<Logger, 'error'>+): Promise<SignInEmailResult> {+ const password = input.password.trim();+ const user = await getUserAccount({ email: input.email, provider: 'email' });++ if (!user) {+ throw new TRPCNotFoundError('User does not exists');+ }++ // If the password starts with $argon2 we use the new password hashing,+ // otherwise it's legacy from Clerk which used bcrypt (ADR-011: no legacy+ // branch — those rows are nulled, so this is now just a generic reject).+ if (!user.account.password?.startsWith('$argon2')) {+ throw new TRPCAccessError('Reset your password, old password has expired');+ }++ const validPassword = await verifyPasswordHash(+ user.account.password,+ password+ );+ if (!validPassword) {+ throw new TRPCAccessError('Incorrect email or password');+ }++ const db = await loadDb();+ const totp = await db.userTotp.findUnique({ where: { userId: user.id } });+ if (totp?.enabledAt) {+ const challengeId = generateSecureId('2fa');+ await db.twoFactorChallenge.create({+ data: {+ id: challengeId,+ userId: user.id,+ expiresAt: new Date(+ Date.now() + TWO_FACTOR_CHALLENGE_TTL_SECONDS * 1000+ ),+ },+ });+ setCookie(TWO_FACTOR_COOKIE, challengeId, {+ maxAge: TWO_FACTOR_CHALLENGE_TTL_SECONDS,+ });+ // Carry the invite through the 2FA challenge so it can be consumed once+ // the user completes the second factor in `signInWithTotp`.+ if (input.inviteId) {+ setCookie(INVITE_COOKIE, input.inviteId, {+ maxAge: TWO_FACTOR_CHALLENGE_TTL_SECONDS,+ });+ }+ return { type: 'totp_required' };+ }++ const { createSession } = await loadAuthSession();+ const token = generateSessionToken();+ const session = await createSession(token, user.id);+ setSessionTokenCookie(setCookie, token, session.expiresAt);+ setLastAuthProviderCookie(setCookie, 'email');++ if (input.inviteId) {+ await consumeInviteForUser(user.id, input.inviteId, logger);+ }++ return { type: 'email' };+}++export interface SignInTotpInput {+ code: string;+}++export async function signInWithTotp(+ input: SignInTotpInput,+ cookies: CookieReader,+ setCookie: ISetCookie,+ logger: Pick<Logger, 'error'>+): Promise<{ type: 'email' }> {+ const challengeId = cookies.get(TWO_FACTOR_COOKIE);+ if (!challengeId) {+ throw new TRPCAccessError('No active two-factor challenge');+ }++ const db = await loadDb();+ const challenge = await db.twoFactorChallenge.findUnique({+ where: { id: challengeId },+ });++ if (!challenge || challenge.expiresAt < new Date()) {+ if (challenge) {+ await db.twoFactorChallenge.delete({ where: { id: challenge.id } });+ }+ setCookie(TWO_FACTOR_COOKIE, '', { maxAge: 0 });+ throw new TRPCAccessError('Two-factor challenge has expired');+ }++ const totp = await db.userTotp.findUnique({+ where: { userId: challenge.userId },+ });+ if (!totp?.enabledAt) {+ await db.twoFactorChallenge.delete({ where: { id: challenge.id } });+ setCookie(TWO_FACTOR_COOKIE, '', { maxAge: 0 });+ throw new TRPCAccessError('Two-factor is not enabled');+ }++ const secret = decrypt(totp.secret);+ const isTotpCode = /^\d{6}$/.test(input.code.replace(/\s+/g, ''));+ let valid = false;++ if (isTotpCode) {+ valid = verifyTotpCode(secret, input.code);+ } else {+ const result = await consumeRecoveryCode({+ hashes: totp.recoveryCodes,+ input: input.code,+ });+ if (result.valid) {+ valid = true;+ await db.userTotp.update({+ where: { userId: challenge.userId },+ data: { recoveryCodes: result.remaining },+ });+ }+ }++ if (!valid) {+ throw new TRPCAccessError('Invalid code');+ }++ await db.twoFactorChallenge.delete({ where: { id: challenge.id } });+ setCookie(TWO_FACTOR_COOKIE, '', { maxAge: 0 });++ const { createSession } = await loadAuthSession();+ const token = generateSessionToken();+ const session = await createSession(token, challenge.userId);+ setSessionTokenCookie(setCookie, token, session.expiresAt);+ setLastAuthProviderCookie(setCookie, 'email');++ const inviteId = cookies.get(INVITE_COOKIE);+ if (inviteId) {+ await consumeInviteForUser(challenge.userId, inviteId, logger);+ setCookie(INVITE_COOKIE, '', { maxAge: 0 });+ }++ return { type: 'email' };+}++export async function getTotpStatus(userId: string) {+ const db = await loadDb();+ const [totp, emailAccount] = await Promise.all([+ db.userTotp.findUnique({ where: { userId } }),+ db.account.findFirst({+ where: { userId, provider: 'email' },+ select: { id: true },+ }),+ ]);+ return {+ enabled: Boolean(totp?.enabledAt),+ enabledAt: totp?.enabledAt ?? null,+ remainingRecoveryCodes: totp?.recoveryCodes.length ?? 0,+ hasEmailProvider: Boolean(emailAccount),+ };+}++export async function setupTotp(userId: string) {+ const db = await loadDb();+ const emailAccount = await db.account.findFirst({+ where: { userId, provider: 'email' },+ select: { id: true },+ });+ if (!emailAccount) {+ throw new TRPCAccessError(+ 'Two-factor authentication is only available for email/password sign-ins. Your account uses a social provider, which handles 2FA on its end.'+ );+ }+ const existing = await db.userTotp.findUnique({ where: { userId } });+ if (existing?.enabledAt) {+ throw new TRPCAccessError(+ 'Two-factor is already enabled. Disable it first to re-configure.'+ );+ }++ const user = await db.user.findUniqueOrThrow({+ where: { id: userId },+ select: { email: true },+ });++ const secret = generateTotpSecret();+ const otpauthUrl = buildOtpauthUrl({ secret, accountName: user.email });+ const qrDataUrl = await generateQrDataUrl(otpauthUrl);++ await db.userTotp.upsert({+ where: { userId },+ create: { userId, secret: encrypt(secret), recoveryCodes: [] },+ update: { secret: encrypt(secret), recoveryCodes: [], enabledAt: null },+ });++ return { otpauthUrl, qrDataUrl, secret };+}++export async function enableTotp(userId: string, code: string) {+ const db = await loadDb();+ const totp = await db.userTotp.findUnique({ where: { userId } });+ if (!totp) {+ throw new TRPCNotFoundError('Start two-factor setup first');+ }+ if (totp.enabledAt) {+ throw new TRPCAccessError('Two-factor is already enabled');+ }++ const secret = decrypt(totp.secret);+ if (!verifyTotpCode(secret, code)) {+ throw new TRPCAccessError('Invalid code');+ }++ const recoveryCodes = generateRecoveryCodes();+ const hashed = await hashRecoveryCodes(recoveryCodes);++ await db.userTotp.update({+ where: { userId },+ data: { enabledAt: new Date(), recoveryCodes: hashed },+ });++ return { recoveryCodes };+}++export async function disableTotp(userId: string, code: string) {+ const db = await loadDb();+ const totp = await db.userTotp.findUnique({ where: { userId } });+ if (!totp?.enabledAt) {+ throw new TRPCAccessError('Two-factor is not enabled');+ }++ const secret = decrypt(totp.secret);+ const isTotpCode = /^\d{6}$/.test(code.replace(/\s+/g, ''));+ const valid = isTotpCode+ ? verifyTotpCode(secret, code)+ : (await consumeRecoveryCode({ hashes: totp.recoveryCodes, input: code }))+ .valid;++ if (!valid) {+ throw new TRPCAccessError('Invalid code');+ }++ await db.userTotp.delete({ where: { userId } });+ await db.twoFactorChallenge.deleteMany({ where: { userId } });+ return { disabled: true };+}++export async function regenerateTotpRecoveryCodes(+ userId: string,+ code: string+) {+ const db = await loadDb();+ const totp = await db.userTotp.findUnique({ where: { userId } });+ if (!totp?.enabledAt) {+ throw new TRPCAccessError('Two-factor is not enabled');+ }+ const secret = decrypt(totp.secret);+ if (!verifyTotpCode(secret, code)) {+ throw new TRPCAccessError('Invalid code');+ }+ const recoveryCodes = generateRecoveryCodes();+ const hashed = await hashRecoveryCodes(recoveryCodes);+ await db.userTotp.update({+ where: { userId },+ data: { recoveryCodes: hashed },+ });+ return { recoveryCodes };+}++export interface ResetPasswordInput {+ token: string;+ password: string;+}++export async function resetPasswordWithToken(+ input: ResetPasswordInput+): Promise<true> {+ const db = await loadDb();+ const resetPassword = await db.resetPassword.findUnique({+ where: { id: input.token },+ });++ if (!resetPassword) {+ throw new TRPCNotFoundError('Reset password not found');+ }+ if (resetPassword.expiresAt < new Date()) {+ throw new TRPCNotFoundError('Reset password expired');+ }++ await db.account.update({+ where: { id: resetPassword.accountId },+ data: { password: await hashPassword(input.password) },+ });+ await db.resetPassword.delete({ where: { id: input.token } });++ return true;+}++export async function requestPasswordReset(input: {+ email: string;+}): Promise<true> {+ const user = await getUserAccount({ email: input.email, provider: 'email' });+ // Deliberately not found-vs-found: V1 always returns `true` here so the+ // endpoint cannot be used to enumerate registered emails.+ if (!user?.account.id) {+ return true;+ }++ const db = await loadDb();+ await db.resetPassword.deleteMany({ where: { accountId: user.account.id } });++ const token = generateSecureId('pw');+ const expiresAt = new Date(Date.now() + RESET_PASSWORD_TTL_MS);+ await db.resetPassword.create({+ data: { id: token, expiresAt, accountId: user.account.id },+ });++ await sendEmail('reset-password', {+ to: input.email,+ data: { url: `${dashboardUrl()}/reset-password?token=${token}` },+ });++ return true;+}++export async function extendSessionCookie(+ cookies: CookieReader,+ hasSession: boolean,+ setCookie: ISetCookie+): Promise<{ extended: boolean; expiresAt?: Date }> {+ const token = cookies.get('session');+ if (!(hasSession && token)) {+ return { extended: false };+ }++ const { validateSessionToken } = await loadAuthSession();+ const session = await validateSessionToken(token);++ if (session.session) {+ setSessionTokenCookie(setCookie, token, session.session.expiresAt);+ return { extended: true, expiresAt: session.session.expiresAt };+ }++ return { extended: false };+}++export interface SignInShareInput {+ password: string;+ shareId: string;+ shareType?: 'overview' | 'dashboard' | 'report';+}++export async function signInToShare(+ input: SignInShareInput,+ setCookie: ISetCookie+): Promise<true> {+ const { password, shareId, shareType = 'overview' } = input;+ const { getShareOverviewById, getShareDashboardById, getShareReportById } =+ await loadShare();++ let share: { password: string | null; public: boolean } | null = null;+ let cookieName = '';++ if (shareType === 'overview') {+ share = await getShareOverviewById(shareId);+ cookieName = `shared-overview-${shareId}`;+ } else if (shareType === 'dashboard') {+ share = await getShareDashboardById(shareId);+ cookieName = `shared-dashboard-${shareId}`;+ } else if (shareType === 'report') {+ share = await getShareReportById(shareId);+ cookieName = `shared-report-${shareId}`;+ }++ if (!share) {+ throw new TRPCNotFoundError('Share not found');+ }+ if (!share.public) {+ throw new TRPCNotFoundError('Share is not public');+ }+ if (!share.password) {+ throw new TRPCNotFoundError('Share is not password protected');+ }++ const validPassword = await verifyPasswordHash(share.password, password);+ if (!validPassword) {+ throw new TRPCAccessError('Incorrect password');+ }++ setCookie(cookieName, '1', { maxAge: 60 * 60 * 24 * 7 });+ return true;+}++// -----------------------------------------------------------------------+// The github/google OAuth callback (apps/api's /oauth/{github,google}/callback+// — DELEGATE PATTERN, same shape as gsc.service.ts#completeGscOAuthCallback).+// State/query parsing and cookie reads stay in each transport (Fastify's+// controller, this package's own auth.routes.ts): only the token exchange,+// user lookup/creation and session issuance live here.++export interface OAuthUser {+ id: string;+ email: string;+ firstName: string;+ lastName?: string;+}++/** Raised for every *expected* failure — the caller shows `.message` verbatim+ * in the `/login?error=` redirect, same as V1's `LogError`. Anything else+ * thrown is an unexpected bug and the caller shows a generic message. */+export class OAuthCallbackError extends Error {+ constructor(+ message: string,+ public readonly context?: Record<string, unknown>+ ) {+ super(message);+ this.name = 'OAuthCallbackError';+ }+}++async function fetchGithubEmail(accessToken: string): Promise<string | null> {+ const emailListRequest = new Request('https://api.github.com/user/emails');+ emailListRequest.headers.set('Authorization', `Bearer ${accessToken}`);+ const emailListResponse = await fetch(emailListRequest);+ const emailListResult: unknown = await emailListResponse.json();+ if (!Array.isArray(emailListResult) || emailListResult.length < 1) {+ return null;+ }+ let email: string | null = null;+ for (const emailRecord of emailListResult) {+ const emailParser = z.object({+ primary: z.boolean(),+ verified: z.boolean(),+ email: z.string(),+ });+ const emailResult = emailParser.safeParse(emailRecord);+ if (!emailResult.success) {+ continue;+ }+ if (emailResult.data.primary && emailResult.data.verified) {+ email = emailResult.data.email;+ }+ }+ return email;+}++export async function fetchGithubOAuthUser(code: string): Promise<OAuthUser> {+ const tokens = await github.validateAuthorizationCode(code);+ const accessToken = tokens.accessToken();+ const email = await fetchGithubEmail(accessToken);+ if (!email) {+ throw new OAuthCallbackError('GitHub email not found or not verified');+ }++ const userRequest = new Request('https://api.github.com/user');+ userRequest.headers.set('Authorization', `Bearer ${accessToken}`);+ const userResponse = await fetch(userRequest);++ const userSchema = z.object({+ id: z.number(),+ login: z.string(),+ name: z+ .string()+ .nullish()+ .transform((val) => val || ''),+ });+ const userJson = await userResponse.json();+ const userResult = userSchema.safeParse(userJson);+ if (!userResult.success) {+ throw new OAuthCallbackError('Error fetching Github user', {+ error: userResult.error,+ githubUser: userJson,+ });+ }++ return {+ id: String(userResult.data.id),+ email,+ firstName: userResult.data.name || userResult.data.login || '',+ };+}++export async function fetchGoogleOAuthUser(+ code: string,+ codeVerifier: string+): Promise<OAuthUser> {+ const tokens = await google.validateAuthorizationCode(code, codeVerifier);+ const claims = Arctic.decodeIdToken(tokens.idToken());++ const claimsSchema = z.object({+ sub: z.string(),+ email: z.string(),+ email_verified: z.boolean(),+ given_name: z.string().optional(),+ family_name: z.string().optional(),+ });+ const claimsResult = claimsSchema.safeParse(claims);+ if (!claimsResult.success) {+ throw new OAuthCallbackError('Error fetching Google user', {+ error: claimsResult.error,+ claims,+ });+ }+ if (!claimsResult.data.email_verified) {+ throw new OAuthCallbackError('Email not verified with Google');+ }++ return {+ id: claimsResult.data.sub,+ email: claimsResult.data.email,+ firstName: claimsResult.data.given_name || '',+ lastName: claimsResult.data.family_name || '',+ };+}++/**+ * Checked by the caller BEFORE exchanging `code` for tokens — same ordering+ * as V1's `validateOAuthCallback`, so a forged `state` never costs an IdP+ * round-trip.+ */+export function assertOAuthState(+ provider: 'github' | 'google',+ state: string,+ storedState: string | null+): void {+ if (!storedState || state !== storedState) {+ throw new OAuthCallbackError('OAuth state mismatch', {+ provider,+ hasStoredState: Boolean(storedState),+ });+ }+}++export interface CompleteOAuthCallbackInput {+ provider: 'github' | 'google';+ oauthUser: OAuthUser;+ inviteId: string | null | undefined;+ setCookie: ISetCookie;+ logger: Pick<Logger, 'error'>;+}++/**+ * State/token-exchange validation stays with the caller (`assertOAuthState`,+ * then the provider-specific `fetch*OAuthUser`); this is the shared half —+ * find-or-create the account and issue a session.+ */+export async function completeOAuthCallback(+ input: CompleteOAuthCallbackInput+): Promise<void> {+ const { provider, oauthUser, inviteId, setCookie, logger } = input;+ const db = await loadDb();++ const account = await db.account.findFirst({+ where: {+ OR: [+ { provider, providerId: oauthUser.id },+ // During migration+ { provider, providerId: null, email: oauthUser.email },+ { provider: 'oauth', user: { email: oauthUser.email } },+ ],+ },+ });++ if (account) {+ await completeExistingOAuthUser({+ account,+ oauthUser,+ provider,+ inviteId,+ setCookie,+ logger,+ });+ return;+ }++ await completeNewOAuthUser({+ oauthUser,+ provider,+ inviteId,+ setCookie,+ logger,+ });+}++async function completeExistingOAuthUser({+ account,+ oauthUser,+ provider,+ inviteId,+ setCookie,+ logger,+}: {+ account: { id: string; userId: string };+ oauthUser: OAuthUser;+ provider: 'github' | 'google';+ inviteId: string | null | undefined;+ setCookie: ISetCookie;+ logger: Pick<Logger, 'error'>;+}) {+ const db = await loadDb();+ const { createSession } = await loadAuthSession();+ const sessionToken = generateSessionToken();+ const session = await createSession(sessionToken, account.userId);++ await db.account.update({+ where: { id: account.id },+ data: { provider, providerId: oauthUser.id, email: oauthUser.email },+ });++ if (inviteId) {+ await consumeInviteForUser(account.userId, inviteId, logger);+ }++ setSessionTokenCookie(setCookie, sessionToken, session.expiresAt);+ setLastAuthProviderCookie(setCookie, provider);+}++async function completeNewOAuthUser({+ oauthUser,+ provider,+ inviteId,+ setCookie,+ logger,+}: {+ oauthUser: OAuthUser;+ provider: 'github' | 'google';+ inviteId: string | null | undefined;+ setCookie: ISetCookie;+ logger: Pick<Logger, 'error'>;+}) {+ const db = await loadDb();+ const { getIsRegistrationAllowed } = await loadRegistration();++ const existingUser = await db.user.findFirst({+ where: { email: oauthUser.email },+ });+ if (existingUser) {+ throw new OAuthCallbackError(+ 'Please sign in using your original authentication method',+ { existingUser, oauthUser, provider }+ );+ }++ // Enforce the self-hosting registration policy here rather than before the+ // IdP redirect — this is the first point where we know the user is new, so+ // returning users are never caught by it.+ if (!(await getIsRegistrationAllowed(inviteId))) {+ // Deliberately no `oauthUser` here — this rejects people who are not+ // users, so their email and name shouldn't land in application logs.+ throw new OAuthCallbackError('Registrations are not allowed', {+ provider,+ inviteId,+ });+ }++ const user = await db.user.create({+ data: {+ email: oauthUser.email,+ firstName: oauthUser.firstName,+ lastName: oauthUser.lastName,+ accounts: {+ create: { provider, providerId: oauthUser.id },+ },+ },+ });++ if (inviteId) {+ try {+ await connectUserToOrganization({ user, inviteId });+ } catch (error) {+ logger.error(+ { error, inviteId, user },+ 'error connecting user to organization'+ );+ }+ }++ const { createSession } = await loadAuthSession();+ const sessionToken = generateSessionToken();+ const session = await createSession(sessionToken, user.id);+ setSessionTokenCookie(setCookie, sessionToken, session.expiresAt);+ setLastAuthProviderCookie(setCookie, provider);+}diff --git a/packages/core/src/modules/cohort/cohort.jobs.test.ts b/packages/core/src/modules/cohort/cohort.jobs.test.tsindex 221282fc3..7cebe5a0f 100644--- a/packages/core/src/modules/cohort/cohort.jobs.test.ts+++ b/packages/core/src/modules/cohort/cohort.jobs.test.ts@@ -36,6 +36,7 @@ function stubJobCtx(cohort: Partial<CohortService>, jobName = 'test'): JobCtx {import: {} as Services['import'],cohort: cohort as CohortService,organization: {} as Services['organization'],+ onboarding: {} as Services['onboarding'],};return {db: {},diff --git a/packages/core/src/modules/gsc/gsc.jobs.test.ts b/packages/core/src/modules/gsc/gsc.jobs.test.tsindex 8caa10557..2d56b0adf 100644--- a/packages/core/src/modules/gsc/gsc.jobs.test.ts+++ b/packages/core/src/modules/gsc/gsc.jobs.test.ts@@ -32,6 +32,7 @@ function stubJobCtx(gsc: Partial<GscService>, jobName = 'test'): JobCtx {import: {} as Services['import'],gsc: gsc as GscService,organization: {} as Services['organization'],+ onboarding: {} as Services['onboarding'],};return {db: {},@@ -130,6 +131,7 @@ test('gscSync fans out one gscProjectSync enqueue per connected project', async],} as GscService,organization: {} as Services['organization'],+ onboarding: {} as Services['onboarding'],},requestId: 'req_1',job: { id: 'job_1', attempt: 0, queue: 'cron', name: 'gscSync' },diff --git a/packages/core/src/modules/import/import.jobs.test.ts b/packages/core/src/modules/import/import.jobs.test.tsindex 11677d559..a90f39943 100644--- a/packages/core/src/modules/import/import.jobs.test.ts+++ b/packages/core/src/modules/import/import.jobs.test.ts@@ -32,6 +32,7 @@ function stubJobCtx(importService: Partial<ImportService>): JobCtx {gsc: {} as Services['gsc'],import: importService as ImportService,organization: {} as Services['organization'],+ onboarding: {} as Services['onboarding'],};return {db: {},diff --git a/packages/core/src/modules/insight/insight.jobs.test.ts b/packages/core/src/modules/insight/insight.jobs.test.tsindex b8ee4d589..b99271198 100644--- a/packages/core/src/modules/insight/insight.jobs.test.ts+++ b/packages/core/src/modules/insight/insight.jobs.test.ts@@ -43,6 +43,7 @@ function stubJobCtx(cohort: {} as Services['cohort'],import: {} as Services['import'],organization: {} as Services['organization'],+ onboarding: {} as Services['onboarding'],};return {db: {},@@ -124,6 +125,7 @@ test('insightsDaily fans out one insightsProject enqueue per candidate, jobId decohort: {} as Services['cohort'],import: {} as Services['import'],organization: {} as Services['organization'],+ onboarding: {} as Services['onboarding'],},requestId: 'req_1',job: { id: 'job_1', attempt: 0, queue: 'cron', name: 'insightsDaily' },diff --git a/packages/core/src/modules/onboarding/onboarding.constants.ts b/packages/core/src/modules/onboarding/onboarding.constants.tsnew file mode 100644index 000000000..d48d773d4--- /dev/null+++ b/packages/core/src/modules/onboarding/onboarding.constants.ts@@ -0,0 +1,57 @@+// Moved from packages/validation/src/index.ts (M6-003, ADR-008's module map:+// onboarding owns "C"). packages/validation/src/index.ts becomes a re-export+// shim for this symbol (same shape as ./cohort.validation.ts since M5-003).+//+// Isomorphic by the AGENTS.md rule: zod and nothing else.++import { z } from 'zod';++export const zOnboardingProject = z+ .object({+ organization: z.string().optional(),+ organizationId: z.string().optional(),+ project: z.string().min(3),+ domain: z.string().url().or(z.literal('').or(z.null())),+ cors: z.array(z.string()).default([]),+ website: z.boolean(),+ app: z.boolean(),+ backend: z.boolean(),+ timezone: z.string().optional(),+ })+ .superRefine((data, ctx) => {+ if (!(data.organization || data.organizationId)) {+ ctx.addIssue({+ code: 'custom',+ message: 'Organization is required',+ path: ['organization'],+ });+ ctx.addIssue({+ code: 'custom',+ message: 'Organization is required',+ path: ['organizationId'],+ });+ }++ if (data.website && !data.domain) {+ ctx.addIssue({+ code: 'custom',+ message: 'Domain is required for website tracking',+ path: ['domain'],+ });+ }++ if (+ data.website === false &&+ data.app === false &&+ data.backend === false+ ) {+ for (const key of ['app', 'backend', 'website']) {+ ctx.addIssue({+ code: 'custom',+ message: 'At least one type must be selected',+ path: [key],+ });+ }+ }+ });+export type IOnboardingProject = z.infer<typeof zOnboardingProject>;diff --git a/packages/core/src/modules/onboarding/onboarding.jobs.test.ts b/packages/core/src/modules/onboarding/onboarding.jobs.test.tsnew file mode 100644index 000000000..611b73c43--- /dev/null+++ b/packages/core/src/modules/onboarding/onboarding.jobs.test.ts@@ -0,0 +1,100 @@+// Job/cron-fragment wiring — no ClickHouse/Postgres touched. The service+// method itself is exercised in onboarding.service.test.ts.++import { expect, test } from 'bun:test';+import type { JobCtx } from '../../context';+import { createRecordingProducers } from '../../jobs/testing';+import { queues } from '../../jobs.registry';+import type { Logger } from '../../logger';+import type { Services } from '../../services';+import { onboardingCronJobs, onboardingCronSchedules } from './onboarding.jobs';+import type { OnboardingService } from './onboarding.service';++function stubLogger(): Logger {+ const noop = () => undefined;+ const logger: Logger = {+ fatal: noop,+ error: noop,+ warn: noop,+ info: noop,+ debug: noop,+ trace: noop,+ child: () => logger,+ };+ return logger;+}++function stubJobCtx(+ onboarding: Partial<OnboardingService>,+ jobName = 'test'+): JobCtx {+ const services: Services = {+ auth: {} as Services['auth'],+ insight: {} as Services['insight'],+ gsc: {} as Services['gsc'],+ import: {} as Services['import'],+ cohort: {} as Services['cohort'],+ organization: {} as Services['organization'],+ onboarding: onboarding as OnboardingService,+ };+ return {+ db: {},+ ch: {},+ redis: {},+ clients: {},+ buffers: {},+ logger: stubLogger(),+ queues: createRecordingProducers(queues).queues,+ services,+ requestId: 'req_1',+ job: { id: 'job_1', attempt: 0, queue: 'cron', name: jobName },+ };+}++test('the cron queue declares onboarding on the cron queue', () => {+ expect(queues.cron.jobs.onboarding).toMatchObject({+ queue: 'cron',+ name: 'onboarding',+ });+});++test('the onboarding cron fragment is spread into the cron queue', () => {+ expect(queues.cron.jobs.onboarding).toBeDefined();+});++test('onboarding delegates to runOnboardingCron', async () => {+ let called = false;+ const ctx = stubJobCtx({+ runOnboardingCron: async () => {+ called = true;+ return { totalOrgs: 1, emailsSent: 1, orgsCompleted: 0, orgsSkipped: 0 };+ },+ });++ await onboardingCronJobs.onboarding.handler({ payload: null, ctx });++ expect(called).toBe(true);+});++test('onboarding does not log when the cron is a self-hosted no-op', async () => {+ const logged: unknown[] = [];+ const ctx = stubJobCtx({ runOnboardingCron: async () => null });+ ctx.logger = {+ ...ctx.logger,+ info: (obj: unknown) => {+ logged.push(obj);+ },+ };++ await onboardingCronJobs.onboarding.handler({ payload: null, ctx });++ expect(logged).toEqual([]);+});++// Byte-identity with the id/cadence schedulers.test.ts's golden snapshot pins+// (apps/worker/src/boot-cron.ts).+test('the onboarding cron fragment carries V1 id and cadence unchanged', () => {+ expect(onboardingCronSchedules).toEqual([+ { id: 'onboarding', schedule: { pattern: '0 * * * *' } },+ ]);+});diff --git a/packages/core/src/modules/onboarding/onboarding.jobs.ts b/packages/core/src/modules/onboarding/onboarding.jobs.tsnew file mode 100644index 000000000..2e6456351--- /dev/null+++ b/packages/core/src/modules/onboarding/onboarding.jobs.ts@@ -0,0 +1,29 @@+// Ported from apps/worker/src/jobs/cron.onboarding.ts + boot-cron.ts's+// `onboarding` schedule (M6-003).+//+// `onboarding` is this module's fragment of the ONE `cron` queue's jobs:+// declared here, spread into jobs.registry.ts and into `CRON_SCHEDULES` by+// jobs/schedulers.ts. Scheduler id and cadence are V1's, unchanged+// (apps/worker/src/boot-cron.ts) — same shape as organization.jobs.ts (M6-001).++import { z } from 'zod';+import { defineJob } from '../../jobs/define';+import type { SchedulerDefinition } from '../../jobs/schedulers';++/** This module's fragment of the `cron` queue's jobs. */+export const onboardingCronJobs = {+ onboarding: defineJob({+ payload: z.null(),+ handler: async ({ ctx }) => {+ const result = await ctx.services.onboarding.runOnboardingCron();+ if (result) {+ ctx.logger.info({ ...result }, 'Completed onboarding email job');+ }+ },+ }),+};++/** This module's fragment of `CRON_SCHEDULES` — id and cadence unchanged. */+export const onboardingCronSchedules: readonly SchedulerDefinition[] = [+ { id: 'onboarding', schedule: { pattern: '0 * * * *' } },+];diff --git a/packages/core/src/modules/onboarding/onboarding.rpc.test.ts b/packages/core/src/modules/onboarding/onboarding.rpc.test.tsnew file mode 100644index 000000000..f876aa451--- /dev/null+++ b/packages/core/src/modules/onboarding/onboarding.rpc.test.ts@@ -0,0 +1,53 @@+// Only the "is anyone logged in" boundary is exercised here — no database.+// The org+project+client creation rides on @openpanel/db (lazy-loaded+// through ./onboarding.service); wiring this router end-to-end against a+// real Postgres is P6's (protectedProcedure) job, not this one's — see+// onboarding.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 { onboardingRouter } from './onboarding.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 onboardingRouter.createCaller(trpcCtx);+}++test('skipOnboardingCheck answers false without touching a database for an anonymous caller', async () => {+ const caller = await anonCaller();+ await expect(caller.skipOnboardingCheck()).resolves.toEqual({+ canSkip: false,+ });+});++test('project rejects an unauthenticated caller before creating anything', async () => {+ const caller = await anonCaller();+ await expect(+ caller.project({+ organization: 'Acme',+ project: 'website',+ domain: 'https://example.com',+ cors: [],+ website: true,+ app: false,+ backend: false,+ })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});diff --git a/packages/core/src/modules/onboarding/onboarding.rpc.ts b/packages/core/src/modules/onboarding/onboarding.rpc.tsnew file mode 100644index 000000000..3d889152b--- /dev/null+++ b/packages/core/src/modules/onboarding/onboarding.rpc.ts@@ -0,0 +1,64 @@+// Ported from packages/trpc/src/routers/onboarding.ts (M6-003).+//+// 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` — same shape as+// organization.rpc.ts/project.rpc.ts. `project`'s input can carry an+// existing `organizationId`, which V1's generic `enforceAccess` middleware+// gates on membership (not admin — joining an org you already belong to+// needs no more than that); this router does the same check explicitly,+// through the organization module's own db-bound lookup (dynamically+// imported, same as organization.rpc.ts's `./src/access`).+//+// V1 keeps serving the live route through packages/trpc's own+// `protectedProcedure`/`publicProcedure` and delegates every handler body to+// `./onboarding.service` (DELEGATE PATTERN) — the same functions this router+// calls.++import { zOnboardingProject } from '@openpanel/validation';+import { createTRPCRouter, procedure } from '../../rpc/base';+import { TRPCAccessError, TRPCForbiddenError } from '../../rpc/errors';+import {+ canSkipOnboarding,+ createOnboardingProject,+} from './onboarding.service';++function loadOrganizationAccess() {+ return import('@openpanel/db/src/services/access.service');+}++function requireLogin(userId: string | null | undefined): string {+ if (!userId) {+ throw new TRPCAccessError('Not authenticated');+ }+ return userId;+}++export const onboardingRouter = createTRPCRouter({+ skipOnboardingCheck: procedure.query(({ ctx }) =>+ canSkipOnboarding(ctx.session.userId)+ ),++ project: procedure+ .input(zOnboardingProject)+ .mutation(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);++ if (input.organizationId) {+ const { getOrganizationAccess } = await loadOrganizationAccess();+ const access = await getOrganizationAccess({+ userId,+ organizationId: input.organizationId,+ });+ if (!access) {+ throw new TRPCForbiddenError(+ 'You do not have access to this organization'+ );+ }+ }++ return createOnboardingProject(input, userId);+ }),+});diff --git a/packages/core/src/modules/onboarding/onboarding.service.test.ts b/packages/core/src/modules/onboarding/onboarding.service.test.tsnew file mode 100644index 000000000..7b98604b2--- /dev/null+++ b/packages/core/src/modules/onboarding/onboarding.service.test.ts@@ -0,0 +1,221 @@+// Onboarding email cron: the sequential drip driven by the+// `organization.onboarding` pointer. Moved from+// apps/worker/src/jobs/cron.onboarding.test.ts (M6-003) — db, the+// organization module's event-count lookup, and email are mocked; asserts+// template selection, day gating, early completion on active subs, and usage+// personalization. `mock.module` is not hoisted, so the subject is imported+// inside `beforeAll` — see AGENTS.md.++import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';+import { subDays } from 'date-fns';++const organizationFindMany = mock(async () => [] as unknown[]);+const organizationUpdate = mock(async () => ({}));+const dbMock = {+ organization: { findMany: organizationFindMany, update: organizationUpdate },+};+mock.module('@openpanel/db/src/prisma-client', () => ({ db: dbMock }));++const getOrganizationEventsCount = mock(async (_projectIds: string[]) => 0);+mock.module('../organization/organization.service', () => ({+ getOrganizationById: mock(async () => null),+ getOrganizationEventsCount,+ // Unused by `runOnboardingCron`, but `../auth/auth.service` (transitively+ // imported for `hashPassword`) statically imports it — a mock module must+ // supply every named export the real module's importers destructure.+ connectUserToOrganization: mock(async () => undefined),+}));++const sendEmail = mock(+ async (+ _template: string,+ _options: unknown+ ): Promise<Record<string, unknown> | null> => ({})+);+mock.module('../../clients/email', () => ({ sendEmail }));++let runOnboardingCron: typeof import('./onboarding.service').runOnboardingCron;++beforeAll(async () => {+ ({ runOnboardingCron } = await import('./onboarding.service'));+});++const logger = {+ info: mock(() => undefined),+ warn: mock(() => undefined),+ error: mock(() => undefined),+};++function org(overrides: Record<string, unknown> = {}) {+ return {+ id: 'org-1',+ createdAt: new Date(),+ onboarding: null,+ subscriptionStatus: 'trialing',+ subscriptionEndsAt: new Date('2026-06-16T12:00:00Z'),+ createdBy: {+ id: 'user-1',+ email: '[email protected]',+ firstName: 'Alex',+ deletedAt: null,+ },+ projects: [{ id: 'proj-1' }],+ ...overrides,+ };+}++beforeEach(() => {+ organizationFindMany.mockClear();+ organizationUpdate.mockClear().mockResolvedValue({});+ getOrganizationEventsCount.mockClear().mockResolvedValue(0);+ sendEmail.mockClear().mockResolvedValue({});+ logger.info.mockClear();+ logger.warn.mockClear();+ logger.error.mockClear();+ process.env.SELF_HOSTED = 'false';+});++test('returns null and does nothing when self-hosted', async () => {+ process.env.SELF_HOSTED = 'true';+ const result = await runOnboardingCron(logger);+ expect(result).toBeNull();+ expect(organizationFindMany).not.toHaveBeenCalled();+});++test('sends the welcome email on day 0 with hasData from clickhouse', async () => {+ getOrganizationEventsCount.mockResolvedValue(123);+ organizationFindMany.mockResolvedValue([org()]);++ const result = await runOnboardingCron(logger);++ expect(result).toMatchObject({ emailsSent: 1 });+ expect(sendEmail).toHaveBeenCalledWith('onboarding-welcome', {+ to: '[email protected]',+ data: expect.objectContaining({ firstName: 'Alex', hasData: true }),+ });+ expect(getOrganizationEventsCount).toHaveBeenCalledWith(['proj-1']);+ expect(organizationUpdate).toHaveBeenCalledWith({+ where: { id: 'org-1' },+ data: { onboarding: 'onboarding-welcome' },+ });+});++test('does not fetch usage for orgs that are gated on days', async () => {+ organizationFindMany.mockResolvedValue([+ org({+ onboarding: 'onboarding-welcome',+ createdAt: subDays(new Date(), 1), // next email is day 2+ }),+ ]);++ const result = await runOnboardingCron(logger);++ expect(result).toMatchObject({ emailsSent: 0, orgsSkipped: 1 });+ expect(sendEmail).not.toHaveBeenCalled();+ expect(getOrganizationEventsCount).not.toHaveBeenCalled();+});++test('sends the no-data branch of what-to-track on day 2', async () => {+ getOrganizationEventsCount.mockResolvedValue(0);+ organizationFindMany.mockResolvedValue([+ org({+ onboarding: 'onboarding-welcome',+ createdAt: subDays(new Date(), 2),+ }),+ ]);++ await runOnboardingCron(logger);++ expect(sendEmail).toHaveBeenCalledWith('onboarding-what-to-track', {+ to: '[email protected]',+ data: expect.objectContaining({ hasData: false, eventsCount: 0 }),+ });+});++test('completes onboarding when the org subscribed before the trial emails', async () => {+ organizationFindMany.mockResolvedValue([+ org({+ onboarding: 'onboarding-feature-request',+ createdAt: subDays(new Date(), 27),+ subscriptionStatus: 'active',+ }),+ ]);++ const result = await runOnboardingCron(logger);++ expect(result).toMatchObject({ emailsSent: 0, orgsCompleted: 1 });+ expect(sendEmail).not.toHaveBeenCalled();+ expect(organizationUpdate).toHaveBeenCalledWith({+ where: { id: 'org-1' },+ data: { onboarding: 'completed' },+ });+});++test('populates recommendedPlan and trial stats in the trial-ending email', async () => {+ // Regression: recommendedPlan used to read subscriptionPeriodEventsCount,+ // which is always 0 for trial orgs (no Polar billing period).+ getOrganizationEventsCount.mockResolvedValue(84_211);+ organizationFindMany.mockResolvedValue([+ org({+ onboarding: 'onboarding-feature-request',+ createdAt: subDays(new Date(), 27),+ }),+ ]);++ await runOnboardingCron(logger);++ expect(sendEmail).toHaveBeenCalledWith('onboarding-trial-ending', {+ to: '[email protected]',+ data: expect.objectContaining({+ hasData: true,+ eventsCount: 84_211,+ trialEndDate: 'June 16',+ // Compact-number casing (100K vs 100k) is ICU-version dependent and+ // differs between macOS and Linux/CI, so match case-insensitively.+ recommendedPlan: expect.stringMatching(+ /100k events per month for \$20\.00/i+ ),+ }),+ });+ // Memoized — one query even though both data and recommendedPlan use it.+ expect(getOrganizationEventsCount).toHaveBeenCalledTimes(1);+});++test('marks onboarding completed once every email has been sent', async () => {+ organizationFindMany.mockResolvedValue([+ org({+ onboarding: 'onboarding-trial-ending',+ createdAt: subDays(new Date(), 31),+ }),+ ]);++ const result = await runOnboardingCron(logger);++ expect(result).toMatchObject({ emailsSent: 0, orgsCompleted: 1 });+ expect(organizationUpdate).toHaveBeenCalledWith({+ where: { id: 'org-1' },+ data: { onboarding: 'completed' },+ });+});++test('completes orgs left on the retired trial-ended pointer', async () => {+ // The day-30 'onboarding-trial-ended' step moved to the wind-down sequence.+ // Orgs still holding that pointer must finish the drip, not restart it from+ // the welcome email. Code migration 21 settles these, but the runner has to+ // be safe on its own for any that slip through.+ organizationFindMany.mockResolvedValue([+ org({+ onboarding: 'onboarding-trial-ended',+ createdAt: subDays(new Date(), 31),+ }),+ ]);++ const result = await runOnboardingCron(logger);++ expect(result).toMatchObject({ emailsSent: 0, orgsCompleted: 1 });+ expect(sendEmail).not.toHaveBeenCalled();+ expect(organizationUpdate).toHaveBeenCalledWith({+ where: { id: 'org-1' },+ data: { onboarding: 'completed' },+ });+});diff --git a/packages/core/src/modules/onboarding/onboarding.service.ts b/packages/core/src/modules/onboarding/onboarding.service.tsnew file mode 100644index 000000000..43b217ffa--- /dev/null+++ b/packages/core/src/modules/onboarding/onboarding.service.ts@@ -0,0 +1,414 @@+// New module (M6-003): the onboarding-project mutation inline in+// packages/trpc/src/routers/onboarding.ts, plus the onboarding email drip+// inline in apps/worker/src/jobs/cron.onboarding.ts. Neither had a+// packages/db/src/services/* home to move from — written directly here,+// same shape as auth.service.ts's Prisma-touching half (M6-003). DELEGATE+// PATTERN: V1's trpc router and cron job, and this package's own+// onboarding.rpc.ts/onboarding.jobs.ts, all call these same functions.+//+// db access is LAZY (`loadDb` below), not a static top-level import — see+// user.service.ts's header for the full reasoning.++import crypto from 'node:crypto';+import { stripTrailingSlash } from '@openpanel/common';+import { getRecommendedPlan } from '@openpanel/payments';+import { format } from 'date-fns';+import type { Logger } from '../../logger';+import type { ServiceDeps } from '../../services';+import {+ runSequence,+ type SequenceStep,+ type SequenceSubject,+ step,+} from '../../shared/email-sequence';+import { hashPassword } from '../auth/auth.service';+import {+ getOrganizationById,+ getOrganizationEventsCount,+} from '../organization/organization.service';+import { getUserById } from '../user/user.service';+import type { IOnboardingProject } from './onboarding.constants';++const TRIAL_DURATION_IN_DAYS = 30;+// Generous trial allowance so trialing orgs never get flagged as+// "limit exceeded" (the limit defaults to 0, which trips on the first event).+const TRIAL_EVENTS_LIMIT = 10_000_000;++function loadDb() {+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);+}++function loadIdService() {+ return import('@openpanel/db/src/services/id.service');+}++export async function canSkipOnboarding(+ userId: string | null | undefined+): Promise<{ canSkip: boolean }> {+ if (!userId) {+ return { canSkip: false };+ }++ const db = await loadDb();+ const members = await db.member.findMany({ where: { userId } });+ if (members.length > 0) {+ return { canSkip: true };+ }++ const projectAccess = await db.projectAccess.findMany({+ where: { userId },+ });+ return { canSkip: projectAccess.length > 0 };+}++async function createOrGetOnboardingOrganization(+ input: IOnboardingProject,+ userId: string+) {+ if (input.organizationId) {+ return await getOrganizationById(input.organizationId);+ }++ if (!input.organization) {+ return null;+ }++ const { getId } = await loadIdService();+ const db = await loadDb();+ const organizationId = await getId('organization', input.organization);++ // Create the organization and its owner (org:admin member) atomically. The+ // `delete` cron treats an organization with no org:admin member as ownerless+ // and removes it, so an organization must never exist without one.+ const [organization] = await db.$transaction([+ db.organization.create({+ data: {+ id: organizationId,+ name: input.organization,+ createdByUserId: userId,+ subscriptionEndsAt: new Date(+ Date.now() + TRIAL_DURATION_IN_DAYS * 24 * 60 * 60 * 1000+ ),+ subscriptionStatus: 'trialing',+ subscriptionPeriodEventsLimit: TRIAL_EVENTS_LIMIT,+ timezone: input.timezone,+ onboarding: '',+ },+ }),+ db.member.create({+ data: {+ email: (await getUserById(userId)).email,+ organizationId,+ role: 'org:admin',+ userId,+ },+ }),+ ]);++ return organization;+}++export interface CreateOnboardingProjectResult {+ id: string;+ name: string;+ organizationId: string;+ projectId: string | null;+ type: string;+ secret: string;+}++export async function createOnboardingProject(+ input: IOnboardingProject,+ userId: string+): Promise<CreateOnboardingProjectResult> {+ const types: ('website' | 'app' | 'backend')[] = [];+ if (input.website) {+ types.push('website');+ }+ if (input.app) {+ types.push('app');+ }+ if (input.backend) {+ types.push('backend');+ }++ const organization = await createOrGetOnboardingOrganization(input, userId);+ if (!organization?.id) {+ throw new Error('Organization slug is missing');+ }++ const cors = [...input.cors];+ if (cors.length === 0 && input.website) {+ cors.push('*');+ }++ const { getId } = await loadIdService();+ const db = await loadDb();++ const project = await db.project.create({+ data: {+ id: await getId('project', input.project),+ name: input.project,+ organizationId: organization.id,+ types,+ domain: input.domain ? stripTrailingSlash(input.domain) : null,+ cors: cors.map((c) => stripTrailingSlash(c)),+ },+ });++ const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;+ const client = await db.client.create({+ data: {+ name: `${project.name} Client`,+ organizationId: organization.id,+ projectId: project.id,+ type: 'write',+ secret: await hashPassword(secret),+ },+ });++ return { ...client, secret };+}++// -----------------------------------------------------------------------+// The onboarding email drip cron (apps/worker/src/jobs/cron.onboarding.ts —+// DELEGATE PATTERN). The `organization.onboarding` column stores the last+// sent step, and step names are equal to template names for historical+// reasons: in-flight orgs already hold those values. Renaming one strands+// every org sitting on it (the runner completes them rather than replaying+// the sequence, but they still stop early).+//+// Stops at day 26 — what happens after the trial expires belongs to the+// (not yet ported) wind-down cron, anchored on expiry rather than signup.++interface OnboardingUsage {+ eventsCount: number;+ hasData: boolean;+}++interface OnboardingCronOrg {+ id: string;+ createdAt: Date;+ onboarding: string | null;+ subscriptionStatus: string | null;+ subscriptionEndsAt: Date | null;+ createdBy: {+ id: string;+ email: string;+ firstName: string | null;+ deletedAt: Date | null;+ } | null;+ projects: { id: string }[];+}++interface OnboardingContext {+ org: OnboardingCronOrg;+ user: NonNullable<OnboardingCronOrg['createdBy']>;+ // Lazy + memoized: only emails past the day gate pay for the ClickHouse count.+ getUsage: () => Promise<OnboardingUsage>;+}++function createUsageGetter(org: OnboardingCronOrg) {+ let promise: Promise<OnboardingUsage> | null = null;+ return () => {+ promise ??= getOrganizationEventsCount(+ org.projects.map((project) => project.id)+ ).then((eventsCount) => ({+ eventsCount,+ hasData: eventsCount > 0,+ }));+ return promise;+ };+}++const getters = {+ firstName: (ctx: OnboardingContext) => ctx.user.firstName || undefined,+ dashboardUrl: (ctx: OnboardingContext) => {+ return `${process.env.DASHBOARD_URL}/${ctx.org.id}`;+ },+ billingUrl: (ctx: OnboardingContext) => {+ return `${process.env.DASHBOARD_URL}/${ctx.org.id}/billing`;+ },+ trialEndDate: (ctx: OnboardingContext) => {+ return ctx.org.subscriptionEndsAt+ ? format(ctx.org.subscriptionEndsAt, 'MMMM d')+ : undefined;+ },+ recommendedPlan: async (ctx: OnboardingContext) => {+ const { eventsCount } = await ctx.getUsage();+ return getRecommendedPlan(+ eventsCount,+ (plan: { formattedEvents: string; formattedPrice: string }) =>+ `${plan.formattedEvents} events per month for ${plan.formattedPrice}`+ );+ },+} as const;++const ONBOARDING_EMAILS: SequenceStep<OnboardingContext>[] = [+ step<OnboardingContext, 'onboarding-welcome'>({+ day: 0,+ step: 'onboarding-welcome',+ template: 'onboarding-welcome',+ data: async (ctx) => ({+ firstName: getters.firstName(ctx),+ dashboardUrl: getters.dashboardUrl(ctx),+ hasData: (await ctx.getUsage()).hasData,+ }),+ }),+ step<OnboardingContext, 'onboarding-what-to-track'>({+ day: 2,+ step: 'onboarding-what-to-track',+ template: 'onboarding-what-to-track',+ data: async (ctx) => {+ const usage = await ctx.getUsage();+ return {+ firstName: getters.firstName(ctx),+ hasData: usage.hasData,+ eventsCount: usage.eventsCount,+ };+ },+ }),+ step<OnboardingContext, 'onboarding-dashboards'>({+ day: 6,+ step: 'onboarding-dashboards',+ template: 'onboarding-dashboards',+ data: async (ctx) => {+ const usage = await ctx.getUsage();+ return {+ firstName: getters.firstName(ctx),+ dashboardUrl: getters.dashboardUrl(ctx),+ hasData: usage.hasData,+ eventsCount: usage.eventsCount,+ };+ },+ }),+ step<OnboardingContext, 'onboarding-feature-request'>({+ day: 14,+ step: 'onboarding-feature-request',+ template: 'onboarding-feature-request',+ data: async (ctx) => ({+ firstName: getters.firstName(ctx),+ hasData: (await ctx.getUsage()).hasData,+ }),+ }),+ step<OnboardingContext, 'onboarding-trial-ending'>({+ day: 26,+ step: 'onboarding-trial-ending',+ template: 'onboarding-trial-ending',+ shouldSend: async ({ org }) => {+ if (org.subscriptionStatus === 'active') {+ return 'complete';+ }+ return true;+ },+ data: async (ctx) => {+ const usage = await ctx.getUsage();+ return {+ firstName: getters.firstName(ctx),+ billingUrl: getters.billingUrl(ctx),+ recommendedPlan: await getters.recommendedPlan(ctx),+ trialEndDate: getters.trialEndDate(ctx),+ hasData: usage.hasData,+ eventsCount: usage.eventsCount,+ };+ },+ }),+];++export type OnboardingCronLogger = Pick<Logger, 'info' | 'warn' | 'error'>;++export interface OnboardingCronSummary {+ totalOrgs: number;+ emailsSent: number;+ orgsCompleted: number;+ orgsSkipped: number;+}++export async function runOnboardingCron(+ logger: OnboardingCronLogger+): Promise<OnboardingCronSummary | null> {+ if (process.env.SELF_HOSTED === 'true') {+ return null;+ }++ logger.info('Starting onboarding email job');++ const db = await loadDb();+ const orgs: OnboardingCronOrg[] = await db.organization.findMany({+ where: {+ OR: [{ onboarding: null }, { onboarding: { notIn: ['completed'] } }],+ deleteAt: null,+ createdBy: { deletedAt: null },+ },+ include: {+ createdBy: {+ select: { id: true, email: true, firstName: true, deletedAt: true },+ },+ projects: { select: { id: true } },+ },+ });++ logger.info(`Found ${orgs.length} organizations in onboarding`);++ const contactable = orgs.filter(+ (org) => org.createdBy && !org.createdBy.deletedAt+ );+ const withoutCreator = orgs.length - contactable.length;++ const subjects: SequenceSubject<OnboardingContext>[] = contactable.map(+ (org) => {+ const user = org.createdBy as NonNullable<OnboardingCronOrg['createdBy']>;+ return {+ id: org.id,+ email: user.email,+ anchor: org.createdAt,+ pointer: org.onboarding,+ ctx: { org, user, getUsage: createUsageGetter(org) },+ };+ }+ );++ const result = await runSequence({+ name: 'onboarding',+ steps: ONBOARDING_EMAILS,+ subjects,+ logger,+ onAdvance: async (subject, stepName) => {+ await db.organization.update({+ where: { id: subject.id },+ data: { onboarding: stepName },+ });+ },+ onComplete: async (subject) => {+ await db.organization.update({+ where: { id: subject.id },+ data: { onboarding: 'completed' },+ });+ },+ });++ const summary: OnboardingCronSummary = {+ totalOrgs: orgs.length,+ emailsSent: result.emailsSent,+ orgsCompleted: result.completed,+ orgsSkipped: result.deferred + result.stepsSkipped + withoutCreator,+ };++ logger.info({ ...summary }, 'Completed onboarding email job');++ return summary;+}++export interface OnboardingService {+ runOnboardingCron(): Promise<OnboardingCronSummary | null>;+}++/** Registered in `services.ts`. Closes over `deps.logger`, the same value+ * `ctx.logger` is, so `ctx.services.onboarding.runOnboardingCron()` takes no+ * arguments — same shape as organization's `runDeleteCron`, which needs no+ * logger of its own at all. */+export function createOnboardingService(deps: ServiceDeps): OnboardingService {+ return {+ runOnboardingCron: () => runOnboardingCron(deps.logger),+ };+}diff --git a/packages/core/src/modules/organization/organization.jobs.test.ts b/packages/core/src/modules/organization/organization.jobs.test.tsindex 52b382436..955a5dcbe 100644--- a/packages/core/src/modules/organization/organization.jobs.test.ts+++ b/packages/core/src/modules/organization/organization.jobs.test.ts@@ -38,6 +38,7 @@ function stubJobCtx(import: {} as Services['import'],cohort: {} as Services['cohort'],organization: organization as OrganizationService,+ onboarding: {} as Services['onboarding'],};return {db: {},diff --git a/packages/core/src/rest.routes.ts b/packages/core/src/rest.routes.tsindex b8052cee2..8b5bd0a57 100644--- a/packages/core/src/rest.routes.ts+++ b/packages/core/src/rest.routes.ts@@ -9,6 +9,7 @@ import { Elysia } from 'elysia';import type { AppDeps } from './context';import { registry } from './metrics';import { assistantRoutes } from './modules/assistant/assistant.routes';+import { authRoutes } from './modules/auth/auth.routes';import { clientRoutes } from './modules/client/client.routes';import { gscRoutes } from './modules/gsc/gsc.routes';import { healthRoutes } from './modules/health/health.routes';@@ -43,17 +44,20 @@ export const publicApiRoutes = (deps: AppDeps) =>.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-// reachable in production yet: main.ts only mounts `dashboardRoutes` once a-// real `AppDeps` exists (P3/P4/P8) — see each module's own routes.ts header-// for its named gap. `/gsc` and `/mcp` are dashboard-scope routes absent from-// the CORS delegator's `corsPaths` allowlist (ADR-002 rule 4) — a quirk to-// port verbatim when app.ts wires CORS, not something to fix here.+// `/ai/agents/*` (M5-005), mcp's `/mcp` (M5-007) and auth's `/oauth/*`+// callbacks (M6-003) joined it. None is reachable in production yet: main.ts+// only mounts `dashboardRoutes` once a real `AppDeps` exists (P3/P4/P8) — see+// each module's own routes.ts header for its named gap. `/gsc` and `/mcp` are+// dashboard-scope routes absent from the CORS delegator's `corsPaths`+// allowlist (ADR-002 rule 4) and get `origin: '*'`; `/oauth` IS in+// `corsPaths` — a quirk to port verbatim when app.ts wires CORS, not+// something to fix here.export const dashboardRoutes = (deps: AppDeps) =>new Elysia({ name: 'core/dashboard-routes' }).use(gscRoutes(deps)).use(assistantRoutes(deps))- .use(mcpRoutes(deps));+ .use(mcpRoutes(deps))+ .use(authRoutes(deps));// healthz/metrics/misc share V1's ops surface (http/context.ts's// UNLOGGED_PATH_PREFIXES) — unauthenticated, uncorsed, unlogged. /metrics anddiff --git a/packages/core/src/rpc.router.ts b/packages/core/src/rpc.router.tsindex 54f582b63..edfc90f42 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 { authRouter } from './modules/auth/auth.rpc';import { clientRouter } from './modules/client/client.rpc';import { cohortRouter } from './modules/cohort/cohort.rpc';import { conversationRouter } from './modules/conversation/conversation.rpc';@@ -12,6 +13,7 @@ import { gscRouter } from './modules/gsc/gsc.rpc';import { healthRouter } from './modules/health/health.rpc';import { importRouter } from './modules/import/import.rpc';import { insightRouter } from './modules/insight/insight.rpc';+import { onboardingRouter } from './modules/onboarding/onboarding.rpc';import { organizationRouter } from './modules/organization/organization.rpc';import { projectRouter } from './modules/project/project.rpc';import { userRouter } from './modules/user/user.rpc';@@ -29,6 +31,8 @@ export const appRouter = createTRPCRouter({user: userRouter,project: projectRouter,client: clientRouter,+ auth: authRouter,+ onboarding: onboardingRouter,});export type AppRouter = typeof appRouter;diff --git a/packages/core/src/services.ts b/packages/core/src/services.tsindex b2139abd9..efa65b2d5 100644--- a/packages/core/src/services.ts+++ b/packages/core/src/services.ts@@ -20,6 +20,10 @@ import {createInsightService,type InsightService,} from './modules/insight/insight.service';+import {+ createOnboardingService,+ type OnboardingService,+} from './modules/onboarding/onboarding.service';import {createOrganizationService,type OrganizationService,@@ -47,6 +51,7 @@ export interface Services {cohort: CohortService;import: ImportService;organization: OrganizationService;+ onboarding: OnboardingService;}export function createServices(deps: ServiceDeps): Services {@@ -60,5 +65,6 @@ export function createServices(deps: ServiceDeps): Services {cohort: createCohortService(deps),import: createImportService(deps),organization: createOrganizationService(deps),+ onboarding: createOnboardingService(deps),};}diff --git a/packages/core/src/shared/email-sequence.test.ts b/packages/core/src/shared/email-sequence.test.tsnew file mode 100644index 000000000..fc327e865--- /dev/null+++ b/packages/core/src/shared/email-sequence.test.ts@@ -0,0 +1,237 @@+// Unit tests for the sequence runner. Moved from+// apps/worker/src/jobs/lib/email-sequence.test.ts (M6-003). `sendEmail` is+// mocked, so these assert decisions — which step fires, whether the pointer+// moves, whether side effects run — rather than delivery. `mock.module` is+// not hoisted, so the subject is imported inside `beforeAll` — see AGENTS.md.++import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';+import { subDays } from 'date-fns';++const sendEmail = mock(+ async (+ _template: string,+ _options: unknown+ ): Promise<Record<string, unknown> | null> => ({})+);+mock.module('../clients/email', () => ({ sendEmail }));++let runSequence: typeof import('./email-sequence').runSequence;+let step: typeof import('./email-sequence').step;+type SequenceStep<TCtx> = import('./email-sequence').SequenceStep<TCtx>;+type SequenceSubject<TCtx> = import('./email-sequence').SequenceSubject<TCtx>;++beforeAll(async () => {+ ({ runSequence, step } = await import('./email-sequence'));+});++interface Ctx {+ id: string;+}++const logger = {+ info: mock(() => undefined),+ warn: mock(() => undefined),+ error: mock(() => undefined),+};++function makeSteps(+ overrides: Partial<SequenceStep<Ctx>>[] = []+): SequenceStep<Ctx>[] {+ const base: SequenceStep<Ctx>[] = [+ step<Ctx, 'onboarding-welcome'>({+ day: 0,+ step: 'first',+ template: 'onboarding-welcome',+ data: () => ({ firstName: 'A', dashboardUrl: 'x', hasData: true }),+ }),+ step<Ctx, 'onboarding-dashboards'>({+ day: 10,+ step: 'second',+ template: 'onboarding-dashboards',+ data: () => ({ firstName: 'A', dashboardUrl: 'x', hasData: true }),+ }),+ ];+ return base.map((entry, index) => ({ ...entry, ...overrides[index] }));+}++function makeSubject(+ pointer: string | null,+ daysAgo: number+): SequenceSubject<Ctx> {+ return {+ id: 'subject-1',+ email: '[email protected]',+ anchor: subDays(new Date(), daysAgo),+ pointer,+ ctx: { id: 'subject-1' },+ };+}++function run(+ steps: SequenceStep<Ctx>[],+ subjects: SequenceSubject<Ctx>[],+ extra: Partial<Parameters<typeof runSequence<Ctx>>[0]> = {}+) {+ const onAdvance = mock(async () => undefined);+ const onComplete = mock(async () => undefined);+ return {+ onAdvance,+ onComplete,+ result: runSequence<Ctx>({+ name: 'test',+ steps,+ subjects,+ onAdvance,+ onComplete,+ logger,+ ...extra,+ }),+ };+}++beforeEach(() => {+ sendEmail.mockClear().mockResolvedValue({});+ logger.info.mockClear();+ logger.warn.mockClear();+ logger.error.mockClear();+});++test('sends the first step and advances the pointer', async () => {+ const { onAdvance, result } = run(makeSteps(), [makeSubject(null, 0)]);++ expect(await result).toMatchObject({ emailsSent: 1 });+ expect(sendEmail).toHaveBeenCalledWith('onboarding-welcome', {+ to: '[email protected]',+ data: expect.objectContaining({ firstName: 'A' }),+ });+ expect(onAdvance).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'subject-1' }),+ 'first'+ );+});++test('defers a step whose day gate has not been reached', async () => {+ const { onAdvance, result } = run(makeSteps(), [makeSubject('first', 3)]);++ expect(await result).toMatchObject({ emailsSent: 0, deferred: 1 });+ expect(sendEmail).not.toHaveBeenCalled();+ expect(onAdvance).not.toHaveBeenCalled();+});++test('completes rather than replays when the pointer is unknown', async () => {+ // The whole reason this branch exists: the old findIndex returned -1 for a+ // removed step, which restarted the sequence from the top.+ const { onAdvance, onComplete, result } = run(makeSteps(), [+ makeSubject('a-step-that-was-renamed', 40),+ ]);++ expect(await result).toMatchObject({ emailsSent: 0, completed: 1 });+ expect(sendEmail).not.toHaveBeenCalled();+ expect(onAdvance).not.toHaveBeenCalled();+ expect(onComplete).toHaveBeenCalledTimes(1);+});++test("advances past a step whose guard returns 'skip' and sends the next", async () => {+ const steps = makeSteps([{ shouldSend: async () => 'skip' as const }]);+ const { onAdvance, result } = run(steps, [makeSubject(null, 40)]);++ expect(await result).toMatchObject({ emailsSent: 1, stepsSkipped: 1 });+ expect(onAdvance).toHaveBeenNthCalledWith(1, expect.anything(), 'first');+ expect(onAdvance).toHaveBeenNthCalledWith(2, expect.anything(), 'second');+ expect(sendEmail).toHaveBeenCalledTimes(1);+ expect(sendEmail).toHaveBeenCalledWith(+ 'onboarding-dashboards',+ expect.anything()+ );+});++test('holds the pointer when a guard returns false', async () => {+ const steps = makeSteps([{ shouldSend: async () => false }]);+ const { onAdvance, result } = run(steps, [makeSubject(null, 40)]);++ expect(await result).toMatchObject({ emailsSent: 0, deferred: 1 });+ expect(onAdvance).not.toHaveBeenCalled();+});++test("finishes the sequence when a guard returns 'complete'", async () => {+ const steps = makeSteps([{ shouldSend: async () => 'complete' as const }]);+ const { onComplete, result } = run(steps, [makeSubject(null, 40)]);++ expect(await result).toMatchObject({ emailsSent: 0, completed: 1 });+ expect(onComplete).toHaveBeenCalledTimes(1);+ expect(sendEmail).not.toHaveBeenCalled();+});++test('completes once the last step has been sent', async () => {+ const { onComplete, result } = run(makeSteps(), [makeSubject('second', 40)]);++ expect(await result).toMatchObject({ completed: 1 });+ expect(onComplete).toHaveBeenCalledTimes(1);+});++test('completes when the final step is skipped', async () => {+ const steps = makeSteps([+ undefined as never,+ { shouldSend: async () => 'skip' as const },+ ]);+ const { onComplete, result } = run(steps, [makeSubject('first', 40)]);++ expect(await result).toMatchObject({ stepsSkipped: 1, completed: 1 });+ expect(onComplete).toHaveBeenCalledTimes(1);+});++test('runs onSent before advancing', async () => {+ const calls: string[] = [];+ const steps = makeSteps([+ {+ onSent: async () => {+ calls.push('onSent');+ },+ },+ ]);+ const onAdvance = mock(async () => {+ calls.push('advance');+ });++ await runSequence<Ctx>({+ name: 'test',+ steps,+ subjects: [makeSubject(null, 0)],+ onAdvance,+ onComplete: mock(async () => undefined),+ logger,+ });++ expect(calls).toEqual(['onSent', 'advance']);+});++test('requireDelivery: does not advance or run onSent when the send is suppressed', async () => {+ // sendEmail resolves null (rather than throwing) for a suppressed or+ // misconfigured send, which is exactly the case a destructive step must+ // not act on.+ sendEmail.mockResolvedValue(null);+ const onSent = mock(async () => undefined);+ const steps = makeSteps([{ requireDelivery: true, onSent }]);+ const { onAdvance, result } = run(steps, [makeSubject(null, 0)]);++ expect(await result).toMatchObject({ emailsSent: 0, failed: 1 });+ expect(onSent).not.toHaveBeenCalled();+ expect(onAdvance).not.toHaveBeenCalled();+ expect(logger.error).toHaveBeenCalled();+});++test('requireDelivery: advances a step without the flag even when the send is suppressed', async () => {+ sendEmail.mockResolvedValue(null);+ const { onAdvance, result } = run(makeSteps(), [makeSubject(null, 0)]);++ expect(await result).toMatchObject({ emailsSent: 1 });+ expect(onAdvance).toHaveBeenCalledWith(expect.anything(), 'first');+});++test('holds the pointer when the send throws', async () => {+ sendEmail.mockRejectedValue(new Error('smtp down'));+ const { onAdvance, result } = run(makeSteps(), [makeSubject(null, 0)]);++ expect(await result).toMatchObject({ emailsSent: 0, failed: 1 });+ expect(onAdvance).not.toHaveBeenCalled();+});diff --git a/packages/core/src/shared/email-sequence.ts b/packages/core/src/shared/email-sequence.tsnew file mode 100644index 000000000..2f0665e5e--- /dev/null+++ b/packages/core/src/shared/email-sequence.ts@@ -0,0 +1,262 @@+// Moved from apps/worker/src/jobs/lib/email-sequence.ts (M6-003). Shared by+// the onboarding drip (modules/onboarding) and, once it moves, the wind-down+// track (apps/worker/src/jobs/cron.wind-down.ts still reaches this through+// the re-export shim apps/worker keeps). `shared/`, not a module, because two+// modules need it (ADR-007 layout: "shared/ when several backend modules+// need it").+//+// A day-gated email sequence runner. Each subject carries a pointer (the+// last step whose email was sent) and an anchor date. On every tick the+// runner resolves the next step, checks the day gate and the step's own+// guard, sends, then advances the pointer.+//+// Three deliberate differences from the original inline implementation in+// cron.onboarding.ts, all of which matter once a sequence ends in deletion:+//+// 1. The pointer resolves by step name and an *unknown* name completes the+// sequence rather than restarting it. The old `findIndex` returned -1 for a+// renamed or removed step, which silently sent the subject back to step 0.+// 2. `'skip'` advances past a step; `false` only defers it. The old code had+// one value for both, so a step that should be passed over stalled the+// sequence permanently.+// 3. `requireDelivery` refuses to advance unless the email actually went out.+// `sendEmail` returns null instead of throwing when a send is suppressed or+// misconfigured, so a step with side effects could otherwise fire on an+// email nobody received.++import { differenceInDays } from 'date-fns';+import {+ type EmailData,+ type EmailTemplate,+ sendEmail,+} from '../clients/email';+import type { Logger } from '../logger';++/**+ * - `true` send it now+ * - `false` not yet — leave the pointer put and reconsider next tick+ * - `'skip'` doesn't apply to this subject — advance without sending+ * - `'complete'` the sequence is finished for this subject+ */+export type StepResult = boolean | 'skip' | 'complete';++export interface SequenceStep<TCtx, T extends EmailTemplate = EmailTemplate> {+ /** Whole days since the anchor before this step may fire. */+ day: number;+ /**+ * Stable identifier persisted as the pointer. Renaming one is a data+ * migration, not a refactor — see the unknown-pointer rule above.+ */+ step: string;+ template: T;+ /**+ * Only advance the pointer if the send is confirmed. Use for any step whose+ * `onSent` has consequences the subject was promised an email about.+ */+ requireDelivery?: boolean;+ shouldSend?: (ctx: TCtx) => Promise<StepResult>;+ data: (ctx: TCtx) => EmailData<T> | Promise<EmailData<T>>;+ /** Applied after a confirmed send, before the pointer advances. */+ onSent?: (ctx: TCtx) => Promise<void>;+}++/** Keeps `template` and `data` correlated; TS can't infer that from the array. */+export function step<TCtx, T extends EmailTemplate>(+ config: SequenceStep<TCtx, T>+): SequenceStep<TCtx, EmailTemplate> {+ return config as SequenceStep<TCtx, EmailTemplate>;+}++export interface SequenceSubject<TCtx> {+ /** For logging only. */+ id: string;+ /** Recipient address. */+ email: string;+ /** Day gates are measured from here. */+ anchor: Date;+ /** Last sent step, or null if the sequence hasn't started. */+ pointer: string | null;+ ctx: TCtx;+}++export interface SequenceResult {+ emailsSent: number;+ completed: number;+ /** Subjects left where they were (day gate or a `false` guard). */+ deferred: number;+ /** Steps advanced past without sending. */+ stepsSkipped: number;+ /** Sends that threw, or that `requireDelivery` rejected. */+ failed: number;+}++export interface RunSequenceOptions<TCtx> {+ /** Sequence name, for log lines. */+ name: string;+ steps: SequenceStep<TCtx, EmailTemplate>[];+ subjects: SequenceSubject<TCtx>[];+ /** Persist the pointer after a send or a skip. */+ onAdvance: (subject: SequenceSubject<TCtx>, step: string) => Promise<void>;+ /**+ * No steps remain, or a guard returned 'complete'. Omit it when the final+ * pointer must be preserved because something else reads it — a wind-down+ * org at 'final_warning' is still blocked from ingesting, so overwriting+ * that pointer with a completion sentinel would quietly unblock it.+ */+ onComplete?: (subject: SequenceSubject<TCtx>) => Promise<void>;+ logger: Pick<Logger, 'info' | 'warn' | 'error'>;+}++export async function runSequence<TCtx>({+ name,+ steps,+ subjects,+ onAdvance,+ onComplete,+ logger,+}: RunSequenceOptions<TCtx>): Promise<SequenceResult> {+ const result: SequenceResult = {+ emailsSent: 0,+ completed: 0,+ deferred: 0,+ stepsSkipped: 0,+ failed: 0,+ };+ const now = new Date();++ for (const subject of subjects) {+ const startIndex = resolveIndex(steps, subject.pointer);++ if (startIndex === 'unknown') {+ // A step that no longer exists. Completing is the safe reading — the+ // alternative is replaying the sequence from the top.+ logger.warn(+ { sequence: name, subject: subject.id, pointer: subject.pointer },+ 'Unknown sequence pointer, marking complete'+ );+ await onComplete?.(subject);+ result.completed++;+ continue;+ }++ // One tick can cross several steps when guards skip, but never more than+ // the sequence length.+ let index = startIndex + 1;++ while (index < steps.length) {+ const current = steps[index];+ if (!current) {+ break;+ }++ if (differenceInDays(now, subject.anchor) < current.day) {+ result.deferred++;+ break;+ }++ const guard = current.shouldSend+ ? await current.shouldSend(subject.ctx)+ : true;++ if (guard === 'complete') {+ await onComplete?.(subject);+ result.completed++;+ break;+ }++ if (guard === false) {+ result.deferred++;+ break;+ }++ if (guard === 'skip') {+ await onAdvance(subject, current.step);+ result.stepsSkipped++;+ index++;+ continue;+ }++ const sent = await sendStep({+ sequence: name,+ subject,+ step: current,+ logger,+ });++ if (!sent) {+ result.failed++;+ break;+ }++ await current.onSent?.(subject.ctx);+ await onAdvance(subject, current.step);+ result.emailsSent++;+ break;+ }++ if (index >= steps.length) {+ await onComplete?.(subject);+ result.completed++;+ }+ }++ logger.info({ sequence: name, ...result }, `Sequence ${name} tick`);++ return result;+}++function resolveIndex<TCtx>(+ steps: SequenceStep<TCtx, EmailTemplate>[],+ pointer: string | null+): number | 'unknown' {+ if (!pointer) {+ return -1;+ }+ const index = steps.findIndex((entry) => entry.step === pointer);+ return index === -1 ? 'unknown' : index;+}++async function sendStep<TCtx>({+ sequence,+ subject,+ step: current,+ logger,+}: {+ sequence: string;+ subject: SequenceSubject<TCtx>;+ step: SequenceStep<TCtx, EmailTemplate>;+ logger: Pick<Logger, 'info' | 'warn' | 'error'>;+}): Promise<boolean> {+ try {+ const data = await current.data(subject.ctx);++ const delivery = await sendEmail(current.template, {+ to: subject.email,+ data: data as never,+ });++ // A null return means suppressed, unparseable, or no provider configured —+ // note that a local environment without RESEND_API_KEY/SMTP_HOST always+ // lands here, so requireDelivery steps won't advance in dev.+ if (current.requireDelivery && delivery === null) {+ logger.error(+ {+ sequence,+ subject: subject.id,+ step: current.step,+ template: current.template,+ },+ 'Sequence email required delivery but was not sent, holding pointer'+ );+ return false;+ }++ return true;+ } catch (error) {+ logger.error(+ { err: error, sequence, subject: subject.id, step: current.step },+ 'Failed to send sequence email'+ );+ return false;+ }+}diff --git a/packages/trpc/src/routers/auth.ts b/packages/trpc/src/routers/auth.tsindex 9c67c35ba..c8cce9ed7 100644--- a/packages/trpc/src/routers/auth.ts+++ b/packages/trpc/src/routers/auth.ts@@ -1,38 +1,28 @@+// Dissolved into @openpanel/core's auth module (M6-003): sign-up/sign-in,+// TOTP challenges, password reset and share unlock moved to+// packages/core/src/modules/auth/auth.service.ts. This router stays+// (DELEGATE PATTERN) — it keeps V1's rate-limiting/protectedProcedure stack+// and delegates every handler body to core's auth functions, same as+// organization's router does (M6-001).+import {- Arctic,- buildOtpauthUrl,- COOKIE_OPTIONS,- consumeRecoveryCode,- deleteSessionTokenCookie,- generateQrDataUrl,- generateRecoveryCodes,- generateSecureId,- generateSessionToken,- generateTotpSecret,- github,- google,- hashUserPassword as hashPassword,- hashRecoveryCodes,- type Logger,- setLastAuthProviderCookie,- setSessionTokenCookie,- verifyPasswordHash,- verifyTotpCode,+ disableTotp,+ enableTotp,+ extendSessionCookie,+ getTotpStatus,+ regenerateTotpRecoveryCodes,+ requestPasswordReset,+ resetPasswordWithToken,+ setupTotp,+ signInToShare,+ signInWithEmail,+ signInWithTotp,+ signOutUser,+ signUpWithEmail,+ startOAuthSignIn,} from '@openpanel/core';import {- connectUserToOrganization,- createSession,- db,- decrypt,- encrypt,- getIsRegistrationAllowed,- getShareOverviewById,- getUserAccount,- invalidateSession,- validateSessionToken,-} from '@openpanel/db';-import { sendEmail } from '@openpanel/email';-import {+ zProvider,zRequestResetPassword,zResetPassword,zSignInEmail,@@ -42,7 +32,6 @@ import {zTotpOrRecoveryCode,} from '@openpanel/validation';import { z } from 'zod';-import { TRPCAccessError, TRPCNotFoundError } from '../errors';import {createTRPCRouter,protectedProcedure,@@ -50,615 +39,77 @@ import {rateLimitMiddleware,} from '../trpc';-const TWO_FACTOR_COOKIE = '2fa_challenge';-const TWO_FACTOR_CHALLENGE_TTL_SECONDS = 5 * 60;-const INVITE_COOKIE = 'inviteId';--const zProvider = z.enum(['email', 'google', 'github']);--/**- * Best-effort consumption of an invite for a user that just authenticated.- * Failures (expired/invalid invite) must not block the sign-in itself, so we- * swallow and log the error instead of rethrowing.- */-async function consumeInviteForUser(- userId: string,- inviteId: string,- log: Pick<Logger, 'error'>-) {- try {- const user = await db.user.findUniqueOrThrow({ where: { id: userId } });- await connectUserToOrganization({ user, inviteId });- } catch (error) {- log.error(- { userId, inviteId, error },- 'Failed to connect user to organization via invite'- );- }-}-export const authRouter = createTRPCRouter({signOut: publicProcedure.mutation(async ({ ctx }) => {- deleteSessionTokenCookie(ctx.setCookie);- if (ctx.session?.session?.id) {- await invalidateSession(ctx.session.session.id);- }+ await signOutUser(ctx.setCookie, ctx.session?.session?.id);}),signInOAuth: publicProcedure.input(z.object({ provider: zProvider, inviteId: z.string().nullish() }))- .mutation(async ({ input, ctx }) => {- // NOTE: no registration check here. At this point we have no identity for- // the caller — the IdP hasn't been hit yet — so we cannot tell a returning- // user from a new sign-up. Gating here locks out every existing OAuth user- // as soon as their session expires. The check lives in the OAuth callback- // (`handleNewUser`), which is the only place we know the user is new.- const { provider } = input;-- if (input.inviteId) {- ctx.setCookie('inviteId', input.inviteId, {- maxAge: 60 * 10,- });- }-- if (provider === 'github') {- const state = Arctic.generateState();- const url = github.createAuthorizationURL(state, [- 'user:email',- 'user:read',- ]);-- ctx.setCookie('github_oauth_state', state, {- maxAge: 60 * 10,- });-- return {- type: 'github',- url: url.toString(),- };- }-- const state = Arctic.generateState();- const codeVerifier = Arctic.generateCodeVerifier();- const url = google.createAuthorizationURL(state, codeVerifier, [- 'openid',- 'profile',- 'email',- ]);-- ctx.setCookie('google_oauth_state', state, {- maxAge: 60 * 10,- });- ctx.setCookie('google_code_verifier', codeVerifier, {- maxAge: 60 * 10,- });-- return {- type: 'google',- url: url.toString(),- };- }),+ .mutation(({ input, ctx }) => startOAuthSignIn(input, ctx.setCookie)),signUpEmail: publicProcedure- .use(- rateLimitMiddleware({- max: 5,- windowMs: 60_000,- })- )+ .use(rateLimitMiddleware({ max: 5, windowMs: 60_000 })).input(zSignUpEmail)- .mutation(async ({ input, ctx }) => {- const isRegistrationAllowed = await getIsRegistrationAllowed(- input.inviteId- );-- if (!isRegistrationAllowed) {- throw new TRPCAccessError('Registrations are not allowed');- }-- const provider = 'email';- const user = await getUserAccount({- email: input.email,- provider,- });-- if (user) {- throw new TRPCNotFoundError('User already exists');- }-- const createdUser = await db.user.create({- data: {- id: generateSecureId('user'),- email: input.email,- firstName: input.firstName,- lastName: input.lastName,- accounts: {- create: {- provider,- password: await hashPassword(input.password),- },- },- },- });-- if (input.inviteId) {- await connectUserToOrganization({- user: createdUser,- inviteId: input.inviteId,- });- }-- const token = generateSessionToken();- const session = await createSession(token, createdUser.id);-- setSessionTokenCookie(ctx.setCookie, token, session.expiresAt);- return session;- }),+ .mutation(({ input, ctx }) => signUpWithEmail(input, ctx.setCookie)),signInEmail: publicProcedure- .use(- rateLimitMiddleware({- max: 3,- windowMs: 30_000,- })- )+ .use(rateLimitMiddleware({ max: 3, windowMs: 30_000 })).input(zSignInEmail)- .mutation(async ({ input, ctx }) => {- const provider = 'email';- const password = input.password.trim();-- const user = await getUserAccount({- email: input.email,- provider,- });-- if (!user) {- throw new TRPCNotFoundError('User does not exists');- }-- if (provider === 'email') {- // if the password starts with $argon2 we use the new password hashing- // otherwise its legacy from Clerk which uses bcrypt- // TODO: Remove this after 2025-06-01 (half year from now)- if (user.account.password?.startsWith('$argon2')) {- const validPassword = await verifyPasswordHash(- user.account.password ?? '',- password- );-- if (!validPassword) {- throw new TRPCAccessError('Incorrect email or password');- }- } else {- throw new TRPCAccessError(- 'Reset your password, old password has expired'- );- }- }-- const totp = await db.userTotp.findUnique({- where: { userId: user.id },- });- if (totp?.enabledAt) {- const challengeId = generateSecureId('2fa');- await db.twoFactorChallenge.create({- data: {- id: challengeId,- userId: user.id,- expiresAt: new Date(- Date.now() + TWO_FACTOR_CHALLENGE_TTL_SECONDS * 1000- ),- },- });- ctx.setCookie(TWO_FACTOR_COOKIE, challengeId, {- maxAge: TWO_FACTOR_CHALLENGE_TTL_SECONDS,- });- // Carry the invite through the 2FA challenge so it can be consumed once- // the user completes the second factor in `signInTotp`.- if (input.inviteId) {- ctx.setCookie(INVITE_COOKIE, input.inviteId, {- maxAge: TWO_FACTOR_CHALLENGE_TTL_SECONDS,- });- }- return { type: 'totp_required' as const };- }-- const token = generateSessionToken();- const session = await createSession(token, user.id);- setSessionTokenCookie(ctx.setCookie, token, session.expiresAt);- setLastAuthProviderCookie(ctx.setCookie, 'email');-- if (input.inviteId) {- await consumeInviteForUser(user.id, input.inviteId, ctx.logger);- }-- return {- type: 'email' as const,- };- }),-+ .mutation(({ input, ctx }) =>+ signInWithEmail(input, ctx.setCookie, ctx.logger)+ ),signInTotp: publicProcedure- .use(- rateLimitMiddleware({- max: 5,- windowMs: 60_000,- })- )+ .use(rateLimitMiddleware({ max: 5, windowMs: 60_000 })).input(z.object({ code: zTotpOrRecoveryCode }))- .mutation(async ({ input, ctx }) => {- const challengeId = ctx.cookies.get(TWO_FACTOR_COOKIE);- if (!challengeId) {- throw new TRPCAccessError('No active two-factor challenge');- }+ .mutation(({ input, ctx }) =>+ signInWithTotp(input, ctx.cookies, ctx.setCookie, ctx.logger)+ ),- const challenge = await db.twoFactorChallenge.findUnique({- where: { id: challengeId },- });-- if (!challenge || challenge.expiresAt < new Date()) {- if (challenge) {- await db.twoFactorChallenge.delete({ where: { id: challenge.id } });- }- ctx.setCookie(TWO_FACTOR_COOKIE, '', { maxAge: 0 });- throw new TRPCAccessError('Two-factor challenge has expired');- }-- const totp = await db.userTotp.findUnique({- where: { userId: challenge.userId },- });- if (!totp?.enabledAt) {- await db.twoFactorChallenge.delete({ where: { id: challenge.id } });- ctx.setCookie(TWO_FACTOR_COOKIE, '', { maxAge: 0 });- throw new TRPCAccessError('Two-factor is not enabled');- }-- const secret = decrypt(totp.secret);- const isTotpCode = /^\d{6}$/.test(input.code.replace(/\s+/g, ''));- let valid = false;-- if (isTotpCode) {- valid = verifyTotpCode(secret, input.code);- } else {- const result = await consumeRecoveryCode({- hashes: totp.recoveryCodes,- input: input.code,- });- if (result.valid) {- valid = true;- await db.userTotp.update({- where: { userId: challenge.userId },- data: { recoveryCodes: result.remaining },- });- }- }-- if (!valid) {- throw new TRPCAccessError('Invalid code');- }-- await db.twoFactorChallenge.delete({ where: { id: challenge.id } });- ctx.setCookie(TWO_FACTOR_COOKIE, '', { maxAge: 0 });-- const token = generateSessionToken();- const session = await createSession(token, challenge.userId);- setSessionTokenCookie(ctx.setCookie, token, session.expiresAt);- setLastAuthProviderCookie(ctx.setCookie, 'email');-- const inviteId = ctx.cookies.get(INVITE_COOKIE);- if (inviteId) {- await consumeInviteForUser(challenge.userId, inviteId, ctx.logger);- ctx.setCookie(INVITE_COOKIE, '', { maxAge: 0 });- }-- return { type: 'email' as const };- }),-- totpStatus: protectedProcedure.query(async ({ ctx }) => {- const userId = ctx.session.userId!;- const [totp, emailAccount] = await Promise.all([- db.userTotp.findUnique({ where: { userId } }),- db.account.findFirst({- where: { userId, provider: 'email' },- select: { id: true },- }),- ]);- return {- enabled: Boolean(totp?.enabledAt),- enabledAt: totp?.enabledAt ?? null,- remainingRecoveryCodes: totp?.recoveryCodes.length ?? 0,- hasEmailProvider: Boolean(emailAccount),- };- }),+ totpStatus: protectedProcedure.query(({ ctx }) =>+ getTotpStatus(ctx.session.userId!)+ ),- totpSetup: protectedProcedure.mutation(async ({ ctx }) => {- const userId = ctx.session.userId!;- const emailAccount = await db.account.findFirst({- where: { userId, provider: 'email' },- select: { id: true },- });- if (!emailAccount) {- throw new TRPCAccessError(- 'Two-factor authentication is only available for email/password sign-ins. Your account uses a social provider, which handles 2FA on its end.'- );- }- const existing = await db.userTotp.findUnique({ where: { userId } });- if (existing?.enabledAt) {- throw new TRPCAccessError(- 'Two-factor is already enabled. Disable it first to re-configure.'- );- }-- const user = await db.user.findUniqueOrThrow({- where: { id: userId },- select: { email: true },- });-- const secret = generateTotpSecret();- const otpauthUrl = buildOtpauthUrl({- secret,- accountName: user.email,- });- const qrDataUrl = await generateQrDataUrl(otpauthUrl);-- await db.userTotp.upsert({- where: { userId },- create: {- userId,- secret: encrypt(secret),- recoveryCodes: [],- },- update: {- secret: encrypt(secret),- recoveryCodes: [],- enabledAt: null,- },- });-- return { otpauthUrl, qrDataUrl, secret };- }),+ totpSetup: protectedProcedure.mutation(({ ctx }) =>+ setupTotp(ctx.session.userId!)+ ),totpEnable: protectedProcedure.use(rateLimitMiddleware({ max: 5, windowMs: 60_000 })).input(z.object({ code: zTotpCode }))- .mutation(async ({ ctx, input }) => {- const userId = ctx.session.userId!;- const totp = await db.userTotp.findUnique({ where: { userId } });- if (!totp) {- throw new TRPCNotFoundError('Start two-factor setup first');- }- if (totp.enabledAt) {- throw new TRPCAccessError('Two-factor is already enabled');- }-- const secret = decrypt(totp.secret);- if (!verifyTotpCode(secret, input.code)) {- throw new TRPCAccessError('Invalid code');- }-- const recoveryCodes = generateRecoveryCodes();- const hashed = await hashRecoveryCodes(recoveryCodes);-- await db.userTotp.update({- where: { userId },- data: {- enabledAt: new Date(),- recoveryCodes: hashed,- },- });-- return { recoveryCodes };- }),+ .mutation(({ ctx, input }) => enableTotp(ctx.session.userId!, input.code)),totpDisable: protectedProcedure.use(rateLimitMiddleware({ max: 5, windowMs: 60_000 })).input(z.object({ code: zTotpOrRecoveryCode }))- .mutation(async ({ ctx, input }) => {- const userId = ctx.session.userId!;- const totp = await db.userTotp.findUnique({ where: { userId } });- if (!totp?.enabledAt) {- throw new TRPCAccessError('Two-factor is not enabled');- }-- const secret = decrypt(totp.secret);- const isTotpCode = /^\d{6}$/.test(input.code.replace(/\s+/g, ''));- const valid = isTotpCode- ? verifyTotpCode(secret, input.code)- : (- await consumeRecoveryCode({- hashes: totp.recoveryCodes,- input: input.code,- })- ).valid;-- if (!valid) {- throw new TRPCAccessError('Invalid code');- }-- await db.userTotp.delete({ where: { userId } });- await db.twoFactorChallenge.deleteMany({ where: { userId } });- return { disabled: true };- }),+ .mutation(({ ctx, input }) => disableTotp(ctx.session.userId!, input.code)),totpRegenerateRecoveryCodes: protectedProcedure.use(rateLimitMiddleware({ max: 3, windowMs: 60_000 })).input(z.object({ code: zTotpCode }))- .mutation(async ({ ctx, input }) => {- const userId = ctx.session.userId!;- const totp = await db.userTotp.findUnique({ where: { userId } });- if (!totp?.enabledAt) {- throw new TRPCAccessError('Two-factor is not enabled');- }- const secret = decrypt(totp.secret);- if (!verifyTotpCode(secret, input.code)) {- throw new TRPCAccessError('Invalid code');- }- const recoveryCodes = generateRecoveryCodes();- const hashed = await hashRecoveryCodes(recoveryCodes);- await db.userTotp.update({- where: { userId },- data: { recoveryCodes: hashed },- });- return { recoveryCodes };- }),+ .mutation(({ ctx, input }) =>+ regenerateTotpRecoveryCodes(ctx.session.userId!, input.code)+ ),resetPassword: publicProcedure.input(zResetPassword)- .use(- rateLimitMiddleware({- max: 3,- windowMs: 60_000,- })- )- .mutation(async ({ input, ctx }) => {- const { token, password } = input;-- const resetPassword = await db.resetPassword.findUnique({- where: {- id: token,- },- });-- if (!resetPassword) {- throw new TRPCNotFoundError('Reset password not found');- }-- if (resetPassword.expiresAt < new Date()) {- throw new TRPCNotFoundError('Reset password expired');- }-- await db.account.update({- where: { id: resetPassword.accountId },- data: {- password: await hashPassword(password),- },- });-- await db.resetPassword.delete({- where: { id: token },- });-- return true;- }),+ .use(rateLimitMiddleware({ max: 3, windowMs: 60_000 }))+ .mutation(({ input }) => resetPasswordWithToken(input)),requestResetPassword: publicProcedure- .use(- rateLimitMiddleware({- max: 3,- windowMs: 60_000,- })- )+ .use(rateLimitMiddleware({ max: 3, windowMs: 60_000 })).input(zRequestResetPassword)- .mutation(async ({ input, ctx }) => {- const user = await getUserAccount({- email: input.email,- provider: 'email',- });+ .mutation(({ input }) => requestPasswordReset(input)),- if (!user) {- return true;- }+ session: publicProcedure.query(({ ctx }) => ctx.session),- if (!user.account.id) {- return true;- }-- await db.resetPassword.deleteMany({- where: {- accountId: user.account.id,- },- });-- const token = generateSecureId('pw');- // expires in 10 minutes- const expiresAt = new Date(Date.now() + 1000 * 60 * 10);-- await db.resetPassword.create({- data: {- id: token,- expiresAt,- accountId: user.account.id,- },- });-- await sendEmail('reset-password', {- to: input.email,- data: {- url: `${process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL}/reset-password?token=${token}`,- },- });-- return true;- }),- session: publicProcedure.query(async ({ ctx }) => {- return ctx.session;- }),-- extendSession: publicProcedure.mutation(async ({ ctx }) => {- const token = ctx.cookies.get('session');- if (!(ctx.session.session && token)) {- return { extended: false };- }-- const session = await validateSessionToken(token);-- if (session.session) {- // Re-set the cookie with updated expiration- setSessionTokenCookie(ctx.setCookie, token, session.session.expiresAt);- return {- extended: true,- expiresAt: session.session.expiresAt,- };- }-- return { extended: false };- }),+ extendSession: publicProcedure.mutation(({ ctx }) =>+ extendSessionCookie(+ ctx.cookies,+ Boolean(ctx.session.session),+ ctx.setCookie+ )+ ),signInShare: publicProcedure- .use(- rateLimitMiddleware({- max: 3,- windowMs: 30_000,- })- )+ .use(rateLimitMiddleware({ max: 3, windowMs: 30_000 })).input(zSignInShare)- .mutation(async ({ input, ctx }) => {- const { password, shareId, shareType = 'overview' } = input;- let share: { password: string | null; public: boolean } | null = null;- let cookieName = '';-- if (shareType === 'overview') {- share = await getShareOverviewById(shareId);- cookieName = `shared-overview-${shareId}`;- } else if (shareType === 'dashboard') {- const { getShareDashboardById } = await import('@openpanel/db');- share = await getShareDashboardById(shareId);- cookieName = `shared-dashboard-${shareId}`;- } else if (shareType === 'report') {- const { getShareReportById } = await import('@openpanel/db');- share = await getShareReportById(shareId);- cookieName = `shared-report-${shareId}`;- }-- if (!share) {- throw new TRPCNotFoundError('Share not found');- }-- if (!share.public) {- throw new TRPCNotFoundError('Share is not public');- }-- if (!share.password) {- throw new TRPCNotFoundError('Share is not password protected');- }-- const validPassword = await verifyPasswordHash(share.password, password);-- if (!validPassword) {- throw new TRPCAccessError('Incorrect password');- }-- ctx.setCookie(cookieName, '1', {- maxAge: 60 * 60 * 24 * 7,- ...COOKIE_OPTIONS,- });-- return true;- }),+ .mutation(({ input, ctx }) => signInToShare(input, ctx.setCookie)),});diff --git a/packages/trpc/src/routers/onboarding.ts b/packages/trpc/src/routers/onboarding.tsindex ae72a131e..c010de227 100644--- a/packages/trpc/src/routers/onboarding.ts+++ b/packages/trpc/src/routers/onboarding.ts@@ -1,143 +1,21 @@-import crypto from 'node:crypto';-import { stripTrailingSlash } from '@openpanel/common';-import { hashPassword } from '@openpanel/core';-import type { IServiceUser, ProjectType } from '@openpanel/db';-import { db, getId, getOrganizationById, getUserById } from '@openpanel/db';+// Dissolved into @openpanel/core's onboarding module (M6-003): the+// org+project+client creation and the "can I skip onboarding" check moved to+// packages/core/src/modules/onboarding/onboarding.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 onboarding functions, same as organization's router does+// (M6-001).+import { canSkipOnboarding, createOnboardingProject } from '@openpanel/core';import { zOnboardingProject } from '@openpanel/validation';-import { addDays } from 'date-fns';-import type { z } from 'zod';import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc';-async function createOrGetOrganization(- input: z.infer<typeof zOnboardingProject>,- user: IServiceUser-) {- if (input.organizationId) {- return await getOrganizationById(input.organizationId);- }-- const TRIAL_DURATION_IN_DAYS = 30;- // Generous trial allowance so trialing orgs never get flagged as- // "limit exceeded" (the limit defaults to 0, which trips on the first event).- const TRIAL_EVENTS_LIMIT = 10_000_000;-- if (input.organization) {- const organizationId = await getId('organization', input.organization);-- // Create the organization and its owner (org:admin member) atomically. The- // `delete` cron treats an organization with no org:admin member as ownerless- // and removes it, so an organization must never exist without one.- const [organization] = await db.$transaction([- db.organization.create({- data: {- id: organizationId,- name: input.organization,- createdByUserId: user.id,- subscriptionEndsAt: addDays(new Date(), TRIAL_DURATION_IN_DAYS),- subscriptionStatus: 'trialing',- subscriptionPeriodEventsLimit: TRIAL_EVENTS_LIMIT,- timezone: input.timezone,- onboarding: '',- },- }),- db.member.create({- data: {- email: user.email,- organizationId,- role: 'org:admin',- userId: user.id,- },- }),- ]);-- return organization;- }-- return null;-}-export const onboardingRouter = createTRPCRouter({- skipOnboardingCheck: publicProcedure.query(async ({ ctx }) => {- if (!ctx.session.userId) {- return { canSkip: false, url: null };- }-- const members = await db.member.findMany({- where: {- userId: ctx.session.userId,- },- });-- if (members.length > 0) {- return {- canSkip: true,- };- }-- const projectAccess = await db.projectAccess.findMany({- where: {- userId: ctx.session.userId,- },- });-- if (projectAccess.length > 0) {- return {- canSkip: true,- };- }-- return { canSkip: false };- }),+ skipOnboardingCheck: publicProcedure.query(({ ctx }) =>+ canSkipOnboarding(ctx.session.userId)+ ),project: protectedProcedure.input(zOnboardingProject)- .mutation(async ({ input, ctx }) => {- const types: ProjectType[] = [];- if (input.website) {- types.push('website');- }- if (input.app) {- types.push('app');- }- if (input.backend) {- types.push('backend');- }-- const user = await getUserById(ctx.session.userId);- const organization = await createOrGetOrganization(input, user);-- if (!organization?.id) {- throw new Error('Organization slug is missing');- }-- if (input.cors.length === 0 && input.website) {- input.cors.push('*');- }-- const project = await db.project.create({- data: {- id: await getId('project', input.project),- name: input.project,- organizationId: organization.id,- types,- domain: input.domain ? stripTrailingSlash(input.domain) : null,- cors: input.cors.map((c) => stripTrailingSlash(c)),- },- });-- const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;- const client = await db.client.create({- data: {- name: `${project.name} Client`,- organizationId: organization.id,- projectId: project.id,- type: 'write',- secret: await hashPassword(secret),- },- });-- return {- ...client,- secret,- };- }),+ .mutation(({ input, ctx }) =>+ createOnboardingProject(input, ctx.session.userId!)+ ),});diff --git a/packages/validation/src/index.ts b/packages/validation/src/index.tsindex 22bcd1e6c..a2eb7d450 100644--- a/packages/validation/src/index.ts+++ b/packages/validation/src/index.ts@@ -376,55 +376,12 @@ export const zCreateReference = z.object({datetime: z.string(),});-export const zOnboardingProject = z- .object({- organization: z.string().optional(),- organizationId: z.string().optional(),- project: z.string().min(3),- domain: z.string().url().or(z.literal('').or(z.null())),- cors: z.array(z.string()).default([]),- website: z.boolean(),- app: z.boolean(),- backend: z.boolean(),- timezone: z.string().optional(),- })- .superRefine((data, ctx) => {- if (!(data.organization || data.organizationId)) {- ctx.addIssue({- code: 'custom',- message: 'Organization is required',- path: ['organization'],- });- ctx.addIssue({- code: 'custom',- message: 'Organization is required',- path: ['organizationId'],- });- }-- if (data.website && !data.domain) {- ctx.addIssue({- code: 'custom',- message: 'Domain is required for website tracking',- path: ['domain'],- });- }-- if (- data.website === false &&- data.app === false &&- data.backend === false- ) {- for (const key of ['app', 'backend', 'website']) {- ctx.addIssue({- code: 'custom',- message: 'At least one type must be selected',- path: [key],- });- }- }- });-+// Moved into @openpanel/core's onboarding module (M6-003, ADR-008's module+// map: onboarding owns "C"). Re-exported here for existing+// @openpanel/validation importers (packages/trpc's onboarding/project+// routers, apps/start's onboarding flow) — same shape as+// ./cohort.validation.ts since M5-003.+export * from '@openpanel/core/modules/onboarding/onboarding.constants';export * from './integrations';export const zNotificationRuleEventConfig = z.object({@@ -509,62 +466,11 @@ export const zProjectUpdate = z.object({});export type IProjectUpdate = z.infer<typeof zProjectUpdate>;-export const zPassword = z.string().min(8);--export const zSignInEmail = z.object({- email: z.string().email().min(1),- password: zPassword,- inviteId: z.string().nullish(),-});-export type ISignInEmail = z.infer<typeof zSignInEmail>;--export const zSignUpEmail = z- .object({- firstName: z.string().min(1),- lastName: z.string().min(1),- email: z.string().email(),- password: zPassword,- confirmPassword: zPassword,- inviteId: z.string().nullish(),- })- .refine((data) => data.password === data.confirmPassword, {- path: ['confirmPassword'],- message: 'Passwords do not match',- });-export type ISignUpEmail = z.infer<typeof zSignUpEmail>;--export const zResetPassword = z.object({- token: z.string(),- password: z.string().min(8),-});-export type IResetPassword = z.infer<typeof zResetPassword>;--export const zRequestResetPassword = z.object({- email: z.string().email(),-});-export type IRequestResetPassword = z.infer<typeof zRequestResetPassword>;--export const zTotpCode = z- .string()- .transform((v) => v.replace(/\s+/g, ''))- .refine((v) => /^\d{6}$/.test(v), { message: 'Enter a 6-digit code' });-export type ITotpCode = z.infer<typeof zTotpCode>;--export const zTotpOrRecoveryCode = z- .string()- .min(1)- .transform((v) => v.trim());-export type ITotpOrRecoveryCode = z.infer<typeof zTotpOrRecoveryCode>;--export const zSignInShare = z.object({- password: z.string().min(1),- shareId: z.string().min(1),- shareType: z- .enum(['overview', 'dashboard', 'report'])- .optional()- .default('overview'),-});-export type ISignInShare = z.infer<typeof zSignInShare>;+// Moved into @openpanel/core's auth module (M6-003, ADR-008's module map:+// auth owns "C"). Re-exported here for existing @openpanel/validation+// importers (packages/trpc's auth router, apps/start's sign-in/sign-up+// forms) — same shape as ./cohort.validation.ts since M5-003.+export * from '@openpanel/core/modules/auth/auth.constants';export const zCheckout = z.object({productPriceId: z.string(),diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 5d7d1d830..ffa380583 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1124,6 +1124,9 @@ importers:'@openpanel/email':specifier: workspace:*version: link:../email+ '@openpanel/payments':+ specifier: workspace:*+ version: link:../payments'@openpanel/redis':specifier: workspace:*version: link:../redis@@ -1157,6 +1160,9 @@ importers:csv-parse:specifier: ^6.1.0version: 6.1.0+ date-fns:+ specifier: ^3.3.1+ version: 3.3.1elysia:specifier: 1.4.30version: 1.4.30(@sinclair/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])