OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M4-007): P4: packages/auth dissolves into core modules/auth service
ralphb470343c643c
diff --git a/apps/api/package.json b/apps/api/package.jsonindex 9e3f65abe..b8539ba67 100644--- a/apps/api/package.json+++ b/apps/api/package.json@@ -27,7 +27,6 @@"@fastify/websocket": "^11.2.0","@hyperdx/node-opentelemetry": "catalog:","@node-rs/argon2": "^2.0.2",- "@openpanel/auth": "workspace:^","@openpanel/common": "workspace:*","@openpanel/constants": "workspace:*","@openpanel/core": "workspace:*",diff --git a/apps/api/src/app.ts b/apps/api/src/app.tsindex d1cacbba6..282d7ebb3 100644--- a/apps/api/src/app.ts+++ b/apps/api/src/app.ts@@ -6,21 +6,18 @@ import cookie from '@fastify/cookie';import cors, { type FastifyCorsOptions } from '@fastify/cors';import fastifySwagger from '@fastify/swagger';import fastifySwaggerUI from '@fastify/swagger-ui';-import {- decodeSessionToken,- EMPTY_SESSION,- type SessionValidationResult,- validateSessionToken,-} from '@openpanel/auth';import { generateId } from '@openpanel/common';-import { getTrustedIpFromHeaders } from '@openpanel/core';+import { decodeSessionToken, getTrustedIpFromHeaders } from '@openpanel/core';import {+ EMPTY_SESSION,getConversationById,getOrganizationByProjectIdCached,getProjectAccess,getSettingsForProject,type IServiceClientWithProject,runWithAlsSession,+ type SessionValidationResult,+ validateSessionToken,} from '@openpanel/db';import type { AppRouter } from '@openpanel/trpc';import { appRouter, createContext } from '@openpanel/trpc';diff --git a/apps/api/src/controllers/gsc-oauth-callback.controller.ts b/apps/api/src/controllers/gsc-oauth-callback.controller.tsindex 61b6dcdee..24cbb502f 100644--- a/apps/api/src/controllers/gsc-oauth-callback.controller.ts+++ b/apps/api/src/controllers/gsc-oauth-callback.controller.ts@@ -1,4 +1,4 @@-import { googleGsc } from '@openpanel/auth';+import { googleGsc } from '@openpanel/core';import { db, encrypt } from '@openpanel/db';import type { FastifyReply, FastifyRequest } from 'fastify';import { z } from 'zod';diff --git a/apps/api/src/controllers/oauth-callback.controller.tsx b/apps/api/src/controllers/oauth-callback.controller.tsxindex ff311a352..94e971655 100644--- a/apps/api/src/controllers/oauth-callback.controller.tsx+++ b/apps/api/src/controllers/oauth-callback.controller.tsx@@ -1,16 +1,16 @@import {Arctic,- createSession,generateSessionToken,github,google,type OAuth2Tokens,setLastAuthProviderCookie,setSessionTokenCookie,-} from '@openpanel/auth';+} from '@openpanel/core';import {type Account,connectUserToOrganization,+ createSession,db,getIsRegistrationAllowed,} from '@openpanel/db';@@ -169,11 +169,14 @@ async function handleNewUser({try {await connectUserToOrganization({ user, inviteId });} catch (error) {- reply.log.error({- error,- inviteId,- user,- }, 'error connecting user to organization');+ reply.log.error(+ {+ error,+ inviteId,+ user,+ },+ 'error connecting user to organization'+ );}}diff --git a/packages/auth/constants.ts b/packages/auth/constants.tsdeleted file mode 100644index d801a97ea..000000000--- a/packages/auth/constants.ts+++ /dev/null@@ -1,14 +0,0 @@-import { parseCookieDomain } from './parse-cookie-domain';--const parsed = parseCookieDomain(- (process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL) ?? '',-);--export const COOKIE_MAX_AGE = 60 * 60 * 24 * 30;-export const COOKIE_OPTIONS = {- domain: parsed.domain,- secure: parsed.secure,- sameSite: 'lax',- httpOnly: true,- path: '/',-} as const;diff --git a/packages/auth/index.ts b/packages/auth/index.tsdeleted file mode 100644index d1628aec9..000000000--- a/packages/auth/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from './src';-export * from './constants';diff --git a/packages/auth/package.json b/packages/auth/package.jsondeleted file mode 100644index 3dd179e6f..000000000--- a/packages/auth/package.json+++ /dev/null@@ -1,30 +0,0 @@-{- "name": "@openpanel/auth",- "version": "0.0.1",- "type": "module",- "main": "index.ts",- "scripts": {- "typecheck": "tsc --noEmit"- },- "dependencies": {- "@node-rs/argon2": "^2.0.2",- "@openpanel/db": "workspace:^",- "@openpanel/validation": "workspace:^",- "@oslojs/crypto": "^1.0.1",- "@oslojs/encoding": "^1.1.0",- "@oslojs/otp": "^1.1.0",- "arctic": "^2.3.0",- "qrcode": "^1.5.4"- },- "devDependencies": {- "@openpanel/tsconfig": "workspace:*",- "@types/node": "catalog:",- "@types/qrcode": "^1.5.6",- "@types/react": "catalog:",- "prisma": "^5.1.1",- "typescript": "catalog:"- },- "peerDependencies": {- "react": "catalog:"- }-}\ No newline at end of filediff --git a/packages/auth/src/index.ts b/packages/auth/src/index.tsdeleted file mode 100644index 1f170515a..000000000--- a/packages/auth/src/index.ts+++ /dev/null@@ -1,5 +0,0 @@-export * from './cookie';-export * from './oauth';-export * from './password';-export * from './session';-export * from './totp';diff --git a/packages/auth/tsconfig.json b/packages/auth/tsconfig.jsondeleted file mode 100644index a4a54fb86..000000000--- a/packages/auth/tsconfig.json+++ /dev/null@@ -1,13 +0,0 @@-{- "extends": "@openpanel/tsconfig/base.json",- "compilerOptions": {- "baseUrl": ".",- "paths": {- "@/*": ["./src/*"]- },- "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json",- "strictNullChecks": true- },- "include": ["."],- "exclude": ["node_modules"]-}diff --git a/packages/core/package.json b/packages/core/package.jsonindex eeb149f88..1ee2fac02 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -26,12 +26,16 @@"@google-cloud/storage": "^7.18.0","@hyperdx/node-opentelemetry": "catalog:","@maxmind/geoip2-node": "^6.1.0",- "@openpanel/auth": "workspace:^",+ "@node-rs/argon2": "^2.0.2","@openpanel/common": "workspace:*","@openpanel/validation": "workspace:*",+ "@oslojs/crypto": "^1.0.1",+ "@oslojs/encoding": "^1.1.0",+ "@oslojs/otp": "^1.1.0","@slack/bolt": "^3.18.0","@slack/oauth": "^3.0.0","@trpc/server": "^11.17.0",+ "arctic": "^2.3.0","bullmq": "6.3.3","elysia": "1.4.30","ipaddr.js": "^2.5.0",@@ -40,13 +44,16 @@"pino": "catalog:","pino-pretty": "catalog:","prom-client": "^15.1.3",+ "qrcode": "^1.5.4","superjson": "^1.13.3","ua-parser-js": "^2.0.6","undici": "^8.10.0","zod": "catalog:"},"devDependencies": {+ "@openpanel/db": "workspace:*","@openpanel/tsconfig": "workspace:*",+ "@types/qrcode": "^1.5.6","bun-types": "1.4.0","tar": "^7.4.3","typescript": "catalog:"diff --git a/packages/core/src/context.test.ts b/packages/core/src/context.test.tsindex a5412517f..4f25eb2d2 100644--- a/packages/core/src/context.test.ts+++ b/packages/core/src/context.test.ts@@ -9,11 +9,12 @@ import type { ServiceDeps, Services } from './services';// mock.module is not hoisted, so the subject is imported inside beforeAll —// see AGENTS.md. Mocking createServices is what makes "not built yet"-// observable at all: the real container is `{}` either way.+// observable at all — this suite cares about WHEN the factory runs, not what+// it returns, so the stub container is cast rather than built for real.const serviceDeps: ServiceDeps[] = [];const createServices = mock((deps: ServiceDeps): Services => {serviceDeps.push(deps);- return {};+ return {} as Services;});mock.module('./services', () => ({ createServices }));diff --git a/packages/core/src/context.ts b/packages/core/src/context.tsindex 083865386..0855ac2f8 100644--- a/packages/core/src/context.ts+++ b/packages/core/src/context.ts@@ -4,7 +4,7 @@// edge reaches the query, the enqueue and the job that enqueue causes// (ADR-007 decision 18, ADR-018 R1).-import type { SessionValidationResult } from '@openpanel/auth';+import type { SessionValidationResult } from '@openpanel/db';import type { QueueProducerHandle, QueueProducers } from './jobs.registry';import type { Logger } from './logger';import { createServices, type Services } from './services';@@ -21,10 +21,13 @@ export type RedisClient = unknown;export type ServiceClients = unknown;export type Buffers = unknown;-// The resolved session. Type-only, so nothing of `@openpanel/auth` (and-// nothing of Prisma beneath it) is loaded at runtime — core stays importable-// with no database, which is what lets `bun test` run offline. The declaration-// moves here for real when auth dissolves into core (P4/P6).+// The resolved session. Type-only, so nothing of `@openpanel/db` is loaded at+// runtime — core stays importable with no database, which is what lets+// `bun test` run offline. `SessionValidationResult` is Prisma-shaped+// (Session + User), so it stays defined next to the Prisma-touching session+// CRUD in @openpanel/db's auth-session.service.ts rather than here — moving+// it to core would need a core -> db runtime dependency, and db already+// depends on core (M4-007).export type Session = SessionValidationResult;/** The env-derived flags core needs. apps/api's config/env.ts is the solediff --git a/packages/core/src/http/context.test.ts b/packages/core/src/http/context.test.tsindex 34b5aec40..6990db9db 100644--- a/packages/core/src/http/context.test.ts+++ b/packages/core/src/http/context.test.ts@@ -6,8 +6,9 @@ import type { Services } from '../services';// mock.module is not hoisted, so the subjects are imported inside beforeAll —// see AGENTS.md. Mocking createServices is what makes "not built yet"-// observable at all: the real container is `{}` either way.-const createServices = mock((): Services => ({}));+// observable at all — this suite cares about WHEN the factory runs, not what+// it returns, so the stub container is cast rather than built for real.+const createServices = mock((): Services => ({}) as Services);mock.module('../services', () => ({ createServices }));const resolveSession = mock(() => Promise.resolve({ userId: 'user_1' }));diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex d17e9bd52..63457ee7d 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -111,6 +111,38 @@ export {REQUEST_ID_LENGTH,REQUEST_ID_LOG_FIELD,} from './logger';+// Dissolved from @openpanel/auth (M4-007) — apps/api's OAuth callbacks and+// @openpanel/trpc's auth/share/user/gsc routers call these directly, the same+// way they reach the other dissolved leaf packages here. `hashPassword` is+// renamed on the way out: `./shared/crypto` already owns that name for the+// (unrelated) scrypt hash client secrets use.+export type { AuthService, OAuth2Tokens } from './modules/auth/auth.service';+export {+ Arctic,+ buildOtpauthUrl,+ COOKIE_MAX_AGE,+ COOKIE_OPTIONS,+ consumeRecoveryCode,+ createAuthService,+ decodeSessionToken,+ deleteSessionTokenCookie,+ generateQrDataUrl,+ generateRecoveryCodes,+ generateSessionToken,+ generateTotpSecret,+ github,+ google,+ googleGsc,+ hashPassword as hashUserPassword,+ hashRecoveryCodes,+ hashSessionToken,+ normalizeRecoveryCode,+ parseCookieDomain,+ setLastAuthProviderCookie,+ setSessionTokenCookie,+ verifyPasswordHash,+ verifyTotpCode,+} from './modules/auth/auth.service';export { dashboardRoutes, opsRoutes, publicApiRoutes } from './rest.routes';// The RPC base is on the barrel because it is the seam `@openpanel/trpc`// builds its 28 routers on: ONE tRPC instance, mounted by V1's Fastifydiff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.tsnew file mode 100644index 000000000..d5efb6a22--- /dev/null+++ b/packages/core/src/modules/auth/auth.service.ts@@ -0,0 +1,120 @@+// Moved from @openpanel/auth (M4-007). Only the DB-independent half lives+// here: token issuance/hashing, argon2 password hashing, TOTP, the OAuth+// clients and cookie helpers. The Prisma-touching half — creating,+// validating and invalidating a `sessions` row — stays in @openpanel/db's+// auth-session.service.ts, because @openpanel/db already depends on+// @openpanel/core (for exactly this module's token hash) and the reverse+// edge would be a cycle. That file calls back into `hashSessionToken` below.++import type { ServiceDeps } from '../../services';+import type { ISetCookie } from '../../shared/cookie';+import {+ deleteSessionTokenCookie,+ setLastAuthProviderCookie,+ setSessionTokenCookie,+} from './src/cookie';+import { parseCookieDomain } from './src/cookie-domain';+import { hashPassword, verifyPasswordHash } from './src/password';+import {+ decodeSessionToken,+ generateSessionToken,+ hashSessionToken,+} from './src/token';+import {+ buildOtpauthUrl,+ consumeRecoveryCode,+ generateQrDataUrl,+ generateRecoveryCodes,+ generateTotpSecret,+ hashRecoveryCodes,+ normalizeRecoveryCode,+ verifyTotpCode,+} from './src/totp';++// Re-exported straight from source (not through the imports above, which+// exist for `createAuthService` below) — `noExportedImports` would otherwise+// flag every one of those imports as "only re-exported", which is false;+// they are also this file's `AuthService` container.+export { COOKIE_MAX_AGE, COOKIE_OPTIONS } from './src/constants';+export {+ deleteSessionTokenCookie,+ setLastAuthProviderCookie,+ setSessionTokenCookie,+} from './src/cookie';+export { parseCookieDomain } from './src/cookie-domain';+export type { OAuth2Tokens } from './src/oauth';+export { Arctic, github, google, googleGsc } from './src/oauth';+export { hashPassword, verifyPasswordHash } from './src/password';+export {+ decodeSessionToken,+ generateSessionToken,+ hashSessionToken,+} from './src/token';+export {+ buildOtpauthUrl,+ consumeRecoveryCode,+ generateQrDataUrl,+ generateRecoveryCodes,+ generateTotpSecret,+ hashRecoveryCodes,+ normalizeRecoveryCode,+ verifyTotpCode,+} from './src/totp';++export interface AuthService {+ hashPassword(password: string): Promise<string>;+ verifyPasswordHash(hash: string, password: string): Promise<boolean>;+ generateSessionToken(): string;+ decodeSessionToken(token: string): string | null;+ hashSessionToken(token: string): string;+ generateTotpSecret(): string;+ buildOtpauthUrl(args: { secret: string; accountName: string }): string;+ generateQrDataUrl(otpauthUrl: string): Promise<string>;+ verifyTotpCode(secret: string, code: string): boolean;+ generateRecoveryCodes(count?: number): string[];+ hashRecoveryCodes(codes: string[]): Promise<string[]>;+ normalizeRecoveryCode(input: string): string;+ consumeRecoveryCode(args: {+ hashes: string[];+ input: string;+ }): Promise<{ valid: boolean; remaining: string[] }>;+ setSessionTokenCookie(+ setCookie: ISetCookie,+ token: string,+ expiresAt: Date+ ): void;+ setLastAuthProviderCookie(setCookie: ISetCookie, provider: string): void;+ deleteSessionTokenCookie(setCookie: ISetCookie): void;+ parseCookieDomain(url: string): {+ domain: string | undefined;+ secure: boolean;+ };+}++/**+ * Registered in `services.ts`. `deps` is unused today (every function here is+ * pure or reads its own env) — kept on the signature because every other+ * module's factory takes it, and a method that later needs `logger` should+ * not change the call site.+ */+export function createAuthService(_deps: ServiceDeps): AuthService {+ return {+ hashPassword,+ verifyPasswordHash,+ generateSessionToken,+ decodeSessionToken,+ hashSessionToken,+ generateTotpSecret,+ buildOtpauthUrl,+ generateQrDataUrl,+ verifyTotpCode,+ generateRecoveryCodes,+ hashRecoveryCodes,+ normalizeRecoveryCode,+ consumeRecoveryCode,+ setSessionTokenCookie,+ setLastAuthProviderCookie,+ deleteSessionTokenCookie,+ parseCookieDomain,+ };+}diff --git a/packages/core/src/modules/auth/src/constants.ts b/packages/core/src/modules/auth/src/constants.tsnew file mode 100644index 000000000..6fe5f7ea6--- /dev/null+++ b/packages/core/src/modules/auth/src/constants.ts@@ -0,0 +1,19 @@+// Read at import time, not through config/env.ts: this is the same pragmatic+// deviation @openpanel/db and @openpanel/redis take (TARGET_ARCHITECTURE §7)+// — ported from @openpanel/auth unchanged rather than threaded through+// AppDeps, which would make every module reachable from a session cookie+// carry a dependency on this one.+import { parseCookieDomain } from './cookie-domain';++const parsed = parseCookieDomain(+ (process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL) ?? ''+);++export const COOKIE_MAX_AGE = 60 * 60 * 24 * 30;+export const COOKIE_OPTIONS = {+ domain: parsed.domain,+ secure: parsed.secure,+ sameSite: 'lax',+ httpOnly: true,+ path: '/',+} as const;diff --git a/packages/auth/parse-cookie-domain.test.ts b/packages/core/src/modules/auth/src/cookie-domain.test.tssimilarity index 98%rename from packages/auth/parse-cookie-domain.test.tsrename to packages/core/src/modules/auth/src/cookie-domain.test.tsindex 992eda741..7ffcbc70e 100644--- a/packages/auth/parse-cookie-domain.test.ts+++ b/packages/core/src/modules/auth/src/cookie-domain.test.ts@@ -1,5 +1,5 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { parseCookieDomain } from './parse-cookie-domain';+import { afterEach, beforeEach, describe, expect, it } from 'bun:test';+import { parseCookieDomain } from './cookie-domain';describe('parseCookieDomain', () => {it('should return undefined domain for empty string', () => {@@ -223,7 +223,7 @@ describe('parseCookieDomain', () => {it('should handle domains with all URL components', () => {expect(- parseCookieDomain('https://example.com:8080/path?param=value#fragment'),+ parseCookieDomain('https://example.com:8080/path?param=value#fragment')).toEqual({domain: '.example.com',secure: true,@@ -274,7 +274,7 @@ describe('parseCookieDomain', () => {it('should throw error for URLs with invalid characters', () => {expect(() =>- parseCookieDomain('http://example.com:invalid-port'),+ parseCookieDomain('http://example.com:invalid-port')).toThrow();});});@@ -296,7 +296,7 @@ describe('parseCookieDomain', () => {it('should handle subdomains of openpanel.dev correctly', () => {expect(- parseCookieDomain('https://staging.dashboard.openpanel.dev'),+ parseCookieDomain('https://staging.dashboard.openpanel.dev')).toEqual({domain: '.openpanel.dev',secure: true,@@ -383,7 +383,7 @@ describe('parseCookieDomain', () => {'gov.ve',];- multiPartTLDs.forEach((tld) => {+ for (const tld of multiPartTLDs) {it(`should handle ${tld} domains correctly`, () => {expect(parseCookieDomain(`https://example.${tld}`)).toEqual({domain: `.example.${tld}`,@@ -397,7 +397,7 @@ describe('parseCookieDomain', () => {secure: true,});});- });+ }});describe('custom multi-part TLDs via COOKIE_TLDS', () => {diff --git a/packages/auth/parse-cookie-domain.ts b/packages/core/src/modules/auth/src/cookie-domain.tssimilarity index 100%rename from packages/auth/parse-cookie-domain.tsrename to packages/core/src/modules/auth/src/cookie-domain.tsdiff --git a/packages/auth/src/cookie.ts b/packages/core/src/modules/auth/src/cookie.tssimilarity index 85%rename from packages/auth/src/cookie.tsrename to packages/core/src/modules/auth/src/cookie.tsindex cfc4970ba..320b48179 100644--- a/packages/auth/src/cookie.ts+++ b/packages/core/src/modules/auth/src/cookie.ts@@ -1,5 +1,5 @@-import type { ISetCookie } from '@openpanel/validation';-import { COOKIE_OPTIONS } from '../constants';+import type { ISetCookie } from '../../../shared/cookie';+import { COOKIE_OPTIONS } from './constants';export function setSessionTokenCookie(setCookie: ISetCookie,diff --git a/packages/auth/src/oauth.ts b/packages/core/src/modules/auth/src/oauth.tssimilarity index 69%rename from packages/auth/src/oauth.tsrename to packages/core/src/modules/auth/src/oauth.tsindex 09f17adec..b14083df3 100644--- a/packages/auth/src/oauth.ts+++ b/packages/core/src/modules/auth/src/oauth.ts@@ -1,10 +1,11 @@+import * as Arctic from 'arctic';import { GitHub } from 'arctic';export type { OAuth2Tokens } from 'arctic';--import * as Arctic from 'arctic';--export { Arctic };+// Re-exported straight from source, not the `Arctic` import above — that one+// is also used below for `Arctic.Google`, so `export { Arctic }` would trip+// `noExportedImports` over a binding that genuinely has a second use.+export * as Arctic from 'arctic';export const github = new GitHub(process.env.GITHUB_CLIENT_ID ?? '',diff --git a/packages/auth/src/password.ts b/packages/core/src/modules/auth/src/password.tssimilarity index 89%rename from packages/auth/src/password.tsrename to packages/core/src/modules/auth/src/password.tsindex b0180ea52..b1b8c25ad 100644--- a/packages/auth/src/password.ts+++ b/packages/core/src/modules/auth/src/password.ts@@ -4,7 +4,7 @@ import { encodeHexLowerCase } from '@oslojs/encoding';export async function hashPassword(password: string): Promise<string> {return await hash(password, {- memoryCost: 19456,+ memoryCost: 19_456,timeCost: 2,outputLen: 32,parallelism: 1,@@ -13,13 +13,13 @@ export async function hashPassword(password: string): Promise<string> {export async function verifyPasswordHash(hash: string,- password: string,+ password: string): Promise<boolean> {return await verify(hash, password);}export async function verifyPasswordStrength(- password: string,+ password: string): Promise<boolean> {if (password.length < 8 || password.length > 255) {return false;@@ -27,7 +27,7 @@ export async function verifyPasswordStrength(const hash = encodeHexLowerCase(sha1(new TextEncoder().encode(password)));const hashPrefix = hash.slice(0, 5);const response = await fetch(- `https://api.pwnedpasswords.com/range/${hashPrefix}`,+ `https://api.pwnedpasswords.com/range/${hashPrefix}`);const data = await response.text();const items = data.split('\n');diff --git a/packages/core/src/modules/auth/src/token.ts b/packages/core/src/modules/auth/src/token.tsnew file mode 100644index 000000000..f2c442c36--- /dev/null+++ b/packages/core/src/modules/auth/src/token.ts@@ -0,0 +1,26 @@+// Session bearer tokens: the browser holds `token`, Postgres stores only its+// hash — a leaked `sessions` row is not a leaked cookie. `hashSessionToken` is+// the single source for that hash so @openpanel/db's session CRUD (which+// cannot live here without a core -> db cycle, see auth.service.ts) and this+// package's own token issuance always agree on the session id.++import crypto from 'node:crypto';+import { sha256 } from '@oslojs/crypto/sha2';+import {+ encodeBase32LowerCaseNoPadding,+ encodeHexLowerCase,+} from '@oslojs/encoding';++export function generateSessionToken(): string {+ const bytes = new Uint8Array(20);+ crypto.getRandomValues(bytes);+ return encodeBase32LowerCaseNoPadding(bytes);+}++export function hashSessionToken(token: string): string {+ return encodeHexLowerCase(sha256(new TextEncoder().encode(token)));+}++export function decodeSessionToken(token: string): string | null {+ return token ? hashSessionToken(token) : null;+}diff --git a/packages/auth/src/totp.ts b/packages/core/src/modules/auth/src/totp.tssimilarity index 96%rename from packages/auth/src/totp.tsrename to packages/core/src/modules/auth/src/totp.tsindex adcbbdb9c..edbf98b43 100644--- a/packages/auth/src/totp.ts+++ b/packages/core/src/modules/auth/src/totp.ts@@ -1,9 +1,9 @@import crypto from 'node:crypto';-import { createTOTPKeyURI, verifyTOTPWithGracePeriod } from '@oslojs/otp';import {decodeBase32IgnorePadding,encodeBase32UpperCaseNoPadding,} from '@oslojs/encoding';+import { createTOTPKeyURI, verifyTOTPWithGracePeriod } from '@oslojs/otp';import qrcode from 'qrcode';import { hashPassword, verifyPasswordHash } from './password';@@ -49,7 +49,7 @@ export function verifyTotpCode(secret: string, code: string): boolean {PERIOD_SECONDS,DIGITS,normalized,- GRACE_PERIOD_SECONDS,+ GRACE_PERIOD_SECONDS);}@@ -75,7 +75,9 @@ export function generateRecoveryCodes(count = 10): string[] {}export async function hashRecoveryCodes(codes: string[]): Promise<string[]> {- return Promise.all(codes.map((code) => hashPassword(normalizeRecoveryCode(code))));+ return Promise.all(+ codes.map((code) => hashPassword(normalizeRecoveryCode(code)))+ );}export function normalizeRecoveryCode(input: string): string {diff --git a/packages/core/src/services.ts b/packages/core/src/services.tsindex e2c3d4fe3..25c7b80c0 100644--- a/packages/core/src/services.ts+++ b/packages/core/src/services.ts@@ -1,8 +1,12 @@-// The composition root. Empty until the first module lands (ADR-007 build-// step 4): the point of writing it now is that the Ctx <-> Services-// circularity compiles.+// The composition root (ADR-007 build step 4). `auth` is the first module to+// land here (M4-007); the Ctx <-> Services circularity was proven compiling+// before it with an empty interface.import type { Ctx } from './context';+import {+ type AuthService,+ createAuthService,+} from './modules/auth/auth.service';/** What every service factory receives — derived from Ctx, so it cannot drift. */export type ServiceDeps = Pick<@@ -19,15 +23,15 @@ export type ServiceDeps = Pick<// 2. Every service method needs an explicit return type, or a factory's// return type cannot be computed from signatures alone. Omit one and// typecheck fails with ts7022/ts7023 naming the method.-//-// biome-ignore lint/suspicious/noEmptyInterface: empty by design until the first module lands, and it must stay an interface — see rule 1.-export interface Services {}--export function createServices(_deps: ServiceDeps): Services {- // When the first module lands, each factory is called with `deps` and a- // `() => container` thunk: captured, not copied, so two services may call- // each other without a cycle.- const container: Services = {};+export interface Services {+ auth: AuthService;+}- return container;+export function createServices(deps: ServiceDeps): Services {+ // When a second module needs to call this one, each factory takes `deps`+ // and a `() => container` thunk: captured, not copied, so two services may+ // call each other without a cycle.+ return {+ auth: createAuthService(deps),+ };}diff --git a/packages/core/test/request-id-end-to-end.test.ts b/packages/core/test/request-id-end-to-end.test.tsindex 9b42f4243..d6e662716 100644--- a/packages/core/test/request-id-end-to-end.test.ts+++ b/packages/core/test/request-id-end-to-end.test.ts@@ -25,7 +25,7 @@ import {REQUEST_ID_HEADER,REQUEST_ID_LENGTH,} from '../src/logger';-import type { ServiceDeps, Services } from '../src/services';+import type { ServiceDeps } from '../src/services';const SUPPLIED_REQUEST_ID = 'adr007-benchmark-3';@@ -34,13 +34,13 @@ interface ProofServices {ingest: { record(name: string): Promise<string> };}-// `Services` is empty until the first module lands, so the container is mocked-// — but the mock is a real service: built from the SCOPED ctx, logging to that-// request's logger and enqueueing through that request's producers. A-// hand-rolled function called from the route would skip exactly the seam under-// test.+// `Services` grows with every module that lands, so this proof mocks the+// whole container with a shape of its own rather than the real one — but the+// mock is a real service: built from the SCOPED ctx, logging to that request's+// logger and enqueueing through that request's producers. A hand-rolled+// function called from the route would skip exactly the seam under test.const createServices = mock(- (deps: ServiceDeps): Services =>+ (deps: ServiceDeps) =>({ingest: {record: async (name: string) => {@@ -158,7 +158,9 @@ function stubDeps() {function buildApp(deps: AppDeps) {const proofRoutes = defineRoutes((app) =>app.post('/proof/track', async ({ ctx }) => ({- jobId: await (ctx.services as ProofServices).ingest.record('e2e'),+ jobId: await (ctx.services as unknown as ProofServices).ingest.record(+ 'e2e'+ ),})));diff --git a/packages/db/index.ts b/packages/db/index.tsindex 550db330c..ea5ab01d4 100644--- a/packages/db/index.ts+++ b/packages/db/index.ts@@ -8,6 +8,7 @@ export * from './src/exports';export * from './src/gsc';export * from './src/prisma-client';export * from './src/services/access.service';+export * from './src/services/auth-session.service';export * from './src/services/chart.service';export * from './src/services/clients.service';export * from './src/services/cohort.service';diff --git a/packages/auth/src/session.ts b/packages/db/src/services/auth-session.service.tssimilarity index 61%rename from packages/auth/src/session.tsrename to packages/db/src/services/auth-session.service.tsindex 652060dcf..6727bf3e4 100644--- a/packages/auth/src/session.ts+++ b/packages/db/src/services/auth-session.service.ts@@ -1,27 +1,40 @@-import crypto from 'node:crypto';-import { db, type Session, type User } from '@openpanel/db';-import { sha256 } from '@oslojs/crypto/sha2';-import {- encodeBase32LowerCaseNoPadding,- encodeHexLowerCase,-} from '@oslojs/encoding';+// Postgres-backed login sessions (a `sessions` row keyed by the hash of a+// browser's cookie). Not to be confused with session.service.ts's ClickHouse+// visitor sessions.+//+// Moved from @openpanel/auth (M4-007), split at the Prisma boundary: token+// issuance/hashing lives in @openpanel/core's auth module (no db needed), and+// this half — the part that actually touches `sessions`/`users` — stays here,+// because @openpanel/core cannot depend on @openpanel/db (db already depends+// on core) without a cycle.-export function generateSessionToken(): string {- const bytes = new Uint8Array(20);- crypto.getRandomValues(bytes);- const token = encodeBase32LowerCaseNoPadding(bytes);- return token;-}+import { decodeSessionToken, hashSessionToken } from '@openpanel/core';+import type { Session, User } from '../prisma-client';+import { db } from '../prisma-client';++const SESSION_TTL_MS = 1000 * 60 * 60 * 24 * 30;+const SESSION_RENEWAL_THRESHOLD_MS = 1000 * 60 * 60 * 24 * 15;+const DEMO_SESSION_TTL_MS = 1000 * 60 * 60 * 24 * 30 * 365;+const DEMO_SESSION_ID = '1';++export type SessionValidationResult =+ | { session: Session; user: User; userId: string }+ | { session: null; user: null; userId: null };++export const EMPTY_SESSION: SessionValidationResult = {+ session: null,+ user: null,+ userId: null,+};export async function createSession(token: string,userId: string): Promise<Session> {- const sessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(token)));const session: Session = {- id: sessionId,+ id: hashSessionToken(token),userId,- expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30),+ expiresAt: new Date(Date.now() + SESSION_TTL_MS),createdAt: new Date(),updatedAt: new Date(),};@@ -31,12 +44,6 @@ export async function createSession(return session;}-export const EMPTY_SESSION: SessionValidationResult = {- session: null,- user: null,- userId: null,-};-export async function createDemoSession(userId: string): Promise<SessionValidationResult> {@@ -50,21 +57,15 @@ export async function createDemoSession(user,userId: user.id,session: {- id: '1',+ id: DEMO_SESSION_ID,userId: user.id,- expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30 * 365),+ expiresAt: new Date(Date.now() + DEMO_SESSION_TTL_MS),createdAt: new Date(),updatedAt: new Date(),},};}-export const decodeSessionToken = (token: string): string | null => {- return token- ? encodeHexLowerCase(sha256(new TextEncoder().encode(token)))- : null;-};-export async function validateSessionToken(token: string | null | undefined): Promise<SessionValidationResult> {@@ -95,8 +96,11 @@ export async function validateSessionToken(await db.session.delete({ where: { id: sessionId } });return EMPTY_SESSION;}- if (Date.now() >= session.expiresAt.getTime() - 1000 * 60 * 60 * 24 * 15) {- session.expiresAt = new Date(Date.now() + 1000 * 60 * 60 * 24 * 30);+ if (+ Date.now() >=+ session.expiresAt.getTime() - SESSION_RENEWAL_THRESHOLD_MS+ ) {+ session.expiresAt = new Date(Date.now() + SESSION_TTL_MS);await db.session.update({where: {id: session.id,@@ -112,7 +116,3 @@ export async function validateSessionToken(export async function invalidateSession(sessionId: string): Promise<void> {await db.session.delete({ where: { id: sessionId } });}--export type SessionValidationResult =- | { session: Session; user: User; userId: string }- | { session: null; user: null; userId: null };diff --git a/packages/trpc/package.json b/packages/trpc/package.jsonindex 9caf7a846..3b95b2671 100644--- a/packages/trpc/package.json+++ b/packages/trpc/package.json@@ -9,7 +9,6 @@},"dependencies": {"@better-agent/core": "^0.1.0-beta.3",- "@openpanel/auth": "workspace:^","@openpanel/common": "workspace:*","@openpanel/constants": "workspace:*","@openpanel/core": "workspace:*",diff --git a/packages/trpc/src/routers/auth.ts b/packages/trpc/src/routers/auth.tsindex f511a6c60..9c67c35ba 100644--- a/packages/trpc/src/routers/auth.ts+++ b/packages/trpc/src/routers/auth.ts@@ -3,33 +3,33 @@ import {buildOtpauthUrl,COOKIE_OPTIONS,consumeRecoveryCode,- createSession,deleteSessionTokenCookie,generateQrDataUrl,generateRecoveryCodes,+ generateSecureId,generateSessionToken,generateTotpSecret,github,google,- hashPassword,+ hashUserPassword as hashPassword,hashRecoveryCodes,- invalidateSession,+ type Logger,setLastAuthProviderCookie,setSessionTokenCookie,- validateSessionToken,verifyPasswordHash,verifyTotpCode,-} from '@openpanel/auth';-import type { Logger } from '@openpanel/core';-import { generateSecureId } from '@openpanel/core';+} from '@openpanel/core';import {connectUserToOrganization,+ createSession,db,decrypt,encrypt,getIsRegistrationAllowed,getShareOverviewById,getUserAccount,+ invalidateSession,+ validateSessionToken,} from '@openpanel/db';import { sendEmail } from '@openpanel/email';import {diff --git a/packages/trpc/src/routers/gsc.ts b/packages/trpc/src/routers/gsc.tsindex 3af5248ec..d1a732aff 100644--- a/packages/trpc/src/routers/gsc.ts+++ b/packages/trpc/src/routers/gsc.ts@@ -1,4 +1,4 @@-import { Arctic, googleGsc } from '@openpanel/auth';+import { Arctic, googleGsc } from '@openpanel/core';import {chQuery,db,@@ -59,7 +59,13 @@ const NORMALIZED_REFERRER_NAME =const AI_REFERRERS = [{canonical: 'chatgpt.com',- aliases: ['chatgpt', 'chatgpt.com', 'chat.openai.com', 'openai', 'openai.com'],+ aliases: [+ 'chatgpt',+ 'chatgpt.com',+ 'chat.openai.com',+ 'openai',+ 'openai.com',+ ],},{canonical: 'claude.ai',@@ -71,18 +77,31 @@ const AI_REFERRERS = [},{canonical: 'gemini.google.com',- aliases: ['gemini', 'google gemini', 'gemini.google.com', 'bard.google.com'],+ aliases: [+ 'gemini',+ 'google gemini',+ 'gemini.google.com',+ 'bard.google.com',+ ],},{canonical: 'copilot.com',- aliases: ['copilot', 'copilot.com', 'copilot.microsoft.com', 'microsoft copilot'],+ aliases: [+ 'copilot',+ 'copilot.com',+ 'copilot.microsoft.com',+ 'microsoft copilot',+ ],},{ canonical: 'grok.com', aliases: ['grok', 'grok.com'] },{canonical: 'mistral.ai',aliases: ['mistral', 'mistral.ai', 'chat.mistral.ai', 'le chat'],},- { canonical: 'kagi.com', aliases: ['kagi', 'kagi.com', 'assistant.kagi.com'] },+ {+ canonical: 'kagi.com',+ aliases: ['kagi', 'kagi.com', 'assistant.kagi.com'],+ },] as const satisfies ReadonlyArray<{canonical: string;aliases: readonly string[];diff --git a/packages/trpc/src/routers/share.ts b/packages/trpc/src/routers/share.tsindex de7b99216..ba725fb3f 100644--- a/packages/trpc/src/routers/share.ts+++ b/packages/trpc/src/routers/share.ts@@ -1,5 +1,4 @@-import ShortUniqueId from 'short-unique-id';-+import { hashUserPassword as hashPassword } from '@openpanel/core';import {db,getDashboardById,@@ -13,15 +12,10 @@ import {zShareOverview,zShareReport,} from '@openpanel/validation';--import { hashPassword } from '@openpanel/auth';+import ShortUniqueId from 'short-unique-id';import { z } from 'zod';import { requireProjectAccess } from '../access';-import {- TRPCAccessError,- TRPCForbiddenError,- TRPCNotFoundError,-} from '../errors';+import { TRPCAccessError, TRPCNotFoundError } from '../errors';import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc';const uid = new ShortUniqueId({ length: 6 });@@ -45,7 +39,7 @@ const uid = new ShortUniqueId({ length: 6 });function lockedShare(id: string,organization: { name: string },- project: { name: string },+ project: { name: string }) {return {id,@@ -71,7 +65,7 @@ export const shareRouter = createTRPCRouter({},});- if (!share || !share.public) {+ if (!(share && share.public)) {throw new TRPCNotFoundError('Share not found');}@@ -156,7 +150,7 @@ export const shareRouter = createTRPCRouter({},});- if (!share || !share.public) {+ if (!(share && share.public)) {throw new TRPCNotFoundError('Dashboard share not found');}@@ -204,7 +198,7 @@ export const shareRouter = createTRPCRouter({const dashboard = await getDashboardById(input.dashboardId,- input.projectId,+ input.projectId);if (!dashboard) {throw new TRPCNotFoundError('Dashboard not found');@@ -244,12 +238,12 @@ export const shareRouter = createTRPCRouter({.input(z.object({shareId: z.string(),- }),+ })).query(async ({ input, ctx }) => {const share = await getShareDashboardById(input.shareId);- if (!share || !share.public) {+ if (!(share && share.public)) {throw new TRPCNotFoundError('Dashboard share not found');}@@ -279,7 +273,7 @@ export const shareRouter = createTRPCRouter({},});- if (!share || !share.public) {+ if (!(share && share.public)) {throw new TRPCNotFoundError('Report share not found');}diff --git a/packages/trpc/src/routers/user.ts b/packages/trpc/src/routers/user.tsindex cc15fb900..bbac16286 100644--- a/packages/trpc/src/routers/user.ts+++ b/packages/trpc/src/routers/user.ts@@ -1,10 +1,8 @@-import { z } from 'zod';--import { deleteSessionTokenCookie } from '@openpanel/auth';+import { deleteSessionTokenCookie } from '@openpanel/core';import { db } from '@openpanel/db';-+import { z } from 'zod';import { TRPCBadRequestError } from '../errors';-import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc';+import { createTRPCRouter, protectedProcedure } from '../trpc';export const userRouter = createTRPCRouter({// Organizations the user created that still have a blocking subscription@@ -17,7 +15,7 @@ export const userRouter = createTRPCRouter({return organizations.filter((organization) =>- organization.hasSubscription && !organization.isWillBeCanceled,+ organization.hasSubscription && !organization.isWillBeCanceled).map((organization) => ({id: organization.id,@@ -31,14 +29,14 @@ export const userRouter = createTRPCRouter({});const blocking = organizations.filter((organization) =>- organization.hasSubscription && !organization.isWillBeCanceled,+ organization.hasSubscription && !organization.isWillBeCanceled);if (blocking.length > 0) {throw new TRPCBadRequestError(`Please cancel the subscription for ${blocking.map((organization) => organization.name)- .join(', ')} before deleting your account.`,+ .join(', ')} before deleting your account.`);}@@ -58,7 +56,7 @@ export const userRouter = createTRPCRouter({z.object({firstName: z.string(),lastName: z.string(),- }),+ })).mutation(async ({ input, ctx }) => {return db.user.update({@@ -76,7 +74,7 @@ export const userRouter = createTRPCRouter({z.object({sameSite: z.enum(['lax', 'strict', 'none']),domain: z.string(),- }),+ })).mutation(async ({ ctx, input }) => {ctx.setCookie('debugCookie', new Date().toISOString(), {@@ -92,7 +90,7 @@ export const userRouter = createTRPCRouter({z.object({sameSite: z.enum(['lax', 'strict', 'none']),domain: z.string(),- }),+ })).query(async ({ ctx, input }) => {ctx.setCookie('debugCookie', new Date().toISOString(), {diff --git a/packages/trpc/src/trpc.ts b/packages/trpc/src/trpc.tsindex 7c03f46cb..d5ff18ab6 100644--- a/packages/trpc/src/trpc.ts+++ b/packages/trpc/src/trpc.ts@@ -11,8 +11,8 @@// `runWithAlsSession` and the access ladder's real lookups. They move into// core with auth at P6, at which point this file is a re-export.-import { COOKIE_OPTIONS, type SessionValidationResult } from '@openpanel/auth';import {+ COOKIE_OPTIONS,type Ctx,createCacheMiddleware,createRateLimitMiddleware,@@ -22,7 +22,7 @@ import {type RpcCache,type TrpcContext,} from '@openpanel/core';-import { runWithAlsSession } from '@openpanel/db';+import { runWithAlsSession, type SessionValidationResult } from '@openpanel/db';import { getRedisCache } from '@openpanel/redis';import { TRPCError } from '@trpc/server';import type { CreateFastifyContextOptions } from '@trpc/server/adapters/fastify';@@ -121,9 +121,14 @@ export async function createContext({** `db`/`ch`/`redis`/`clients`/`buffers` are core's `unknown` stubs until P3-P8* wire the real clients, and V1's routers reach for their own singletons- * regardless. `queues` throws rather than returning an empty object: a V1- * router that tried to enqueue through core would otherwise silently do- * nothing.+ * regardless. `queues` and `services` throw rather than returning an empty+ * object: a V1 router that reached for either through core would otherwise+ * silently do nothing (`queues`) or hit `undefined` (`services`) instead of+ * the loud error that tells it to reach `@openpanel/db`/`@openpanel/core`+ * directly, as the rest of V1 does. `services` is not built via core's+ * `createServices` here on purpose — that factory is deliberately absent from+ * the curated barrel (index.test.ts), so nothing outside `apps/api`'s+ * `main.ts` constructs a `Services` container.*/function v1CtxScope(req: CreateFastifyContextOptions['req']): Ctx {return {@@ -134,7 +139,7 @@ function v1CtxScope(req: CreateFastifyContextOptions['req']): Ctx {buffers: undefined,logger: req.log,queues: NOT_WIRED_QUEUES,- services: {},+ services: NOT_WIRED_SERVICES,requestId: String(req.id),};}@@ -147,6 +152,14 @@ const NOT_WIRED_QUEUES = new Proxy({} as QueueProducers, {},});+const NOT_WIRED_SERVICES = new Proxy({} as Ctx['services'], {+ get(_target, name) {+ throw new Error(+ `ctx.services.${String(name)} is not wired on the V1 Fastify path — reach @openpanel/core's or @openpanel/db's module directly, as the rest of V1 does`+ );+ },+});+/** Node's header bag is a record of strings and string arrays; core wants a `Headers`. */function toHeaders(source: Record<string, string | string[] | undefined>) {const headers = new Headers();diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d15f7f70c..cb7888ad2 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -125,9 +125,6 @@ importers:'@node-rs/argon2':specifier: ^2.0.2version: 2.0.2- '@openpanel/auth':- specifier: workspace:^- version: link:../../packages/auth'@openpanel/common':specifier: workspace:*version: link:../../packages/common@@ -1013,55 +1010,6 @@ importers:specifier: 'catalog:'version: 5.9.3- packages/auth:- dependencies:- '@node-rs/argon2':- specifier: ^2.0.2- version: 2.0.2- '@openpanel/db':- specifier: workspace:^- version: link:../db- '@openpanel/validation':- specifier: workspace:^- version: link:../validation- '@oslojs/crypto':- specifier: ^1.0.1- version: 1.0.1- '@oslojs/encoding':- specifier: ^1.1.0- version: 1.1.0- '@oslojs/otp':- specifier: ^1.1.0- version: 1.1.0- arctic:- specifier: ^2.3.0- version: 2.3.0- qrcode:- specifier: ^1.5.4- version: 1.5.4- react:- specifier: 'catalog:'- version: 19.2.3- devDependencies:- '@openpanel/tsconfig':- specifier: workspace:*- version: link:../../tooling/typescript- '@types/node':- specifier: 'catalog:'- version: 24.10.1- '@types/qrcode':- specifier: ^1.5.6- version: 1.5.6- '@types/react':- specifier: 'catalog:'- version: 19.2.7- prisma:- specifier: ^5.1.1- version: 5.9.1- typescript:- specifier: 'catalog:'- version: 5.9.3-packages/common:dependencies:'@openpanel/constants':@@ -1158,15 +1106,24 @@ importers:'@maxmind/geoip2-node':specifier: ^6.1.0version: 6.1.0- '@openpanel/auth':- specifier: workspace:^- version: link:../auth+ '@node-rs/argon2':+ specifier: ^2.0.2+ version: 2.0.2'@openpanel/common':specifier: workspace:*version: link:../common'@openpanel/validation':specifier: workspace:*version: link:../validation+ '@oslojs/crypto':+ specifier: ^1.0.1+ version: 1.0.1+ '@oslojs/encoding':+ specifier: ^1.1.0+ version: 1.1.0+ '@oslojs/otp':+ specifier: ^1.1.0+ version: 1.1.0'@slack/bolt':specifier: ^3.18.0@@ -1176,6 +1133,9 @@ importers:'@trpc/server':specifier: ^11.17.0version: 11.17.0([email protected])+ arctic:+ specifier: ^2.3.0+ version: 2.3.0bullmq:specifier: 6.3.3version: 6.3.3([email protected]([email protected]))@@ -1200,6 +1160,9 @@ importers:prom-client:specifier: ^15.1.3version: 15.1.3+ qrcode:+ specifier: ^1.5.4+ version: 1.5.4superjson:specifier: ^1.13.3version: 1.13.3@@ -1213,9 +1176,15 @@ importers:specifier: 'catalog:'version: 4.3.6devDependencies:+ '@openpanel/db':+ specifier: workspace:*+ version: link:../db'@openpanel/tsconfig':specifier: workspace:*version: link:../../tooling/typescript+ '@types/qrcode':+ specifier: ^1.5.6+ version: 1.5.6bun-types:specifier: 1.4.0version: 1.4.0@@ -1765,9 +1734,6 @@ importers:'@better-agent/core':specifier: ^0.1.0-beta.3version: 0.1.0-beta.3- '@openpanel/auth':- specifier: workspace:^- version: link:../auth'@openpanel/common':specifier: workspace:*version: link:../common