OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M6-006): integration + subscription modules into core (slack + polar webhooks)
ralphf820e24dfe7c
diff --git a/apps/api/src/controllers/webhook.controller.ts b/apps/api/src/controllers/webhook.controller.tsindex 8ca78fffc..f9b9f112a 100644--- a/apps/api/src/controllers/webhook.controller.ts+++ b/apps/api/src/controllers/webhook.controller.ts@@ -5,16 +5,18 @@ import { fileURLToPath } from 'node:url';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);-import { tryCatch } from '@openpanel/common';+// Dissolved into @openpanel/core's integration + subscription modules+// (M6-006): the Slack token-exchange/upsert logic moved to+// integration.service.ts's `completeSlackOAuthCallback`, and the Polar event+// validation/dispatch logic moved to subscription.service.ts's+// `handlePolarWebhookEvent`. This controller stays the LIVE route (DELEGATE+// PATTERN) — it keeps Fastify's `rawBody` config (signature verification+// breaks on any body parsing) and delegates to those functions, the same+// function core's own `/webhook/slack` and `/webhook/polar` routes call.import {- safeWebhookFetcher,- sendSlackNotification,- slackInstaller,+ completeSlackOAuthCallback,+ handlePolarWebhookEvent,} from '@openpanel/core';-import { db, getOrganizationByProjectIdCached, Prisma } from '@openpanel/db';-import { getProduct, validatePolarEvent } from '@openpanel/payments';-import { publishEvent } from '@openpanel/redis';-import { zSlackAuthResponse } from '@openpanel/validation';import type { FastifyReply, FastifyRequest } from 'fastify';import { z } from 'zod';@@ -23,14 +25,6 @@ const paramsSchema = z.object({state: z.string(),});-const metadataSchema = z.object({- organizationId: z.string(),- integrationId: z.string(),- // Optional for back-compat with install URLs generated before integrations- // became project-scoped; the post-install redirect falls back to the org page.- projectId: z.string().optional(),-});-export async function slackWebhook(request: FastifyRequest<{Querystring: unknown;@@ -44,525 +38,41 @@ export async function slackWebhook(return reply.status(400).send({ error: 'Invalid params' });}- const veryfiedState = await slackInstaller.stateStore?.verifyStateParam(- new Date(),- parsedParams.data.state- );- const parsedMetadata = metadataSchema.safeParse(- JSON.parse(veryfiedState?.metadata ?? '{}')- );-- if (!parsedMetadata.success) {- request.log.error(parsedMetadata.error, 'Invalid metadata');- return reply.status(400).send({ error: 'Invalid metadata' });- }-- const slackOauthAccessUrl = [- 'https://slack.com/api/oauth.v2.access',- `?client_id=${process.env.SLACK_CLIENT_ID}`,- `&client_secret=${process.env.SLACK_CLIENT_SECRET}`,- `&code=${parsedParams.data.code}`,- `&redirect_uri=${process.env.SLACK_OAUTH_REDIRECT_URL}`,- ].join('');-try {- const response = await fetch(slackOauthAccessUrl);- const json = await response.json();- const parsedJson = zSlackAuthResponse.safeParse(json);-- if (!parsedJson.success) {- request.log.error(- {- zod: parsedJson,- json,- },- 'Failed to parse slack auth response'- );- const html = fs.readFileSync(path.join(__dirname, 'error.html'), 'utf8');- return reply.status(500).header('Content-Type', 'text/html').send(html);- }-- // Send a notification first to confirm the connection- await sendSlackNotification({- fetcher: safeWebhookFetcher,- webhookUrl: parsedJson.data.incoming_webhook.url,- message:- '👋 Hello. You have successfully connected OpenPanel.dev to your Slack workspace.',- });-- const { organizationId, integrationId, projectId } = parsedMetadata.data;-- await db.integration.update({- where: {- id: integrationId,- organizationId,- },- data: {- config: {- type: 'slack',- ...parsedJson.data,- },- },- });+ const { organizationId, projectId } = await completeSlackOAuthCallback(+ parsedParams.data+ );const dashboardUrl =process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL;- // Integrations are project-scoped; the org-level integrations route no longer- // exists. Newer installs carry projectId in their metadata. Older in-flight- // installs (started before the project-scoped routes shipped) may lack it —- // fall back to the org landing page rather than a now-404 integrations URL.+ // Integrations are project-scoped; the org-level integrations route no+ // longer exists. Newer installs carry projectId in their metadata. Older+ // in-flight installs (started before the project-scoped routes shipped)+ // may lack it — fall back to the org landing page rather than a now-404+ // integrations URL.return reply.redirect(projectId? `${dashboardUrl}/${organizationId}/${projectId}/integrations/installed`: `${dashboardUrl}/${organizationId}`);} catch (err) {- request.log.error(err);+ request.log.error(err, 'Slack OAuth callback error');const html = fs.readFileSync(path.join(__dirname, 'error.html'), 'utf8');return reply.status(500).header('Content-Type', 'text/html').send(html);}}-async function clearOrganizationCache(organizationId: string) {- const projects = await db.project.findMany({- where: {- organizationId,- },- });- for (const project of projects) {- await getOrganizationByProjectIdCached.clear(project.id);- }-}--type PolarEvent = ReturnType<typeof validatePolarEvent>;-type PolarSubscriptionData = Extract<- PolarEvent,- { type: 'subscription.updated' }->['data'];--const subscriptionMetadataSchema = z.object({- organizationId: z.string(),- // `userId` is only used for the `subscriptionCreatedByUserId` audit field, so- // it is optional — a missing one must not block syncing the subscription.- userId: z.string().optional(),-});--// Org columns whose before→after transition is logged on every sync.-const TRACKED_SUBSCRIPTION_FIELDS = [- 'subscriptionId',- 'subscriptionStatus',- 'subscriptionProductId',- 'subscriptionPriceId',- 'subscriptionStartsAt',- 'subscriptionEndsAt',- 'subscriptionCanceledAt',- 'subscriptionCancelReason',- 'subscriptionInterval',- 'subscriptionPeriodEventsLimit',- 'subscriptionPauseAtPeriodEnd',- 'subscriptionResumesAt',- 'subscriptionFirstStartedAt',-] as const;--const CANCELLATION_REASONS = [- 'too_expensive',- 'missing_features',- 'switched_service',- 'unused',- 'customer_service',- 'low_quality',- 'too_complex',- 'other',-] as const;--type CancellationReason = (typeof CANCELLATION_REASONS)[number];--// Polar types the reason as an open enum (unknown strings can appear); only-// store values our own union knows about.-function parseCancellationReason(- reason: string | null | undefined-): CancellationReason | null {- return CANCELLATION_REASONS.includes(reason as CancellationReason)- ? (reason as CancellationReason)- : null;-}--type PolarSubscriptionDiscount = PolarSubscriptionData['discount'];--// Compact summary of Polar's embedded discount object so the dashboard can-// show that a discount is active (save offer or any Polar discount code).-export function toSubscriptionDiscount(- discount: PolarSubscriptionDiscount-): PrismaJson.IPrismaSubscriptionDiscount | null {- if (!discount) {- return null;- }- return {- id: discount.id,- name: discount.name,- type: discount.type === 'fixed' ? 'fixed' : 'percentage',- basisPoints: 'basisPoints' in discount ? discount.basisPoints : null,- amount: 'amount' in discount ? discount.amount : null,- currency: 'currency' in discount ? discount.currency : null,- duration:- discount.duration === 'repeating'- ? 'repeating'- : discount.duration === 'forever'- ? 'forever'- : 'once',- durationInMonths:- 'durationInMonths' in discount ? discount.durationInMonths : null,- };-}--const normalizeLogValue = (value: unknown) =>- value instanceof Date ? value.toISOString() : (value ?? null);--// Builds a `{ field: { from, to } }` map of changed columns. `undefined`-// after-values are skipped — Prisma reads them as "leave the column untouched".-function diffOrganizationFields(- before: Record<string, unknown>,- after: Record<string, unknown>,- fields: readonly string[]-) {- const changes: Record<string, { from: unknown; to: unknown }> = {};- for (const field of fields) {- if (after[field] === undefined) {- continue;- }- const from = normalizeLogValue(before[field]);- const to = normalizeLogValue(after[field]);- if (from !== to) {- changes[field] = { from, to };- }- }- return changes;-}--/**- * Syncs the full Polar subscription state onto the organization. Used for every- * `subscription.*` event (created, active, updated, canceled, revoked,- * past_due, uncanceled) since they all carry the same Subscription object and- * `status` drives the rest. This covers new subscriptions, cancellations,- * reactivations, plan changes and payment-state changes in one place.- */-async function syncSubscriptionToOrg(- data: PolarSubscriptionData,- eventType: string,- log: FastifyRequest['log']-) {- const metadata = subscriptionMetadataSchema.parse(data.metadata);- const isCanceled = data.status === 'canceled';-- const organization = await db.organization.findUniqueOrThrow({- where: {- id: metadata.organizationId,- },- });-- // An organization maps to a single subscription in our DB, but can have- // several in Polar (e.g. after re-subscribing). A canceled/revoked event for- // a subscription that is no longer the org's current one must not clobber the- // newer active subscription.- if (isCanceled && organization.subscriptionId !== data.id) {- log.info(- {- organizationId: metadata.organizationId,- eventType,- eventSubscriptionId: data.id,- orgSubscriptionId: organization.subscriptionId,- },- 'polar webhook: ignoring canceled event for non-current subscription'- );- return;- }-- // Polar can deliver subscription events out of order: at renewal the new- // period can arrive first, then a stale event for the *previous* period lands- // a few seconds later. A billing period never moves backwards, so for the- // same subscription we ignore any event whose period starts before the one we- // already stored — otherwise the stale event resets the org to the expired- // period and the usage counter (recomputed over that window) gets stuck.- if (- organization.subscriptionId === data.id &&- organization.subscriptionStartsAt &&- data.currentPeriodStart < organization.subscriptionStartsAt- ) {- log.info(- {- organizationId: metadata.organizationId,- eventType,- eventSubscriptionId: data.id,- eventPeriodStart: data.currentPeriodStart,- storedPeriodStart: organization.subscriptionStartsAt,- },- 'polar webhook: ignoring stale subscription event (older billing period)'- );- return;- }-- const product = await getProduct(data.productId);- const rawEventsLimit = product.metadata?.eventsLimit;- const parsedEventsLimit =- typeof rawEventsLimit === 'number'- ? rawEventsLimit- : typeof rawEventsLimit === 'string'- ? Number(rawEventsLimit)- : Number.NaN;- const hasValidEventsLimit = Number.isFinite(parsedEventsLimit);- const subscriptionPeriodEventsLimit = hasValidEventsLimit- ? parsedEventsLimit- : organization.subscriptionPeriodEventsLimit;-- if (!hasValidEventsLimit) {- log.warn(- { product },- 'No valid eventsLimit on product, preserving existing organization limit'- );- }-- const updateData = {- subscriptionId: data.id,- subscriptionCustomerId: data.customer.id,- subscriptionPriceId: data.prices[0]?.id ?? null,- subscriptionProductId: data.productId,- subscriptionStatus: data.status,- subscriptionStartsAt: data.currentPeriodStart,- subscriptionCanceledAt: data.canceledAt,- subscriptionEndsAt: isCanceled- ? data.cancelAtPeriodEnd- ? data.currentPeriodEnd- : data.canceledAt- : data.currentPeriodEnd,- subscriptionInterval: data.recurringInterval,- // Cancellation feedback + pause state mirror Polar so portal-driven cancels- // and pauses are captured too (our in-app flows also set them via the API,- // which just echoes back through here).- subscriptionCancelReason: parseCancellationReason(- data.customerCancellationReason- ),- subscriptionCancelComment: data.customerCancellationComment ?? null,- subscriptionPauseAtPeriodEnd: data.pauseAtPeriodEnd,- subscriptionResumesAt: data.resumesAt,- subscriptionDiscount:- toSubscriptionDiscount(data.discount) ?? Prisma.DbNull,- // Stable tenure anchor: keep the stored value while the subscription id is- // unchanged; a new subscription (re-subscribe) restarts tenure.- subscriptionFirstStartedAt:- organization.subscriptionId === data.id- ? (organization.subscriptionFirstStartedAt ?? data.createdAt)- : data.createdAt,- subscriptionPeriodEventsLimit,- subscriptionPeriodEventsCountExceededAt:- typeof subscriptionPeriodEventsLimit === 'number' &&- organization.subscriptionPeriodEventsCountExceededAt &&- typeof organization.subscriptionPeriodEventsLimit === 'number' &&- organization.subscriptionPeriodEventsLimit < subscriptionPeriodEventsLimit- ? null- : undefined,- // A raised limit re-arms the usage alerts for the new headroom.- ...(typeof subscriptionPeriodEventsLimit === 'number' &&- typeof organization.subscriptionPeriodEventsLimit === 'number' &&- organization.subscriptionPeriodEventsLimit < subscriptionPeriodEventsLimit- ? { usageWarningSentAt: null, usageExceededSentAt: null }- : {}),- // Reaching checkout takes the org out of the wind-down population for good- // — that sequence only targets trials that never had a subscription — so- // release the ingestion block and any scheduled deletion. Guarded on the- // org actually being in wind-down so we never clear a `deleteAt` the owner- // set themselves. The wind-down cron re-checks this too, for the webhook we- // never receive.- ...(organization.windDownStartedAt- ? { windDownStartedAt: null, windDownStep: null, deleteAt: null }- : {}),- };-- const changes = diffOrganizationFields(- organization as unknown as Record<string, unknown>,- updateData as unknown as Record<string, unknown>,- TRACKED_SUBSCRIPTION_FIELDS- );-- await db.organization.update({- where: {- id: metadata.organizationId,- },- data: updateData,- });-- await clearOrganizationCache(metadata.organizationId);-- await publishEvent('organization', 'subscription_updated', {- organizationId: metadata.organizationId,- });-- log.info(- {- organizationId: metadata.organizationId,- eventType,- subscriptionId: data.id,- previousStatus: organization.subscriptionStatus,- status: data.status,- changes,- },- Object.keys(changes).length > 0- ? `polar webhook: synced subscription for ${metadata.organizationId} (${Object.keys(changes).join(', ')} changed)`- : `polar webhook: synced subscription for ${metadata.organizationId} (no field changes)`- );-}-export async function polarWebhook(request: FastifyRequest<{Querystring: unknown;}>,reply: FastifyReply) {- // Don't log the raw body: it can carry customer free text (e.g. the- // cancellation comment) that the logger's redaction patterns don't cover.- // `eventCtx` is logged right after validation instead.- request.log.info('polar webhook received');-- const validation = await tryCatch(async () =>- validatePolarEvent(- request.rawBody!,- request.headers as Record<string, string>,- process.env.POLAR_WEBHOOK_SECRET ?? ''- )+ await handlePolarWebhookEvent(+ request.rawBody!,+ request.headers as Record<string, string>,+ request.log);- if (!validation.ok) {- request.log.error(- { err: validation.error },- 'polar webhook: failed to parse event'- );- throw validation.error;- }-- const event = validation.data;-- const eventOrganizationId =- 'metadata' in event.data &&- event.data.metadata &&- typeof event.data.metadata === 'object' &&- 'organizationId' in event.data.metadata- ? String(event.data.metadata.organizationId)- : undefined;-- const eventCtx = {- eventType: event.type,- eventId: 'id' in event.data ? event.data.id : undefined,- organizationId: eventOrganizationId,- };-- request.log.info(- eventCtx,- `polar webhook: processing ${event.type}${eventOrganizationId ? ` for ${eventOrganizationId}` : ''}`- );-- if (- 'data' in event &&- 'product' in event.data &&- event.data.product?.name === 'Supporter'- ) {- request.log.info(eventCtx, 'polar webhook: supporter event ignored');- return reply.status(202).send('OK');- }-- const handler = await tryCatch(async () => {- switch (event.type) {- // A new paid billing cycle resets the org's usage counter. Polar sends- // `order.updated` (not `order.created`) and the order moves through- // pending -> paid, so we only act on the `paid` + `subscription_cycle`- // transition. Re-deliveries of the same paid order just reset to 0 again,- // which is harmless (and safely under-counts at worst).- case 'order.updated': {- if (- event.data.billingReason !== 'subscription_cycle' ||- event.data.status !== 'paid'- ) {- request.log.info(- { ...eventCtx, billingReason: event.data.billingReason },- 'polar webhook: order.updated ignored (not a paid billing cycle)'- );- return;- }-- const metadata = z- .object({- organizationId: z.string(),- })- .parse(event.data.metadata);-- const previous = await db.organization.findUnique({- where: { id: metadata.organizationId },- select: { subscriptionPeriodEventsCount: true },- });-- await db.organization.update({- where: {- id: metadata.organizationId,- },- data: {- subscriptionPeriodEventsCount: 0,- subscriptionPeriodEventsCountExceededAt: null,- // New cycle — the usage alerts may fire again.- usageWarningSentAt: null,- usageExceededSentAt: null,- },- });-- await clearOrganizationCache(metadata.organizationId);-- request.log.info(- {- ...eventCtx,- previousEventsCount: previous?.subscriptionPeriodEventsCount,- },- `polar webhook: new billing cycle for ${metadata.organizationId}, reset usage counter ${previous?.subscriptionPeriodEventsCount ?? 0} -> 0`- );- return;- }- // All subscription lifecycle events carry the same Subscription object;- // sync them through a single path (new subs, cancellations, revokes,- // reactivations, plan changes, payment-state changes).- // Pause/resume transitions arrive via `subscription.updated` (the SDK's- // webhook union has no dedicated paused/reactivated payloads yet) and are- // reflected in `status` / `pauseAtPeriodEnd` / `resumesAt` below.- case 'subscription.created':- case 'subscription.active':- case 'subscription.updated':- case 'subscription.uncanceled':- case 'subscription.canceled':- case 'subscription.revoked':- case 'subscription.past_due': {- await syncSubscriptionToOrg(event.data, event.type, request.log);- return;- }- default: {- request.log.info(- eventCtx,- 'polar webhook: unhandled event type, acking'- );- }- }- });-- if (!handler.ok) {- request.log.error(- { err: handler.error, ...eventCtx },- `polar webhook: ${event.type} handler failed`- );- throw handler.error;- }-return reply.status(202).send('OK');}--function isToday(date: Date) {- const today = new Date();- return (- date.getDate() === today.getDate() &&- date.getMonth() === today.getMonth() &&- date.getFullYear() === today.getFullYear()- );-}diff --git a/packages/core/src/clients/integrations/discord.ts b/packages/core/src/clients/integrations/discord.tsindex 85a98910d..e70a0265c 100644--- a/packages/core/src/clients/integrations/discord.ts+++ b/packages/core/src/clients/integrations/discord.ts@@ -1,6 +1,7 @@// Ported from @openpanel/integrations (dissolved into core — M4-005).// Cred to (@OpenStatusHQ) https://github.com/openstatusHQ/openstatus/blob/main/packages/notifications/discord/src/index.ts+import { DISCORD_TEST_NOTIFICATION_MESSAGE } from '../../modules/integration/integration.constants';import {browserFetcher,postWebhook,@@ -36,7 +37,6 @@ export function sendTestDiscordNotification(return sendDiscordNotification({webhookUrl,fetcher,- message:- '**🧪 Test [OpenPanel.dev](<https://openpanel.dev/>)**\nIf you can read this, your Slack webhook is functioning correctly!\n',+ message: DISCORD_TEST_NOTIFICATION_MESSAGE,});}diff --git a/packages/core/src/clients/integrations/object-store/gcs-adapter.ts b/packages/core/src/clients/integrations/object-store/gcs-adapter.tsindex b3d396f4e..eaf407ccc 100644--- a/packages/core/src/clients/integrations/object-store/gcs-adapter.ts+++ b/packages/core/src/clients/integrations/object-store/gcs-adapter.ts@@ -3,7 +3,7 @@ import { Storage } from '@google-cloud/storage';import {type IGCSExportConfig,parseServiceAccountKey,-} from '@openpanel/validation';+} from '../../../modules/integration/integration.constants';import { decryptCredential } from '../../../shared/encryption';import { createLogger, type ILogger } from '../../logger';import type {diff --git a/packages/core/src/clients/integrations/object-store/s3-adapter.ts b/packages/core/src/clients/integrations/object-store/s3-adapter.tsindex 86cb80091..6c1c042ce 100644--- a/packages/core/src/clients/integrations/object-store/s3-adapter.ts+++ b/packages/core/src/clients/integrations/object-store/s3-adapter.ts@@ -9,7 +9,7 @@ import {S3Client,} from '@aws-sdk/client-s3';import { AssumeRoleCommand, STSClient } from '@aws-sdk/client-sts';-import type { IS3ExportConfig } from '@openpanel/validation';+import type { IS3ExportConfig } from '../../../modules/integration/integration.constants';import { decryptCredential } from '../../../shared/encryption';import { assertSafeUrl, createPinnedLookup } from '../../../shared/ssrf';import { createLogger, type ILogger } from '../../logger';diff --git a/packages/core/src/clients/integrations/registry.ts b/packages/core/src/clients/integrations/registry.tsindex 080e54bbb..623b0ba29 100644--- a/packages/core/src/clients/integrations/registry.ts+++ b/packages/core/src/clients/integrations/registry.ts@@ -1,5 +1,8 @@// Ported from @openpanel/integrations (dissolved into core — M4-005).-import { type IIntegrationConfig, looksEncrypted } from '@openpanel/validation';+import {+ type IIntegrationConfig,+ looksEncrypted,+} from '../../modules/integration/integration.constants';import { encryptCredential } from '../../shared/encryption';import {execute as executeJavaScriptTemplate,diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex bcfdda231..99e9f7ea4 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -134,6 +134,12 @@ export type {ChatRunContext,FilterCommandResult,} from './modules/assistant/assistant.service';+// Slack's OAuth token-exchange wire contract (M6-006) — not integration+// config (stays out of the `*.constants` subpath, see+// modules/integration/src/slack-contract.ts's header), but apps/api's+// webhook controller still needs it to validate Slack's `oauth.v2.access`+// response, the same way it reaches slackInstaller above.+export { zSlackAuthResponse } from './modules/integration/src/slack-contract';import type { PageContext } from './modules/assistant/assistant.constants';@@ -339,6 +345,56 @@ export {selectGscSite,syncGscData,} from './modules/gsc/gsc.service';+// Moved from packages/trpc/src/routers/integration.ts, plus the Slack OAuth+// callback business logic out of+// apps/api/src/controllers/webhook.controller.ts (M6-006, ADR-008's module+// map: integration owns "S"+"C") — packages/trpc's integration router and+// apps/api's webhook controller call these directly, the same way V1 reaches+// every other dissolved service here.+export type { CompleteSlackOAuthCallbackResult } from './modules/integration/integration.service';+export {+ completeSlackOAuthCallback,+ createOrUpdateSlackIntegration,+ deleteIntegration,+ getIntegrationById,+ listIntegrationsForProject,+ SlackOAuthCallbackError,+ testExportIntegrationConnection,+ testIntegrationConnection,+ upsertIntegration,+} from './modules/integration/integration.service';+// Dissolved from @openpanel/db's services/notification.service.ts (M6-005,+// "rules + dispatch stay together") — packages/trpc's notification router,+// packages/db's own enqueue orchestration (createNotification et al, which+// stays there — see that file's header for why) and apps/worker's+// notification job all call these directly, the same way V1 reaches every+// other dissolved service here. packages/db/src/services/notification.service.ts+// stays a re-export shim for the pieces that moved.+export type {+ INotificationPayload,+ INotificationRuleCached,+ NotificationService,+} from './modules/notification/notification.service';+export {+ APP_NOTIFICATION_INTEGRATION_ID,+ BASE_INTEGRATIONS,+ createNotificationService,+ createOrUpdateNotificationRule,+ deleteNotificationRule,+ deliverNotification,+ EMAIL_NOTIFICATION_INTEGRATION_ID,+ getFunnelRules,+ getHasFunnelRules,+ getNotificationRuleByIdOrThrow,+ getNotificationRulesByProjectId,+ isBaseIntegration,+ listNotificationRules,+ listNotifications,+ matchEvent,+ matchEventFilters,+ notificationTemplateEvent,+ notificationTemplateFunnel,+} from './modules/notification/notification.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@@ -404,38 +460,6 @@ export {updateOrganization,updateOrganizationMemberAccess,} from './modules/organization/organization.service';-// Dissolved from @openpanel/db's services/notification.service.ts (M6-005,-// "rules + dispatch stay together") — packages/trpc's notification router,-// packages/db's own enqueue orchestration (createNotification et al, which-// stays there — see that file's header for why) and apps/worker's-// notification job all call these directly, the same way V1 reaches every-// other dissolved service here. packages/db/src/services/notification.service.ts-// stays a re-export shim for the pieces that moved.-export type {- INotificationPayload,- INotificationRuleCached,- NotificationService,-} from './modules/notification/notification.service';-export {- APP_NOTIFICATION_INTEGRATION_ID,- BASE_INTEGRATIONS,- createNotificationService,- createOrUpdateNotificationRule,- deleteNotificationRule,- deliverNotification,- EMAIL_NOTIFICATION_INTEGRATION_ID,- getFunnelRules,- getHasFunnelRules,- getNotificationRuleByIdOrThrow,- getNotificationRulesByProjectId,- isBaseIntegration,- listNotificationRules,- listNotifications,- matchEvent,- matchEventFilters,- notificationTemplateEvent,- notificationTemplateFunnel,-} from './modules/notification/notification.service';// Dissolved from @openpanel/db's services/project.service.ts (M6-002) —// packages/trpc's project router, apps/api's manage controller and several// core modules' `src/access.ts` call these directly, the same way V1@@ -499,8 +523,8 @@ export {createShareReport,getShareByProjectId,getShareDashboard,- getShareDashboardById,getShareDashboardByDashboardId,+ getShareDashboardById,getShareDashboardReports,getShareDashboardSettings,getShareOverview,@@ -514,6 +538,25 @@ export {validateReportAccess,validateShareAccess,} from './modules/share/share.service';+// Moved from packages/trpc/src/routers/subscription.ts, plus the Polar+// webhook business logic out of+// apps/api/src/controllers/webhook.controller.ts (M6-006, ADR-008's module+// map: subscription owns "S"+"C") — packages/trpc's subscription router and+// apps/api's webhook controller call these directly, the same way V1 reaches+// every other dissolved service here.+export {+ applySaveDiscount,+ cancelSubscription,+ checkout,+ getCurrentSubscriptionProduct,+ getUsage,+ handlePolarWebhookEvent,+ listProducts,+ pauseSubscription,+ portal,+ resumeSubscription,+ toSubscriptionDiscount,+} from './modules/subscription/subscription.service';// Dissolved from @openpanel/db's services/user.service.ts (M6-001) —// packages/trpc's auth/onboarding routers call `getUserById`/// `getUserAccount` directly through @openpanel/db's re-export shim, the samediff --git a/packages/validation/src/integrations.test.ts b/packages/core/src/modules/integration/integration.constants.test.tssimilarity index 93%rename from packages/validation/src/integrations.test.tsrename to packages/core/src/modules/integration/integration.constants.test.tsindex 39655dfda..b4d542d04 100644--- a/packages/validation/src/integrations.test.ts+++ b/packages/core/src/modules/integration/integration.constants.test.ts@@ -1,10 +1,13 @@-import { describe, expect, it } from 'vitest';+// Ported from packages/validation/src/integrations.test.ts (M6-006, vitest ->+// bun:test per the module map).++import { describe, expect, it } from 'bun:test';import {isKind,parseServiceAccountKey,zGCSExportConfig,zS3ExportConfig,-} from './integrations';+} from './integration.constants';describe('isKind', () => {it('matches a declared capability', () => {@@ -44,7 +47,7 @@ describe('parseServiceAccountKey', () => {}expect(result.credentials.project_id).toBe('openpanel-test');expect(result.credentials.client_email).toBe(- '[email protected]',);});@@ -54,7 +57,7 @@ describe('parseServiceAccountKey', () => {...JSON.parse(SERVICE_ACCOUNT),credential_source: { file: '/proc/self/environ' },token_url: 'https://attacker.example/collect',- }),+ }));expect(result.ok).toBe(true);if (!result.ok) {@@ -75,7 +78,7 @@ describe('parseServiceAccountKey', () => {subject_token_type: 'urn:ietf:params:oauth:token-type:jwt',token_url: 'https://attacker.example/collect',credential_source: { file: '/proc/self/environ' },- }),+ }));expect(result.ok).toBe(false);if (result.ok) {@@ -100,8 +103,8 @@ describe('parseServiceAccountKey', () => {expect(parseServiceAccountKey('"a string"').ok).toBe(false);expect(parseServiceAccountKey(- JSON.stringify({ type: 'service_account', project_id: 'p' }),- ).ok,+ JSON.stringify({ type: 'service_account', project_id: 'p' })+ ).ok).toBe(false);});});@@ -124,7 +127,7 @@ describe('write-only secrets', () => {it('allows a blank credential (means "keep the stored one" on update)', () => {expect(- zGCSExportConfig.safeParse({ ...base, serviceAccountKey: '' }).success,+ zGCSExportConfig.safeParse({ ...base, serviceAccountKey: '' }).success).toBe(true);});@@ -133,7 +136,7 @@ describe('write-only secrets', () => {zGCSExportConfig.safeParse({...base,serviceAccountKey: JSON.stringify({ type: 'external_account' }),- }).success,+ }).success).toBe(false);});@@ -149,7 +152,7 @@ describe('write-only secrets', () => {authMode: 'access_key',accessKeyId: 'AKIA',secretAccessKey: 'enc:c29tZS1jaXBoZXJ0ZXh0',- }).success,+ }).success).toBe(false);});});diff --git a/packages/validation/src/integrations.ts b/packages/core/src/modules/integration/integration.constants.tssimilarity index 89%rename from packages/validation/src/integrations.tsrename to packages/core/src/modules/integration/integration.constants.tsindex 63e5d901f..b46cb20d4 100644--- a/packages/validation/src/integrations.ts+++ b/packages/core/src/modules/integration/integration.constants.ts@@ -1,3 +1,16 @@+// Moved from packages/validation/src/integrations.ts (M6-006, ADR-008's+// module map: integration owns "C"). packages/validation/src/index.ts becomes+// a re-export shim of this file (same shape as ./notification.constants.ts+// since M6-005), so packages/trpc's integration router and apps/start's+// integration forms keep resolving these symbols through+// @openpanel/validation's existing barrel unchanged.+//+// `zSlackAuthResponse` does NOT move here even though it is zod-only and+// would pass `constants-stay-isomorphic`: it is Slack's OAuth token-exchange+// wire contract, not integration config a form validates against — nothing+// in apps/start ever sees it. It stays in `./src/slack-contract.ts`, defined+// as `zSlackConfig` minus the persisted `type` discriminant (see that file).+import { z } from 'zod';// ---------------------------------------------------------------------------@@ -108,7 +121,13 @@ export function parseServiceAccountKey(raw: string): IServiceAccountKeyResult {// Per-type config schemas// ----------------------------------------------------------------------------export const zSlackAuthResponse = z.object({+// The Slack integration's persisted config is exactly Slack's OAuth+// token-exchange response (`oauth.v2.access`) plus our own `type` tag —+// `./src/slack-contract.ts`'s `zSlackAuthResponse` is this schema minus+// `type`, kept the other direction (constants owns the shape, src derives+// from it) so the two can never drift.+export const zSlackConfig = z.object({+ type: z.literal('slack'),ok: z.literal(true),app_id: z.string(),authed_user: z.object({@@ -129,12 +148,6 @@ export const zSlackAuthResponse = z.object({url: z.string().url(),}),});--export const zSlackConfig = z- .object({- type: z.literal('slack'),- })- .extend(zSlackAuthResponse.shape);export type ISlackConfig = z.infer<typeof zSlackConfig>;export const zWebhookConfig = z.object({@@ -469,3 +482,13 @@ type _DescriptorTypes = (typeof INTEGRATION_DESCRIPTORS)[number]['type'];type _AssertDescriptorCoverage = Assert<Equal<IIntegrationType, _DescriptorTypes>>;++// ---------------------------------------------------------------------------+// Discord test-notification wording (previously hardcoded in+// clients/integrations/discord.ts's `sendTestDiscordNotification` as a+// copy-pasted Slack message — "your Slack webhook is functioning correctly!"+// on a Discord test send). Named and fixed here per the module map.+// ---------------------------------------------------------------------------++export const DISCORD_TEST_NOTIFICATION_MESSAGE =+ '**🧪 Test [OpenPanel.dev](<https://openpanel.dev/>)**\nIf you can read this, your Discord webhook is functioning correctly!\n';diff --git a/packages/core/src/modules/integration/integration.routes.ts b/packages/core/src/modules/integration/integration.routes.tsnew file mode 100644index 000000000..02bc93ffe--- /dev/null+++ b/packages/core/src/modules/integration/integration.routes.ts@@ -0,0 +1,64 @@+// The Slack OAuth callback (M6-006), `GET /webhook/slack`. V1's Fastify+// controller (apps/api/src/controllers/webhook.controller.ts's `slackWebhook`)+// stays the LIVE route (DELEGATE PATTERN) and delegates its token-exchange/+// upsert logic to integration.service.ts's `completeSlackOAuthCallback` — the+// same function this route calls, same shape as gsc.routes.ts (M5-002) /+// auth.routes.ts (M6-003).+//+// NAMED GAP, same as those two: this route is not yet reachable — main.ts+// does not mount `publicApiRoutes` until a real `AppDeps` exists (P3/P4/P8).+// V1's controller also renders an HTML error page from a local `error.html`+// file on failure; this route redirects to `/login?error=...` instead (same+// simplification gsc.routes.ts/auth.routes.ts already made for their own+// OAuth callbacks) since it serves no traffic yet.++import { redirect } from 'elysia';+import { z } from 'zod';+import { defineRoutes } from '../../http/define';+import { completeSlackOAuthCallback } from './integration.service';++const slackCallbackQuery = 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) {+ const url = new URL('/login', dashboardUrl() || 'http://localhost');+ url.searchParams.set('error', message);+ return redirect(url.toString());+}++export const integrationRoutes = defineRoutes((app) =>+ app.get(+ '/webhook/slack',+ async ({ query, ctx }) => {+ try {+ const { organizationId, projectId } =+ await completeSlackOAuthCallback(query);++ // Integrations are project-scoped; the org-level integrations route no+ // longer exists. Newer installs carry projectId in their metadata.+ // Older in-flight installs (started before the project-scoped routes+ // shipped) may lack it — fall back to the org landing page rather+ // than a now-404 integrations URL.+ return redirect(+ projectId+ ? `${dashboardUrl()}/${organizationId}/${projectId}/integrations/installed`+ : `${dashboardUrl()}/${organizationId}`+ );+ } catch (error) {+ ctx.logger.error({ err: error }, 'Slack OAuth callback error');+ const message =+ error instanceof Error ? error.message : 'An error occurred';+ return loginErrorRedirect(message);+ }+ },+ { query: slackCallbackQuery, detail: { hide: true } }+ )+);diff --git a/packages/core/src/modules/integration/integration.rpc.ts b/packages/core/src/modules/integration/integration.rpc.tsnew file mode 100644index 000000000..0454ec7a2--- /dev/null+++ b/packages/core/src/modules/integration/integration.rpc.ts@@ -0,0 +1,111 @@+// Ported from packages/trpc/src/routers/integration.ts (M6-006).+//+// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware+// stack — lands in core with auth (rpc/base.ts: "those need the resolved+// Session shape and the access rules, so they land with auth (P6)"). Until+// then this router does its own minimal "is anyone logged in" check inline,+// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route+// through packages/trpc's own `protectedProcedure` (full stack included) and+// delegates its handler bodies to core's integration functions (DELEGATE+// PATTERN), so nothing here is a live regression.+//+// Every access assertion (including the data-dependent "authorize against the+// EXISTING row" rule) lives in integration.service.ts, not here — see that+// file's header for why.++import { z } from 'zod';+import { createTRPCRouter, procedure } from '../../rpc/base';+import { TRPCAccessError } from '../../rpc/errors';+import {+ zCreateGCSExportIntegration,+ zCreateS3ExportIntegration,+ zCreateSlackIntegration,+ zIntegrationConfig,+} from './integration.constants';+import {+ createOrUpdateSlackIntegration,+ deleteIntegration,+ getIntegrationById,+ listIntegrationsForProject,+ testExportIntegrationConnection,+ testIntegrationConnection,+ upsertIntegration,+} from './integration.service';++function requireLogin(userId: string | null | undefined): string {+ if (!userId) {+ throw new TRPCAccessError('Not authenticated');+ }+ return userId;+}++export const integrationRouter = createTRPCRouter({+ get: procedure+ .input(z.object({ id: z.string() }))+ .query(({ input, ctx }) =>+ getIntegrationById(requireLogin(ctx.session.userId), input.id)+ ),++ list: procedure+ .input(z.object({ projectId: z.string() }))+ .query(({ input, ctx }) =>+ listIntegrationsForProject(+ requireLogin(ctx.session.userId),+ input.projectId+ )+ ),++ createOrUpdateSlack: procedure+ .input(zCreateSlackIntegration)+ .mutation(({ input, ctx }) =>+ createOrUpdateSlackIntegration(requireLogin(ctx.session.userId), input)+ ),++ // Generic create/update for any form-configured integration. Per-type+ // behavior lives in the server plugin; no switch here.+ createOrUpdate: procedure+ .input(+ z.object({+ id: z.string().optional(),+ name: z.string().min(1),+ projectId: z.string().min(1),+ config: zIntegrationConfig,+ })+ )+ .mutation(({ input, ctx }) =>+ upsertIntegration(requireLogin(ctx.session.userId), input)+ ),++ // Back-compat alias for the export forms; delegates to the same generic path.+ // TODO: remove once the dashboard calls `createOrUpdate` directly.+ createOrUpdateExport: procedure+ .input(z.union([zCreateS3ExportIntegration, zCreateGCSExportIntegration]))+ .mutation(({ input, ctx }) =>+ upsertIntegration(requireLogin(ctx.session.userId), input)+ ),++ testConnection: procedure+ .input(+ z.object({+ projectId: z.string().min(1),+ config: zIntegrationConfig,+ })+ )+ .mutation(({ input, ctx }) =>+ testIntegrationConnection(requireLogin(ctx.session.userId), input)+ ),++ // Back-compat alias for the export forms; same gate as `testConnection`.+ // TODO: remove once the dashboard calls `testConnection` directly.+ testExportConnection: procedure+ .input(z.union([zCreateS3ExportIntegration, zCreateGCSExportIntegration]))+ .mutation(({ input, ctx }) =>+ testExportIntegrationConnection(requireLogin(ctx.session.userId), input)+ ),++ delete: procedure+ .input(z.object({ id: z.string() }))+ .mutation(({ input: { id }, ctx }) =>+ deleteIntegration(requireLogin(ctx.session.userId), id)+ ),+});diff --git a/packages/core/src/modules/integration/integration.service.ts b/packages/core/src/modules/integration/integration.service.tsnew file mode 100644index 000000000..e4d580a48--- /dev/null+++ b/packages/core/src/modules/integration/integration.service.ts@@ -0,0 +1,455 @@+// Moved from packages/trpc/src/routers/integration.ts (M6-006, ADR-008's+// module map: integration owns "S"+"C"). V1's router stays the LIVE route+// (DELEGATE PATTERN) and delegates every handler body to these functions,+// same as notification's router does (M6-005).+//+// Authorization here is data-dependent — an update must authorize against the+// EXISTING row's scope, not the attacker-controlled input — so, unlike the+// simple input-shape ladder checks project.rpc.ts/notification.rpc.ts do+// themselves, the access assertions travel WITH the business logic, ported+// verbatim from the router's own `assertProjectAccessAndGetOrg`/+// `assertIntegrationAccess` helpers. `./src/access.ts` binds the shared+// ladder to @openpanel/db, the same way every other module's does.+//+// db access is LAZY (`loadDb` below), not a static top-level import — see+// organization.service.ts's header for the full reasoning (constructing+// @openpanel/db's clients at import time would spawn a pino-pretty transport+// worker thread per test file).++import { z } from 'zod';+import {+ carryOverConfigSecrets,+ encryptConfigSecrets,+ findEncryptedSecretField,+ findMissingSecretFields,+ getServerIntegration,+ redactConfigSecrets,+} from '../../clients/integrations/registry';+import { safeWebhookFetcher } from '../../clients/integrations/safe-fetcher';+import {+ getSlackInstallUrl,+ sendSlackNotification,+ slackInstaller,+} from '../../clients/integrations/slack';+import { TRPCBadRequestError, TRPCForbiddenError } from '../../rpc/errors';+import { BASE_INTEGRATIONS } from '../notification/notification.service';+import type { IIntegrationConfig, ISlackConfig } from './integration.constants';+import { zSlackAuthResponse } from './src/slack-contract';++function loadDb() {+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);+}++function loadAccess() {+ return import('./src/access');+}++// Credentials are write-only: they are encrypted at rest and never travel back+// to a client. `read` on a project is bare membership, so returning the stored+// ciphertext would hand every project member the org's object-store keys — and+// because `decryptCredential` accepts any `enc:` blob under the single global+// key, that ciphertext is a replayable bearer token, not an opaque handle.+function redactIntegration<T extends { config: unknown }>(integration: T): T {+ const config = redactConfigSecrets(integration.config);+ return config === integration.config+ ? integration+ : { ...integration, config };+}++// A client never legitimately holds a ciphertext (see redactIntegration), so+// one arriving on the wire is an attempt to replay a secret lifted from another+// integration into an attacker-chosen destination.+function rejectEncryptedSecrets(config: unknown) {+ const field = findEncryptedSecretField(config);+ if (field) {+ throw new TRPCBadRequestError(+ `\`${field}\` looks like a stored, already-encrypted value. Paste the real credential, or leave it blank to keep the current one.`+ );+ }+}++// Assert the user can act on the project at `level`, and return the project's+// organizationId (still stored on the integration for org-level queries/cascades).+async function assertProjectAccessAndGetOrg(+ userId: string,+ projectId: string,+ level: 'read' | 'write'+) {+ const { requireProjectAccess } = await loadAccess();+ await requireProjectAccess({ userId, projectId, level });++ const db = await loadDb();+ const project = await db.project.findUniqueOrThrow({+ where: { id: projectId },+ select: { organizationId: true },+ });+ return project.organizationId;+}++// Access check for an existing integration of either scope. Project-scoped rows+// go through the project ladder; legacy org-wide rows (projectId null) have no+// project access level to consult, so a write to one — it is shared by every+// project in the org — is admin-tier, while a read only needs membership.+async function assertIntegrationAccess(+ userId: string,+ integration: { projectId: string | null; organizationId: string },+ level: 'read' | 'write'+) {+ const {+ getOrganizationAccess,+ requireOrganizationAdmin,+ requireProjectAccess,+ } = await loadAccess();++ if (integration.projectId) {+ await requireProjectAccess({+ userId,+ projectId: integration.projectId,+ level,+ });+ return;+ }++ if (level === 'write') {+ await requireOrganizationAdmin({+ userId,+ organizationId: integration.organizationId,+ message: 'Only organization admins can change an org-wide integration',+ });+ return;+ }++ const access = await getOrganizationAccess({+ userId,+ organizationId: integration.organizationId,+ });+ if (!access) {+ throw new TRPCForbiddenError('You do not have access to this integration');+ }+}++export async function getIntegrationById(userId: string, id: string) {+ const db = await loadDb();+ const integration = await db.integration.findUniqueOrThrow({+ where: { id },+ });++ await assertIntegrationAccess(userId, integration, 'read');++ return redactIntegration(integration);+}++export async function listIntegrationsForProject(+ userId: string,+ projectId: string+) {+ const organizationId = await assertProjectAccessAndGetOrg(+ userId,+ projectId,+ 'read'+ );++ const db = await loadDb();+ const integrations = await db.integration.findMany({+ where: {+ // The project's own integrations, plus legacy org-wide integrations+ // (projectId null) so they stay visible/selectable during the+ // transition off org-scoping.+ OR: [{ projectId }, { projectId: null, organizationId }],+ config: {+ not: {},+ },+ },+ });++ return [...BASE_INTEGRATIONS, ...integrations.map(redactIntegration)];+}++// Credentials are write-only: they are encrypted at rest and never travel back+// to a client. `read` on a project is bare membership, so returning the stored+// ciphertext would hand every project member the org's object-store keys — and+// because `decryptCredential` accepts any `enc:` blob under the single global+// key, that ciphertext is a replayable bearer token, not an opaque handle.+//+// Shared create/update path for any form-configured integration. All per-type+// behavior (validation, connection test, credential encryption) is delegated to+// the integration's server plugin — adding a new integration needs no change here.+export async function upsertIntegration(+ userId: string,+ input: {+ id?: string;+ name: string;+ projectId: string;+ config: IIntegrationConfig;+ }+) {+ // Authorize first. For an update, authorize against the EXISTING integration's+ // scope — not the attacker-controlled input.projectId — so a user with access+ // to one project can't update another project's integration in the same org.+ rejectEncryptedSecrets(input.config);++ const db = await loadDb();++ let organizationId: string;+ let storedConfig: unknown;+ if (input.id) {+ const existing = await db.integration.findUniqueOrThrow({+ where: { id: input.id },+ select: { projectId: true, organizationId: true, config: true },+ });+ await assertIntegrationAccess(userId, existing, 'write');+ organizationId = existing.organizationId;+ storedConfig = existing.config;+ } else {+ organizationId = await assertProjectAccessAndGetOrg(+ userId,+ input.projectId,+ 'write'+ );+ }++ // A blank secret means "keep the stored one" — the client can't resubmit what+ // it was never given. On create there is nothing to fall back to.+ const submitted = input.id+ ? carryOverConfigSecrets(input.config, storedConfig)+ : input.config;++ const missing = findMissingSecretFields(submitted);+ if (missing.length > 0) {+ throw new TRPCBadRequestError(+ `Missing credential${missing.length > 1 ? 's' : ''}: ${missing.join(', ')}`+ );+ }++ const plugin = getServerIntegration(submitted.type);++ const validation = plugin.validateConfig?.(submitted);+ if (validation && !validation.valid) {+ throw new TRPCBadRequestError(`Invalid config: ${validation.error}`);+ }++ // Test the connection with the real credentials before saving. `submitted`+ // may carry a still-encrypted value forward from the stored row; the adapters+ // decrypt on construction, so this works for both new and carried-over keys.+ const testResult = await plugin.testConnection?.(submitted);+ if (testResult && !testResult.success) {+ throw new TRPCBadRequestError(`Failed to connect: ${testResult.error}`);+ }++ const config = encryptConfigSecrets(submitted);++ if (input.id) {+ return db.integration.update({+ where: { id: input.id, organizationId },+ data: { name: input.name, config },+ });+ }+ return db.integration.create({+ data: {+ name: input.name,+ organizationId,+ projectId: input.projectId,+ config,+ },+ });+}++export async function createOrUpdateSlackIntegration(+ userId: string,+ input: { id?: string; name: string; projectId: string }+) {+ // For an update, authorize against the existing integration's scope so a+ // user can't clear/re-install another project's Slack integration.+ let organizationId: string;+ // Carried into the OAuth metadata and the post-callback redirect, so it+ // has to be the row's own project — not whatever `input` asked for, which+ // on an update is unauthorized and may point at a different project.+ let projectId: string;++ const db = await loadDb();++ if (input.id) {+ const existing = await db.integration.findUniqueOrThrow({+ where: { id: input.id },+ select: { projectId: true, organizationId: true },+ });+ await assertIntegrationAccess(userId, existing, 'write');+ organizationId = existing.organizationId;+ projectId = existing.projectId ?? input.projectId;+ } else {+ organizationId = await assertProjectAccessAndGetOrg(+ userId,+ input.projectId,+ 'write'+ );+ projectId = input.projectId;+ }++ const res = input.id+ ? await db.integration.update({+ where: {+ id: input.id,+ organizationId,+ },+ data: {+ name: input.name,+ // This is empty and will be filled by the webhook+ config: {} as ISlackConfig,+ },+ })+ : await db.integration.create({+ data: {+ name: input.name,+ organizationId,+ projectId: input.projectId,+ // This is empty and will be filled by the webhook+ config: {} as ISlackConfig,+ },+ });++ return {+ ...res,+ slackInstallUrl: await getSlackInstallUrl({+ integrationId: res.id,+ organizationId,+ projectId,+ }),+ };+}++// Generic, registry-driven connection test. Gated on project write access:+// it makes the server connect outbound to a caller-supplied destination with+// caller-supplied credentials, so it must not be reachable by anyone who+// merely holds a session.+export async function testIntegrationConnection(+ userId: string,+ input: { projectId: string; config: IIntegrationConfig }+) {+ const { requireProjectAccess } = await loadAccess();+ await requireProjectAccess({+ userId,+ projectId: input.projectId,+ level: 'write',+ });+ rejectEncryptedSecrets(input.config);++ return (+ (await getServerIntegration(input.config.type).testConnection?.(+ input.config+ )) ?? { success: true }+ );+}++// Back-compat alias for the export forms; same gate as `testIntegrationConnection`.+export async function testExportIntegrationConnection(+ userId: string,+ input: { projectId: string; config: IIntegrationConfig }+) {+ const { requireProjectAccess } = await loadAccess();+ await requireProjectAccess({+ userId,+ projectId: input.projectId,+ level: 'write',+ });+ rejectEncryptedSecrets(input.config);++ return (+ (await getServerIntegration(input.config.type).testConnection?.(+ input.config+ )) ?? { success: false, error: 'Unknown export type' }+ );+}++export async function deleteIntegration(userId: string, id: string) {+ const db = await loadDb();+ const integration = await db.integration.findUniqueOrThrow({+ where: { id },+ });++ await assertIntegrationAccess(userId, integration, 'write');++ return db.integration.delete({+ where: { id },+ });+}++// -- Slack OAuth callback -----------------------------------------------+// Ported from apps/api/src/controllers/webhook.controller.ts's+// `slackWebhook` (M6-006). V1's Fastify controller stays the LIVE route+// (DELEGATE PATTERN) and delegates the token-exchange/upsert logic here, the+// same function this module's own `/webhook/slack` route+// (integration.routes.ts) calls.++const slackOAuthMetadataSchema = z.object({+ organizationId: z.string(),+ integrationId: z.string(),+ // Optional for back-compat with install URLs generated before integrations+ // became project-scoped; the post-install redirect falls back to the org page.+ projectId: z.string().optional(),+});++export class SlackOAuthCallbackError extends Error {}++export interface CompleteSlackOAuthCallbackResult {+ organizationId: string;+ projectId?: string;+}++export async function completeSlackOAuthCallback(params: {+ code: string;+ state: string;+}): Promise<CompleteSlackOAuthCallbackResult> {+ const verifiedState = await slackInstaller.stateStore?.verifyStateParam(+ new Date(),+ params.state+ );+ const parsedMetadata = slackOAuthMetadataSchema.safeParse(+ JSON.parse(verifiedState?.metadata ?? '{}')+ );++ if (!parsedMetadata.success) {+ throw new SlackOAuthCallbackError('Invalid metadata');+ }++ const slackOauthAccessUrl = [+ 'https://slack.com/api/oauth.v2.access',+ `?client_id=${process.env.SLACK_CLIENT_ID}`,+ `&client_secret=${process.env.SLACK_CLIENT_SECRET}`,+ `&code=${params.code}`,+ `&redirect_uri=${process.env.SLACK_OAUTH_REDIRECT_URL}`,+ ].join('');++ const response = await fetch(slackOauthAccessUrl);+ const json = await response.json();+ const parsedJson = zSlackAuthResponse.safeParse(json);++ if (!parsedJson.success) {+ throw new SlackOAuthCallbackError('Failed to parse slack auth response');+ }++ // Send a notification first to confirm the connection+ await sendSlackNotification({+ fetcher: safeWebhookFetcher,+ webhookUrl: parsedJson.data.incoming_webhook.url,+ message:+ '👋 Hello. You have successfully connected OpenPanel.dev to your Slack workspace.',+ });++ const { organizationId, integrationId, projectId } = parsedMetadata.data;++ const db = await loadDb();+ await db.integration.update({+ where: {+ id: integrationId,+ organizationId,+ },+ data: {+ config: {+ type: 'slack',+ ...parsedJson.data,+ },+ },+ });++ return { organizationId, projectId };+}diff --git a/packages/core/src/modules/integration/src/access.ts b/packages/core/src/modules/integration/src/access.tsnew file mode 100644index 000000000..12efcfeac--- /dev/null+++ b/packages/core/src/modules/integration/src/access.ts@@ -0,0 +1,27 @@+// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for+// this module's own router — the same binding packages/trpc/src/access.ts+// does for V1, self-contained here because the general core -> db binding+// itself moves with auth (P6), not this wave. Same shape as+// ../../notification/src/access.ts (M6-005).++import {+ canWriteProject,+ getOrganizationAccess,+ getProjectAccess,+} from '@openpanel/db/src/services/access.service';+import { getProjectById } from '@openpanel/db/src/services/project.service';+import { createAccessChecks } from '../../../shared/access';++const checks = createAccessChecks({+ getProjectAccess,+ canWriteProject,+ getOrganizationAccess,+ getProjectById,+});++export const requireProjectAccess = checks.requireProjectAccess;+export const requireOrganizationAdmin = checks.requireOrganizationAdmin;+// `assertIntegrationAccess`'s read-branch on a legacy org-wide row needs bare+// membership, not the admin gate — re-exported raw, same as+// packages/trpc/src/access.ts does for V1's integration router.+export { getOrganizationAccess } from '@openpanel/db/src/services/access.service';diff --git a/packages/core/src/modules/integration/src/slack-contract.test.ts b/packages/core/src/modules/integration/src/slack-contract.test.tsnew file mode 100644index 000000000..84a89faff--- /dev/null+++ b/packages/core/src/modules/integration/src/slack-contract.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'bun:test';+import { zSlackAuthResponse } from './slack-contract';++const VALID_RESPONSE = {+ ok: true,+ app_id: 'A1',+ authed_user: { id: 'U1' },+ scope: 'incoming-webhook,chat:write',+ token_type: 'bot',+ access_token: 'xoxb-1',+ bot_user_id: 'B1',+ team: { id: 'T1', name: 'Team' },+ incoming_webhook: {+ channel: '#general',+ channel_id: 'C1',+ configuration_url: 'https://slack.example/config',+ url: 'https://hooks.slack.example/services/1',+ },+};++describe('zSlackAuthResponse', () => {+ it('accepts a real oauth.v2.access response (no `type` tag on the wire)', () => {+ expect(zSlackAuthResponse.safeParse(VALID_RESPONSE).success).toBe(true);+ });++ it('rejects a response missing the incoming_webhook grant', () => {+ const { incoming_webhook: _drop, ...rest } = VALID_RESPONSE;+ expect(zSlackAuthResponse.safeParse(rest).success).toBe(false);+ });+});diff --git a/packages/core/src/modules/integration/src/slack-contract.ts b/packages/core/src/modules/integration/src/slack-contract.tsnew file mode 100644index 000000000..2be616717--- /dev/null+++ b/packages/core/src/modules/integration/src/slack-contract.ts@@ -0,0 +1,11 @@+// Slack's OAuth token-exchange response (`oauth.v2.access`) — the wire+// contract `integration.routes.ts`'s `/webhook/slack` callback parses the+// JSON it gets back from Slack against, before it's ever stored as a+// `zSlackConfig`. Not integration config a frontend form validates against,+// so it doesn't belong in `integration.constants.ts` even though it's+// zod-only (constants are for isomorphic vocabulary, not third-party API+// contracts) — it's exactly `zSlackConfig` minus the persisted `type` tag.++import { zSlackConfig } from '../integration.constants';++export const zSlackAuthResponse = zSlackConfig.omit({ type: true });diff --git a/packages/core/src/modules/notification/notification.service.ts b/packages/core/src/modules/notification/notification.service.tsindex c484545b2..8b8cd2c85 100644--- a/packages/core/src/modules/notification/notification.service.ts+++ b/packages/core/src/modules/notification/notification.service.ts@@ -21,23 +21,19 @@// would spawn a pino-pretty transport worker thread per test file).import { stripLeadingAndTrailingSlashes } from '@openpanel/common';-import type {- IServiceCreateEventPayload,- IServiceEvent,-} from '@openpanel/db';+import type { IServiceCreateEventPayload, IServiceEvent } from '@openpanel/db';import type { Integration, Prisma } from '@openpanel/db/src/prisma-client';import { cacheable } from '@openpanel/redis';-import {- type IChartEvent,- type IChartEventFilter,- type IIntegrationConfig,- isKind,-} from '@openpanel/validation';+import type { IChartEvent, IChartEventFilter } from '@openpanel/validation';import { pathOr } from 'ramda';import { sendEmail } from '../../clients/email';import { getServerIntegration } from '../../clients/integrations/registry';import { TRPCBadRequestError, TRPCForbiddenError } from '../../rpc/errors';import type { ServiceDeps } from '../../services';+import {+ type IIntegrationConfig,+ isKind,+} from '../integration/integration.constants';import type { ICreateNotificationRule } from './notification.constants';export const APP_NOTIFICATION_INTEGRATION_ID = 'app';@@ -263,7 +259,10 @@ function isValidPayload<T>(dbNull: unknown): value is T {return (- value !== null && value !== undefined && value !== jsonNull && value !== dbNull+ value !== null &&+ value !== undefined &&+ value !== jsonNull &&+ value !== dbNull);}@@ -443,7 +442,7 @@ export async function createOrUpdateNotificationRule(const orgWideSameOrg =integration.projectId === null &&integration.organizationId === project.organizationId;- if (!sameProject && !orgWideSameOrg) {+ if (!(sameProject || orgWideSameOrg)) {throw new TRPCForbiddenError('Integration does not belong to this project');diff --git a/packages/core/src/modules/subscription/src/access.ts b/packages/core/src/modules/subscription/src/access.tsnew file mode 100644index 000000000..d9f12fa60--- /dev/null+++ b/packages/core/src/modules/subscription/src/access.ts@@ -0,0 +1,23 @@+// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for+// this module's own router — the same binding packages/trpc/src/access.ts+// does for V1, self-contained here because the general core -> db binding+// itself moves with auth (P6), not this wave. Same shape as+// ../../notification/src/access.ts (M6-005) / ../../integration/src/access.ts+// (M6-006).++import {+ canWriteProject,+ getOrganizationAccess,+ getProjectAccess,+} from '@openpanel/db/src/services/access.service';+import { getProjectById } from '@openpanel/db/src/services/project.service';+import { createAccessChecks } from '../../../shared/access';++const checks = createAccessChecks({+ getProjectAccess,+ canWriteProject,+ getOrganizationAccess,+ getProjectById,+});++export const requireOrganizationAdmin = checks.requireOrganizationAdmin;diff --git a/packages/core/src/modules/subscription/subscription.constants.ts b/packages/core/src/modules/subscription/subscription.constants.tsnew file mode 100644index 000000000..575ed1bfb--- /dev/null+++ b/packages/core/src/modules/subscription/subscription.constants.ts@@ -0,0 +1,45 @@+// Moved from packages/validation/src/index.ts (M6-006, ADR-008's module map:+// subscription owns "C"). packages/validation/src/index.ts becomes a+// re-export shim of this file (same shape as ./notification.constants.ts+// since M6-005), so packages/trpc's subscription router and apps/start's+// billing forms keep resolving these symbols through @openpanel/validation's+// existing barrel unchanged.+//+// Isomorphic by the AGENTS.md rule: zod and nothing else.++import { z } from 'zod';++export const zCheckout = z.object({+ productPriceId: z.string(),+ organizationId: z.string(),+ projectId: z.string().nullish(),+ productId: z.string(),+});+export type ICheckout = z.infer<typeof zCheckout>;++// Mirrors Polar's CustomerCancellationReason enum.+export const zCancellationReason = z.enum([+ 'too_expensive',+ 'missing_features',+ 'switched_service',+ 'unused',+ 'customer_service',+ 'low_quality',+ 'too_complex',+ 'other',+]);+export type ICancellationReason = z.infer<typeof zCancellationReason>;++export const zCancelSubscription = z.object({+ organizationId: z.string(),+ reason: zCancellationReason,+ comment: z.string().trim().max(1000).optional(),+});+export type ICancelSubscription = z.infer<typeof zCancelSubscription>;++export const zPauseSubscription = z.object({+ organizationId: z.string(),+ // Months after the current period end before billing automatically resumes.+ months: z.union([z.literal(1), z.literal(2), z.literal(3)]),+});+export type IPauseSubscription = z.infer<typeof zPauseSubscription>;diff --git a/packages/core/src/modules/subscription/subscription.routes.ts b/packages/core/src/modules/subscription/subscription.routes.tsnew file mode 100644index 000000000..50a8b966f--- /dev/null+++ b/packages/core/src/modules/subscription/subscription.routes.ts@@ -0,0 +1,35 @@+// The Polar webhook (M6-006), `POST /webhook/polar`. V1's Fastify controller+// (apps/api/src/controllers/webhook.controller.ts's `polarWebhook`) stays the+// LIVE route (DELEGATE PATTERN) and delegates to+// subscription.service.ts's `handlePolarWebhookEvent` — the same function+// this route calls.+//+// RAW BYTES, deliberately: `validatePolarEvent` verifies Polar's signature+// over the exact request body, so this handler reads `await request.text()`+// and declares no `body` schema — any parsing (JSON or otherwise) before the+// signature check breaks it. V1 gets the same raw bytes via+// `fastify-raw-body`'s `{ rawBody: true }` route config; this is the Elysia+// equivalent named in ADR-002's plugin substitutions ("raw body → `await+// request.text()` in the one polar webhook handler").+//+// NAMED GAP, same as gsc.routes.ts / import.routes.ts: this route is not yet+// reachable — main.ts does not mount `publicApiRoutes` until a real+// `AppDeps` exists (P3/P4/P8).++import { defineRoutes } from '../../http/define';+import { handlePolarWebhookEvent } from './subscription.service';++export const subscriptionRoutes = defineRoutes((app) =>+ app.post('/webhook/polar', async ({ request, ctx, status }) => {+ const rawBody = await request.text();+ const headers = Object.fromEntries(request.headers);++ try {+ await handlePolarWebhookEvent(rawBody, headers, ctx.logger);+ } catch {+ return status(500, 'Error');+ }++ return status(202, 'OK');+ })+);diff --git a/packages/core/src/modules/subscription/subscription.rpc.ts b/packages/core/src/modules/subscription/subscription.rpc.tsnew file mode 100644index 000000000..c2a0509bc--- /dev/null+++ b/packages/core/src/modules/subscription/subscription.rpc.ts@@ -0,0 +1,90 @@+// Ported from packages/trpc/src/routers/subscription.ts (M6-006).+//+// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware+// stack — lands in core with auth (rpc/base.ts: "those need the resolved+// Session shape and the access rules, so they land with auth (P6)"). Until+// then this router does its own minimal "is anyone logged in" check inline,+// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route+// through packages/trpc's own `protectedProcedure` (full stack included) and+// delegates its handler bodies to core's subscription functions (DELEGATE+// PATTERN), so nothing here is a live regression.+//+// `requireOrganizationAdmin` lives in subscription.service.ts, not here —+// see that file's header.++import { z } from 'zod';+import { createTRPCRouter, procedure } from '../../rpc/base';+import { TRPCAccessError } from '../../rpc/errors';+import {+ zCancelSubscription,+ zCheckout,+ zPauseSubscription,+} from './subscription.constants';+import {+ applySaveDiscount,+ cancelSubscription,+ checkout,+ getCurrentSubscriptionProduct,+ getUsage,+ listProducts,+ pauseSubscription,+ portal,+ resumeSubscription,+} from './subscription.service';++function requireLogin(userId: string | null | undefined): string {+ if (!userId) {+ throw new TRPCAccessError('Not authenticated');+ }+ return userId;+}++export const subscriptionRouter = createTRPCRouter({+ getCurrent: procedure+ .input(z.object({ organizationId: z.string() }))+ .query(({ input }) => getCurrentSubscriptionProduct(input.organizationId)),++ checkout: procedure+ .input(zCheckout)+ .mutation(({ input, ctx }) =>+ checkout(requireLogin(ctx.session.userId), input, ctx.remoteAddress)+ ),++ products: procedure+ .input(z.object({ organizationId: z.string() }))+ .query(({ input }) => listProducts(input.organizationId)),++ usage: procedure+ .input(z.object({ organizationId: z.string() }))+ .query(({ input }) => getUsage(input.organizationId)),++ cancelSubscription: procedure+ .input(zCancelSubscription)+ .mutation(({ input, ctx }) =>+ cancelSubscription(requireLogin(ctx.session.userId), input)+ ),++ pauseSubscription: procedure+ .input(zPauseSubscription)+ .mutation(({ input, ctx }) =>+ pauseSubscription(requireLogin(ctx.session.userId), input)+ ),++ resumeSubscription: procedure+ .input(z.object({ organizationId: z.string() }))+ .mutation(({ input, ctx }) =>+ resumeSubscription(requireLogin(ctx.session.userId), input.organizationId)+ ),++ applySaveDiscount: procedure+ .input(z.object({ organizationId: z.string() }))+ .mutation(({ input, ctx }) =>+ applySaveDiscount(requireLogin(ctx.session.userId), input.organizationId)+ ),++ portal: procedure+ .input(z.object({ organizationId: z.string() }))+ .mutation(({ input, ctx }) =>+ portal(requireLogin(ctx.session.userId), input.organizationId)+ ),+});diff --git a/packages/core/src/modules/subscription/subscription.service.ts b/packages/core/src/modules/subscription/subscription.service.tsnew file mode 100644index 000000000..539e6e1bd--- /dev/null+++ b/packages/core/src/modules/subscription/subscription.service.ts@@ -0,0 +1,811 @@+// Moved from packages/trpc/src/routers/subscription.ts (checkout, products,+// usage, cancel/pause/resume, save-discount, portal) and from+// apps/api/src/controllers/webhook.controller.ts's `polarWebhook` (M6-006).+// V1's router and controller stay the LIVE routes (DELEGATE PATTERN) and+// delegate every handler body to these functions, same as every other+// dissolved service in this package.+//+// `requireOrganizationAdmin` travels with the business logic here rather than+// living in subscription.rpc.ts the way project.rpc.ts's simple ladder checks+// do: every mutating procedure in this module gates on it first, before+// touching Polar — same call as `./src/access.ts`'s `requireOrganizationAdmin`,+// kept close to the Polar call it guards.+//+// db access, `./src/access.ts` AND `getCache` are all LAZY+// (`loadDb`/`loadAccess`/`loadCache` below), not a static top-level import —+// see organization.service.ts's header for the db half (constructing+// @openpanel/db's clients at import time would spawn a pino-pretty transport+// worker thread per test file); `./src/access.ts` needs the same treatment+// because it calls `createAccessChecks({ canWriteProject, ... })` at ITS OWN+// top level; a static import here would reach into+// @openpanel/db/src/services/access.service as soon as anything imports+// @openpanel/core's barrel (this module is a static re-export there, not a+// lazy one), which broke a vitest suite that partially mocks that module+// (packages/trpc/src/routers/share.test.ts) with no `canWriteProject` export+// at all. `getCache` hit the same barrel chain from the other direction: a+// static `import { getCache } from '@openpanel/redis'` here broke every core+// test that partially mocks `@openpanel/redis` (no `getCache` export) and+// reaches this module through @openpanel/db's re-export shims+// (project.service.ts / notification.service.ts -> @openpanel/core's barrel+// -> here), e.g. organization.service.test.ts's `connectUserToOrganization`+// path via access.service.ts.++import {+ applySubscriptionDiscount,+ cancelSubscription as cancelPolarSubscription,+ changeSubscription,+ createCheckout,+ createPortal,+ getProduct,+ getProducts,+ pauseSubscription as pausePolarSubscription,+ reactivateSubscription,+ resumeSubscription as resumePolarSubscription,+ unpauseSubscription,+ validatePolarEvent,+} from '@openpanel/payments';+import { addMonths, subDays } from 'date-fns';+import { z } from 'zod';+import type { Logger } from '../../logger';+import { TRPCBadRequestError } from '../../rpc/errors';+import {+ getOrganizationBillingEventsCountSerieCached,+ getOrganizationById,+ getOrganizationByProjectIdCached,+} from '../organization/organization.service';+import {+ type ICancellationReason,+ type ICancelSubscription,+ type ICheckout,+ type IPauseSubscription,+ zCancellationReason,+} from './subscription.constants';++const POLAR_PRODUCTS_CACHE_KEY = 'polar:products';+const POLAR_PRODUCTS_CACHE_TTL_SECONDS = 60 * 60 * 24;+const DEFAULT_USAGE_WINDOW_DAYS = 30;++function loadDb() {+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);+}++function loadPrisma() {+ return import('@openpanel/db/src/prisma-client').then((m) => m.Prisma);+}++function loadAccess() {+ return import('./src/access');+}++function loadCache() {+ return import('@openpanel/redis').then((m) => m.getCache);+}++export async function getCurrentSubscriptionProduct(organizationId: string) {+ const organization = await getOrganizationById(organizationId);++ if (!organization.subscriptionProductId) {+ return null;+ }++ return getProduct(organization.subscriptionProductId);+}++export async function checkout(+ userId: string,+ input: ICheckout,+ ipAddress: string | undefined+) {+ const { requireOrganizationAdmin } = await loadAccess();+ await requireOrganizationAdmin({+ userId,+ organizationId: input.organizationId,+ });++ const db = await loadDb();+ const [user, organization] = await Promise.all([+ db.user.findFirstOrThrow({ where: { id: userId } }),+ db.organization.findFirstOrThrow({ where: { id: input.organizationId } }),+ ]);++ // A paused (or pause-scheduled) subscription still exists in Polar — a+ // checkout here would create a second one, and a plan change would race+ // the pending pause. Resume first, then change plans.+ if (+ organization.subscriptionId &&+ (organization.subscriptionStatus === 'paused' ||+ organization.subscriptionPauseAtPeriodEnd)+ ) {+ throw new TRPCBadRequestError(+ 'Your subscription is paused or scheduled to pause — resume it before changing plans'+ );+ }++ // An organization has at most one Polar subscription (we have no free+ // tier in Polar — the free plan is handled on our side). So an upgrade or+ // downgrade is an in-place product change, never a cancel + re-subscribe.+ // Reactivate first if it was scheduled to cancel, otherwise change the+ // product on the existing subscription.+ if (+ organization.subscriptionId &&+ organization.subscriptionStatus === 'active'+ ) {+ if (organization.subscriptionCanceledAt) {+ await reactivateSubscription(organization.subscriptionId);+ return null;+ }++ // Already on this product — nothing to change.+ if (organization.subscriptionProductId === input.productId) {+ return null;+ }++ await changeSubscription(organization.subscriptionId, input.productId);+ return null;+ }++ const checkoutSession = await createCheckout({+ productId: input.productId,+ organizationId: input.organizationId,+ user,+ ipAddress,+ });++ return { url: checkoutSession.url };+}++export async function listProducts(organizationId: string) {+ const db = await loadDb();+ const organization = await db.organization.findUniqueOrThrow({+ where: { id: organizationId },+ select: { subscriptionPeriodEventsCount: true },+ });++ const getCache = await loadCache();++ return (+ await getCache(+ POLAR_PRODUCTS_CACHE_KEY,+ POLAR_PRODUCTS_CACHE_TTL_SECONDS,+ () => getProducts()+ )+ ).map((product) => {+ const eventsLimit = product.metadata.eventsLimit;+ return {+ ...product,+ disabled:+ typeof eventsLimit === 'number' &&+ organization.subscriptionPeriodEventsCount >= eventsLimit+ ? 'This product is not applicable since you have exceeded the limits for this subscription.'+ : null,+ };+ });+}++export async function getUsage(organizationId: string) {+ const db = await loadDb();+ const organization = await db.organization.findUniqueOrThrow({+ where: { id: organizationId },+ include: { projects: { select: { id: true } } },+ });++ if (+ organization.hasSubscription &&+ organization.subscriptionStartsAt &&+ organization.subscriptionEndsAt+ ) {+ return getOrganizationBillingEventsCountSerieCached(organization, {+ startDate: organization.subscriptionStartsAt,+ endDate: organization.subscriptionEndsAt,+ });+ }++ return getOrganizationBillingEventsCountSerieCached(organization, {+ startDate: subDays(new Date(), DEFAULT_USAGE_WINDOW_DAYS),+ endDate: new Date(),+ });+}++export async function cancelSubscription(+ userId: string,+ input: ICancelSubscription+) {+ const { requireOrganizationAdmin } = await loadAccess();+ await requireOrganizationAdmin({+ userId,+ organizationId: input.organizationId,+ });++ const organization = await getOrganizationById(input.organizationId);+ if (!organization.subscriptionId) {+ throw new TRPCBadRequestError('Organization has no subscription');+ }++ const res = await cancelPolarSubscription(organization.subscriptionId, {+ reason: input.reason,+ comment: input.comment,+ });++ // The webhook echoes these back, but persist immediately so a missed or+ // delayed delivery can't lose the reason — or leave `canceledAt` unset,+ // which would make the plan-change path skip reactivation and silently+ // keep the cancellation scheduled.+ const db = await loadDb();+ await db.organization.update({+ where: { id: input.organizationId },+ data: {+ subscriptionCancelReason: input.reason,+ subscriptionCancelComment: input.comment ?? null,+ subscriptionCanceledAt: res.canceledAt,+ subscriptionEndsAt: res.cancelAtPeriodEnd+ ? res.currentPeriodEnd+ : (res.canceledAt ?? organization.subscriptionEndsAt),+ },+ });++ return res;+}++export async function pauseSubscription(+ userId: string,+ input: IPauseSubscription+) {+ const { requireOrganizationAdmin } = await loadAccess();+ await requireOrganizationAdmin({+ userId,+ organizationId: input.organizationId,+ });++ const organization = await getOrganizationById(input.organizationId);+ if (!organization.subscriptionId) {+ throw new TRPCBadRequestError('Organization has no subscription');+ }+ // Only a plain active subscription can be paused — this rejects paused,+ // pause-scheduled (pausing), canceling, canceled, unpaid, etc. before we+ // hit Polar with a nonsensical update.+ if (organization.subscriptionState !== 'active') {+ throw new TRPCBadRequestError('Only an active subscription can be paused');+ }+ if (!organization.subscriptionEndsAt) {+ throw new TRPCBadRequestError('Subscription has no current period end');+ }++ // Polar pauses at period end; the resume date counts from there.+ const resumesAt = addMonths(organization.subscriptionEndsAt, input.months);++ await pausePolarSubscription(organization.subscriptionId, resumesAt);++ // Optimistic mirror — the subscription.updated webhook confirms it.+ const db = await loadDb();+ await db.organization.update({+ where: { id: input.organizationId },+ data: {+ subscriptionPauseAtPeriodEnd: true,+ subscriptionResumesAt: resumesAt,+ },+ });++ return { resumesAt };+}++export async function resumeSubscription(+ userId: string,+ organizationId: string+) {+ const { requireOrganizationAdmin } = await loadAccess();+ await requireOrganizationAdmin({ userId, organizationId });++ const organization = await getOrganizationById(organizationId);+ if (!organization.subscriptionId) {+ throw new TRPCBadRequestError('Organization has no subscription');+ }++ if (organization.subscriptionStatus === 'paused') {+ // Already paused — resuming starts a new billing period immediately.+ await resumePolarSubscription(organization.subscriptionId);+ } else if (organization.subscriptionPauseAtPeriodEnd) {+ // Pause is only scheduled — just clear it.+ await unpauseSubscription(organization.subscriptionId);+ } else {+ throw new TRPCBadRequestError('Subscription is not paused');+ }++ const db = await loadDb();+ await db.organization.update({+ where: { id: organizationId },+ data: {+ subscriptionPauseAtPeriodEnd: false,+ subscriptionResumesAt: null,+ },+ });++ return { success: true };+}++export async function applySaveDiscount(+ userId: string,+ organizationId: string+) {+ const { requireOrganizationAdmin } = await loadAccess();+ await requireOrganizationAdmin({ userId, organizationId });++ const discountId = process.env.POLAR_SAVE_DISCOUNT_ID;+ if (!discountId) {+ throw new TRPCBadRequestError('Save discount is not configured');+ }++ const organization = await getOrganizationById(organizationId);+ if (!organization.subscriptionId) {+ throw new TRPCBadRequestError('Organization has no subscription');+ }++ // Claim the one-time offer atomically BEFORE calling Polar: a+ // conditional update lets exactly one concurrent request through. Roll+ // the claim back if Polar rejects, so a transient failure doesn't burn+ // the offer.+ const db = await loadDb();+ const claimed = await db.organization.updateMany({+ where: { id: organizationId, subscriptionSaveDiscountAppliedAt: null },+ data: { subscriptionSaveDiscountAppliedAt: new Date() },+ });+ if (claimed.count === 0) {+ throw new TRPCBadRequestError('The save discount has already been used');+ }++ try {+ await applySubscriptionDiscount(organization.subscriptionId, discountId);+ } catch (error) {+ await db.organization.updateMany({+ where: { id: organizationId },+ data: { subscriptionSaveDiscountAppliedAt: null },+ });+ throw error;+ }++ return { success: true };+}++export async function portal(userId: string, organizationId: string) {+ const { requireOrganizationAdmin } = await loadAccess();+ await requireOrganizationAdmin({ userId, organizationId });++ const organization = await getOrganizationById(organizationId);+ if (!organization.subscriptionCustomerId) {+ throw new TRPCBadRequestError('Organization has no subscription');+ }++ const created = await createPortal({+ customerId: organization.subscriptionCustomerId,+ });++ return { url: created.customerPortalUrl };+}++// -- Polar webhook --------------------------------------------------------+// Ported from apps/api/src/controllers/webhook.controller.ts's `polarWebhook`+// + its private helpers (M6-006). V1's Fastify controller stays the LIVE+// route (DELEGATE PATTERN) and delegates here — the same function this+// module's own `/webhook/polar` route (subscription.routes.ts) calls.+// `validatePolarEvent` verifies the signature over the RAW body bytes; any+// body parsing before this call breaks that verification, which is why both+// callers read `await request.text()` / `request.rawBody` rather than a+// parsed JSON body.++type PolarEvent = ReturnType<typeof validatePolarEvent>;+type PolarSubscriptionData = Extract<+ PolarEvent,+ { type: 'subscription.updated' }+>['data'];+type PolarSubscriptionDiscount = PolarSubscriptionData['discount'];++const subscriptionMetadataSchema = z.object({+ organizationId: z.string(),+ // `userId` is only used for the `subscriptionCreatedByUserId` audit field, so+ // it is optional — a missing one must not block syncing the subscription.+ userId: z.string().optional(),+});++// Org columns whose before→after transition is logged on every sync.+const TRACKED_SUBSCRIPTION_FIELDS = [+ 'subscriptionId',+ 'subscriptionStatus',+ 'subscriptionProductId',+ 'subscriptionPriceId',+ 'subscriptionStartsAt',+ 'subscriptionEndsAt',+ 'subscriptionCanceledAt',+ 'subscriptionCancelReason',+ 'subscriptionInterval',+ 'subscriptionPeriodEventsLimit',+ 'subscriptionPauseAtPeriodEnd',+ 'subscriptionResumesAt',+ 'subscriptionFirstStartedAt',+] as const;++// Polar types the reason as an open enum (unknown strings can appear); only+// store values our own union knows about.+function parseCancellationReason(+ reason: string | null | undefined+): ICancellationReason | null {+ const parsed = zCancellationReason.safeParse(reason);+ return parsed.success ? parsed.data : null;+}++// Compact summary of Polar's embedded discount object so the dashboard can+// show that a discount is active (save offer or any Polar discount code).+export function toSubscriptionDiscount(+ discount: PolarSubscriptionDiscount+): PrismaJson.IPrismaSubscriptionDiscount | null {+ if (!discount) {+ return null;+ }+ return {+ id: discount.id,+ name: discount.name,+ type: discount.type === 'fixed' ? 'fixed' : 'percentage',+ basisPoints: 'basisPoints' in discount ? discount.basisPoints : null,+ amount: 'amount' in discount ? discount.amount : null,+ currency: 'currency' in discount ? discount.currency : null,+ duration:+ discount.duration === 'repeating'+ ? 'repeating'+ : discount.duration === 'forever'+ ? 'forever'+ : 'once',+ durationInMonths:+ 'durationInMonths' in discount ? discount.durationInMonths : null,+ };+}++const normalizeLogValue = (value: unknown) =>+ value instanceof Date ? value.toISOString() : (value ?? null);++// Builds a `{ field: { from, to } }` map of changed columns. `undefined`+// after-values are skipped — Prisma reads them as "leave the column untouched".+function diffOrganizationFields(+ before: Record<string, unknown>,+ after: Record<string, unknown>,+ fields: readonly string[]+) {+ const changes: Record<string, { from: unknown; to: unknown }> = {};+ for (const field of fields) {+ if (after[field] === undefined) {+ continue;+ }+ const from = normalizeLogValue(before[field]);+ const to = normalizeLogValue(after[field]);+ if (from !== to) {+ changes[field] = { from, to };+ }+ }+ return changes;+}++async function clearOrganizationCache(organizationId: string) {+ const db = await loadDb();+ const projects = await db.project.findMany({ where: { organizationId } });+ for (const project of projects) {+ await getOrganizationByProjectIdCached.clear(project.id);+ }+}++/**+ * Syncs the full Polar subscription state onto the organization. Used for every+ * `subscription.*` event (created, active, updated, canceled, revoked,+ * past_due, uncanceled) since they all carry the same Subscription object and+ * `status` drives the rest. This covers new subscriptions, cancellations,+ * reactivations, plan changes and payment-state changes in one place.+ */+async function syncSubscriptionToOrg(+ data: PolarSubscriptionData,+ eventType: string,+ logger: Logger+) {+ const metadata = subscriptionMetadataSchema.parse(data.metadata);+ const isCanceled = data.status === 'canceled';++ const db = await loadDb();+ const organization = await db.organization.findUniqueOrThrow({+ where: { id: metadata.organizationId },+ });++ // An organization maps to a single subscription in our DB, but can have+ // several in Polar (e.g. after re-subscribing). A canceled/revoked event for+ // a subscription that is no longer the org's current one must not clobber the+ // newer active subscription.+ if (isCanceled && organization.subscriptionId !== data.id) {+ logger.info(+ {+ organizationId: metadata.organizationId,+ eventType,+ eventSubscriptionId: data.id,+ orgSubscriptionId: organization.subscriptionId,+ },+ 'polar webhook: ignoring canceled event for non-current subscription'+ );+ return;+ }++ // Polar can deliver subscription events out of order: at renewal the new+ // period can arrive first, then a stale event for the *previous* period lands+ // a few seconds later. A billing period never moves backwards, so for the+ // same subscription we ignore any event whose period starts before the one we+ // already stored — otherwise the stale event resets the org to the expired+ // period and the usage counter (recomputed over that window) gets stuck.+ if (+ organization.subscriptionId === data.id &&+ organization.subscriptionStartsAt &&+ data.currentPeriodStart < organization.subscriptionStartsAt+ ) {+ logger.info(+ {+ organizationId: metadata.organizationId,+ eventType,+ eventSubscriptionId: data.id,+ eventPeriodStart: data.currentPeriodStart,+ storedPeriodStart: organization.subscriptionStartsAt,+ },+ 'polar webhook: ignoring stale subscription event (older billing period)'+ );+ return;+ }++ const product = await getProduct(data.productId);+ const rawEventsLimit = product.metadata?.eventsLimit;+ const parsedEventsLimit =+ typeof rawEventsLimit === 'number'+ ? rawEventsLimit+ : typeof rawEventsLimit === 'string'+ ? Number(rawEventsLimit)+ : Number.NaN;+ const hasValidEventsLimit = Number.isFinite(parsedEventsLimit);+ const subscriptionPeriodEventsLimit = hasValidEventsLimit+ ? parsedEventsLimit+ : organization.subscriptionPeriodEventsLimit;++ if (!hasValidEventsLimit) {+ logger.warn(+ { product },+ 'No valid eventsLimit on product, preserving existing organization limit'+ );+ }++ const Prisma = await loadPrisma();++ const updateData = {+ subscriptionId: data.id,+ subscriptionCustomerId: data.customer.id,+ subscriptionPriceId: data.prices[0]?.id ?? null,+ subscriptionProductId: data.productId,+ subscriptionStatus: data.status,+ subscriptionStartsAt: data.currentPeriodStart,+ subscriptionCanceledAt: data.canceledAt,+ subscriptionEndsAt: isCanceled+ ? data.cancelAtPeriodEnd+ ? data.currentPeriodEnd+ : data.canceledAt+ : data.currentPeriodEnd,+ subscriptionInterval: data.recurringInterval,+ // Cancellation feedback + pause state mirror Polar so portal-driven cancels+ // and pauses are captured too (our in-app flows also set them via the API,+ // which just echoes back through here).+ subscriptionCancelReason: parseCancellationReason(+ data.customerCancellationReason+ ),+ subscriptionCancelComment: data.customerCancellationComment ?? null,+ subscriptionPauseAtPeriodEnd: data.pauseAtPeriodEnd,+ subscriptionResumesAt: data.resumesAt,+ subscriptionDiscount:+ toSubscriptionDiscount(data.discount) ?? Prisma.DbNull,+ // Stable tenure anchor: keep the stored value while the subscription id is+ // unchanged; a new subscription (re-subscribe) restarts tenure.+ subscriptionFirstStartedAt:+ organization.subscriptionId === data.id+ ? (organization.subscriptionFirstStartedAt ?? data.createdAt)+ : data.createdAt,+ subscriptionPeriodEventsLimit,+ subscriptionPeriodEventsCountExceededAt:+ typeof subscriptionPeriodEventsLimit === 'number' &&+ organization.subscriptionPeriodEventsCountExceededAt &&+ typeof organization.subscriptionPeriodEventsLimit === 'number' &&+ organization.subscriptionPeriodEventsLimit < subscriptionPeriodEventsLimit+ ? null+ : undefined,+ // A raised limit re-arms the usage alerts for the new headroom.+ ...(typeof subscriptionPeriodEventsLimit === 'number' &&+ typeof organization.subscriptionPeriodEventsLimit === 'number' &&+ organization.subscriptionPeriodEventsLimit < subscriptionPeriodEventsLimit+ ? { usageWarningSentAt: null, usageExceededSentAt: null }+ : {}),+ // Reaching checkout takes the org out of the wind-down population for good+ // — that sequence only targets trials that never had a subscription — so+ // release the ingestion block and any scheduled deletion. Guarded on the+ // org actually being in wind-down so we never clear a `deleteAt` the owner+ // set themselves. The wind-down cron re-checks this too, for the webhook we+ // never receive.+ ...(organization.windDownStartedAt+ ? { windDownStartedAt: null, windDownStep: null, deleteAt: null }+ : {}),+ };++ const changes = diffOrganizationFields(+ organization as unknown as Record<string, unknown>,+ updateData as unknown as Record<string, unknown>,+ TRACKED_SUBSCRIPTION_FIELDS+ );++ await db.organization.update({+ where: { id: metadata.organizationId },+ data: updateData,+ });++ await clearOrganizationCache(metadata.organizationId);++ const { publishEvent } = await import('@openpanel/redis');+ await publishEvent('organization', 'subscription_updated', {+ organizationId: metadata.organizationId,+ });++ logger.info(+ {+ organizationId: metadata.organizationId,+ eventType,+ subscriptionId: data.id,+ previousStatus: organization.subscriptionStatus,+ status: data.status,+ changes,+ },+ Object.keys(changes).length > 0+ ? `polar webhook: synced subscription for ${metadata.organizationId} (${Object.keys(changes).join(', ')} changed)`+ : `polar webhook: synced subscription for ${metadata.organizationId} (no field changes)`+ );+}++/**+ * Handles one verified Polar webhook event. `rawBody`/`headers` MUST be the+ * unparsed request bytes — `validatePolarEvent` verifies the signature over+ * them, and any body parsing upstream (JSON, form, anything) breaks that+ * verification. `apps/api`'s Fastify controller (via `fastify-raw-body`) and+ * this module's own Elysia route (via `request.text()`) both preserve this.+ */+export async function handlePolarWebhookEvent(+ rawBody: string | Buffer,+ headers: Record<string, string>,+ logger: Logger+): Promise<void> {+ // Don't log the raw body: it can carry customer free text (e.g. the+ // cancellation comment) that the logger's redaction patterns don't cover.+ // `eventCtx` is logged right after validation instead.+ logger.info('polar webhook received');++ let event: PolarEvent;+ try {+ event = validatePolarEvent(+ rawBody,+ headers,+ process.env.POLAR_WEBHOOK_SECRET ?? ''+ );+ } catch (err) {+ logger.error({ err }, 'polar webhook: failed to parse event');+ throw err;+ }++ const eventOrganizationId =+ 'metadata' in event.data &&+ event.data.metadata &&+ typeof event.data.metadata === 'object' &&+ 'organizationId' in event.data.metadata+ ? String(event.data.metadata.organizationId)+ : undefined;++ const eventCtx = {+ eventType: event.type,+ eventId: 'id' in event.data ? event.data.id : undefined,+ organizationId: eventOrganizationId,+ };++ logger.info(+ eventCtx,+ `polar webhook: processing ${event.type}${eventOrganizationId ? ` for ${eventOrganizationId}` : ''}`+ );++ if (+ 'data' in event &&+ 'product' in event.data &&+ event.data.product?.name === 'Supporter'+ ) {+ logger.info(eventCtx, 'polar webhook: supporter event ignored');+ return;+ }++ try {+ await dispatchPolarWebhookEvent(event, eventCtx, logger);+ } catch (err) {+ logger.error(+ { err, ...eventCtx },+ `polar webhook: ${event.type} handler failed`+ );+ throw err;+ }+}++async function dispatchPolarWebhookEvent(+ event: PolarEvent,+ eventCtx: {+ eventType: string;+ eventId: unknown;+ organizationId: string | undefined;+ },+ logger: Logger+): Promise<void> {+ switch (event.type) {+ // A new paid billing cycle resets the org's usage counter. Polar sends+ // `order.updated` (not `order.created`) and the order moves through+ // pending -> paid, so we only act on the `paid` + `subscription_cycle`+ // transition. Re-deliveries of the same paid order just reset to 0 again,+ // which is harmless (and safely under-counts at worst).+ case 'order.updated': {+ if (+ event.data.billingReason !== 'subscription_cycle' ||+ event.data.status !== 'paid'+ ) {+ logger.info(+ { ...eventCtx, billingReason: event.data.billingReason },+ 'polar webhook: order.updated ignored (not a paid billing cycle)'+ );+ return;+ }++ const metadata = z+ .object({ organizationId: z.string() })+ .parse(event.data.metadata);++ const db = await loadDb();+ const previous = await db.organization.findUnique({+ where: { id: metadata.organizationId },+ select: { subscriptionPeriodEventsCount: true },+ });++ await db.organization.update({+ where: { id: metadata.organizationId },+ data: {+ subscriptionPeriodEventsCount: 0,+ subscriptionPeriodEventsCountExceededAt: null,+ // New cycle — the usage alerts may fire again.+ usageWarningSentAt: null,+ usageExceededSentAt: null,+ },+ });++ await clearOrganizationCache(metadata.organizationId);++ logger.info(+ {+ ...eventCtx,+ previousEventsCount: previous?.subscriptionPeriodEventsCount,+ },+ `polar webhook: new billing cycle for ${metadata.organizationId}, reset usage counter ${previous?.subscriptionPeriodEventsCount ?? 0} -> 0`+ );+ return;+ }+ // All subscription lifecycle events carry the same Subscription object;+ // sync them through a single path (new subs, cancellations, revokes,+ // reactivations, plan changes, payment-state changes).+ // Pause/resume transitions arrive via `subscription.updated` (the SDK's+ // webhook union has no dedicated paused/reactivated payloads yet) and are+ // reflected in `status` / `pauseAtPeriodEnd` / `resumesAt` below.+ case 'subscription.created':+ case 'subscription.active':+ case 'subscription.updated':+ case 'subscription.uncanceled':+ case 'subscription.canceled':+ case 'subscription.revoked':+ case 'subscription.past_due': {+ await syncSubscriptionToOrg(event.data, event.type, logger);+ return;+ }+ default: {+ logger.info(eventCtx, 'polar webhook: unhandled event type, acking');+ }+ }+}diff --git a/packages/core/src/rest.routes.ts b/packages/core/src/rest.routes.tsindex 8b5bd0a57..da490d9ed 100644--- a/packages/core/src/rest.routes.ts+++ b/packages/core/src/rest.routes.ts@@ -14,8 +14,10 @@ import { clientRoutes } from './modules/client/client.routes';import { gscRoutes } from './modules/gsc/gsc.routes';import { healthRoutes } from './modules/health/health.routes';import { importRoutes } from './modules/import/import.routes';+import { integrationRoutes } from './modules/integration/integration.routes';import { mcpRoutes } from './modules/mcp/mcp.routes';import { projectRoutes } from './modules/project/project.routes';+import { subscriptionRoutes } from './modules/subscription/subscription.routes';// ADR-002/ADR-003 pin: @elysiajs/openapi at the 1.4.15 fallback (2.0 is// NO-GO per spike 6). `specPath` is set explicitly rather than taking the@@ -52,12 +54,19 @@ export const publicApiRoutes = (deps: AppDeps) =>// 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.+// integration's `/webhook/slack` and subscription's `/webhook/polar` (M6-006)+// joined it too — like `/oauth`, `/webhook` IS in the CORS delegator's+// `corsPaths` allowlist (ADR-002 rule 4), unlike `/gsc`/`/mcp`, and both are+// the same shape of unauthenticated third-party-redirected callback as+// `/oauth`'s.export const dashboardRoutes = (deps: AppDeps) =>new Elysia({ name: 'core/dashboard-routes' }).use(gscRoutes(deps)).use(assistantRoutes(deps)).use(mcpRoutes(deps))- .use(authRoutes(deps));+ .use(authRoutes(deps))+ .use(integrationRoutes(deps))+ .use(subscriptionRoutes(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 3627feb2b..3f4e78b79 100644--- a/packages/core/src/rpc.router.ts+++ b/packages/core/src/rpc.router.ts@@ -14,12 +14,14 @@ 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 { integrationRouter } from './modules/integration/integration.rpc';import { notificationRouter } from './modules/notification/notification.rpc';import { onboardingRouter } from './modules/onboarding/onboarding.rpc';import { organizationRouter } from './modules/organization/organization.rpc';import { projectRouter } from './modules/project/project.rpc';import { referenceRouter } from './modules/reference/reference.rpc';import { shareRouter } from './modules/share/share.rpc';+import { subscriptionRouter } from './modules/subscription/subscription.rpc';import { userRouter } from './modules/user/user.rpc';import { createTRPCRouter } from './rpc/base';@@ -41,6 +43,8 @@ export const appRouter = createTRPCRouter({share: shareRouter,email: emailRouter,notification: notificationRouter,+ integration: integrationRouter,+ subscription: subscriptionRouter,});export type AppRouter = typeof appRouter;diff --git a/packages/trpc/src/routers/integration.ts b/packages/trpc/src/routers/integration.tsindex 915f79726..cb0413a94 100644--- a/packages/trpc/src/routers/integration.ts+++ b/packages/trpc/src/routers/integration.ts@@ -1,285 +1,45 @@+// Dissolved into @openpanel/core's integration module (M6-006): the CRUD,+// Slack OAuth install and connection-test bodies moved to+// packages/core/src/modules/integration/integration.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 integration functions, same as notification's router does+// (M6-005).+import {- carryOverConfigSecrets,- encryptConfigSecrets,- findEncryptedSecretField,- findMissingSecretFields,- getServerIntegration,- getSlackInstallUrl,- redactConfigSecrets,+ createOrUpdateSlackIntegration,+ deleteIntegration,+ getIntegrationById,+ listIntegrationsForProject,+ testExportIntegrationConnection,+ testIntegrationConnection,+ upsertIntegration,} from '@openpanel/core';-import { BASE_INTEGRATIONS, db } from '@openpanel/db';import {- type IIntegrationConfig,- type ISlackConfig,zCreateGCSExportIntegration,zCreateS3ExportIntegration,zCreateSlackIntegration,zIntegrationConfig,} from '@openpanel/validation';import { z } from 'zod';-import {- getOrganizationAccess,- requireOrganizationAdmin,- requireProjectAccess,-} from '../access';-import { TRPCBadRequestError, TRPCForbiddenError } from '../errors';import { createTRPCRouter, protectedProcedure } from '../trpc';-// Assert the user can act on the project at `level`, and return the project's-// organizationId (still stored on the integration for org-level queries/cascades).-async function assertProjectAccessAndGetOrg(- userId: string,- projectId: string,- level: 'read' | 'write'-) {- await requireProjectAccess({ userId, projectId, level });-- const project = await db.project.findUniqueOrThrow({- where: { id: projectId },- select: { organizationId: true },- });- return project.organizationId;-}--// Credentials are write-only: they are encrypted at rest and never travel back-// to a client. `read` on a project is bare membership, so returning the stored-// ciphertext would hand every project member the org's object-store keys — and-// because `decryptCredential` accepts any `enc:` blob under the single global-// key, that ciphertext is a replayable bearer token, not an opaque handle.-function redactIntegration<T extends { config: unknown }>(integration: T): T {- const config = redactConfigSecrets(integration.config);- return config === integration.config- ? integration- : { ...integration, config };-}--// A client never legitimately holds a ciphertext (see redactIntegration), so-// one arriving on the wire is an attempt to replay a secret lifted from another-// integration into an attacker-chosen destination.-function rejectEncryptedSecrets(config: unknown) {- const field = findEncryptedSecretField(config);- if (field) {- throw new TRPCBadRequestError(- `\`${field}\` looks like a stored, already-encrypted value. Paste the real credential, or leave it blank to keep the current one.`- );- }-}--// Shared create/update path for any form-configured integration. All per-type-// behavior (validation, connection test, credential encryption) is delegated to-// the integration's server plugin — adding a new integration needs no change here.-async function upsertIntegration(- userId: string,- input: {- id?: string;- name: string;- projectId: string;- config: IIntegrationConfig;- }-) {- // Authorize first. For an update, authorize against the EXISTING integration's- // scope — not the attacker-controlled input.projectId — so a user with access- // to one project can't update another project's integration in the same org.- rejectEncryptedSecrets(input.config);-- let organizationId: string;- let storedConfig: unknown;- if (input.id) {- const existing = await db.integration.findUniqueOrThrow({- where: { id: input.id },- select: { projectId: true, organizationId: true, config: true },- });- await assertIntegrationAccess(userId, existing, 'write');- organizationId = existing.organizationId;- storedConfig = existing.config;- } else {- organizationId = await assertProjectAccessAndGetOrg(- userId,- input.projectId,- 'write'- );- }-- // A blank secret means "keep the stored one" — the client can't resubmit what- // it was never given. On create there is nothing to fall back to.- const submitted = input.id- ? carryOverConfigSecrets(input.config, storedConfig)- : input.config;-- const missing = findMissingSecretFields(submitted);- if (missing.length > 0) {- throw new TRPCBadRequestError(- `Missing credential${missing.length > 1 ? 's' : ''}: ${missing.join(', ')}`- );- }-- const plugin = getServerIntegration(submitted.type);-- const validation = plugin.validateConfig?.(submitted);- if (validation && !validation.valid) {- throw new TRPCBadRequestError(`Invalid config: ${validation.error}`);- }-- // Test the connection with the real credentials before saving. `submitted`- // may carry a still-encrypted value forward from the stored row; the adapters- // decrypt on construction, so this works for both new and carried-over keys.- const testResult = await plugin.testConnection?.(submitted);- if (testResult && !testResult.success) {- throw new TRPCBadRequestError(`Failed to connect: ${testResult.error}`);- }-- const config = encryptConfigSecrets(submitted);-- if (input.id) {- return db.integration.update({- where: { id: input.id, organizationId },- data: { name: input.name, config },- });- }- return db.integration.create({- data: {- name: input.name,- organizationId,- projectId: input.projectId,- config,- },- });-}--// Access check for an existing integration of either scope. Project-scoped rows-// go through the project ladder; legacy org-wide rows (projectId null) have no-// project access level to consult, so a write to one — it is shared by every-// project in the org — is admin-tier, while a read only needs membership.-async function assertIntegrationAccess(- userId: string,- integration: { projectId: string | null; organizationId: string },- level: 'read' | 'write'-) {- if (integration.projectId) {- await requireProjectAccess({- userId,- projectId: integration.projectId,- level,- });- return;- }-- if (level === 'write') {- await requireOrganizationAdmin({- userId,- organizationId: integration.organizationId,- message: 'Only organization admins can change an org-wide integration',- });- return;- }-- const access = await getOrganizationAccess({- userId,- organizationId: integration.organizationId,- });- if (!access) {- throw new TRPCForbiddenError('You do not have access to this integration');- }-}-export const integrationRouter = createTRPCRouter({get: protectedProcedure.input(z.object({ id: z.string() }))- .query(async ({ input, ctx }) => {- const integration = await db.integration.findUniqueOrThrow({- where: {- id: input.id,- },- });-- await assertIntegrationAccess(ctx.session.userId, integration, 'read');-- return redactIntegration(integration);- }),+ .query(({ input, ctx }) =>+ getIntegrationById(ctx.session.userId, input.id)+ ),list: protectedProcedure.input(z.object({ projectId: z.string() }))- .query(async ({ input, ctx }) => {- const organizationId = await assertProjectAccessAndGetOrg(- ctx.session.userId,- input.projectId,- 'read'- );-- const integrations = await db.integration.findMany({- where: {- // The project's own integrations, plus legacy org-wide integrations- // (projectId null) so they stay visible/selectable during the- // transition off org-scoping.- OR: [- { projectId: input.projectId },- { projectId: null, organizationId },- ],- config: {- not: {},- },- },- });-- return [...BASE_INTEGRATIONS, ...integrations.map(redactIntegration)];- }),+ .query(({ input, ctx }) =>+ listIntegrationsForProject(ctx.session.userId, input.projectId)+ ),createOrUpdateSlack: protectedProcedure.input(zCreateSlackIntegration)- .mutation(async ({ input, ctx }) => {- // For an update, authorize against the existing integration's scope so a- // user can't clear/re-install another project's Slack integration.- let organizationId: string;- // Carried into the OAuth metadata and the post-callback redirect, so it- // has to be the row's own project — not whatever `input` asked for, which- // on an update is unauthorized and may point at a different project.- let projectId: string;- if (input.id) {- const existing = await db.integration.findUniqueOrThrow({- where: { id: input.id },- select: { projectId: true, organizationId: true },- });- await assertIntegrationAccess(ctx.session.userId, existing, 'write');- organizationId = existing.organizationId;- projectId = existing.projectId ?? input.projectId;- } else {- organizationId = await assertProjectAccessAndGetOrg(- ctx.session.userId,- input.projectId,- 'write'- );- projectId = input.projectId;- }-- const res = input.id- ? await db.integration.update({- where: {- id: input.id,- organizationId,- },- data: {- name: input.name,- // This is empty and will be filled by the webhook- config: {} as ISlackConfig,- },- })- : await db.integration.create({- data: {- name: input.name,- organizationId,- projectId: input.projectId,- // This is empty and will be filled by the webhook- config: {} as ISlackConfig,- },- });-- return {- ...res,- slackInstallUrl: await getSlackInstallUrl({- integrationId: res.id,- organizationId,- projectId,- }),- };- }),+ .mutation(({ input, ctx }) =>+ createOrUpdateSlackIntegration(ctx.session.userId, input)+ ),// Generic create/update for any form-configured integration. Per-type// behavior lives in the server plugin; no switch here.createOrUpdate: protectedProcedure@@ -308,53 +68,19 @@ export const integrationRouter = createTRPCRouter({config: zIntegrationConfig,}))- .mutation(async ({ input, ctx }) => {- await requireProjectAccess({- userId: ctx.session.userId,- projectId: input.projectId,- level: 'write',- });- rejectEncryptedSecrets(input.config);-- return (- (await getServerIntegration(input.config.type).testConnection?.(- input.config- )) ?? { success: true }- );- }),+ .mutation(({ input, ctx }) =>+ testIntegrationConnection(ctx.session.userId, input)+ ),// Back-compat alias for the export forms; same gate as `testConnection`.// TODO: remove once the dashboard calls `testConnection` directly.testExportConnection: protectedProcedure.input(z.union([zCreateS3ExportIntegration, zCreateGCSExportIntegration]))- .mutation(async ({ input, ctx }) => {- await requireProjectAccess({- userId: ctx.session.userId,- projectId: input.projectId,- level: 'write',- });- rejectEncryptedSecrets(input.config);-- return (- (await getServerIntegration(input.config.type).testConnection?.(- input.config- )) ?? { success: false, error: 'Unknown export type' }- );- }),+ .mutation(({ input, ctx }) =>+ testExportIntegrationConnection(ctx.session.userId, input)+ ),delete: protectedProcedure.input(z.object({ id: z.string() }))- .mutation(async ({ input: { id }, ctx }) => {- const integration = await db.integration.findUniqueOrThrow({- where: {- id,- },- });-- await assertIntegrationAccess(ctx.session.userId, integration, 'write');-- return db.integration.delete({- where: {- id,- },- });- }),+ .mutation(({ input: { id }, ctx }) =>+ deleteIntegration(ctx.session.userId, id)+ ),});diff --git a/packages/trpc/src/routers/subscription.ts b/packages/trpc/src/routers/subscription.tsindex 979999c70..94d379196 100644--- a/packages/trpc/src/routers/subscription.ts+++ b/packages/trpc/src/routers/subscription.ts@@ -1,343 +1,74 @@+// Dissolved into @openpanel/core's subscription module (M6-006): the+// checkout/products/usage/cancel/pause/resume/save-discount/portal bodies+// moved to packages/core/src/modules/subscription/subscription.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 subscription functions, same as notification's+// router does (M6-005).+import {- db,- getOrganizationAccess,- getOrganizationBillingEventsCountSerieCached,- getOrganizationById,-} from '@openpanel/db';-import {- applySubscriptionDiscount,+ applySaveDiscount,cancelSubscription,- changeSubscription,- createCheckout,- createPortal,- getProduct,- getProducts,+ checkout,+ getCurrentSubscriptionProduct,+ getUsage,+ listProducts,pauseSubscription,- reactivateSubscription,+ portal,resumeSubscription,- unpauseSubscription,-} from '@openpanel/payments';-import { getCache } from '@openpanel/redis';+} from '@openpanel/core';import {zCancelSubscription,zCheckout,zPauseSubscription,} from '@openpanel/validation';-import { addMonths, subDays } from 'date-fns';import { z } from 'zod';-import { TRPCBadRequestError, TRPCForbiddenError } from '../errors';import { createTRPCRouter, protectedProcedure } from '../trpc';-async function requireAdmin(userId: string, organizationId: string) {- const access = await getOrganizationAccess({ userId, organizationId });- if (access?.role !== 'org:admin') {- throw new TRPCForbiddenError('Only organization admins can manage billing');- }-}-export const subscriptionRouter = createTRPCRouter({getCurrent: protectedProcedure.input(z.object({ organizationId: z.string() }))- .query(async ({ input }) => {- const organization = await getOrganizationById(input.organizationId);-- if (!organization.subscriptionProductId) {- return null;- }-- return getProduct(organization.subscriptionProductId);- }),+ .query(({ input }) => getCurrentSubscriptionProduct(input.organizationId)),checkout: protectedProcedure.input(zCheckout)- .mutation(async ({ input, ctx }) => {- await requireAdmin(ctx.session.userId, input.organizationId);- const [user, organization] = await Promise.all([- db.user.findFirstOrThrow({- where: {- id: ctx.session.user.id,- },- }),- db.organization.findFirstOrThrow({- where: {- id: input.organizationId,- },- }),- ]);-- // A paused (or pause-scheduled) subscription still exists in Polar — a- // checkout here would create a second one, and a plan change would race- // the pending pause. Resume first, then change plans.- if (- organization.subscriptionId &&- (organization.subscriptionStatus === 'paused' ||- organization.subscriptionPauseAtPeriodEnd)- ) {- throw new TRPCBadRequestError(- 'Your subscription is paused or scheduled to pause — resume it before changing plans'- );- }-- // An organization has at most one Polar subscription (we have no free- // tier in Polar — the free plan is handled on our side). So an upgrade or- // downgrade is an in-place product change, never a cancel + re-subscribe.- // Reactivate first if it was scheduled to cancel, otherwise change the- // product on the existing subscription.- if (- organization.subscriptionId &&- organization.subscriptionStatus === 'active'- ) {- if (organization.subscriptionCanceledAt) {- await reactivateSubscription(organization.subscriptionId);- return null;- }-- // Already on this product — nothing to change.- if (organization.subscriptionProductId === input.productId) {- return null;- }-- await changeSubscription(organization.subscriptionId, input.productId);- return null;- }-- const checkout = await createCheckout({- productId: input.productId,- organizationId: input.organizationId,- user,- ipAddress: ctx.remoteAddress,- });-- return {- url: checkout.url,- };- }),+ .mutation(({ input, ctx }) =>+ checkout(ctx.session.userId, input, ctx.remoteAddress)+ ),products: protectedProcedure.input(z.object({ organizationId: z.string() }))- .query(async ({ input }) => {- const organization = await db.organization.findUniqueOrThrow({- where: {- id: input.organizationId,- },- select: {- subscriptionPeriodEventsCount: true,- },- });-- return (- await getCache('polar:products', 60 * 60 * 24, () => getProducts())- ).map((product) => {- const eventsLimit = product.metadata.eventsLimit;- return {- ...product,- disabled:- typeof eventsLimit === 'number' &&- organization.subscriptionPeriodEventsCount >= eventsLimit- ? 'This product is not applicable since you have exceeded the limits for this subscription.'- : null,- };- });- }),+ .query(({ input }) => listProducts(input.organizationId)),usage: protectedProcedure- .input(- z.object({- organizationId: z.string(),- })- )- .query(async ({ input }) => {- const organization = await db.organization.findUniqueOrThrow({- where: {- id: input.organizationId,- },- include: {- projects: { select: { id: true } },- },- });-- if (- organization.hasSubscription &&- organization.subscriptionStartsAt &&- organization.subscriptionEndsAt- ) {- return getOrganizationBillingEventsCountSerieCached(organization, {- startDate: organization.subscriptionStartsAt,- endDate: organization.subscriptionEndsAt,- });- }-- return getOrganizationBillingEventsCountSerieCached(organization, {- startDate: subDays(new Date(), 30),- endDate: new Date(),- });- }),+ .input(z.object({ organizationId: z.string() }))+ .query(({ input }) => getUsage(input.organizationId)),cancelSubscription: protectedProcedure.input(zCancelSubscription)- .mutation(async ({ input, ctx }) => {- await requireAdmin(ctx.session.userId, input.organizationId);- const organization = await getOrganizationById(input.organizationId);- if (!organization.subscriptionId) {- throw new TRPCBadRequestError('Organization has no subscription');- }-- const res = await cancelSubscription(organization.subscriptionId, {- reason: input.reason,- comment: input.comment,- });-- // The webhook echoes these back, but persist immediately so a missed or- // delayed delivery can't lose the reason — or leave `canceledAt` unset,- // which would make the plan-change path skip reactivation and silently- // keep the cancellation scheduled.- await db.organization.update({- where: { id: input.organizationId },- data: {- subscriptionCancelReason: input.reason,- subscriptionCancelComment: input.comment ?? null,- subscriptionCanceledAt: res.canceledAt,- subscriptionEndsAt: res.cancelAtPeriodEnd- ? res.currentPeriodEnd- : (res.canceledAt ?? organization.subscriptionEndsAt),- },- });-- return res;- }),+ .mutation(({ input, ctx }) =>+ cancelSubscription(ctx.session.userId, input)+ ),pauseSubscription: protectedProcedure.input(zPauseSubscription)- .mutation(async ({ input, ctx }) => {- await requireAdmin(ctx.session.userId, input.organizationId);- const organization = await getOrganizationById(input.organizationId);- if (!organization.subscriptionId) {- throw new TRPCBadRequestError('Organization has no subscription');- }- // Only a plain active subscription can be paused — this rejects paused,- // pause-scheduled (pausing), canceling, canceled, unpaid, etc. before we- // hit Polar with a nonsensical update.- if (organization.subscriptionState !== 'active') {- throw new TRPCBadRequestError(- 'Only an active subscription can be paused'- );- }- if (!organization.subscriptionEndsAt) {- throw new TRPCBadRequestError('Subscription has no current period end');- }-- // Polar pauses at period end; the resume date counts from there.- const resumesAt = addMonths(- organization.subscriptionEndsAt,- input.months- );-- await pauseSubscription(organization.subscriptionId, resumesAt);-- // Optimistic mirror — the subscription.updated webhook confirms it.- await db.organization.update({- where: { id: input.organizationId },- data: {- subscriptionPauseAtPeriodEnd: true,- subscriptionResumesAt: resumesAt,- },- });-- return { resumesAt };- }),+ .mutation(({ input, ctx }) => pauseSubscription(ctx.session.userId, input)),resumeSubscription: protectedProcedure.input(z.object({ organizationId: z.string() }))- .mutation(async ({ input, ctx }) => {- await requireAdmin(ctx.session.userId, input.organizationId);- const organization = await getOrganizationById(input.organizationId);- if (!organization.subscriptionId) {- throw new TRPCBadRequestError('Organization has no subscription');- }-- if (organization.subscriptionStatus === 'paused') {- // Already paused — resuming starts a new billing period immediately.- await resumeSubscription(organization.subscriptionId);- } else if (organization.subscriptionPauseAtPeriodEnd) {- // Pause is only scheduled — just clear it.- await unpauseSubscription(organization.subscriptionId);- } else {- throw new TRPCBadRequestError('Subscription is not paused');- }-- await db.organization.update({- where: { id: input.organizationId },- data: {- subscriptionPauseAtPeriodEnd: false,- subscriptionResumesAt: null,- },- });-- return { success: true };- }),+ .mutation(({ input, ctx }) =>+ resumeSubscription(ctx.session.userId, input.organizationId)+ ),applySaveDiscount: protectedProcedure.input(z.object({ organizationId: z.string() }))- .mutation(async ({ input, ctx }) => {- await requireAdmin(ctx.session.userId, input.organizationId);- const discountId = process.env.POLAR_SAVE_DISCOUNT_ID;- if (!discountId) {- throw new TRPCBadRequestError('Save discount is not configured');- }-- const organization = await getOrganizationById(input.organizationId);- if (!organization.subscriptionId) {- throw new TRPCBadRequestError('Organization has no subscription');- }-- // Claim the one-time offer atomically BEFORE calling Polar: a- // conditional update lets exactly one concurrent request through. Roll- // the claim back if Polar rejects, so a transient failure doesn't burn- // the offer.- const claimed = await db.organization.updateMany({- where: {- id: input.organizationId,- subscriptionSaveDiscountAppliedAt: null,- },- data: { subscriptionSaveDiscountAppliedAt: new Date() },- });- if (claimed.count === 0) {- throw new TRPCBadRequestError(- 'The save discount has already been used'- );- }-- try {- await applySubscriptionDiscount(- organization.subscriptionId,- discountId- );- } catch (error) {- await db.organization.updateMany({- where: { id: input.organizationId },- data: { subscriptionSaveDiscountAppliedAt: null },- });- throw error;- }-- return { success: true };- }),+ .mutation(({ input, ctx }) =>+ applySaveDiscount(ctx.session.userId, input.organizationId)+ ),portal: protectedProcedure.input(z.object({ organizationId: z.string() }))- .mutation(async ({ input, ctx }) => {- await requireAdmin(ctx.session.userId, input.organizationId);- const organization = await getOrganizationById(input.organizationId);- if (!organization.subscriptionCustomerId) {- throw new TRPCBadRequestError('Organization has no subscription');- }-- const portal = await createPortal({- customerId: organization.subscriptionCustomerId,- });-- return {- url: portal.customerPortalUrl,- };- }),+ .mutation(({ input, ctx }) =>+ portal(ctx.session.userId, input.organizationId)+ ),});diff --git a/packages/validation/src/index.ts b/packages/validation/src/index.tsindex 138d8cefb..3c1554d0a 100644--- a/packages/validation/src/index.ts+++ b/packages/validation/src/index.ts@@ -359,14 +359,16 @@ export const zCreateReference = z.object({datetime: z.string(),});-// 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';-+// Moved into @openpanel/core's integration module (M6-006, ADR-008's module+// map: integration owns "C"). Re-exported here for existing+// @openpanel/validation importers (packages/trpc's integration router,+// apps/start's integration forms) — same shape as ./onboarding.constants.ts+// re-export since M6-003. `zSlackAuthResponse` does NOT come along: it moved+// to the module's `src/` (Slack's own OAuth wire contract, not integration+// config) and is now reached through @openpanel/core's curated barrel+// instead — apps/api/src/controllers/webhook.controller.ts (the one former+// importer) updated to match.+export * from '@openpanel/core/modules/integration/integration.constants';// Moved into @openpanel/core's notification module (M6-005, ADR-008's module// map: notification owns "C"). Re-exported here for existing// @openpanel/validation importers (packages/trpc's notification router,@@ -376,6 +378,12 @@ export * from './integrations';// file, so the resulting module cycle resolves at the value level: see// notification.constants.ts's header.export * from '@openpanel/core/modules/notification/notification.constants';+// 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 const zProjectFilterIp = z.object({type: z.literal('ip'),@@ -428,41 +436,12 @@ export type IProjectUpdate = z.infer<typeof zProjectUpdate>;// 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(),- organizationId: z.string(),- projectId: z.string().nullish(),- productId: z.string(),-});-export type ICheckout = z.infer<typeof zCheckout>;--// Mirrors Polar's CustomerCancellationReason enum.-export const zCancellationReason = z.enum([- 'too_expensive',- 'missing_features',- 'switched_service',- 'unused',- 'customer_service',- 'low_quality',- 'too_complex',- 'other',-]);-export type ICancellationReason = z.infer<typeof zCancellationReason>;--export const zCancelSubscription = z.object({- organizationId: z.string(),- reason: zCancellationReason,- comment: z.string().trim().max(1000).optional(),-});-export type ICancelSubscription = z.infer<typeof zCancelSubscription>;--export const zPauseSubscription = z.object({- organizationId: z.string(),- // Months after the current period end before billing automatically resumes.- months: z.union([z.literal(1), z.literal(2), z.literal(3)]),-});-export type IPauseSubscription = z.infer<typeof zPauseSubscription>;+// Moved into @openpanel/core's subscription module (M6-006, ADR-008's module+// map: subscription owns "C"). Re-exported here for existing+// @openpanel/validation importers (packages/trpc's subscription router,+// apps/start's billing forms) — same shape as ./onboarding.constants.ts+// re-export since M6-003.+export * from '@openpanel/core/modules/subscription/subscription.constants';export const zGroupId = z.string()