@murumets-ee/auth 0.1.5 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.d.mts","names":[],"sources":["../src/schema.ts"],"mappings":";;;;;;;;AA0BA;;;;;;;;;;;;;;;;;;cAAa,IAAA,yBAAI,kBAAA;;;;QAef,sBAAA,CAAA,QAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAEW,OAAA,yBAAO,kBAAA;;;;QAmBnB,sBAAA,CAAA,QAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAEY,OAAA,yBAAO,kBAAA;;;;QAsBnB,sBAAA,CAAA,QAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAEY,YAAA,yBAAY,kBAAA;;;;QAcxB,sBAAA,CAAA,QAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAEY,YAAA,yBAAY,kBAAA;;;;QAWxB,sBAAA,CAAA,QAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAEY,MAAA,yBAAM,kBAAA;;;;QAiBlB,sBAAA,CAAA,QAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAEY,UAAA,yBAAU,kBAAA;;;;QAoBtB,sBAAA,CAAA,QAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAEY,aAAA,iBAAa,SAAA;YAKvB,cAAA,CAAA,IAAA;;;;;cAEU,gBAAA,EAKV,cAAA,CAL0B,SAAA;QAK1B,cAAA,CAAA,GAAA;AAAA;AAAA,cAEU,gBAAA,EAKV,cAAA,CAL0B,SAAA;QAK1B,cAAA,CAAA,GAAA;AAAA;AAAA,cAEU,qBAAA,iBAAqB,SAAA;WAG/B,cAAA,CAAA,IAAA;;;cAEU,eAAA,iBAAe,SAAA;gBASzB,cAAA,CAAA,GAAA;;;cAEU,mBAAA,iBAAmB,SAAA;gBAS7B,cAAA,CAAA,GAAA"}
@@ -0,0 +1 @@
1
+ import{a as e,c as t,d as n,f as r,i,m as a,n as o,o as s,p as c,r as l,s as u,t as d,u as f}from"./schema-Je6e5yt2.mjs";export{d as account,o as accountRelations,l as invitation,i as invitationRelations,e as member,s as memberRelations,u as organization,t as organizationRelations,f as session,n as sessionRelations,r as user,c as userRelations,a as verification};
@@ -0,0 +1,2 @@
1
+ import{l as e}from"./schema-Je6e5yt2.mjs";import{a as t,l as n}from"./permissions-DREmJByu.mjs";import{createAccessControl as r}from"better-auth/plugins/access";import{sql as i}from"drizzle-orm";import{betterAuth as a}from"better-auth";import{drizzleAdapter as o}from"better-auth/adapters/drizzle";import{APIError as s,createAuthMiddleware as c}from"better-auth/api";import{nextCookies as l}from"better-auth/next-js";import{admin as u}from"better-auth/plugins";import{organization as d}from"better-auth/plugins/organization";function f(e){let t=e?.context?.session,n=t?.user;return{id:n?.id??t?.userId,name:n?.name}}const p=new Set([`updatedAt`,`createdAt`]);function m(e,t){function n(e){t?.log(e).catch(()=>{})}let r=null;return{user:{create:{after:async t=>{try{await e.readWrite.execute(i`UPDATE "user" SET role = 'admin' WHERE id = ${t.id} AND (SELECT COUNT(*) FROM "user") = 1`)}catch{}n({action:`auth.signup`,entityType:`user`,entityId:t.id,userId:t.id,userName:t.name,changes:{fields:{name:t.name,email:t.email}}})}},update:{before:async e=>{let t={};for(let[n,r]of Object.entries(e))p.has(n)||n===`id`||(t[n]=r);r=Object.keys(t).length>0?t:null},after:async(e,t)=>{let i=f(t),a=r;r=null,n({action:`auth.user.update`,entityType:`user`,entityId:e.id,userId:i.id,userName:i.name,changes:a?{fields:a}:void 0,metadata:{targetUser:e.name}})}},delete:{after:async(e,t)=>{let r=f(t);n({action:`auth.user.delete`,entityType:`user`,entityId:e.id,userId:r.id,userName:r.name,metadata:{targetUser:e.name}})}}}}}const h=[`/sign-in/email`,`/sign-in/social`],g={"/change-password":`auth.password.change`,"/forget-password":`auth.password.reset_request`,"/reset-password":`auth.password.reset`},_={"/admin/set-role":`auth.admin.set_role`,"/admin/ban-user":`auth.admin.ban`,"/admin/unban-user":`auth.admin.unban`,"/admin/create-user":`auth.admin.create_user`,"/admin/remove-user":`auth.admin.remove_user`,"/admin/impersonate-user":`auth.admin.impersonate`,"/admin/stop-impersonating":`auth.admin.stop_impersonating`,"/admin/revoke-session":`auth.admin.revoke_session`,"/admin/revoke-sessions":`auth.admin.revoke_sessions`};function v(e){function t(t){e.log(t).catch(()=>{})}return{after:c(async e=>{if(h.some(t=>e.path.startsWith(t))){let n=e.context.returned?.status;if(!n)return;if(n>=400){let r=e.body?.email;t({action:`auth.login.failed`,metadata:{...typeof r==`string`?{email:r}:{},status:n,path:e.path}})}else{let n=e.context.newSession;n?.user?.id&&t({action:`auth.login`,entityType:`user`,entityId:n.user.id,userId:n.user.id,userName:n.user.name})}return}if(e.path===`/sign-out`){let n=e.context.returned;if(!n?.status||n.status<400){let n=f(e);n.id&&t({action:`auth.logout`,entityType:`user`,entityId:n.id,userId:n.id,userName:n.name})}return}let n=g[e.path];if(n){let r=e.context.returned;if(!r?.status||r.status<400){let r=f(e),i=e.body;t({action:n,entityType:`user`,userId:r.id,userName:r.name,metadata:{...typeof i?.email==`string`?{email:i.email}:{},path:e.path}})}return}let r=_[e.path];if(!r)return;let i=e.context.returned;if(i?.status&&i.status>=400)return;let a=f(e),o=e.body;t({action:r,entityType:`user`,entityId:o?.userId??void 0,userId:a.id,userName:a.name,metadata:{targetUserId:o?.userId,...o?.role?{role:o.role}:{},path:e.path}})})}}function y(e){return c(async t=>{if(t.path!==`/sign-up/email`)return;let n=await e.readWrite.execute(i`SELECT COUNT(*)::text as count FROM "user"`);if(Number(n[0]?.count)>0)throw new s(`FORBIDDEN`,{message:`Sign-up is closed`})})}function b(i,s,c){let f=[...s.entities.values()],p=r(n(f)),h=t(p,f),g={};i.social?.google&&(g.google=i.social.google),i.social?.github&&(g.github=i.social.github);let _=i.schema??e;return a({database:o(s.db.readWrite,{provider:`pg`,schema:_}),emailAndPassword:{enabled:i.providers?.includes(`email`)??!0},socialProviders:g,session:{expiresIn:i.session?.expiresIn??3600*2,updateAge:i.session?.updateAge??3600},rateLimit:{enabled:!0,window:60,max:100,storage:`memory`,customRules:{"/sign-in/email":{window:60,max:5},"/sign-in/social":{window:60,max:10},"/sign-up/email":{window:60,max:3},"/forget-password":{window:60,max:3},"/reset-password":{window:60,max:5},"/admin/*":{window:60,max:20}}},databaseHooks:m(s.db,c),hooks:{before:y(s.db),...c?v(c):{}},plugins:[u({ac:p,roles:h,defaultRole:`authenticated`}),...i.organizations?[d({ac:p,roles:h})]:[],...i.betterAuthPlugins??[],l()]})}export{b as createAuthServer};
2
+ //# sourceMappingURL=server-B7Gdv2He.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-B7Gdv2He.mjs","names":["defaultAuthSchema"],"sources":["../src/server.ts"],"sourcesContent":["/**\n * Server-side auth instance factory.\n *\n * Creates a configured `betterAuth()` instance using the toolkit's database\n * connection and entity definitions. This is server-only code.\n */\n\nimport type { ToolkitApp } from '@murumets-ee/core'\nimport type { AuditLogger } from '@murumets-ee/logging'\nimport type { Auth as BetterAuthBase, BetterAuthOptions } from 'better-auth'\nimport { betterAuth } from 'better-auth'\nimport { drizzleAdapter } from 'better-auth/adapters/drizzle'\nimport { APIError, createAuthMiddleware } from 'better-auth/api'\nimport { nextCookies } from 'better-auth/next-js'\nimport { admin } from 'better-auth/plugins'\nimport type { Role } from 'better-auth/plugins/access'\nimport { createAccessControl } from 'better-auth/plugins/access'\nimport { organization } from 'better-auth/plugins/organization'\nimport { sql as drizzleSql } from 'drizzle-orm'\nimport { buildDefaultRoles, buildStatements } from './permissions.js'\nimport * as defaultAuthSchema from './schema.js'\nimport type { AdminUser, AuthConfig } from './types.js'\n\n// ---------------------------------------------------------------------------\n// Audit hooks — wired into better-auth's databaseHooks\n// ---------------------------------------------------------------------------\n\n/** Extract acting admin's id and name from better-auth hook context.\n * ctx is GenericEndpointContext | null — we access session safely via optional chaining. */\nfunction getActor(ctx: unknown) {\n const session = (ctx as { context?: { session?: Record<string, unknown> } } | null)?.context\n ?.session\n const user = session?.user as { id?: string; name?: string } | undefined\n return {\n id: user?.id ?? (session?.userId as string | undefined),\n name: user?.name,\n }\n}\n\n/** Fields to strip from user update audit payloads */\nconst SKIP_FIELDS = new Set(['updatedAt', 'createdAt'])\n\nfunction buildDatabaseHooks(db: ToolkitApp['db'], auditLogger?: AuditLogger) {\n /** Fire-and-forget audit — never block auth operations */\n function audit(entry: Parameters<AuditLogger['log']>[0]) {\n auditLogger?.log(entry).catch(() => {})\n }\n\n // `before` captures changed fields, `after` has full user + actor ctx.\n // Bridge with a simple variable — updates are sequential per request.\n let pendingFields: Record<string, unknown> | null = null\n\n return {\n user: {\n create: {\n after: async (user: Record<string, unknown>) => {\n // Auto-promote first user to admin (fresh DB setup).\n // Single atomic statement — if two signups race, only one sees count=1.\n try {\n await db.readWrite.execute(\n drizzleSql`UPDATE \"user\" SET role = 'admin' WHERE id = ${user.id as string} AND (SELECT COUNT(*) FROM \"user\") = 1`,\n )\n } catch {\n // Non-fatal — don't block signup if promotion fails\n }\n\n // Signup — actor is the new user themselves\n audit({\n action: 'auth.signup',\n entityType: 'user',\n entityId: user.id as string,\n userId: user.id as string,\n userName: user.name as string,\n changes: {\n fields: { name: user.name, email: user.email },\n },\n })\n },\n },\n update: {\n // `before` receives only the changed fields — capture them\n before: async (userData: Record<string, unknown>) => {\n const fields: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(userData)) {\n if (SKIP_FIELDS.has(key) || key === 'id') continue\n fields[key] = value\n }\n pendingFields = Object.keys(fields).length > 0 ? fields : null\n },\n // `after` has full user (name) + ctx (actor session) — log everything\n after: async (user: Record<string, unknown>, ctx: unknown) => {\n const actor = getActor(ctx)\n const fields = pendingFields\n pendingFields = null\n audit({\n action: 'auth.user.update',\n entityType: 'user',\n entityId: user.id as string,\n userId: actor.id,\n userName: actor.name,\n changes: fields ? { fields } : undefined,\n metadata: {\n targetUser: user.name as string | undefined,\n },\n })\n },\n },\n delete: {\n after: async (user: Record<string, unknown>, ctx: unknown) => {\n const actor = getActor(ctx)\n audit({\n action: 'auth.user.delete',\n entityType: 'user',\n entityId: user.id as string,\n userId: actor.id,\n userName: actor.name,\n metadata: {\n targetUser: user.name as string | undefined,\n },\n })\n },\n },\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// Request-level hooks — catches failed logins, password changes, etc.\n// ---------------------------------------------------------------------------\n\n/** Auth paths where a non-2xx response means a failed attempt worth logging */\nconst SIGN_IN_PATHS = ['/sign-in/email', '/sign-in/social']\n\n/** Auth paths for session/password lifecycle events */\nconst SIGN_OUT_PATH = '/sign-out'\nconst PASSWORD_PATHS: Record<string, string> = {\n '/change-password': 'auth.password.change',\n '/forget-password': 'auth.password.reset_request',\n '/reset-password': 'auth.password.reset',\n}\n\n/** Paths that should be audit-logged when successful */\nconst AUDIT_ADMIN_PATHS: Record<string, string> = {\n '/admin/set-role': 'auth.admin.set_role',\n '/admin/ban-user': 'auth.admin.ban',\n '/admin/unban-user': 'auth.admin.unban',\n '/admin/create-user': 'auth.admin.create_user',\n '/admin/remove-user': 'auth.admin.remove_user',\n '/admin/impersonate-user': 'auth.admin.impersonate',\n '/admin/stop-impersonating': 'auth.admin.stop_impersonating',\n '/admin/revoke-session': 'auth.admin.revoke_session',\n '/admin/revoke-sessions': 'auth.admin.revoke_sessions',\n}\n\nfunction buildRequestHooks(auditLogger: AuditLogger) {\n function audit(entry: Parameters<AuditLogger['log']>[0]) {\n auditLogger.log(entry).catch(() => {})\n }\n\n return {\n after: createAuthMiddleware(async (ctx) => {\n // --- Login attempt logging ---\n const isSignIn = SIGN_IN_PATHS.some((p) => ctx.path.startsWith(p))\n if (isSignIn) {\n const returned = ctx.context.returned as { status?: number } | undefined\n const status = returned?.status\n if (!status) return\n\n if (status >= 400) {\n const email = (ctx.body as Record<string, unknown> | undefined)?.email\n audit({\n action: 'auth.login.failed',\n metadata: {\n ...(typeof email === 'string' ? { email } : {}),\n status,\n path: ctx.path,\n },\n })\n } else {\n const newSession = ctx.context.newSession as\n | { user?: { id?: string; name?: string } }\n | undefined\n if (newSession?.user?.id) {\n audit({\n action: 'auth.login',\n entityType: 'user',\n entityId: newSession.user.id,\n userId: newSession.user.id,\n userName: newSession.user.name,\n })\n }\n }\n return\n }\n\n // --- Logout logging ---\n if (ctx.path === SIGN_OUT_PATH) {\n const returned = ctx.context.returned as { status?: number } | undefined\n if (!returned?.status || returned.status < 400) {\n const actor = getActor(ctx)\n if (actor.id) {\n audit({\n action: 'auth.logout',\n entityType: 'user',\n entityId: actor.id,\n userId: actor.id,\n userName: actor.name,\n })\n }\n }\n return\n }\n\n // --- Password change/reset logging ---\n const passwordAction = PASSWORD_PATHS[ctx.path]\n if (passwordAction) {\n const returned = ctx.context.returned as { status?: number } | undefined\n if (!returned?.status || returned.status < 400) {\n const actor = getActor(ctx)\n const body = ctx.body as Record<string, unknown> | undefined\n audit({\n action: passwordAction,\n entityType: 'user',\n userId: actor.id,\n userName: actor.name,\n metadata: {\n // For reset requests, log the email (not sensitive — it's the input)\n ...(typeof body?.email === 'string' ? { email: body.email } : {}),\n path: ctx.path,\n },\n })\n }\n return\n }\n\n // --- Admin operation audit logging (impersonation, role changes, bans, etc.) ---\n const auditAction = AUDIT_ADMIN_PATHS[ctx.path]\n if (!auditAction) return\n\n const returned = ctx.context.returned as { status?: number } | undefined\n if (returned?.status && returned.status >= 400) return // failed — skip\n\n const actor = getActor(ctx)\n const body = ctx.body as Record<string, unknown> | undefined\n audit({\n action: auditAction,\n entityType: 'user',\n entityId: (body?.userId as string) ?? undefined,\n userId: actor.id,\n userName: actor.name,\n metadata: {\n targetUserId: body?.userId as string | undefined,\n ...(body?.role ? { role: body.role as string } : {}),\n path: ctx.path,\n },\n })\n }),\n }\n}\n\n// ---------------------------------------------------------------------------\n// Signup gate — closes registration after the first user exists\n// ---------------------------------------------------------------------------\n\nfunction buildSignupGate(db: ToolkitApp['db']) {\n return createAuthMiddleware(async (ctx) => {\n if (ctx.path !== '/sign-up/email') return\n const result = await db.readWrite.execute<{ count: string }>(\n drizzleSql`SELECT COUNT(*)::text as count FROM \"user\"`,\n )\n if (Number(result[0]?.count) > 0) {\n throw new APIError('FORBIDDEN', { message: 'Sign-up is closed' })\n }\n })\n}\n\n// ---------------------------------------------------------------------------\n// Server factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a better-auth server instance wired to the toolkit.\n *\n * Called during plugin init — the returned instance powers:\n * - `auth.api.getSession()` for session resolution\n * - `auth.api.listUsers()` for admin user management\n * - Route handler via `toNextJsHandler(auth)`\n *\n * IMPORTANT: Plugins are inlined in the `betterAuth()` call so TypeScript\n * preserves the literal plugin types. Extracting them into a `BetterAuthPlugin[]`\n * variable erases specific endpoint types (admin, organization, etc.).\n *\n * The explicit `BetterAuthBase` return type annotation is required because\n * better-auth 1.6's internals use zod@4 types that tsdown's dts generator\n * cannot name portably across pnpm's `.pnpm/zod@4.x` symlink paths (TS2742).\n * The annotation widens to better-auth's generic `Auth` type — specific\n * plugin endpoint types (`auth.api.listUsers` etc.) are still accessible\n * because better-auth's `InferAPI` helper resolves them at the consumer's\n * compile time against their installed better-auth version.\n */\nexport function createAuthServer(\n config: AuthConfig,\n app: ToolkitApp,\n auditLogger?: AuditLogger,\n): BetterAuthBase {\n const entities = [...app.entities.values()]\n const statement = buildStatements(entities)\n const ac = createAccessControl(statement)\n const roles: Record<string, Role> = buildDefaultRoles(ac, entities)\n\n // Build social provider config\n const socialProviders: Record<string, { clientId: string; clientSecret: string }> = {}\n if (config.social?.google) {\n socialProviders.google = config.social.google\n }\n if (config.social?.github) {\n socialProviders.github = config.social.github\n }\n\n // Plugins are inlined so TS infers the literal tuple type.\n // DO NOT extract into a typed variable — `BetterAuthPlugin[]` erases endpoint types.\n // nextCookies() must be last — required for Next.js server actions.\n // Default to the pre-baked schema from `@murumets-ee/auth/schema` so\n // consumers don't need to generate one with `@better-auth/cli`. They\n // can still override via `auth({ schema: customSchema })` if they've\n // extended better-auth with plugins that add tables.\n const schema = config.schema ?? defaultAuthSchema\n\n // Widen the config to BetterAuthOptions so betterAuth() returns\n // Auth<BetterAuthOptions> (= BetterAuthBase). This is required because:\n // 1. Without a return type annotation, tsdown fails with TS2742\n // (zod@4 internal types can't be named portably in .d.mts)\n // 2. The admin plugin with custom ac/roles makes Auth<SpecificConfig>\n // structurally incompatible with Auth (better-auth#8855)\n // Widening the config erases plugin-specific API types at compile time,\n // but plugin endpoints (listUsers, etc.) are fully functional at runtime.\n // Consumers already access them via typed wrappers in AdminPagesConfig.\n const authOptions: BetterAuthOptions = {\n database: drizzleAdapter(app.db.readWrite, {\n provider: 'pg',\n schema,\n }),\n\n emailAndPassword: {\n enabled: config.providers?.includes('email') ?? true,\n },\n\n socialProviders,\n\n session: {\n expiresIn: config.session?.expiresIn ?? 60 * 60 * 2, // 2 hours (admin CMS — short-lived)\n updateAge: config.session?.updateAge ?? 60 * 60, // 1 hour\n },\n\n // Rate limiting — strict on sensitive paths, relaxed global default\n rateLimit: {\n enabled: true,\n window: 60, // 60s global window\n max: 100, // 100 req/min default\n storage: 'memory',\n customRules: {\n '/sign-in/email': { window: 60, max: 5 }, // 5 login attempts/min\n '/sign-in/social': { window: 60, max: 10 },\n '/sign-up/email': { window: 60, max: 3 }, // 3 signups/min\n '/forget-password': { window: 60, max: 3 }, // 3 resets/min\n '/reset-password': { window: 60, max: 5 },\n '/admin/*': { window: 60, max: 20 }, // admin ops capped\n },\n },\n\n databaseHooks: buildDatabaseHooks(app.db, auditLogger),\n hooks: {\n before: buildSignupGate(app.db),\n ...(auditLogger ? buildRequestHooks(auditLogger) : {}),\n },\n\n plugins: [\n admin({ ac, roles, defaultRole: 'authenticated' }),\n ...(config.organizations ? [organization({ ac, roles })] : []),\n ...(config.betterAuthPlugins ?? []),\n nextCookies(),\n ],\n }\n\n return betterAuth(authOptions)\n}\n\n/** Type of the auth server instance. Aliased from better-auth's generic\n * `Auth` because the explicit annotation on `createAuthServer` means\n * `ReturnType<typeof createAuthServer>` is already `BetterAuthBase`. */\nexport type Auth = BetterAuthBase\n\n/**\n * Structural interface for the server-side admin API methods.\n *\n * The widened `Auth` type (BetterAuthBase) doesn't expose admin plugin\n * endpoints. This interface describes just the methods consumers need\n * so they can access them without `as any`.\n *\n * Usage: `(auth.api as AuthAdminApi).listUsers(...)`\n */\nexport interface AuthAdminApi {\n listUsers: (opts: {\n headers: Headers\n query: {\n limit: number\n sortBy: string\n sortDirection: 'asc' | 'desc'\n }\n }) => Promise<{ users: AdminUser[]; total: number }>\n}\n"],"mappings":"6gBA6BA,SAAS,EAAS,EAAc,CAC9B,IAAM,EAAW,GAAoE,SACjF,QACE,EAAO,GAAS,KACtB,MAAO,CACL,GAAI,GAAM,IAAO,GAAS,OAC1B,KAAM,GAAM,KACb,CAIH,MAAM,EAAc,IAAI,IAAI,CAAC,YAAa,YAAY,CAAC,CAEvD,SAAS,EAAmB,EAAsB,EAA2B,CAE3E,SAAS,EAAM,EAA0C,CACvD,GAAa,IAAI,EAAM,CAAC,UAAY,GAAG,CAKzC,IAAI,EAAgD,KAEpD,MAAO,CACL,KAAM,CACJ,OAAQ,CACN,MAAO,KAAO,IAAkC,CAG9C,GAAI,CACF,MAAM,EAAG,UAAU,QACjB,CAAU,+CAA+C,EAAK,GAAa,wCAC5E,MACK,EAKR,EAAM,CACJ,OAAQ,cACR,WAAY,OACZ,SAAU,EAAK,GACf,OAAQ,EAAK,GACb,SAAU,EAAK,KACf,QAAS,CACP,OAAQ,CAAE,KAAM,EAAK,KAAM,MAAO,EAAK,MAAO,CAC/C,CACF,CAAC,EAEL,CACD,OAAQ,CAEN,OAAQ,KAAO,IAAsC,CACnD,IAAM,EAAkC,EAAE,CAC1C,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,EAAS,CAC7C,EAAY,IAAI,EAAI,EAAI,IAAQ,OACpC,EAAO,GAAO,GAEhB,EAAgB,OAAO,KAAK,EAAO,CAAC,OAAS,EAAI,EAAS,MAG5D,MAAO,MAAO,EAA+B,IAAiB,CAC5D,IAAM,EAAQ,EAAS,EAAI,CACrB,EAAS,EACf,EAAgB,KAChB,EAAM,CACJ,OAAQ,mBACR,WAAY,OACZ,SAAU,EAAK,GACf,OAAQ,EAAM,GACd,SAAU,EAAM,KAChB,QAAS,EAAS,CAAE,SAAQ,CAAG,IAAA,GAC/B,SAAU,CAC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,CAClC,GAAa,CACd,CACF,CAE6B"}
@@ -0,0 +1,71 @@
1
+ import { BetterAuthPlugin } from "better-auth";
2
+
3
+ //#region src/types.d.ts
4
+ /**
5
+ * better-auth base user fields + admin plugin fields.
6
+ * Base: id, createdAt, updatedAt, email, emailVerified, name, image
7
+ * Admin plugin adds: role, banned, banReason, banExpires
8
+ *
9
+ * Defined here (not in server.ts) so client.ts can import it
10
+ * without crossing the server-only boundary.
11
+ */
12
+ interface AdminUser {
13
+ id: string;
14
+ createdAt: Date;
15
+ updatedAt: Date;
16
+ email: string;
17
+ emailVerified: boolean;
18
+ name: string;
19
+ image?: string | null;
20
+ role?: string | null;
21
+ banned: boolean | null;
22
+ banReason?: string | null;
23
+ banExpires?: Date | null;
24
+ }
25
+ /**
26
+ * Auth plugin configuration
27
+ */
28
+ interface AuthConfig {
29
+ /** Auth providers to enable. Default: ['email'] */
30
+ providers?: ('email' | 'google' | 'github')[];
31
+ /** OAuth credentials (required when using social providers) */
32
+ social?: {
33
+ google?: {
34
+ clientId: string;
35
+ clientSecret: string;
36
+ };
37
+ github?: {
38
+ clientId: string;
39
+ clientSecret: string;
40
+ };
41
+ };
42
+ /** Session configuration */
43
+ session?: {
44
+ /** Session lifetime in seconds. Default: 7200 (2 hours) */expiresIn?: number; /** How often to refresh the session in seconds. Default: 3600 (1 hour) */
45
+ updateAge?: number;
46
+ };
47
+ /** Enable organization/multi-tenant support (maps to entity scope: 'team') */
48
+ organizations?: boolean;
49
+ /**
50
+ * Drizzle schema objects for the auth tables.
51
+ *
52
+ * Defaults to the canonical schema pre-baked in
53
+ * `@murumets-ee/auth/schema`. Override only if you're extending
54
+ * better-auth with custom plugins that add their own tables.
55
+ */
56
+ schema?: Record<string, unknown>;
57
+ /**
58
+ * Additional better-auth plugins to include.
59
+ * Use this for plugins not managed by the toolkit (e.g., twoFactor, magicLink).
60
+ */
61
+ betterAuthPlugins?: BetterAuthPlugin[];
62
+ /**
63
+ * Audit logging for auth events (login, signup, user update, ban, etc.).
64
+ * Enabled by default — writes to the toolkit_audit_logs table.
65
+ * Set to `false` to disable.
66
+ */
67
+ audit?: false;
68
+ }
69
+ //#endregion
70
+ export { AuthConfig as n, AdminUser as t };
71
+ //# sourceMappingURL=types-Dxs8Jhxs.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-Dxs8Jhxs.d.mts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;AAUA;;;;;;UAAiB,SAAA;EACf,EAAA;EACA,SAAA,EAAW,IAAA;EACX,SAAA,EAAW,IAAA;EACX,KAAA;EACA,aAAA;EACA,IAAA;EACA,KAAA;EACA,IAAA;EACA,MAAA;EACA,SAAA;EACA,UAAA,GAAa,IAAA;AAAA;;;;UAME,UAAA;EANE;EAQjB,SAAA;EAFyB;EAKzB,MAAA;IACE,MAAA;MAAW,QAAA;MAAkB,YAAA;IAAA;IAC7B,MAAA;MAAW,QAAA;MAAkB,YAAA;IAAA;EAAA;EAI/B;EAAA,OAAA;IAIE,2DAFA,SAAA,WAeF;IAbE,SAAA;EAAA;EAmBkB;EAfpB,aAAA;EAsBK;;;;;;;EAbL,MAAA,GAAS,MAAA;;;;;EAMT,iBAAA,GAAoB,gBAAA;;;;;;EAOpB,KAAA;AAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@murumets-ee/auth",
3
- "version": "0.1.5",
3
+ "version": "0.3.0",
4
4
  "license": "Elastic-2.0",
