Files
pn-new-crm/src/lib/auth/index.ts

85 lines
2.5 KiB
TypeScript
Raw Normal View History

import { betterAuth } from 'better-auth';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
import { db } from '@/lib/db';
/**
* Better Auth server configuration.
*
* Sessions are stored in PostgreSQL (not Redis) per SECURITY-GUIDELINES.md §1.2.
* The drizzle adapter handles session persistence via the existing `sessions` table.
*/
/**
* In dev, allow requests from any LAN IP so the same `pnpm dev` instance can
* serve both localhost (Mac) and the LAN IP (iPhone on Wi-Fi). In production,
* trustedOrigins is locked down to NEXT_PUBLIC_APP_URL only.
*/
/**
* In dev, allow localhost + any LAN-IP origin so the same `pnpm dev` instance
* can serve both Mac (localhost) and iPhone-on-Wi-Fi (192.168.x.x). The
* function form is preferred over a static list because the LAN IP can vary
* across networks. In production, lock down to NEXT_PUBLIC_APP_URL only.
*/
const isProd = process.env.NODE_ENV === 'production';
const DEV_ORIGIN_PATTERNS = [
/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/,
/^https?:\/\/192\.168\.\d+\.\d+(:\d+)?$/,
/^https?:\/\/10\.\d+\.\d+\.\d+(:\d+)?$/,
];
const trustedOrigins: (request?: Request) => Promise<string[]> = async (request) => {
if (isProd) {
const prodUrl = process.env.NEXT_PUBLIC_APP_URL;
return prodUrl ? [prodUrl] : [];
}
const origin = request?.headers.get('origin') ?? '';
if (origin && DEV_ORIGIN_PATTERNS.some((re) => re.test(origin))) {
return [origin];
}
return ['http://localhost:3000', 'http://localhost:3001'];
};
export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: 'pg',
}),
trustedOrigins,
emailAndPassword: {
enabled: true,
feat(platform): residential module + admin UI + reliability fixes Residential platform - New schema: residentialClients, residentialInterests (separate from marina/yacht clients) with migration 0010 - Service layer with CRUD + audit + sockets + per-port portal toggle - v1 + public API routes (/api/v1/residential/*, /api/public/residential-inquiries) - List + detail pages with inline editing for clients and interests - Per-user residentialAccess toggle on userPortRoles (migration 0011) - Permission keys: residential_clients, residential_interests - Sidebar nav + role form integration - Smoke spec covering page loads, UI create flow, public endpoint Admin & shared UI - Admin → Forms (form templates CRUD) with validators + service - Notification preferences page (in-app + email per type) - Email composition + accounts list + threads view - Branded auth shell shared across CRM + portal auth surfaces - Inline editing extended to yacht/company/interest detail pages - InlineTagEditor + per-entity tags endpoints (yachts, companies) - Notes service polymorphic across clients/interests/yachts/companies - Client list columns: yachtCount + companyCount badges - Reservation file-download via presigned URL (replaces stale <a href>) Route handler refactor - Extracted yachts/companies/berths reservation handlers to sibling handlers.ts files (Next.js 15 route.ts only allows specific exports) Reliability fixes - apiFetch double-stringify bug fixed across 13 components (apiFetch already JSON.stringifies its body; passing a stringified body produced double-encoded JSON which failed zod validation) - SocketProvider gated behind useSyncExternalStore-based mount check to avoid useSession() SSR crashes under React 19 + Next 15 - apiFetch falls back to URL-pathname → port-id resolution when the Zustand store hasn't hydrated yet (fresh contexts, e2e tests) - CRM invite flow (schema, service, route, email, dev script) - Dashboard route → [portSlug]/dashboard/page.tsx + redirect - Document the dev-server restart-after-migration gotcha in CLAUDE.md Tests - 5-case residential smoke spec - Integration test updates for new service signatures Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 21:54:32 +02:00
minPasswordLength: 9,
// Accounts are admin-created only — no self-service email verification flow.
requireEmailVerification: false,
},
session: {
// Enable cookie-level session caching to reduce DB reads (5-minute cache).
cookieCache: {
enabled: true,
maxAge: 5 * 60,
},
// Absolute session lifetime: 24 hours.
expiresIn: 60 * 60 * 24,
// Refresh the session whenever the user is active in the last 25% of its lifetime (6h).
updateAge: 60 * 60 * 6,
},
advanced: {
cookiePrefix: 'pn-crm',
defaultCookieAttributes: {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict' as const,
},
},
logger: {
disabled: false,
level: 'error' as const,
},
});
export type Session = typeof auth.$Infer.Session;
export type User = typeof auth.$Infer.Session.user;