5
5
  "type": "module",
6
6
  "exports": {
@@ -16,6 +16,10 @@
16
16
  "types": "./dist/plugin.d.mts",
17
17
  "import": "./dist/plugin.mjs"
18
18
  },
19
+ "./schema": {
20
+ "types": "./dist/schema.d.mts",
21
+ "import": "./dist/schema.mjs"
22
+ },
19
23
  "./admin": {
20
24
  "types": "./dist/admin/index.d.mts",
21
25
  "import": "./dist/admin/index.mjs"
@@ -24,24 +28,25 @@
24
28
  "files": [
25
29
  "dist"
26
30
  ],
31
+ "scripts": {
32
+ "build": "tsdown",
33
+ "dev": "tsdown --watch",
34
+ "test": "vitest",
35
+ "gen:schema": "npx @better-auth/cli generate --config scripts/schema-source.ts --output src/schema.ts -y"
36
+ },
27
37
  "dependencies": {
28
- "better-auth": "^1.4.0",
38
+ "@murumets-ee/core": "workspace:*",
39
+ "@murumets-ee/db": "workspace:*",
40
+ "@murumets-ee/entity": "workspace:*",
41
+ "@murumets-ee/logging": "workspace:*",
42
+ "better-auth": "^1.6.2",
29
43
  "drizzle-orm": "^0.45.0",
30
- "server-only": "^0.0.1",
31
- "@murumets-ee/core": "0.1.6",
32
- "@murumets-ee/db": "0.1.5",
33
- "@murumets-ee/logging": "0.1.6",
34
- "@murumets-ee/entity": "0.1.5"
44
+ "server-only": "^0.0.1"
35
45
  },
36
46
  "devDependencies": {
37
47
  "@types/node": "^22.10.5",
38
48
  "tsdown": "^0.21.7",
39
49
  "typescript": "^5.7.3",
40
50
  "vitest": "^2.1.8"
41
- },
42
- "scripts": {
43
- "build": "tsdown",
44
- "dev": "tsdown --watch",
45
- "test": "vitest"
46
51
  }
47
- }
52
+ }
package/LICENSE DELETED
@@ -1,94 +0,0 @@
1
- Elastic License 2.0 (ELv2)
2
-
3
- URL: https://www.elastic.co/licensing/elastic-license
4
-
5
- ## Acceptance
6
-
7
- By using the software, you agree to all of the terms and conditions below.
8
-
9
- ## Copyright License
10
-
11
- The licensor grants you a non-exclusive, royalty-free, worldwide,
12
- non-sublicensable, non-transferable license to use, copy, distribute, make
13
- available, and prepare derivative works of the software, in each case subject
14
- to the limitations and conditions below.
15
-
16
- ## Limitations
17
-
18
- You may not provide the software to third parties as a hosted or managed
19
- service, where the service provides users with access to any substantial set
20
- of the features or functionality of the software.
21
-
22
- You may not move, change, disable, or circumvent the license key functionality
23
- in the software, and you may not remove or obscure any functionality in the
24
- software that is protected by the license key.
25
-
26
- You may not alter, remove, or obscure any licensing, copyright, or other
27
- notices of the licensor in the software. Any use of the licensor's trademarks
28
- is subject to applicable law.
29
-
30
- ## Patents
31
-
32
- The licensor grants you a license, under any patent claims the licensor can
33
- license, or becomes able to license, to make, have made, use, sell, offer for
34
- sale, import and have imported the software, in each case subject to the
35
- limitations and conditions in this license. This license does not cover any
36
- patent claims that you cause to be infringed by modifications or additions to
37
- the software. If you or your company make any written claim that the software
38
- infringes or contributes to infringement of any patent, your patent license
39
- for the software granted under these terms ends immediately. If your company
40
- makes such a claim, your patent license ends immediately for work on behalf
41
- of your company.
42
-
43
- ## Notices
44
-
45
- You must ensure that anyone who gets a copy of any part of the software from
46
- you also gets a copy of these terms.
47
-
48
- If you modify the software, you must include in any modified copies of the
49
- software prominent notices stating that you have modified the software.
50
-
51
- ## No Other Rights
52
-
53
- These terms do not imply any licenses other than those expressly granted in
54
- these terms.
55
-
56
- ## Termination
57
-
58
- If you use the software in violation of these terms, such use is not licensed,
59
- and your licenses will automatically terminate. If the licensor provides you
60
- with a notice of your violation, and you cease all violation of this license
61
- no later than 30 days after you receive that notice, your licenses will be
62
- reinstated retroactively. However, if you violate these terms after such
63
- reinstatement, any additional violation of these terms will cause your
64
- licenses to terminate automatically and permanently.
65
-
66
- ## No Liability
67
-
68
- As far as the law allows, the software comes as is, without any warranty or
69
- condition, and the licensor will not be liable to you for any damages arising
70
- out of these terms or the use or nature of the software, under any kind of
71
- legal claim.
72
-
73
- ## Definitions
74
-
75
- The **licensor** is the entity offering these terms, and the **software** is
76
- the software the licensor makes available under these terms, including any
77
- portion of it.
78
-
79
- **you** refers to the individual or entity agreeing to these terms.
80
-
81
- **your company** is any legal entity, sole proprietorship, or other kind of
82
- organization that you work for, plus all organizations that have control over,
83
- are under the control of, or are under common control with that organization.
84
- **control** means ownership of substantially all the assets of an entity, or
85
- the power to direct the management and policies of an entity (for example, by
86
- voting right, contract, or otherwise). Control can be direct or indirect.
87
-
88
- **your licenses** are all the licenses granted to you for the software under
89
- these terms.
90
-
91
- **use** means anything you do with the software requiring one of your
92
- licenses.
93
-
94
- **trademark** means trademarks, service marks, and similar rights.